1

I am working on a hobby retargetable C compiler in OCaml and I'm building it bottom up. So far I have an annotated AST type, abridged:

type 'e expr =
    | Int of 'e * int
    | Var of 'e * var
    | Neg of 'e * 'e expr
    | Add of 'e * 'e expr * 'e expr
    | Sub of 'e * 'e expr * 'e expr

and a three-address code type (again abridged):

type node = Copy of location * location
          | Unary of location * unary_op * location
          | Binary of location * location * binary_op * location

and location = Temp of int | Int of int | Var of string

and unary_op = Neg

and binary_op = Add | Sub

I have functions written that will transform an AST into a list of TAC nodes ignoring the annotations. Regarding this I have two questions:

  1. What do I do differently when transforming a type-annotated AST to a list of TAC nodes? Should I add annotations to TAC nodes too? This would allow me to later transform high level int/char types into lower-level ones like I16/I8.

  2. How do I handle scoping? What if I have two Vars that have the same name in different scopes?

4

1 回答 1

1

如何将注释传递给您的 TAC 是一个非常开放的问题,但我同意您可能想要这样做。

范围界定的一种方法是名称擦除。在解析作用域时,将每个唯一标识符替换为唯一的“名称”(或直接使用对符号表条目的引用。)(这有时称为gensymming,在传统的 Lispgensym函数之后。)更正式地说,它是α-减少,取自 λ 演算的术语。这适用于诸如 C 之类的语言,其中名称对运行时不可用。

运行时内省可以访问名称的语言(Python、Javascript)使这个过程稍微复杂一些,但您仍然可以将名称的每次使用与特定范围相关联。在作用域可以是动态的语言(Perl、Lisp)中,您必须在 TAC 中引入名称解析操作。

于 2015-06-19T19:05:21.407 回答