Skip to content

Función value

La función value define una plantilla para cada expression:

value⟦expressionvalue⟦arithmetic → left:expression operator:string right:expression⟧ =
     value⟦left⟧
     value⟦right⟧
     if operator == "+"
         ADD<arithmetic.type>
     if operator == "-"
         SUB<arithmetic.type>
     if operator == "*"
         MUL<arithmetic.type>
     if operator == "/"
         DIV<arithmetic.type>

value⟦variable → name:string⟧ =
     address⟦variable⟧
     LOAD<variable.type>

value⟦intLiteral → intValue:int⟧ =
     PUSH {intValue}

value⟦floatLiteral → floatValue:float⟧ =
     PUSHF {floatValue}

La implementación sería en este caso:

java
public class Value extends AbstractCodeFunction {

    private Map<String, String> instruccion = new HashMap<>();

    public Value(MaplCodeSpecification specification) {
        super(specification);

        instruccion.put("+", "add");
        instruccion.put("-", "sub");
        instruccion.put("*", "mul");
        instruccion.put("/", "div");
    }

    public Object visit(Arithmetic arithmetic, Object param) {
        value(arithmetic.getLeft());
        value(arithmetic.getRight());
        out(instruccion.get(arithmetic.getOperator()), arithmetic.getType());
        return null;
    }

    public Object visit(Variable variable, Object param) {
        address(variable);
        out("load", variable.getType());
        return null;
    }

    public Object visit(IntLiteral intLiteral, Object param) {
        out("push " + intLiteral.getIntValue());
        return null;
    }

    public Object visit(FloatLiteral floatLiteral, Object param) {
        out("pushf " + floatLiteral.getFloatValue());
        return null;
    }
}

Como puede observarse, se ha simplificado la implementación de la plantilla value⟦arithmetic⟧ utilizando una tabla hash para evitar los if (los cuales también hubieran sido aceptables en un lenguaje tan sencillo).