terminal/datatype/parser rules in xtext

人盡茶涼 提交于 2019-12-04 13:52:49

How do you define an integer with sign?

  • Treat it as two separate tokens '-' and INT, and use a parser rule instead of a lexer rule.

How do you define a float with sign?

  • Treat it as two separate tokens '-' and FLOAT, and use a parser rule instead of a lexer rule.

How do you define a date rule?

  • Treat it as five separate tokens and use a parser rule instead of a lexer rule.

I don't know the answer to the last question since this is in Xtext as opposed to just ANTLR.

Later I found the original antlr grammar for what I want to do therefore I simply translate the antlr grammar to xtext grammar. Here is how I defining those basic types:

terminal fragment A: 'a'|'A';  
   ... 
terminal fragment Z: 'z'|'Z';

terminal fragment DIGIT: '0'..'9';
terminal fragment LETTER: ('a'..'z'|'A'..'Z');
terminal fragment HEX: ('a'..'f'|'A'..'F'|'0'..'9'); 

terminal fragment EXPONENT: E ('+'|'-')? DIGIT+;
terminal INTEGER returns ecore::EInt: '-'? DIGIT+;
terminal FLOAT returns ecore::EFloat: INTEGER EXPONENT | INTEGER '.' DIGIT* EXPONENT?;

terminal BOOLEAN: T R U E | F A L S E;

The Date rule in original grammar is treated as a string.

About rules name (Rules: Antlr Grammar => xtext Grammar)

  • parser rule: starting with lowercase => rules starting with uppercase (each will be a Java Class)
  • terminal rule: starting with uppercase => using all uppercase with terminal prefix
  • fragment terminal rule: fragment ID => terminal fragment ID

In antlr a list of arguments is defined like this:

functionArgs
  : '(' ')'
  | '(' t1=term ( ',' tn=term )* ')'
;

The corresponding xtext grammar is:

FunctionArgs
 : '(' ')'
 | '(' ts+=Term  (',' ts+=Term )* ')'
;

For those parser rules with an argument enclosed by [ ]

properties[PropertyDefinitions props]
  : property[props] (K_AND property[props])*
;

Most of the time they could be moved to the left hand side

Properties
  : props+=Property (K_AND props+=Property)*
;

Now it's working as expected.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!