I'd like to know, how can I create a DSL, using Xtext. This is my code, that I created:
Model:
(entities += Entity)*
(access += Acessing)*
;
Entity:
'entity' name = ID '{'
( variables += Variable )*
'}'
;
Variable:
'var' name=ID
;
Acessing:
'use' (entity = [Entity])'.'(variable = [Variable])
;
The code is a little bit incomplete, but in this way I'd like perform this operation as follows:
entity user {
var name
var phone
var address
}
use user.phone
I understand that I can use this tag [Entity]
as a identifier from a specific element, but I don't know how can I get those sub elements from it.
How can I procede?
You are using the name
attribute for Entity
and Variable
. This is a special attribute which Xtext automatically uses to create namespaces and delivers a working scope provider for free. Elements are identified by their qualified name. You need only a single reference to access them.
To solve your problem, you only have to modify your Use
grammar rule and introduce a rule which describes a qualified name. Your grammar then could look like this:
Model:
(entities+=Entity)*
(access+=Acessing)*;
Entity:
'entity' name=ID '{'
(variables+=Variable)*
'}';
Variable:
'var' name=ID;
Acessing:
'use' var=[Variable|QualifiedName];
QualifiedName:
ID ('.' ID)*;
As you can see, it now uses the QualifiedName
name to identify a variable. I have just tried it and it works out of the box.