001    package org.hackystat.telemetry.analyzer.evaluator;
002    
003    import java.util.TreeMap;
004    
005    import org.hackystat.telemetry.analyzer.language.ast.Constant;
006    import org.hackystat.telemetry.analyzer.language.ast.Variable;
007    
008    /**
009     * Variable resolver. It maps <code>Variable</code>s to <code>Constant</code>s.
010     * 
011     * @author (Cedric) Qin ZHANG
012     */
013    public class VariableResolver {
014    
015      /** Key is variable name, value is instance of Constant. */
016      private TreeMap<String, Constant> map = new TreeMap<String, Constant>();
017      
018      /**
019       * Adds a variable-constant pair so that later the variable can be resolved.
020       * 
021       * @param variable The variable.
022       * @param constant The constant.
023       * @throws TelemetryEvaluationException If a variable with the same name has already been added.
024       */
025      public void add(Variable variable, Constant constant) throws TelemetryEvaluationException {
026        String varName = variable.getName();
027        if (this.map.containsKey(varName)) {
028          throw new TelemetryEvaluationException("Variable " + varName + " already added.");
029        }
030        this.map.put(varName, constant);
031      }
032      
033      /**
034       * Resolves a variable to a constant.
035       * 
036       * @param variable The variable to be resolved.
037       * @return The constant the variable resolves to.
038       * @throws TelemetryEvaluationException If the variable cannot be resolved to a constant.
039       */
040      public Constant resolve(Variable variable) throws TelemetryEvaluationException {
041        String varName = variable.getName();
042        if (! this.map.containsKey(varName)) {
043          throw new TelemetryEvaluationException("Variable " + varName + " not found.");
044        }
045        return this.map.get(varName);
046      }
047    }