【acwj】04,An Actual Compiler 一个真正的编译器

搬运自https://github.com/DoctorWkt/acwj,一个介绍如何使用C语言编写一个可自举的类C语言编译器的说明。进行了粗略的翻译。【acwj】04,An Actual Compiler 一个真正的编译器It’s about time that I met my promise of actually writing a compiler. So in this part of the journey we are going to replace the interpreter.
摘要由CSDN通过智能技术生成

搬运自https://github.com/DoctorWkt/acwj,一个介绍如何使用C语言编写一个可自举的类C语言编译器的说明。进行了粗略的翻译。

【acwj】04,An Actual Compiler 一个真正的编译器

It’s about time that I met my promise of actually writing a compiler. So in this part of the journey we are going to replace the interpreter in our program with code that generates x86-64 assembly code.

现在是我兑现承诺的时候了,我要真正编写一个编译器。因此,在旅程的这一部分,我们将用生成x86-64汇编代码的代码替换程序中的解释器。

Revising the Interpreter 修改解释器

Before we do, it will be worthwhile to revisit the interpreter code in interp.c:

在此之前,我们有必要重温interp.c中的解释器代码:

int interpretAST(struct ASTnode *n) {
   
  int leftval, rightval;

  if (n->left) leftval = interpretAST(n->left);
  if (n->right) rightval = interpretAST(n->right);

  switch (n->op) {
   
    case A_ADD:      return (leftval + rightval);
    case A_SUBTRACT: return (leftval - rightval);
    case A_MULTIPLY: return (leftval * rightval);
    case A_DIVIDE:   return (leftval / rightval);
    case A_INTLIT:   return (n->intvalue);

    default:
      fprintf(stderr, "Unknown AST operator %d\n", n->op);
      exit(1);
  }
}

The interpretAST() function walks the given AST tree depth-first. It evaluates any left sub-tree, then the right sub-tree. Finally, it uses the op value at the base of the current tree to operate on these children.

函数interpretAST() 的作用是:首先遍历给定的AST树深度。它计算所有左子树,然后再计算右子树。最后,它使用当前树底部的op值进行操作。

If the op value is one of the four maths operators, then this maths operation is performed. If the op value indicates that the node is simply an integer literal, the literal value is return.

如果op值是四个数学运算符之一,则执行此数学运算。如果op值指示节点只是一个整数字面值,则返回。

The function returns the final value for this tree. And, as it is recursive, it will calculate the final value for a whole tree one sub-sub-tree at a time.

函数返回此树的最终值。而且,由于它是递归的,它将一次计算一棵整棵树的最终值,一个子树。

Changing to Assembly Code Generation 更改为汇编代码生成器

We are going to write an assembly code generator which is generic. This is, in turn, going to call out to a set of CPU-specific code generation functions.

我们将要编写一个通用的汇编代码生成器。意思是说,反过来调用一组与特定CPU有关的代码生成函数。

Here is the generic assembly code generator in gen.c:
以下是汇编代码的生成器

// Given an AST, generate
// assembly code recursively
static int genAST(struct ASTnode *n) {
   
  int leftreg, rightreg;

  // Get the left and right sub-tree values
  if (n->left) leftreg = genAST(n->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值