0

I'm writing an Xtext grammar and I want to support cross-reference for usage of variables or parameters in my target language.

So the target language looks something like:

function(p1) {
  x1 = eat(p1) // line 1
  x2 = eat(x1) // line 2
}

And for that, I've defined:

Instruction:
  name=Value '=' 'eat' '(' ref=[Instruction|Value] ')'

This works for line 2, but fails for line 1 because a parameter is not an instruction. I've tried defining it like:

Instruction:
  name=Value '=' 'eat' '(' ref=([Instruction|Value] | [Parameter|Value]) ')'

Or various variations of this - e.g. using a single Ref rule which can be one of the two possible reference possibilities - but all of these are rejected by Xtext. Is this doable, and if so, how?

(I guess an alternative will be to define a single element which represents both a parameter and an instruction and then refer to it, but I could not figure out how to do that without allowing the syntax or an entire instruction to appear in the parameter list)

Oak
  • 26,231
  • 8
  • 93
  • 152

2 Answers2

0

If both Instruction and Parameter have a common ancestor, then you could write a rule that refers to that ancestor.

Then some minor validator/content assist configuration you can disallow any other possible configuration.

This is not the nicest solution, as it introduces a base class, that is used in the model instead of the downcasted version, but I don't know any other way to solve this issue.

Zoltán Ujhelyi
  • 13,788
  • 2
  • 32
  • 37
  • I haven't yet delved into xtext's code, only the grammar so far, but if what you describe is the only solution then it looks like I have no choice. – Oak Jul 17 '12 at 11:39
0

I found a solution. As I suspected, the parameter and the instruction have to have a common ancestor - but that ancestor does not have to actually ever appear in the right-hand-side of any grammar rule. So I defined:

ValueDef:
  Parameter | Instruction

and then

Instruction:
  name=Value '=' 'eat' '(' ref=[ValueDef|Value] ')'

... and the rules for Instruction and Parameter themselves were left unchanged. That means an instruction is not viable where a parameter is expected, but both define ValueDef references.

Oak
  • 26,231
  • 8
  • 93
  • 152