private SymbolSet follow(Symbol symbol)
{
System.out.println();
System.out.println("Calculate FOLLOW set for "+symbol);
SymbolSet followset = new SymbolSet();
// if symbol is start symbol, then add symbol for end of file
if (symbol.equals(grammar.getStartSymbol()))
followset.addSymbol(new EndOfFile());
// if production A -> a B b exists, then add every symbol of
// FIRST(b) except the symbol for an empty list to FOLLOW(B)
SymbolList definition;
for (int production = 0; production<grammar.getProductionCount(); production++)
{
definition = grammar.getProduction(production).getDefinition();
for (int position = 0; position<definition.getSymbolCount(); position++)
if (definition.getSymbol(position).equals(symbol))
{
System.out.println("Found "+symbol+" at position "+position+" in production "+production);
SymbolSet firstset = null;
if ((position+1)<definition.getSymbolCount())
{
SymbolList rest = new SymbolList();
for (int restposition = position+1; restposition<definition.getSymbolCount();
restposition++)
rest.addSymbol(definition.getSymbol(restposition));
firstset = firstsets.getFirstSet(rest);
System.out.println("first("+rest+")="+firstset);
followset.addSymbol(firstset);
followset.removeSymbol(EMPTYLIST);
}
if ((position+1)==definition.getSymbolCount())
System.out.println(symbol+" is last symbol of production "+production);
// if a production A -> a B or A -> a B b exist and FIRST(b)
// contains the symbol for an empty list, then every symbol
// of FOLLOW(A) belongs to FOLLOW(B)
if ((((position+1)==definition.getSymbolCount()) || (firstset.contains(EMPTYLIST))) &&
(!grammar.getProduction(production).getSymbol().equals(symbol)))
followset.addSymbol(follow(grammar.getProduction(production).getSymbol()));
}
}