简体   繁体   中英

XText establishing cross-references for a generic type

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 (eg the LinkedList in the above example) it should only be valid to use it as a generic (eg 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 (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM