本文整理汇总了Golang中mojom/mojom_parser/mojom.NewMojomDescriptor函数的典型用法代码示例。如果您正苦于以下问题:Golang NewMojomDescriptor函数的具体用法?Golang NewMojomDescriptor怎么用?Golang NewMojomDescriptor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewMojomDescriptor函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestSingleFileResolutionSuccess
// TestSingleFileResolutionSuccess() iterates through a series of test cases.
// For each case we expect for parsing and resolution to succeed. Then we
// execute a given callback test function to test that resolution produced
// the desired result.
func TestSingleFileResolutionSuccess(t *testing.T) {
test := singleFileSuccessTest{}
////////////////////////////////////////////////////////////
// Test Case: A local constant name shadows an enum name.
////////////////////////////////////////////////////////////
{
contents := `
enum Color{
RED, BLUE
};
struct MyStruct {
const Color RED = BLUE;
Color a_color = RED; // This should resolve to the local constant RED,
// and therefore the concrete value should be BLUE.
};`
testFunc := func(descriptor *mojom.MojomDescriptor) error {
myStructType := descriptor.TypesByKey["TYPE_KEY:MyStruct"].(*mojom.MojomStruct)
aColorField := myStructType.Fields[0]
concreteValue := aColorField.DefaultValue.ResolvedConcreteValue().(*mojom.EnumValue)
key := concreteValue.ValueKey()
if key != "TYPE_KEY:Color.BLUE" {
return fmt.Errorf("%s != TYPE_KEY:Color.BLUE", key)
}
return nil
}
test.addTestCase("", contents, testFunc)
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
fileName := fmt.Sprintf("file%d", i)
parser := MakeParser(fileName, fileName, c.mojomContents, descriptor, nil)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", fileName, parser.GetError().Error())
continue
}
err := descriptor.Resolve()
if err != nil {
t.Errorf("Resolution failed for test case %d: %s", i, err.Error())
continue
}
if c.testFunc != nil {
if err := c.testFunc(descriptor); err != nil {
t.Errorf("%s:\n%s", fileName, err.Error())
continue
}
}
}
}
示例2: ParseFiles
// Parses each of the given .mojom files and all of the files in the
// import graph rooted by each file. A single MojomDescriptor is created and
// populated with the result of parsing all of those files. If the parsing is
// successful then err will be nil.
//
// fileNames must not be nil or we will panic.
func (d *ParseDriver) ParseFiles(fileNames []string) (descriptor *mojom.MojomDescriptor, err error) {
if fileNames == nil {
// We panic instead of returning an error here because this would be a programming error
// as opposed to an error in the input.
panic("fileNames may not be nil.")
}
filesToProcess := make([]*FileReference, len(fileNames))
descriptor = mojom.NewMojomDescriptor()
for i, fileName := range fileNames {
filesToProcess[i] = &FileReference{specifiedPath: fileName}
}
for len(filesToProcess) > 0 {
currentFile := filesToProcess[0]
filesToProcess = filesToProcess[1:]
if err = d.fileProvider.findFile(currentFile); err != nil {
return
}
if !descriptor.ContainsFile(currentFile.absolutePath) {
contents, fileReadError := d.fileProvider.provideContents(currentFile)
if fileReadError != nil {
err = fileReadError
return
}
parser := MakeParser(currentFile.absolutePath, contents, descriptor)
parser.SetDebugMode(d.debugMode)
parser.Parse()
if d.debugMode {
fmt.Printf("\nParseTree for %s:", currentFile)
fmt.Println(parser.GetParseTree())
}
if !parser.OK() {
err = fmt.Errorf("\nError while parsing %s: \n%s\n",
currentFile, parser.GetError().Error())
return
}
mojomFile := d.fileExtractor.extractMojomFile(&parser)
for _, importedFile := range mojomFile.Imports {
filesToProcess = append(filesToProcess,
&FileReference{importedFrom: currentFile, specifiedPath: importedFile})
}
}
}
// Perform type and value resolution
if err = descriptor.Resolve(); err != nil {
return
}
// Compute data for generators.
err = descriptor.ComputeDataForGenerators()
return
}
示例3: ParseFiles
// Parses each of the given .mojom files and all of the files in the
// import graph rooted by each file. A single MojomDescriptor is created and
// populated with the result of parsing all of those files. The returned
// ParseResult contains the populuted MojomDescriptor and any error that
// occurred.
func (d *ParseDriver) ParseFiles(fileNames []string) ParseResult {
if fileNames == nil {
panic("fileNames may not be nil.")
}
filesToProcess := make([]*FileReference, len(fileNames))
descriptor := mojom.NewMojomDescriptor()
for i, fileName := range fileNames {
filesToProcess[i] = &FileReference{specifiedPath: fileName}
}
for len(filesToProcess) > 0 {
currentFile := filesToProcess[0]
filesToProcess = filesToProcess[1:]
if err := d.fileProvider.FindFile(currentFile); err != nil {
return ParseResult{Err: err, Descriptor: descriptor}
}
if !descriptor.ContainsFile(currentFile.absolutePath) {
contents, fileReadError := d.fileProvider.ProvideContents(currentFile)
if fileReadError != nil {
return ParseResult{Err: fileReadError, Descriptor: descriptor}
}
parser := MakeParser(currentFile.absolutePath, contents, descriptor)
parser.SetDebugMode(d.debugMode)
parser.Parse()
if d.debugMode {
fmt.Printf("\nParseTree for %s:", currentFile)
fmt.Println(parser.GetParseTree())
}
if !parser.OK() {
parseError := fmt.Errorf("\nError while parsing %s: \n%s\n",
currentFile, parser.GetError().Error())
return ParseResult{Err: parseError, Descriptor: descriptor}
}
mojomFile := parser.GetMojomFile()
for _, importedFile := range mojomFile.Imports {
filesToProcess = append(filesToProcess,
&FileReference{importedFrom: currentFile, specifiedPath: importedFile})
}
}
}
// Perform type and value resolution
if resolutionError := descriptor.Resolve(); resolutionError != nil {
return ParseResult{Err: resolutionError, Descriptor: descriptor}
}
// Compute data for generators.
computationError := descriptor.ComputeDataForGenerators()
return ParseResult{Err: computationError, Descriptor: descriptor}
}
示例4: TestTwoFileSerialization
//.........这里部分代码省略.........
struct FooA{
};`
contentsB := `
module a.b.c;
struct FooB{
};`
importingName := "myLittleFriend" // File A is importing File B using this name.
topLevel := false // Simulate the File B is not a top-level file.
test.addTestCase("a.b.c", contentsA, contentsB, topLevel, importingName)
// DeclaredMojomObjects
test.expectedFileA().DeclaredMojomObjects.Structs = &[]string{"TYPE_KEY:a.b.c.FooA"}
test.expectedFileB().DeclaredMojomObjects.Structs = &[]string{"TYPE_KEY:a.b.c.FooB"}
// struct FooA
test.expectedGraph().ResolvedTypes["TYPE_KEY:a.b.c.FooA"] = &mojom_types.UserDefinedTypeStructType{mojom_types.MojomStruct{
DeclData: newDeclData(test.expectedFileA().FileName, "FooA", "a.b.c.FooA"),
Fields: []mojom_types.StructField{}}}
// struct FooB
test.expectedGraph().ResolvedTypes["TYPE_KEY:a.b.c.FooB"] = &mojom_types.UserDefinedTypeStructType{mojom_types.MojomStruct{
DeclData: newDeclData(test.expectedFileB().FileName, "FooB", "a.b.c.FooB"),
Fields: []mojom_types.StructField{}}}
test.endTestCase()
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
descriptor := mojom.NewMojomDescriptor()
// Parse file A.
parserA := parser.MakeParser(c.expectedFileA.FileName, *c.expectedFileA.SpecifiedFileName, c.mojomContentsA, descriptor, nil)
parserA.Parse()
if !parserA.OK() {
t.Errorf("Parsing error for %s: %s", c.expectedFileA.FileName, parserA.GetError().Error())
continue
}
mojomFileA := parserA.GetMojomFile()
// Parse file B.
var importedFrom *mojom.MojomFile
if !c.topLevel {
// If file B is not a top-level file then when the parser for it is constructed we give it a non-nil |importedFrom|.
importedFrom = mojomFileA
}
parserB := parser.MakeParser(c.expectedFileB.FileName, *c.expectedFileB.SpecifiedFileName, c.mojomContentsB, descriptor, importedFrom)
parserB.Parse()
if !parserB.OK() {
t.Errorf("Parsing error for %s: %s", c.expectedFileB.FileName, parserB.GetError().Error())
continue
}
mojomFileB := parserB.GetMojomFile()
// Set the canonical file name for the imported files. In real operation
// this step is done in parser_driver.go when each of the imported files are parsed.
if c.importingName != "" {
// The call to SetCanonicalImportName does a lookup in a map for a key corresponding to the
// first argument. Thus here we are also testing that |importingName| is in fact string
// that was parsed from the .mojom file.
mojomFileA.SetCanonicalImportName(c.importingName, mojomFileB.CanonicalFileName)
}
示例5: TestSingleFileSerialization
//.........这里部分代码省略.........
ShortName: stringPointer("Foo"),
FullIdentifier: stringPointer("mojom.test.Foo"),
DeclaredOrdinal: -1,
DeclarationOrder: -1,
SourceFileInfo: &mojom_types.SourceFileInfo{
FileName: test.fileName(),
},
ContainedDeclarations: &mojom_types.ContainedDeclarations{
Enums: &[]string{"TYPE_KEY:mojom.test.Foo.Hats"}},
},
Fields: []mojom_types.StructField{
// field x
{
DeclData: test.newDeclData("x", ""),
Type: &mojom_types.TypeSimpleType{mojom_types.SimpleType_InT32},
},
// field y
{
DeclData: test.newDeclData("y", ""),
Type: &mojom_types.TypeStringType{mojom_types.StringType{false}},
DefaultValue: &mojom_types.DefaultFieldValueValue{&mojom_types.ValueLiteralValue{&mojom_types.LiteralValueStringValue{"hello"}}},
},
// field z
{
DeclData: test.newDeclData("z", ""),
Type: &mojom_types.TypeStringType{mojom_types.StringType{true}},
},
},
}}
// enum Hats
test.expectedGraph().ResolvedTypes["TYPE_KEY:mojom.test.Foo.Hats"] = &mojom_types.UserDefinedTypeEnumType{mojom_types.MojomEnum{
DeclData: test.newDeclData("Hats", "mojom.test.Foo.Hats"),
Values: []mojom_types.EnumValue{
// Note(rudominer) It is a bug that we need to copy the enum values here.
// See https://github.com/domokit/mojo/issues/513.
// value TOP
test.expectedGraph().ResolvedValues["TYPE_KEY:mojom.test.Foo.Hats.TOP"].(*mojom_types.UserDefinedValueEnumValue).Value,
// value COWBOY
test.expectedGraph().ResolvedValues["TYPE_KEY:mojom.test.Foo.Hats.COWBOY"].(*mojom_types.UserDefinedValueEnumValue).Value,
},
}}
test.endTestCase()
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for _, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
parser := parser.MakeParser(c.fileName, c.mojomContents, descriptor)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", c.fileName, parser.GetError().Error())
continue
}
if err := descriptor.Resolve(); err != nil {
t.Errorf("Resolve error for %s: %s", c.fileName, err.Error())
continue
}
if err := descriptor.ComputeEnumValueIntegers(); err != nil {
t.Errorf("ComputeEnumValueIntegers error for %s: %s", c.fileName, err.Error())
continue
}
if err := descriptor.ComputeDataForGenerators(); err != nil {
t.Errorf("ComputeDataForGenerators error for %s: %s", c.fileName, err.Error())
continue
}
// Simulate setting the canonical file name for the imported files. In real operation
// this step is done in parser_driver.go when each of the imported files are parsed.
mojomFile := parser.GetMojomFile()
if mojomFile.Imports != nil {
for _, imp := range mojomFile.Imports {
imp.CanonicalFileName = fmt.Sprintf("%s.canonical", imp.SpecifiedName)
}
}
// Serialize
EmitLineAndColumnNumbers = c.lineAndcolumnNumbers
bytes, err := Serialize(descriptor)
if err != nil {
t.Errorf("Serialization error for %s: %s", c.fileName, err.Error())
continue
}
// Deserialize
decoder := bindings.NewDecoder(bytes, nil)
fileGraph := mojom_files.MojomFileGraph{}
fileGraph.Decode(decoder)
// Compare
if err := compareFileGraphs(c.expectedGraph, &fileGraph); err != nil {
t.Errorf("%s:\n%s", c.fileName, err.Error())
continue
}
}
}
示例6: TestSingleFileSerialization
//.........这里部分代码省略.........
DeclaredOrdinal: -1,
DeclarationOrder: -1,
SourceFileInfo: &mojom_types.SourceFileInfo{
FileName: test.fileName(),
},
ContainedDeclarations: &mojom_types.ContainedDeclarations{
Enums: &[]string{"TYPE_KEY:mojom.test.Foo.Hats"}},
},
Fields: []mojom_types.StructField{
// field x
{
DeclData: test.newShortDeclData("x"),
Type: &mojom_types.TypeSimpleType{mojom_types.SimpleType_InT32},
},
// field y
{
DeclData: test.newShortDeclDataA("y", &[]mojom_types.Attribute{{"min_version", &mojom_types.LiteralValueInt8Value{2}}}),
Type: &mojom_types.TypeStringType{mojom_types.StringType{false}},
DefaultValue: &mojom_types.DefaultFieldValueValue{&mojom_types.ValueLiteralValue{&mojom_types.LiteralValueStringValue{"hello"}}},
},
// field z
{
DeclData: test.newShortDeclData("z"),
Type: &mojom_types.TypeStringType{mojom_types.StringType{true}},
},
},
}}
// enum Hats
test.expectedGraph().ResolvedTypes["TYPE_KEY:mojom.test.Foo.Hats"] = &mojom_types.UserDefinedTypeEnumType{mojom_types.MojomEnum{
DeclData: test.newContainedDeclData("Hats", "mojom.test.Foo.Hats", stringPointer("TYPE_KEY:mojom.test.Foo")),
Values: []mojom_types.EnumValue{
// Note(rudominer) It is a bug that we need to copy the enum values here.
// See https://github.com/domokit/mojo/issues/513.
// value TOP
test.expectedGraph().ResolvedValues["TYPE_KEY:mojom.test.Foo.Hats.TOP"].(*mojom_types.UserDefinedValueEnumValue).Value,
// value COWBOY
test.expectedGraph().ResolvedValues["TYPE_KEY:mojom.test.Foo.Hats.COWBOY"].(*mojom_types.UserDefinedValueEnumValue).Value,
// value HARD
test.expectedGraph().ResolvedValues["TYPE_KEY:mojom.test.Foo.Hats.HARD"].(*mojom_types.UserDefinedValueEnumValue).Value,
},
}}
test.endTestCase()
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for _, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
parser := parser.MakeParser(c.fileName, c.fileName, c.mojomContents, descriptor, nil)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", c.fileName, parser.GetError().Error())
continue
}
if err := descriptor.Resolve(); err != nil {
t.Errorf("Resolve error for %s: %s", c.fileName, err.Error())
continue
}
if err := descriptor.ComputeEnumValueIntegers(); err != nil {
t.Errorf("ComputeEnumValueIntegers error for %s: %s", c.fileName, err.Error())
continue
}
if err := descriptor.ComputeDataForGenerators(); err != nil {
t.Errorf("ComputeDataForGenerators error for %s: %s", c.fileName, err.Error())
continue
}
// Simulate setting the canonical file name for the imported files. In real operation
// this step is done in parser_driver.go when each of the imported files are parsed.
mojomFile := parser.GetMojomFile()
if mojomFile.Imports != nil {
for _, imp := range mojomFile.Imports {
imp.CanonicalFileName = fmt.Sprintf("%s.canonical", imp.SpecifiedName)
}
}
// Serialize
EmitLineAndColumnNumbers = c.lineAndcolumnNumbers
bytes, _, err := Serialize(descriptor, false)
if err != nil {
t.Errorf("Serialization error for %s: %s", c.fileName, err.Error())
continue
}
// Deserialize
decoder := bindings.NewDecoder(bytes, nil)
fileGraph := mojom_files.MojomFileGraph{}
fileGraph.Decode(decoder)
// Compare
if err := compareFileGraphs(c.expectedGraph, &fileGraph); err != nil {
t.Errorf("%s:\n%s", c.fileName, err.Error())
continue
}
}
}
示例7: TestSingleFileResolutionErrors
// TestSingleFileResolutionErrors() tests that appropriate error messages are generated
// when a .mojom file contains unresolved references.
func TestSingleFileResolutionErrors(t *testing.T) {
test := singleFileTest{}
////////////////////////////////////////////////////////////
// Test Case: One unresolved value reference
////////////////////////////////////////////////////////////
{
contents := `
struct Foo{
int32 x = Bar;
};`
test.addTestCase(contents, []string{
"Undefined value: \"Bar\"",
"int32 x = Bar;",
"^^^"})
}
////////////////////////////////////////////////////////////
// Test Case:Two unresolved value references
////////////////////////////////////////////////////////////
{
contents := `
const bool F = Baz;
struct Foo{
int32 x = Bar;
};`
test.addTestCase(contents, []string{
"Undefined value: \"Baz\"", "Undefined value: \"Bar\""})
}
////////////////////////////////////////////////////////////
// Test Case: One unresolved type reference
////////////////////////////////////////////////////////////
{
contents := `
struct Foo{
Bar x;
};`
test.addTestCase(contents, []string{"Undefined type: \"Bar\""})
}
////////////////////////////////////////////////////////////
// Test Case: Multiple unresolved types and values.
////////////////////////////////////////////////////////////
{
contents := `
const int32 X = Boom;
struct Foo{
Bar x;
Baz y = Bing;
int32 z = X;
};
struct Foo2 {
Foo f = default;
};`
test.addTestCase(contents, []string{
"Undefined type: \"Bar\"", "Undefined type: \"Baz\"",
"Undefined value: \"Boom\"", "Undefined value: \"Bing\"",
"Use of unresolved value: \"X\"",
"^^^^"}) // There will be four carets in the snippet because of "Boom"
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
specifiedName := ""
if c.importedFrom == nil {
specifiedName = c.fileName
}
parser := MakeParser(c.fileName, specifiedName, c.mojomContents, descriptor, c.importedFrom)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", c.fileName, parser.GetError().Error())
continue
}
err := descriptor.Resolve()
if err == nil {
t.Errorf("Resolution unexpectedly succeeded for test case %d.", i)
continue
}
got := err.Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.fileName, expected, got)
//.........这里部分代码省略.........
示例8: TestSingleFileTypeValidationErrors
//.........这里部分代码省略.........
TOP
};
const Hats MY_HAT = 1;
`
test.addTestCase(contents, []string{
"Illegal assignment",
"Const MY_HAT of type Hats may not be assigned the value 1 of type int8."})
}
////////////////////////////////////////////////////////////
// Group 3: Invalid use of interface request.
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Test Case: Make an interface request out of a struct
////////////////////////////////////////////////////////////
{
contents := `
struct Foo{
};
struct Bar{
Foo& x;
};
`
test.addTestCase(contents, []string{
"Invalid interface request specification",
"Foo&. Foo is not an interface type"})
}
////////////////////////////////////////////////////////////
// Test Case: Make a nullable interface request out of a struct
////////////////////////////////////////////////////////////
{
contents := `
struct Foo{
};
struct Bar{
Foo&? x;
};
`
test.addTestCase(contents, []string{
"Invalid interface request specification",
"Foo&?. Foo is not an interface type"})
}
////////////////////////////////////////////////////////////
// Group 4: Invalid use of nullable
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Test Case: Make nullable enum.
////////////////////////////////////////////////////////////
{
contents := `
enum Hats {
COWBOY,
TOP
};
struct Bar{
Hats? my_hat;
};
`
test.addTestCase(contents, []string{
"The type Hats? is invalid because Hats is an enum type and these may not be made nullable."})
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
specifiedName := ""
if c.importedFrom == nil {
specifiedName = c.fileName
}
parser := MakeParser(c.fileName, specifiedName, c.mojomContents, descriptor, c.importedFrom)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", c.fileName, parser.GetError().Error())
continue
}
err := descriptor.Resolve()
if err == nil {
t.Errorf("Resolution unexpectedly succeeded for test case %d.", i)
continue
}
got := err.Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.fileName, expected, got)
}
}
}
}
示例9: TestFindReachableTypes
//.........这里部分代码省略.........
enum Color {
RED, BLUE
};
enum Height {
SHORT, TALL
};
struct Struct1{};
struct Struct2{};
interface Interface1 {
const Color FAVORITE_COLOR = RED;
Foo(map<Height, int8> x) => (string y);
};
interface Interface2 {
Foo(int32 x) => (array<Struct1?> y);
};
`
test.addTestCase(contents,
"Interface1",
[]string{"Interface1", "Color", "Height"},
)
test.addTestCase(contents,
"Interface2",
[]string{"Interface2", "Struct1"},
)
}
////////////////////////////////////////////////////////////
// Test Cases
////////////////////////////////////////////////////////////
{
contents := `
enum Color {
RED, BLUE
};
enum Height {
SHORT, TALL
};
struct Struct1{};
struct Struct2{};
interface Interface1 {
const Color FAVORITE_COLOR = RED;
Foo(int32 x) => (string y);
Bar(map<string, Height> z) => ();
};
interface Interface2 {
Foo(int32 x) => (map<Height, Struct1?> y);
};
`
test.addTestCase(contents,
"Interface1",
[]string{"Interface1", "Color", "Height"},
)
test.addTestCase(contents,
"Interface2",
[]string{"Interface2", "Height", "Struct1"},
)
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
fileName := fmt.Sprintf("file%d", i)
parser := MakeParser(fileName, fileName, c.mojomContents, descriptor, nil)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", fileName, parser.GetError().Error())
continue
}
err := descriptor.Resolve()
if err != nil {
t.Errorf("Resolution failed for test case %d: %s", i, err.Error())
continue
}
userDefinedType := descriptor.TypesByKey[mojom.ComputeTypeKey(c.typeToSearch)]
result := userDefinedType.FindReachableTypes()
if err := compareTypeSets(descriptor, c.expectedReachableTypes, result); err != nil {
t.Errorf("Case %d, unexpected typeset for %s: %s\n", i, c.typeToSearch, err.Error())
continue
}
}
}
示例10: TestSingleFileValueValidationErrors
//.........这里部分代码省略.........
////////////////////////////////////////////////////////////
// Test Case: Field name shadows constant name
////////////////////////////////////////////////////////////
{
contents := `
const int32 foo = 42;
struct MyStruct {
string foo = "hello";
int32 bar = foo;
};`
test.addTestCase(contents, []string{
"Error",
"\"foo\" does not refer to a value. It refers to the field MyStruct.foo at"})
}
////////////////////////////////////////////////////////////
// Test Case: Method name shadows constant name
////////////////////////////////////////////////////////////
{
contents := `
const int32 foo = 42;
interface MyInterface {
foo();
const int32 bar = foo;
};`
test.addTestCase(contents, []string{
"Error",
"\"foo\" does not refer to a value. It refers to the method MyInterface.foo at"})
}
////////////////////////////////////////////////////////////
// Test Case: Field name shadows type name
////////////////////////////////////////////////////////////
{
contents := `
struct SomethingGood{};
struct MySecondStruct {
int32 SomethingGood = 7;
SomethingGood x = default;
};`
test.addTestCase(contents, []string{
"Error",
"\"SomethingGood\" does not refer to a type. It refers to the field MySecondStruct.SomethingGood at"})
}
////////////////////////////////////////////////////////////
// Test Case: Method name shadows type name
////////////////////////////////////////////////////////////
{
contents := `
struct SomethingGood{};
interface MyInterface {
SomethingGood();
DoIt(SomethingGood x);
};`
test.addTestCase(contents, []string{
"Error",
"\"SomethingGood\" does not refer to a type. It refers to the method MyInterface.SomethingGood at"})
}
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range test.cases {
// Parse and resolve the mojom input.
descriptor := mojom.NewMojomDescriptor()
specifiedName := ""
if c.importedFrom == nil {
specifiedName = c.fileName
}
parser := MakeParser(c.fileName, specifiedName, c.mojomContents, descriptor, c.importedFrom)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing error for %s: %s", c.fileName, parser.GetError().Error())
continue
}
err := descriptor.Resolve()
if err == nil {
t.Errorf("Resolution unexpectedly succeeded for test case %d.", i)
continue
}
got := err.Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.fileName, expected, got)
}
}
}
}
示例11: ParseFiles
// Parses each of the given .mojom files and all of the files in the
// import graph rooted by each file. A single MojomDescriptor is created and
// populated with the result of parsing all of those files. If the parsing is
// successful then err will be nil.
//
// fileNames must not be nil or we will panic.
func (d *ParseDriver) ParseFiles(fileNames []string) (descriptor *mojom.MojomDescriptor, err error) {
if fileNames == nil {
// We panic instead of returning an error here because this would be a programming error
// as opposed to an error in the input.
panic("fileNames may not be nil.")
}
filesToProcess := make([]*FileReference, len(fileNames))
descriptor = mojom.NewMojomDescriptor()
for i, fileName := range fileNames {
filesToProcess[i] = &FileReference{specifiedPath: fileName}
}
for len(filesToProcess) > 0 {
currentFile := filesToProcess[0]
filesToProcess = filesToProcess[1:]
if err = d.fileProvider.findFile(currentFile); err != nil {
return
}
if currentFile.importedFrom != nil {
// Tell the importing file about the absolute path of the imported file.
// Note that we must do this even if the imported file has already been processed
// because a given file may be imported by multiple files and each of those need
// to be told about the absolute path of the imported file.
currentFile.importedFrom.mojomFile.SetCanonicalImportName(currentFile.specifiedPath, currentFile.absolutePath)
}
if !descriptor.ContainsFile(currentFile.absolutePath) {
contents, fileReadError := d.fileProvider.provideContents(currentFile)
if fileReadError != nil {
err = fileReadError
return
}
parser := MakeParser(currentFile.absolutePath, contents, descriptor)
parser.SetDebugMode(d.debugMode)
// Invoke parser.Parse() (but skip doing so in tests sometimes.)
d.parseInvoker.invokeParse(&parser)
if d.debugMode {
fmt.Printf("\nParseTree for %s:", currentFile)
fmt.Println(parser.GetParseTree())
}
if !parser.OK() {
err = fmt.Errorf("\nError while parsing %s: \n%s\n",
currentFile, parser.GetError().Error())
return
}
currentFile.mojomFile = d.fileExtractor.extractMojomFile(&parser)
for _, importedFile := range currentFile.mojomFile.Imports {
// Note that it is important that we append all of the imported files here even
// if some of them have already been processed. That is because when the imported
// file is pulled from the queue it will be pre-processed during which time the
// absolute path to the file will be discovered and this absolute path will be
// set in |mojomFile| which is necessary for serializing mojomFile.
filesToProcess = append(filesToProcess,
&FileReference{importedFrom: currentFile, specifiedPath: importedFile.SpecifiedName})
}
}
}
// Perform type and value resolution
if err = descriptor.Resolve(); err != nil {
return
}
// Compute enum value integers.
if err = descriptor.ComputeEnumValueIntegers(); err != nil {
return
}
// Compute data for generators.
err = descriptor.ComputeDataForGenerators()
return
}
示例12: TestDuplicateNameErrorsTwoFiles
//.........这里部分代码省略.........
`
cases[testCaseNum].file2.mojomContents = `
module a.b.c;
const double Hats = 4.9;
`
expectError("Duplicate definition for \"Hats\". Previous definition with the same fully-qualified name:")
expectError("interface a.b.c.Hats at " + fileName1())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (another value with the same name as a type in a different scope)
////////////////////////////////////////////////////////////
startTestCase()
cases[testCaseNum].file1.mojomContents = `
module a.b.c.Hats;
interface COWBOY{};
`
cases[testCaseNum].file2.mojomContents = `
module a.b.c;
enum Hats {
COWBOY = 1,
TOP
};
`
expectError("Duplicate definition for \"COWBOY\". Previous definition with the same fully-qualified name:")
expectError("interface a.b.c.Hats.COWBOY at " + fileName1())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (a type with the same name as a value in a different scope)
////////////////////////////////////////////////////////////
startTestCase()
cases[testCaseNum].file1.mojomContents = `
module a.b.c;
enum Hats {
COWBOY = 1,
TOP
};
`
cases[testCaseNum].file2.mojomContents = `
module a.b.c.Hats;
interface COWBOY{};
`
expectError("Duplicate definition for \"COWBOY\". Previous definition with the same fully-qualified name:")
expectError("enum value a.b.c.Hats.COWBOY at " + fileName1())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (a value with the same name as a method in a different scope)
////////////////////////////////////////////////////////////
startTestCase()
cases[testCaseNum].file1.mojomContents = `
module a.b;
interface Big {
Run();
};
`
cases[testCaseNum].file2.mojomContents = `
module a.b.Big;
const int32 Run = 0;
`
expectError("Duplicate definition for \"Run\". Previous definition with the same fully-qualified name:")
expectError("method a.b.Big.Run at " + fileName1())
endTestCase()
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range cases {
descriptor := mojom.NewMojomDescriptor()
parser := MakeParser(c.file1.fileName, c.file1.fileName, c.file1.mojomContents, descriptor, nil)
parser.Parse()
if !parser.OK() {
t.Errorf("Parsing was supposed to succeed for file1 but did not for test case %d: %s", i, parser.GetError().Error())
}
parser = MakeParser(c.file2.fileName, c.file2.fileName, c.file2.mojomContents, descriptor, nil)
parser.Parse()
if parser.OK() {
t.Errorf("Parsing was supposed to fail for file2 but did not for test case %d", i)
} else {
got := parser.GetError().Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.file2.fileName, expected, got)
}
}
}
}
}
示例13: TestErrorParsing
//.........这里部分代码省略.........
expectError("Expecting module, import, interface, struct, union, enum or constant.")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (import before module)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
import "another.file";
module mojom.test;
`
expectError("The module declaration must come before the import statements.")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (duplicate method names)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
interface MyInterface {
MethodA();
MethodB();
MethodC();
MethodB();
MethodD();
};
`
expectError("Duplicate definition of method 'MethodB'. There is already a method with that name in interface MyInterface.")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (Invalid method ordinal: too big for uint32)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
interface MyInterface {
[email protected]();
};
`
expectError("MethodA")
expectError("4294967295")
expectError("Invalid ordinal string")
expectError("Ordinals must be decimal integers between 0 and 4294967294")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (Invalid method ordinal: too big for int64)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
interface MyInterface {
[email protected]();
};
`
expectError("MethodA")
expectError("999999999999999999999999999999999999999")
expectError("Invalid ordinal string")
expectError("Ordinals must be decimal integers between 0 and 4294967294")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (Invalid method ordinal: negative)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
interface MyInterface {
[email protected]();
};
`
expectError("MethodA")
// Note that the lexer return "@" as the ordinal token, stopping when
// it sees the non-digit "-".
expectError("Invalid ordinal string")
expectError("Ordinals must be decimal integers between 0 and 4294967294")
endTestCase()
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range cases {
descriptor := mojom.NewMojomDescriptor()
parser := MakeParser(c.fileName, c.mojomContents, descriptor)
parser.Parse()
if parser.OK() {
t.Errorf("Parsing was supposed to fail but did not for test case %d", i)
} else {
got := parser.GetError().Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.fileName, expected, got)
}
}
}
}
}
示例14: TestDuplicateNameErrorsSingleFile
//.........这里部分代码省略.........
////////////////////////////////////////////////////////////
// Test Case (A field and a constant with the same name)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
struct MyStruct {
string Foo;
int32 Bar;
const int32 Bar = 7;
};
`
expectError("Duplicate definition for \"Bar\". Previous definition with the same fully-qualified name:")
expectError("field MyStruct.Bar at " + fileName())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (two types with the same name in file scope)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
module a.b.c;
interface Foo {
};
struct Bar {
};
struct Foo {
};
`
expectError("Duplicate definition for \"Foo\". Previous definition with the same fully-qualified name:")
expectError("interface a.b.c.Foo at " + fileName())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (two values with the same name in file scope)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
module a.b.c;
const int32 NUM_HATS = 6;
const string NUM_HATS = "6";
`
expectError("Duplicate definition for \"NUM_HATS\". Previous definition with the same fully-qualified name:")
expectError("const a.b.c.NUM_HATS at " + fileName())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (a value with the same name as a type at file scope)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
module a.b.c;
union Foo {
};
const int32 Foo = 42;
`
expectError("Duplicate definition for \"Foo\". Previous definition with the same fully-qualified name:")
expectError("union a.b.c.Foo at " + fileName())
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (a type with the same name as a value)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `
module a.b.c;
const int32 Foo = 42;
union Foo {
};
`
expectError("Duplicate definition for \"Foo\". Previous definition with the same fully-qualified name:")
expectError("const a.b.c.Foo at " + fileName())
endTestCase()
////////////////////////////////////////////////////////////
// Execute all of the test cases.
////////////////////////////////////////////////////////////
for i, c := range cases {
descriptor := mojom.NewMojomDescriptor()
parser := MakeParser(c.fileName, c.fileName, c.mojomContents, descriptor, nil)
parser.Parse()
if parser.OK() {
t.Errorf("Parsing was supposed to fail but did not for test case %d", i)
} else {
got := parser.GetError().Error()
for _, expected := range c.expectedErrors {
if !strings.Contains(got, expected) {
t.Errorf("%s:\n*****expected to contain:\n%s\n****actual\n%s", c.fileName, expected, got)
}
}
}
}
}
示例15: TestSuccessfulParsing
// TestSuccessfulParsing contains a series of test cases in which we
// run the parser on a valid mojom input string and compare the resulting
// MojomFile to an expected one.
func TestSuccessfulParsing(t *testing.T) {
type testCase struct {
fileName string
mojomContents string
expectedFile *mojom.MojomFile
}
cases := make([]testCase, 0)
testCaseNum := 0
var expectedFile *mojom.MojomFile
startTestCase := func(moduleNameSpace string) {
descriptor := mojom.NewMojomDescriptor()
fileName := fmt.Sprintf("file%d", testCaseNum)
expectedFile = descriptor.AddMojomFile(fileName)
expectedFile.InitializeFileScope(moduleNameSpace)
cases = append(cases, testCase{fileName, "", expectedFile})
}
endTestCase := func() {
testCaseNum += 1
}
// Note(rudominer) The structure of this method is designed to allow
// test cases to be rearranged and new test cases to be inserted at
// arbitrary locations. Do not hard-code anything that refers to the
// position of a test case in the list.
////////////////////////////////////////////////////////////
// Test Case (empty file)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = ""
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (module statement only)
////////////////////////////////////////////////////////////
startTestCase("mojom.test")
cases[testCaseNum].mojomContents = `module mojom.test;`
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (module statement with attributes)
////////////////////////////////////////////////////////////
startTestCase("mojom.test")
cases[testCaseNum].mojomContents = `[cool=true]module mojom.test;`
expectedFile.Attributes = mojom.NewAttributes()
expectedFile.Attributes.List = append(expectedFile.Attributes.List,
mojom.MojomAttribute{"cool", mojom.MakeBoolLiteralValue(true)})
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (import statements only)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `import "a.file";`
expectedFile.AddImport("a.file")
endTestCase()
////////////////////////////////////////////////////////////
// Test Case (module and import statements only)
////////////////////////////////////////////////////////////
startTestCase("mojom.test")
cases[testCaseNum].mojomContents = `
module mojom.test;
import "a.file";`
{
expectedFile.AddImport("a.file")
endTestCase()
}
////////////////////////////////////////////////////////////
// Test Case (module with attributes and import statements only)
////////////////////////////////////////////////////////////
startTestCase("mojom.test")
cases[testCaseNum].mojomContents = `
[cool=true]
module mojom.test;
import "a.file";`
{
expectedFile.Attributes = mojom.NewAttributes()
expectedFile.Attributes.List = append(expectedFile.Attributes.List,
mojom.MojomAttribute{"cool", mojom.MakeBoolLiteralValue(true)})
expectedFile.AddImport("a.file")
endTestCase()
}
////////////////////////////////////////////////////////////
// Test Case (one empty sruct)
////////////////////////////////////////////////////////////
startTestCase("")
cases[testCaseNum].mojomContents = `struct Foo{};`
expectedFile.AddStruct(mojom.NewMojomStruct(mojom.DeclTestData("Foo")))
endTestCase()
////////////////////////////////////////////////////////////
// Test Case
//.........这里部分代码省略.........