5

The followings are my grammar rules:

Stmts: (stmts += Stmt ';')* ;
Stmt: Stmt1 | Stmt2 | Stmt3 ... ;

I want to know each Stmt# is #-th stmt in stmts and their exactly location (#-th line in original document). Such that I could point out the location when user make mistakes.

I override the validator constructor and store an HashMap <Stmt, Integer> to get each Stmt# is the #-th Stmt in stmts(Not sure if this is the correct way to do though...). However I have no idea how to get their line number.

Any help?

Ray Wu
  • 993
  • 16
  • 34

2 Answers2

5

Given an EObject you can easily get the position in the source file using org.eclipse.xtext.nodemodel.util.NodeModelUtils.getNode(EObject).

For example:

    INode node = NodeModelUtils.getNode(o);
    System.out.println(String.format("Node goes from line %s to line %s",node.getStartLine(), node.getEndLine()));
stefan.schwetschke
  • 8,862
  • 1
  • 26
  • 30
  • If I put the first line in any @Check annotated method I'll get `- This expression is not allowed in this context, since it doesn't cause any side effects.`, where did I do wrong? – Ray Wu Aug 27 '13 at 18:32
  • I don't know which @Check annotation you put in here, but I think I can explain the error message. If you only put the first line in, you are only reading a value, but not changing anything. So the reading is pointless, if you don't do anything with the value you read. Put in both lines and the error should go away. – stefan.schwetschke Aug 28 '13 at 04:08
  • I know what happened...I'm using xtext 2.4 and default language of xtext validator is xtend not java. First line in xtend should be `val INode node = NodeModelUtils.getNode(o);` Thank you Stefan, that's exactly what I want. – Ray Wu Aug 28 '13 at 17:35
0

For pointing out mistakes simply writing a declarative validator is better suited - in that case, you simply give Xtext problematic EObject, and it manages to trace it back to the source. Furthermore, a validator stub is generated in your language project.

However, if you need to manually trace back the nodes, there is the Injectable ILocationInFileProvider that can help you.

Zoltán Ujhelyi
  • 13,788
  • 2
  • 32
  • 37