您的位置:首页 > 编程语言

Tiny语言编译器之代码生成

2014-02-24 15:04 225 查看
 
代码生成是Tiny编译器的最后一项工作,代码生成的基础是语法树和符号表,遍历语法树,生成能够被TM虚拟机执行的指令,其中if语句和repeat语句需要利用emitSkip、emitBackup进行代码回填,因为只有全部语句指令生成完成以后才知道跳转地址。代码生成的源代码如下:

#include "globals.h"

#include "symtab.h"

#include "code.h"

#include "cgen.h"

static int tempOffset = 0;

static void cgen(TreeNode* tree);

//产生语句的代码

static void genStmt(TreeNode* tree)

{

    TreeNode *p1, *p2, *p3;

    int savedLoc1, savedLoc2, currentLoc;

    int loc;

    switch(tree->kind.stmt)

    {

    case IfK:

        p1=tree->child[0];

        p2=tree->child[1];

        p3=tree->child[2];

        //逻辑表达式的代码

        cgen(p1);

        savedLoc1=emitSkip(1); //回填位置1

        //then部分代码

        cgen(p2);

        savedLoc2=emitSkip(1);//回填位置2

        currentLoc=emitSkip(0);

        emitBackup(savedLoc1);

        emitRM_Abs("JEQ", ac, currentLoc, "if: jmp to else"); //回填位置1的代码

        emitRestore();

        //else部分代码

        cgen(p3);

        currentLoc=emitSkip(0);

        emitBackup(savedLoc2);

        emitRM_Abs("LDA", pc, currentLoc, "jmp to end"); //回填位置2的代码

        emitRestore();

        break;

    case RepeatK:

        p1=tree->child[0];

        p2=tree->child[1];

        savedLoc1=emitSkip(0);

        cgen(p1);

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: