user3560285
user3560285

Reputation: 15

Identifying identical parts in xtend (based on xtext grammar)

Part of my xText grammar is as follows:

Transition:
   'Transition' from=TransitionTerminal;
TransitionTerminal: StateTerminal|SubStateTerminal;
StateTerminal: 'st' state=[State|ID];
State: 'state' name=ID;

Now, I want to identify Transitions with the same TransitionTerminal as in 'from'. So, in xtend I would write:

var origin = transition.from
//to check 'from' given some other Transition t, I use:
if(origin==t.from) {}

However, the above if statement is never entered. I suppose that additional nesting based on the provided grammar needs to be provided. Any help on how to achieve this is welcome.

Upvotes: 0

Views: 78

Answers (3)

Fabien Fleureau
Fabien Fleureau

Reputation: 693

You are comparing two instances (transition.from and t.from) that can't be equals because there will always be two different objects generated by Xtext. You have to implements your own comparator.

Here an example of what should be your code:

var origin = transition.from
//to check 'from' given some other Transition t, I use:
if(compare(origin, t.from)) {}

def compare(EObject origin, EObject from) {
    if (origin instanceof State && from instanceof State) {
        return ((State) origin).name == ((State) from).name;
    else if (origin instanceof StateTerminal && from instanceof StateTerminal) {
        ...
    }
    return false;
}

Edit:

Using EcoreUtil.equals(EObject, EObject) as proposed by Sebastian Zarnekow is a better solution.

Upvotes: 0

Sebastian Zarnekow
Sebastian Zarnekow

Reputation: 6729

You may want to try to use EcoreUtil.equals(EObject, EObject) to compare two instances of EObject structurally as in:

if(EcoreUtil.equals(origin, t.from) {}

Upvotes: 1

shillner
shillner

Reputation: 1846

Wait, I found the problem. There cannot be identical TransitionTerminals in multiple 'from' properties since you are creating new TransitionTerminals for each Transition when writing 'Transition st state ...'.

You will either have to use equality comparison or declare the TransitionTerminal anywhere else and use a real reference to it. Then you should be able to use ==.

Upvotes: 0

Related Questions