grammar lavanda; @header { import java.util.HashMap; import java.util.LinkedList; } @members { HashMap inTable = new HashMap(); } lavanda : cabec sacos { System.out.println("Total sacos: " + $sacos.nSacos); for(Object o : $sacos.outEnv.keySet()) System.out.println((String) o + "\t" + (Integer) $sacos.outEnv.get(o)); } ; cabec : DATA ID ; sacos returns [ int nSacos = 0, HashMap outEnv = new HashMap() ] @init { LinkedList clientIds = new LinkedList(); LinkedList bagIds = new LinkedList(); HashMap inEnv = new HashMap(); } : ( saco[inEnv, clientIds, bagIds] { $nSacos++; $outEnv = $saco.outEnv; } )+ ; saco [ HashMap inEnv, LinkedList clientIds, LinkedList bagIds ] returns [ HashMap outEnv ] : NUM { if(bagIds.contains(Integer.parseInt($NUM.text))) System.err.println("Bag ID already exists!"); bagIds.add(Integer.parseInt($NUM.text)); } ID { if(clientIds.contains($ID.text)) System.err.println("Client ID already exists!"); clientIds.add($ID.text); } '(' lotes[inEnv] ')' { System.out.print("Numero de lotes para o ID " + $ID.text + ": " + $lotes.nLotes); System.out.println(" Custo: " + $lotes.custoTotal); $outEnv = $lotes.outEnv; } ; lotes [ HashMap inEnv ] returns [ HashMap outEnv, int nLotes = 0, int custoTotal = 0] : l1=lote[$inEnv] { $nLotes++; $custoTotal += $l1.custoTotal; $outEnv = $l1.outEnv; } (',' l2=lote[$outEnv] { $nLotes++; $custoTotal += $l2.custoTotal; $outEnv = $l2.outEnv; } )* ; lote [ HashMap inEnv ] returns [ int custoTotal, HashMap outEnv ] : tipo NUM { $custoTotal = (Integer) inTable.get($tipo.name) * Integer.parseInt($NUM.text); if(!$inEnv.containsKey($tipo.name)) $inEnv.put($tipo.name, 0); $inEnv.put($tipo.name, (Integer) $inEnv.get($tipo.name) + 1); $outEnv = $inEnv; } ; tipo returns [ String name ] : classe '-' tinto '-' fio { $name = $classe.name + '-' + $tinto.name + '-' + $fio.name; } ; classe returns [ String name ] : 'corpo' { $name = "corpo"; } | 'casa' { $name = "casa"; } ; tinto returns [ String name ] : 'br' { $name = "br"; } | 'cor' { $name = "cor"; } ; fio returns [ String name ] : 'alg' { $name = "alg"; } | 'la' { $name = "la"; } | 'fib' { $name = "fib"; } ; fragment LETTER : 'a'..'z'|'A'..'Z' ; fragment DIGIT : '0'..'9' ; ID : LETTER+; NUM : DIGIT+; DATA : DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT DIGIT DIGIT ; WS : ('\r'|'\n'|' '|'\t')+ {skip();} ;