How do you design the parser to retain identifiers to check if the same identifier is being repeated later in the input?

Terence Parr

You need what we typically call a symbol table. This is usually just a hashtable that records the symbols you see in a particular scope (if you have scopes, that is). So, if you see the definition of a variable called "salary", add it to the symbol table. Later, when your grammar references an ID (I mean, "identifier") you can look up the text for the ID in the symbol table to see if it has been seen before. The following grammar fragment may help.

class P extends Parser;
    class Symbol {
        String name;
        public Symbol(String name) {
            this.name = name;

    public java.util.Hashtable symbols = new java.util.Hashtable();

decl : "int" v:ID SEMI
       {symbols.put(v.getText(), new Symbol(v.getText()));}

expr : atom (PLUS atom)* ;

// ...

atom : INT
     | id:ID
       {if ( symbols.get(id.getText())==null ) { /*error*/ }}