I built a lexer and a parser, using JavaCC, for a small programming language. An example of a valid program in the programming language is:
DEF MAIN { FUNCTION1(4) };
DEF FUNCTION1 x { x+3 } ;
In the above example I want the program to output 7 but to do this a call to FUNCTION1 needs to be made. I know that I have to store intermediate representations somewhere in order to achieve this. How can I do that with Hash Maps?
Suppose the intermediate representation for a function is represented by an object of class Function
. The you could have a symbol table that maps function names (presumably represented by objects of type String
) to Function
objects. The symbol table can be represented by a hash map, e.g.
class SymbolTable extends HashMap<String, Function> { }
You can create an empty symbol table at the start and then fill it as you parse. E.g., something like this.
SymbolTable Program( )
{
SymbolTable table = new SymbolTable() ;
}
{
( FunctionDefinition( table ) )*
<EOF>
{ return SymbolTable ; }
}
void FunctionDefinition( SymbolTable table )
{
Function f ;
String name ;
}
{
<DEF>
name = <NAME>
f = FunctionBody()
";"
{
if( table.hasKey( name ) { ...do something... } ;
else { table.add(name, f) ; }
}
}