XText 为泛型类型建立交叉引用
这就是我想要的,我正在尝试解析
type Number(); // define a type called "Number" with no member variables
type Point(Number x, Number y); // define a type called Point with member variables
// and something with generic types
type Pair[T, V](T first, V second);
// and even something cyclic:
type LinkedList[T](T payload, LinkedList[T] rest);
,这是我的 xtext 语法,允许它:
TypeDecl returns SSType:
'type' name=TypeName
('[' typeParams += TypeName (',' typeParams += TypeName)* ']')?
'(' (args += Arg (',' args += Arg)*)? ')' ';'
;
TypeName returns SSTypeName:
name=ID
;
Type:
tn = [SSTypeName] ('[' typeParams += Type (',' typeParams += Type)* ']')?
;
Arg:
type = Type argName = ID
;
哪个有效,但在它接受的内容上过于自由。如果某些内容被声明为泛型(例如上例中的 LinkedList),则仅将其用作泛型才有效(例如 LinkedList[Number]
而不是 LinkedList
)并且理想情况下将强制执行类型参数的数量。
当然,如果某些东西被声明为不是泛型类型(例如 Number),则为其提供类型参数应该是无效的。
它将错误接受的内容示例:
type Wrong1(Number[Blah] a); // number doesn't have type arguments
type Wrong2(Pair a); // Pair has type arguments
type Wrong3(Pair[Number, Number, Number] a); // wrong arity
任何有关如何正确执行此操作的建议、评论、代码或提示将不胜感激。
This is what I want I am trying to parse
type Number(); // define a type called "Number" with no member variables
type Point(Number x, Number y); // define a type called Point with member variables
// and something with generic types
type Pair[T, V](T first, V second);
// and even something cyclic:
type LinkedList[T](T payload, LinkedList[T] rest);
And here's my xtext grammar that allows it:
TypeDecl returns SSType:
'type' name=TypeName
('[' typeParams += TypeName (',' typeParams += TypeName)* ']')?
'(' (args += Arg (',' args += Arg)*)? ')' ';'
;
TypeName returns SSTypeName:
name=ID
;
Type:
tn = [SSTypeName] ('[' typeParams += Type (',' typeParams += Type)* ']')?
;
Arg:
type = Type argName = ID
;
Which works, but is way too liberal in what it accepts. If something is declared as a generic (e.g. the LinkedList in the above example) it should only be valid to use it as a generic (e.g. LinkedList[Number]
and not LinkedList
) and ideally the arity of the type arguments would be enforced.
And of course, if something is declared to not be a generic type (e.g. Number), it shouldn't be valid to give it type arguments.
Example of stuff it will wrongly accept:
type Wrong1(Number[Blah] a); // number doesn't have type arguments
type Wrong2(Pair a); // Pair has type arguments
type Wrong3(Pair[Number, Number, Number] a); // wrong arity
Any suggestions, comments, code or tips on how to do this properly would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在验证器中强制执行正确数量的类型参数。通常最好有一个自由的范围提供者和一个严格的验证器来提供更好的错误消息。
You should enforce the correct number of type arguments in your validator. It often better to have a liberal scope provider and a strict validator to provide better error messages.