• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang compilercommon.InputSource函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/serulian/compiler/compilercommon.InputSource函数的典型用法代码示例。如果您正苦于以下问题:Golang InputSource函数的具体用法?Golang InputSource怎么用?Golang InputSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了InputSource函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestParser

func TestParser(t *testing.T) {
	for _, test := range parserTests {
		if os.Getenv("FILTER") != "" {
			if !strings.Contains(test.name, os.Getenv("FILTER")) {
				continue
			} else {
				fmt.Printf("Matched Test: %v\n", test.name)
			}
		}

		moduleNode := createAstNode(compilercommon.InputSource(test.name), NodeTypeGlobalModule)

		Parse(moduleNode, createAstNode, compilercommon.InputSource(test.name), test.input())
		parseTree := getParseTree((moduleNode).(*testNode), 0)
		assert := assert.New(t)

		expected := strings.TrimSpace(test.tree())
		found := strings.TrimSpace(parseTree)

		if os.Getenv("REGEN") == "true" {
			test.writeTree(found)
		} else {
			if !assert.Equal(expected, found, test.name) {
				t.Log(parseTree)
			}
		}
	}
}
开发者ID:Serulian,项目名称:compiler,代码行数:28,代码来源:parser_test.go


示例2: conductParsing

// conductParsing performs parsing of a source file found at the given path.
func (p *PackageLoader) conductParsing(sourceFile pathInformation) {
	inputSource := compilercommon.InputSource(sourceFile.path)

	// Add the file to the package map as a package of one file.
	p.packageMap.Add(sourceFile.sourceKind, sourceFile.referenceId, PackageInfo{
		kind:        sourceFile.sourceKind,
		referenceId: sourceFile.referenceId,
		modulePaths: []compilercommon.InputSource{inputSource},
	})

	// Ensure the file exists.
	if ok, _ := exists(sourceFile.path); !ok {
		p.errors <- compilercommon.SourceErrorf(sourceFile.sal, "Could not find source file '%s'", sourceFile.path)
		return
	}

	// Load the source file's contents.
	contents, err := ioutil.ReadFile(sourceFile.path)
	if err != nil {
		p.errors <- compilercommon.SourceErrorf(sourceFile.sal, "Could not load source file '%s'", sourceFile.path)
		return
	}

	// Parse the source file.
	handler, hasHandler := p.handlers[sourceFile.sourceKind]
	if !hasHandler {
		log.Fatalf("Missing handler for source file of kind: [%v]", sourceFile.sourceKind)
	}

	handler.Parse(inputSource, string(contents), p.handleImport)
}
开发者ID:Serulian,项目名称:compiler,代码行数:32,代码来源:packageloader.go


示例3: scopeUnaryExpression

// scopeUnaryExpression scopes a unary expression in the SRG.
func (sb *scopeBuilder) scopeUnaryExpression(node compilergraph.GraphNode, opName string, predicate compilergraph.Predicate, context scopeContext) *scopeInfoBuilder {
	// Get the scope of the sub expression.
	childScope := sb.getScope(node.GetNode(predicate), context)

	// Ensure that the child scope is valid.
	if !childScope.GetIsValid() {
		return newScope().Invalid()
	}

	// Ensure that the operator exists under the resolved type.
	childType := childScope.ResolvedTypeRef(sb.sg.tdg)
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))
	operator, rerr := childType.ResolveAccessibleMember(opName, module, typegraph.MemberResolutionOperator)
	if rerr != nil {
		sb.decorateWithError(node, "Operator '%v' is not defined on type '%v'", opName, childType)
		return newScope().Invalid()
	}

	returnType, _ := operator.ReturnType()

	// Check for nullable values.
	if childType.NullValueAllowed() {
		sb.decorateWithError(node, "Cannot invoke operator '%v' on nullable type '%v'", opName, childType)
		return newScope().Invalid().CallsOperator(operator).Resolving(returnType.TransformUnder(childType))
	}

	return newScope().Valid().CallsOperator(operator).Resolving(returnType.TransformUnder(childType))
}
开发者ID:Serulian,项目名称:compiler,代码行数:29,代码来源:scope_op_expr.go


示例4: scopeInCollectionExpression

// scopeInCollectionExpression scopes an 'in' collection expression in the SRG.
func (sb *scopeBuilder) scopeInCollectionExpression(node compilergraph.GraphNode, context scopeContext) proto.ScopeInfo {
	// Get the scope of the left and right expressions.
	leftScope := sb.getScope(node.GetNode(parser.NodeBinaryExpressionLeftExpr), context)
	rightScope := sb.getScope(node.GetNode(parser.NodeBinaryExpressionRightExpr), context)

	// Ensure that both scopes are valid.
	if !leftScope.GetIsValid() || !rightScope.GetIsValid() {
		return newScope().Invalid().GetScope()
	}

	// Ensure that the right side has a 'contains' operator defined.
	rightType := rightScope.ResolvedTypeRef(sb.sg.tdg)
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))
	operator, rerr := rightType.ResolveAccessibleMember("contains", module, typegraph.MemberResolutionOperator)
	if rerr != nil {
		sb.decorateWithError(node, "Operator 'contains' is not defined on type '%v'", rightType)
		return newScope().Invalid().GetScope()
	}

	// Ensure the right side is not nullable.
	if rightType.NullValueAllowed() {
		sb.decorateWithError(node, "Cannot invoke operator 'in' on nullable value of type '%v'", rightType)
		return newScope().Invalid().GetScope()
	}

	// Ensure that the left side can be used as the operator's parameter.
	parameterType := operator.ParameterTypes()[0].TransformUnder(rightType)
	leftType := leftScope.ResolvedTypeRef(sb.sg.tdg)
	if serr := leftType.CheckSubTypeOf(parameterType); serr != nil {
		sb.decorateWithError(node, "Cannot invoke operator 'in' with value of type '%v': %v", leftType, serr)
		return newScope().Invalid().GetScope()
	}

	return newScope().Valid().CallsOperator(operator).Resolving(sb.sg.tdg.BoolTypeReference()).GetScope()
}
开发者ID:Serulian,项目名称:compiler,代码行数:36,代码来源:scope_op_expr.go


示例5: salForValues

// salForValues returns a SourceAndLocation for the given string predicate values.
func salForValues(sourceStr string, bytePositionStr string) compilercommon.SourceAndLocation {
	source := compilercommon.InputSource(sourceStr)
	bytePosition, err := strconv.Atoi(bytePositionStr)
	if err != nil {
		panic(fmt.Sprintf("Expected int value for byte position, found: %v", bytePositionStr))
	}

	return compilercommon.NewSourceAndLocation(source, bytePosition)
}
开发者ID:Serulian,项目名称:compiler,代码行数:10,代码来源:webidl.go


示例6: conductParsing

func conductParsing(t *testing.T, test goldenTest, source []byte) (*parseTree, formatterNode) {
	parseTree := newParseTree(source)
	inputSource := compilercommon.InputSource(test.filename)
	rootNode := parser.Parse(parseTree.createAstNode, nil, inputSource, string(source))
	if !assert.Empty(t, parseTree.errors, "Expected no parse errors for test %s", test.name) {
		return nil, formatterNode{}
	}

	return parseTree, rootNode.(formatterNode)
}
开发者ID:Serulian,项目名称:compiler,代码行数:10,代码来源:sourceformatter_test.go


示例7: TestNameScoping

func TestNameScoping(t *testing.T) {
	for _, test := range nameScopeTests {
		if os.Getenv("FILTER") != "" && !strings.Contains(test.name, os.Getenv("FILTER")) {
			continue
		}

		source := fmt.Sprintf("tests/namescope/%s.seru", test.source)
		testSRG := getSRG(t, source, "tests/testlib")

		_, found := testSRG.FindModuleBySource(compilercommon.InputSource(source))
		if !assert.True(t, found, "Test module not found") {
			continue
		}

		// Find the commented node.
		commentedNode, commentFound := testSRG.FindCommentedNode("/* " + test.comment + " */")
		if !assert.True(t, commentFound, "Comment %v for test %v not found", test.comment, test.name) {
			continue
		}

		// Resolve the name from the node.
		result, nameFound := testSRG.FindNameInScope(test.queryName, commentedNode)
		if !test.result.isValid {
			assert.False(t, nameFound, "Test %v expected name %v to not be found. Found: %v", test.name, test.queryName, result)
			continue
		}

		if !assert.Equal(t, result.IsNamedScope(), !test.result.isExternal, "External scope mismatch on test %s", test.name) {
			continue
		}

		if result.IsNamedScope() {
			resolved := result.AsNamedScope()
			if !assert.True(t, nameFound, "Test %v expected name %v to be found", test.name, test.queryName) {
				continue
			}

			if !assert.Equal(t, test.result.expectedNodeType, resolved.Kind(), "Test %v expected node of kind %v", test.name, test.result.expectedNodeType) {
				continue
			}

			if !assert.Equal(t, test.result.expectedName, resolved.Name(), "Test %v expected name %v", test.name, test.result.expectedName) {
				continue
			}

			if !assert.Equal(t, test.result.expectedKind, resolved.ScopeKind(), "Test %v expected kind %v", test.name, test.result.expectedKind) {
				continue
			}
		} else {
			if !assert.Equal(t, test.result.expectedName, result.AsPackageImport().name, "Mismatch name on imported package for test %s", test.name) {
				continue
			}
		}
	}
}
开发者ID:Serulian,项目名称:compiler,代码行数:55,代码来源:scopename_test.go


示例8: TestComplexResolveTypePath

func TestComplexResolveTypePath(t *testing.T) {
	testSRG := getSRG(t, "tests/complexresolve/entrypoint.seru")

	// Lookup the entrypoint module.
	entrypointModule, ok := testSRG.FindModuleBySource(compilercommon.InputSource("tests/complexresolve/entrypoint.seru"))
	assert.True(t, ok, "Could not find entrypoint module")

	// Lookup all the expected types.

	// In module.
	assertResolveTypePath(t, entrypointModule, "SomeClass", "SomeClass")

	// from ... import ... on module
	assertResolveTypePath(t, entrypointModule, "AnotherClass", "AnotherClass")
	assertResolveTypePath(t, entrypointModule, "BestClass", "AThirdClass")

	// from ... import ... on package
	assertResolveTypePath(t, entrypointModule, "FirstClass", "FirstClass")
	assertResolveTypePath(t, entrypointModule, "SecondClass", "SecondClass")
	assertResolveTypePath(t, entrypointModule, "BusinessClass", "FirstClass")

	// Direct imports.
	assertResolveTypePath(t, entrypointModule, "anothermodule.AnotherClass", "AnotherClass")

	assertResolveTypePath(t, entrypointModule, "subpackage.FirstClass", "FirstClass")
	assertResolveTypePath(t, entrypointModule, "subpackage.SecondClass", "SecondClass")

	// Ensure that an non-exported type is still accessible inside the package..
	assertResolveTypePath(t, entrypointModule, "anothermodule.localClass", "localClass")

	// Other package.
	assertResolveTypePath(t, entrypointModule, "anotherpackage.ExportedPackageClass", "ExportedPackageClass")

	// Ensure that an non-exported type is not accessible from another package.
	_, found := entrypointModule.ResolveTypePath("anotherpackage.otherPackageClass")
	assert.False(t, found, "Expected otherPackageClass to not be exported")

	// Lookup another module.
	anotherModule, ok := testSRG.FindModuleBySource(compilercommon.InputSource("tests/complexresolve/anothermodule.seru"))
	assert.True(t, ok, "Could not find another module")
	assertResolveTypePath(t, anotherModule, "localClass", "localClass")
}
开发者ID:Serulian,项目名称:compiler,代码行数:42,代码来源:modules_test.go


示例9: collect

// collect gathers the emitted tokens into a slice.
func collect(t *lexerTest) (tokens []lexeme) {
	l := lex(compilercommon.InputSource(t.name), t.input)
	for {
		token := l.nextToken()
		tokens = append(tokens, token)
		if token.kind == tokenTypeEOF || token.kind == tokenTypeError {
			break
		}
	}
	return
}
开发者ID:Serulian,项目名称:compiler,代码行数:12,代码来源:lex_test.go


示例10: TestBasicResolveTypePath

func TestBasicResolveTypePath(t *testing.T) {
	testSRG := getSRG(t, "tests/basic/basic.seru")

	// Lookup the basic module.
	basicModule, ok := testSRG.FindModuleBySource(compilercommon.InputSource("tests/basic/basic.seru"))
	assert.True(t, ok, "Could not find basic module")

	// Lookup both expected types.
	assertResolveTypePath(t, basicModule, "SomeClass", "SomeClass")
	assertResolveTypePath(t, basicModule, "AnotherClass", "AnotherClass")
}
开发者ID:Serulian,项目名称:compiler,代码行数:11,代码来源:modules_test.go


示例11: scopeMemberAccessExpression

// scopeMemberAccessExpression scopes a member access expression in the SRG.
func (sb *scopeBuilder) scopeMemberAccessExpression(node compilergraph.GraphNode, context scopeContext) proto.ScopeInfo {
	// Get the scope of the child expression.
	childScope := sb.getScope(node.GetNode(parser.NodeMemberAccessChildExpr), context)
	if !childScope.GetIsValid() {
		return newScope().Invalid().GetScope()
	}

	memberName := node.Get(parser.NodeMemberAccessIdentifier)
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))

	switch childScope.GetKind() {

	case proto.ScopeKind_VALUE:
		childType := childScope.ResolvedTypeRef(sb.sg.tdg)
		if childType.IsNullable() {
			sb.decorateWithError(node, "Cannot access name '%v' under nullable type '%v'. Please use the ?. operator to ensure type safety.", memberName, childType)
			return newScope().Invalid().GetScope()
		}

		typeMember, rerr := childType.ResolveAccessibleMember(memberName, module, typegraph.MemberResolutionInstance)
		if rerr != nil {
			sb.decorateWithError(node, "%v", rerr)
			return newScope().Invalid().GetScope()
		}

		memberScope := sb.getNamedScopeForMember(typeMember)
		context.staticDependencyCollector.checkNamedScopeForDependency(memberScope)

		return newScope().ForNamedScopeUnderType(memberScope, childType, context).GetScope()

	case proto.ScopeKind_GENERIC:
		namedScope, _ := sb.getNamedScopeForScope(childScope)
		sb.decorateWithError(node, "Cannot attempt member access of '%v' under %v %v, as it is generic without specification", memberName, namedScope.Title(), namedScope.Name())
		return newScope().Invalid().GetScope()

	case proto.ScopeKind_STATIC:
		staticType := childScope.StaticTypeRef(sb.sg.tdg)
		namedScope, _ := sb.getNamedScopeForScope(childScope)
		memberScope, rerr := namedScope.ResolveStaticMember(memberName, module, staticType)
		if rerr != nil {
			sb.decorateWithError(node, "%v", rerr)
			return newScope().Invalid().GetScope()
		}
		return newScope().ForNamedScopeUnderType(memberScope, staticType, context).GetScope()

	default:
		panic("Unknown scope kind")
	}

	return newScope().Invalid().GetScope()
}
开发者ID:Serulian,项目名称:compiler,代码行数:52,代码来源:scope_access_expr.go


示例12: TestModuleMembers

func TestModuleMembers(t *testing.T) {
	testSRG := getSRG(t, "tests/members/module.seru")

	// Ensure both module-level members are found.
	module, _ := testSRG.FindModuleBySource(compilercommon.InputSource("tests/members/module.seru"))
	members := module.GetMembers()

	if !assert.Equal(t, 2, len(members), "Expected 2 members found") {
		return
	}

	assert.Equal(t, members[0].MemberKind(), VarMember)
	assert.Equal(t, members[1].MemberKind(), FunctionMember)
}
开发者ID:Serulian,项目名称:compiler,代码行数:14,代码来源:members_test.go


示例13: scopeStreamMemberAccessExpression

// scopeStreamMemberAccessExpression scopes a stream member access expression in the SRG.
func (sb *scopeBuilder) scopeStreamMemberAccessExpression(node compilergraph.GraphNode, context scopeContext) proto.ScopeInfo {
	// Get the scope of the child expression.
	childScope := sb.getScope(node.GetNode(parser.NodeMemberAccessChildExpr), context)
	if !childScope.GetIsValid() {
		return newScope().Invalid().GetScope()
	}

	memberName := node.Get(parser.NodeMemberAccessIdentifier)
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))

	switch childScope.GetKind() {
	case proto.ScopeKind_VALUE:
		childType := childScope.ResolvedTypeRef(sb.sg.tdg)

		// Ensure the child type is a stream.
		generics, serr := childType.CheckConcreteSubtypeOf(sb.sg.tdg.StreamType())
		if serr != nil {
			sb.decorateWithError(node, "Cannot attempt stream access of name '%v' under non-stream type '%v': %v", memberName, childType, serr)
			return newScope().Invalid().GetScope()
		}

		valueType := generics[0]
		typeMember, rerr := valueType.ResolveAccessibleMember(memberName, module, typegraph.MemberResolutionInstance)
		if rerr != nil {
			sb.decorateWithError(node, "%v", rerr)
			return newScope().Invalid().GetScope()
		}

		memberScope := sb.getNamedScopeForMember(typeMember)
		context.staticDependencyCollector.checkNamedScopeForDependency(memberScope)

		return newScope().ForNamedScopeUnderModifiedType(memberScope, valueType, makeStream, context).GetScope()

	case proto.ScopeKind_GENERIC:
		namedScope, _ := sb.getNamedScopeForScope(childScope)
		sb.decorateWithError(node, "Cannot attempt stream member access of '%v' under %v %v, as it is generic without specification", memberName, namedScope.Title(), namedScope.Name())
		return newScope().Invalid().GetScope()

	case proto.ScopeKind_STATIC:
		namedScope, _ := sb.getNamedScopeForScope(childScope)
		sb.decorateWithError(node, "Cannot attempt stream member access of '%v' under %v %v, as it is a static type", memberName, namedScope.Title(), namedScope.Name())
		return newScope().Invalid().GetScope()

	default:
		panic("Unknown scope kind")
	}

	return newScope().Invalid().GetScope()
}
开发者ID:Serulian,项目名称:compiler,代码行数:50,代码来源:scope_access_expr.go


示例14: getModulesMap

// getModulesMap returns the modules map for the modules in the SRG.
func (g *SRG) getModulesMap() map[compilercommon.InputSource]SRGModule {
	if g.modulePathMap == nil {
		moduleMap := map[compilercommon.InputSource]SRGModule{}
		it := g.findAllNodes(parser.NodeTypeFile).BuildNodeIterator(parser.NodePredicateSource)
		for it.Next() {
			moduleMap[compilercommon.InputSource(it.GetPredicate(parser.NodePredicateSource).String())] = SRGModule{it.Node(), g}
		}

		// Cache the map.
		g.modulePathMap = moduleMap
		return moduleMap
	}

	return g.modulePathMap
}
开发者ID:Serulian,项目名称:compiler,代码行数:16,代码来源:modules.go


示例15: ResolveType

// ResolveType attempts to resolve the type path referenced by this type ref.
// Panics if this is not a RefKind of TypeRefPath.
func (t SRGTypeRef) ResolveType() (TypeResolutionResult, bool) {
	// Find the parent module.
	source := compilercommon.InputSource(t.GraphNode.Get(parser.NodePredicateSource))
	srgModule, found := t.srg.FindModuleBySource(source)
	if !found {
		panic(fmt.Sprintf("Unknown parent module: %s", source))
	}

	// Resolve the type path under the module.
	resolutionPath := t.ResolutionPath()
	resolvedType, typeFound := srgModule.ResolveTypePath(resolutionPath)
	if typeFound {
		return resolvedType, true
	}

	// If not found and the path is a single name, try to resolve as a generic
	// under a parent function or type.
	if strings.ContainsRune(resolutionPath, '.') {
		// Not a single name.
		return TypeResolutionResult{}, false
	}

	containingFilter := func(q compilergraph.GraphQuery) compilergraph.Query {
		// For this filter, we check if the defining type (or type member) if the
		// generic is the same type (or type member) containing the typeref. To do so,
		// we perform a check that the start rune and end rune of the definition
		// contains the range of the start and end rune, respectively, of the typeref. Since
		// we know both nodes are in the same module, and the SRG is a tree, this validates
		// that we are in the correct scope without having to walk the tree upward.
		startRune := t.GraphNode.GetValue(parser.NodePredicateStartRune).Int()
		endRune := t.GraphNode.GetValue(parser.NodePredicateEndRune).Int()

		return q.
			In(parser.NodeTypeDefinitionGeneric, parser.NodePredicateTypeMemberGeneric).
			HasWhere(parser.NodePredicateStartRune, compilergraph.WhereLTE, startRune).
			HasWhere(parser.NodePredicateEndRune, compilergraph.WhereGTE, endRune)
	}

	resolvedGenericNode, genericFound := t.srg.layer.
		StartQuery().                                         // Find a node...
		Has(parser.NodeGenericPredicateName, resolutionPath). // With the generic name..
		Has(parser.NodePredicateSource, string(source)).      // That is in this module...
		IsKind(parser.NodeTypeGeneric).                       // That is a generic...
		FilterBy(containingFilter).                           // Filter by whether its defining type or member contains this typeref.
		TryGetNode()

	return resultForTypeOrGeneric(SRGTypeOrGeneric{resolvedGenericNode, t.srg}), genericFound
}
开发者ID:Serulian,项目名称:compiler,代码行数:50,代码来源:typeref.go


示例16: FindNameInScope

// FindNameInScope finds the given name accessible from the scope under which the given node exists, if any.
func (g *SRG) FindNameInScope(name string, node compilergraph.GraphNode) (SRGScopeOrImport, bool) {
	// Attempt to resolve the name as pointing to a parameter, var statement, loop var or with var.
	srgNode, srgNodeFound := g.findAddedNameInScope(name, node)
	if srgNodeFound {
		return SRGNamedScope{srgNode, g}, true
	}

	// If still not found, try to resolve as a type or import.
	nodeSource := node.Get(parser.NodePredicateSource)
	parentModule, parentModuleFound := g.FindModuleBySource(compilercommon.InputSource(nodeSource))
	if !parentModuleFound {
		panic(fmt.Sprintf("Missing module for source %v", nodeSource))
	}

	// Try to resolve as a local member.
	srgTypeOrMember, typeOrMemberFound := parentModule.FindTypeOrMemberByName(name, ModuleResolveAll)
	if typeOrMemberFound {
		return SRGNamedScope{srgTypeOrMember.GraphNode, g}, true
	}

	// Try to resolve as an imported member.
	localImportNode, localImportFound := parentModule.findImportWithLocalName(name)
	if localImportFound {
		// Retrieve the package for the imported member.
		packageInfo := g.getPackageForImport(localImportNode)
		resolutionName := localImportNode.Get(parser.NodeImportPredicateSubsource)

		// If an SRG package, then continue with the resolution. Otherwise,
		// we return a named scope that says that the name needs to be furthered
		// resolved in the package by the type graph.
		if packageInfo.IsSRGPackage() {
			packageTypeOrMember, packagetypeOrMemberFound := packageInfo.FindTypeOrMemberByName(resolutionName)
			if packagetypeOrMemberFound {
				return SRGNamedScope{packageTypeOrMember.GraphNode, g}, true
			}
		}

		return SRGExternalPackageImport{packageInfo.packageInfo, resolutionName, g}, true
	}

	// Try to resolve as an imported package.
	importNode, importFound := parentModule.findImportByPackageName(name)
	if importFound {
		return SRGNamedScope{importNode, g}, true
	}

	return SRGNamedScope{}, false
}
开发者ID:Serulian,项目名称:compiler,代码行数:49,代码来源:scopename.go


示例17: loadLocalPackage

// loadLocalPackage loads the package found at the path relative to the package directory.
func (p *PackageLoader) loadLocalPackage(packagePath pathInformation) {
	// Ensure the directory exists.
	if ok, _ := exists(packagePath.path); !ok {
		p.errors <- compilercommon.SourceErrorf(packagePath.sal, "Could not find directory '%s'", packagePath.path)
		return
	}

	// Read the contents of the directory.
	directoryContents, err := ioutil.ReadDir(packagePath.path)
	if err != nil {
		p.errors <- compilercommon.SourceErrorf(packagePath.sal, "Could not load directory '%s'", packagePath.path)
		return
	}

	// Add the package information to the map.
	packageInfo := &PackageInfo{
		kind:        packagePath.sourceKind,
		referenceId: packagePath.referenceId,
		modulePaths: make([]compilercommon.InputSource, 0),
	}

	// Load the handler for the package.
	handler, hasHandler := p.handlers[packagePath.sourceKind]
	if !hasHandler {
		log.Fatalf("Missing handler for source file of kind: [%v]", packagePath.sourceKind)
	}

	// Find all source files in the directory and add them to the paths list.
	var fileFound bool
	for _, fileInfo := range directoryContents {
		if path.Ext(fileInfo.Name()) == handler.PackageFileExtension() {
			fileFound = true
			filePath := path.Join(packagePath.path, fileInfo.Name())
			p.pushPath(pathSourceFile, packagePath.sourceKind, filePath, packagePath.sal)

			// Add the source file to the package information.
			packageInfo.modulePaths = append(packageInfo.modulePaths, compilercommon.InputSource(filePath))
		}
	}

	p.packageMap.Add(packagePath.sourceKind, packagePath.referenceId, *packageInfo)
	if !fileFound {
		p.warnings <- compilercommon.SourceWarningf(packagePath.sal, "Package '%s' has no source files", packagePath.path)
		return
	}
}
开发者ID:Serulian,项目名称:compiler,代码行数:47,代码来源:packageloader.go


示例18: TestLexerPositioning

func TestLexerPositioning(t *testing.T) {
	text := `this.foo // some comment
class SomeClass`

	l := lex(compilercommon.InputSource("position test"), text)
	checkNext(t, l, text, lexeme{tokenTypeKeyword, 0, "this"}, 0, 0)
	checkNext(t, l, text, lexeme{tokenTypeDotAccessOperator, 4, "."}, 0, 4)
	checkNext(t, l, text, lexeme{tokenTypeIdentifer, 5, "foo"}, 0, 5)
	checkNext(t, l, text, lexeme{tokenTypeWhitespace, 8, " "}, 0, 8)
	checkNext(t, l, text, lexeme{tokenTypeSinglelineComment, 9, "// some comment"}, 0, 9)

	checkNext(t, l, text, lexeme{tokenTypeSyntheticSemicolon, 24, "\n"}, 0, 24)

	checkNext(t, l, text, lexeme{tokenTypeKeyword, 25, "class"}, 1, 0)
	checkNext(t, l, text, lexeme{tokenTypeWhitespace, 30, " "}, 1, 5)
	checkNext(t, l, text, lexeme{tokenTypeIdentifer, 31, "SomeClass"}, 1, 6)
	checkNext(t, l, text, lexeme{tokenTypeEOF, 40, ""}, 1, 15)
}
开发者ID:Serulian,项目名称:compiler,代码行数:18,代码来源:lex_test.go


示例19: scopeStructuralNewExpressionEntry

// scopeStructuralNewExpressionEntry scopes a single entry in a structural new expression.
func (sb *scopeBuilder) scopeStructuralNewExpressionEntry(node compilergraph.GraphNode, context scopeContext) proto.ScopeInfo {
	parentNode := node.GetIncomingNode(parser.NodeStructuralNewExpressionChildEntry)
	parentExprScope := sb.getScope(parentNode.GetNode(parser.NodeStructuralNewTypeExpression), context)

	parentType := parentExprScope.StaticTypeRef(sb.sg.tdg)
	if parentExprScope.GetKind() == proto.ScopeKind_VALUE {
		parentType = parentExprScope.ResolvedTypeRef(sb.sg.tdg)
	}

	entryName := node.Get(parser.NodeStructuralNewEntryKey)

	// Get the scope for the value.
	valueScope := sb.getScope(node.GetNode(parser.NodeStructuralNewEntryValue), context)
	if !valueScope.GetIsValid() {
		return newScope().Invalid().GetScope()
	}

	// Lookup the member associated with the entry name.
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))
	member, rerr := parentType.ResolveAccessibleMember(entryName, module, typegraph.MemberResolutionInstance)
	if rerr != nil {
		sb.decorateWithError(node, "%v", rerr)
		return newScope().Invalid().GetScope()
	}

	// Ensure the member is assignable.
	if member.IsReadOnly() {
		sb.decorateWithError(node, "%v %v under type %v is read-only", member.Title(), member.Name(), parentType)
		return newScope().Invalid().GetScope()
	}

	// Get the member's assignable type, transformed under the parent type, and ensure it is assignable
	// from the type of the value.
	assignableType := member.AssignableType().TransformUnder(parentType)
	valueType := valueScope.ResolvedTypeRef(sb.sg.tdg)

	if aerr := valueType.CheckSubTypeOf(assignableType); aerr != nil {
		sb.decorateWithError(node, "Cannot assign value of type %v to %v %v: %v", valueType, member.Title(), member.Name(), aerr)
		return newScope().Invalid().GetScope()
	}

	return newScope().ForNamedScope(sb.getNamedScopeForMember(member), context).Valid().GetScope()
}
开发者ID:Serulian,项目名称:compiler,代码行数:44,代码来源:scope_literal_expr.go


示例20: scopeBinaryExpression

// scopeBinaryExpression scopes a binary expression in the SRG.
func (sb *scopeBuilder) scopeBinaryExpression(node compilergraph.GraphNode, opName string, context scopeContext) *scopeInfoBuilder {
	// Get the scope of the left and right expressions.
	leftScope := sb.getScope(node.GetNode(parser.NodeBinaryExpressionLeftExpr), context)
	rightScope := sb.getScope(node.GetNode(parser.NodeBinaryExpressionRightExpr), context)

	// Ensure that both scopes are valid.
	if !leftScope.GetIsValid() || !rightScope.GetIsValid() {
		return newScope().Invalid()
	}

	// Ensure that both scopes have the same type.
	leftType := leftScope.ResolvedTypeRef(sb.sg.tdg)
	rightType := rightScope.ResolvedTypeRef(sb.sg.tdg)

	if leftType != rightType {
		sb.decorateWithError(node, "Operator '%v' requires operands of the same type. Found: '%v' and '%v'", opName, leftType, rightType)
		return newScope().Invalid()
	}

	// Ensure that the operator exists under the resolved type.
	module := compilercommon.InputSource(node.Get(parser.NodePredicateSource))
	operator, rerr := leftType.ResolveAccessibleMember(opName, module, typegraph.MemberResolutionOperator)
	if rerr != nil {
		sb.decorateWithError(node, "Operator '%v' is not defined on type '%v'", opName, leftType)
		return newScope().Invalid()
	}

	returnType, _ := operator.ReturnType()

	// Check for nullable values.
	if leftType.NullValueAllowed() {
		sb.decorateWithError(node, "Cannot invoke operator '%v' on nullable type '%v'", opName, leftType)
		return newScope().Invalid().CallsOperator(operator).Resolving(returnType.TransformUnder(leftType))
	}

	if rightType.NullValueAllowed() {
		sb.decorateWithError(node, "Cannot invoke operator '%v' on nullable type '%v'", opName, rightType)
		return newScope().Invalid().CallsOperator(operator).Resolving(returnType.TransformUnder(leftType))
	}

	return newScope().Valid().CallsOperator(operator).Resolving(returnType.TransformUnder(leftType))
}
开发者ID:Serulian,项目名称:compiler,代码行数:43,代码来源:scope_op_expr.go



注:本文中的github.com/serulian/compiler/compilercommon.InputSource函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang compilergraph.GraphNode类代码示例发布时间:2022-05-28
下一篇:
Golang jwt.Claims函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap