Programming-Language-Design / src / visitor / codegeneration / attribute_grammars / code_templates / ExecuteCG.txt
ExecuteCG.txt
Raw
Code function for Statement, Program and Definition

    execute[[Program: program -> definition*]] =
        <' *  Global variables>
        definition*.forEach(def -> execute[[def]])

    execute[[VarDefinition: vardefinition -> ID type]] =
        <' * > type ID <(offset> vardefinition.offset <)>

    execute[[FuncDefinition: funcdefinition -> ID type statement*]] =
		< > ID <:>
        <' *  Parameters:>
        type.parameter*.forEach(def -> execute[[def]];);
        <' *  Local variables:>
        int bytesLocals = 0;
        statement*.forEach(stmt -> {
            if (stmt instanceof VarDefinition){
                bytesLocals = ((VarDefinition) stmt).getOffset();
                execute[[stmt]];
            }
        });
        if(bytesLocals!=0)
                <enter> -bytesLocals;

        int bytesParams = type.parameters.stream().mapToInt(param -> param.type.numberOfBytes()).sum();
        int bytesReturn = type.returnType.numberOfBytes();
        statement*.forEach(stmt->{
            if (!stmt instanceof VarDefinition)
                execute[[stmt]];
        });

    execute[[WriteStatement: statement -> exp]] =
        <' * Write >
        value[[exp]];
        <out> exp.type.suffix();

    execute[[ReadStatement: statement -> exp]] =
        <' * Read >
        address[[exp]]
        <in> exp.type.suffix()
        <store> exp.type.suffix()

    execute[[Assignment: statement -> exp1 exp2]] =
        address[[exp1]]
        value[[exp2]]
        <store> exp1.type.suffix()

    execute[[WhileLoop: statement1 -> expression statement2*]] =
        int labelNumber = cg.getLabels(2);
        <label>labelNumber<:>
        value[[expression]]
        <jz label>labelNumber+1
        statement2*.forEach(stmt -> execute[[stmt]]);
        <jmp label>labelNumber
        <label>labelNumber+1<:>

    execute[[IfElse: statement1 -> expression statement2* statement3*]] =
        int labelNumber = cg.getLabels(2);
        value[[expression]]
        <jz label>labelNumber
        statement2*.forEach(stmt -> execute[[stmt]]);
        <jmp label>labelNumber+1
        <label>labelNumber<:>
        statement3*.forEach(stmt -> execute[[stmt]]);
        <label>labelNumber+1<:>

    execute[[Return: statement -> exp]](int byteReturn, int bytesLocals, int bytesParam)=
        value[[exp]
        <push> exp.type.suffix();
        <ret> bytesReturn <,> bytesLocals <,> bytesParam

    execute[[FunctionInvocation: statement -> exp1 exp2*]]=
        exp2*.forEach(arg -> value[[arg]]);
        <call> exp1.name;
        if(!(exp1.type.returnType instanceof VoidType))
            <pop> exp1.type.returnType.suffix()