Programming-Language-Design / src / visitor / identification / SymbolTable.java
SymbolTable.java
Raw
package visitor.identification;

import ast.definition.Definition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SymbolTable {

    private int scope = 0;
    private List<Map<String, Definition>> table;

    public SymbolTable() {
        this.table = new ArrayList<>();
        table.add(new HashMap<>());
    }

    public void set() {
        table.add(new HashMap<>());
        this.scope++;
    }

    public void reset() {
        table.remove(getScope());
        this.scope--;
    }

    public boolean insert(Definition definition) {
        if (findInCurrentScope(definition.getName()) == null) {
            table.get(getScope()).put(definition.getName(), definition);
            definition.setScope(getScope());
            return true;
        }
        return false;
    }

    public Definition find(String id) {
        for (int i = table.size() - 1; i >= 0; i--) {
            if (table.get(i).get(id) != null)
                return table.get(i).get(id);
        }
        return null;
    }

    public Definition findInCurrentScope(String id) {
        if (table.get(getScope()).get(id) == null)
            return null;
        return table.get(getScope()).get(id);
    }

    public int getScope() {
        return scope;
    }
}