JDoe
JDoe

Reputation: 221

Xtext - Validating for duplicate names

I have the following grammer, but I want to do some validation on this. I want to make an error if there are duplicate names in the "players" list.

Grammer:

Football:
    'Club' name=STRING playerList=PlayerList
     footballObjects+=FootballObject
;

FootballObject:
     Player | Coach
;

PlayerList:
     players+=[Player] ( players+=[Player] )* 
;

Player:
    'Player' name=ID
;

I tried the following:

@Check
def checkGreetingStartsWithCapital(Football model) {
    val names = newHashSet
    for (g : model.playersList.players) {
        if(!names.add(g.name))
            error("duplicate" , g, FOOTBALLPACKAGE.Literals.FOOTBALL__PLAYERS_LIST)
    }
}

But this does not work. Any ideas why?

Upvotes: 0

Views: 454

Answers (1)

Christian Dietrich
Christian Dietrich

Reputation: 11868

The easiest is to mark the list entry by calling error not on the referenced player but on the playersList itself and call the error method that takes an index as well. e.g.

error("bad", playersList, MyDslPackage.Literals.PLAYERS_LIST__PLAYERS, index)

Upvotes: 2

Related Questions