001package jmri.jmrit.logixng.util.parser;
002
003import java.util.Map;
004
005import jmri.JmriException;
006import jmri.jmrit.logixng.SymbolTable;
007
008/**
009 * A parsed expression
010 */
011public class ExpressionNodeIdentifier implements ExpressionNode {
012
013    private final Token _token;
014    private final Variable _variable;
015    
016    public ExpressionNodeIdentifier(Token token, Map<String, Variable> variables) throws IdentifierNotExistsException {
017        _token = token;
018        Variable variable = variables.get(token.getString());
019        
020        if (variable == null) {
021            // Assume the identifier is a local variable.
022            // Local variables may not be known when the expression is parsed.
023            
024            variable = new LocalVariableExpressionVariable(token.getString());
025        }
026        
027        _variable = variable;
028    }
029    
030    public String getIdentifier() {
031        return _token.getString();
032    }
033    
034    @Override
035    public Object calculate(SymbolTable symbolTable) throws JmriException {
036        return _variable.getValue(symbolTable);
037    }
038    
039    /** {@inheritDoc} */
040    @Override
041    public boolean canBeAssigned() {
042        // If the identifier is a local variable, assignment is possible. And
043        // we don't know if the identifier is a valid local variable until the
044        // expression is calculated. So we assume that it is.
045        return true;
046    }
047    
048    /** {@inheritDoc} */
049    @Override
050    public void assignValue(SymbolTable symbolTable, Object value) throws JmriException {
051        if (_variable != null) {
052            _variable.setValue(symbolTable, value);
053        }
054    }
055    
056    /** {@inheritDoc} */
057    @Override
058    public String getDefinitionString() {
059        return "Identifier:"+_token.getString();
060    }
061    
062}