Question

I have studied question 15588452 to know how to build a symbol table.

My question is the implementation details how to make a symbol table support more data types,

I don't want to just support integers like:

memory = new HashMap<String, Integer>();

As far as I can think out(pardon me, I haven't finished the whole dragon book about compilers), are the following 2 way.

First way : build a map contains a Symbol object:

Map<String, Symbol> symbolMap = new LinkedHashMap<String, Symbol>();

And Symbol object have name, type, data block info like below :

public class Symbol {
    protected Scope scope; // scope info
    protected String name;
    protected ValueType type;//contains type info ,like int float
    protected Object  value;//contains the real value
}

when resolve its value, we can make type cast, cast to the type it need like:

float a = (float)symbol.value;//convert object field to float

this will cause lots of if..else type check.

Or we calculate the memory size and resolve the memory block.

Second way : use more map that contains different type data,when make assignment like :

Map<String, Integer> intMap = new LinkedHashMap<String, Integer>();

Map<String, Double> doubleMap = new LinkedHashMap<String, Double>();

int a = 5;//put in intMap

double b = 1.34;//put in doubleMap

we put it in different map as well as we resolve it, this look a little stupid.

How to support more types in a gentle way ?

Anyone who has experienced, please give some insights, thank you .

Was it helpful?

Solution

To be more specific, you want more than just a symbol table. You want to be able to store values associated with those symbols at runtime. For such an interpreter, people tend to make typed memory cells kind of like your first way. Typically symbols have a data type pointer and then, if in an interpreter, a reference to the data. You look things up in the current scope and it walks up the scope tree until it finds the first symbol and then simply gets its value out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top