目录
正在加载目录…
正在阅读专栏 Let’s Build a Compiler! 编译器实践教程 第 9 篇 · 共 14 篇 · 64%

A top view:从顶层组织 compiler

发布于 2026-09-16 15:47 · 最后编辑于 2026-09-16 15:47 · 版本 v1 · 字数 2,186 · 预计阅读 5 分钟 👁 11 次阅读

LET'S BUILD A COMPILER!

作者:Jack W. Crenshaw, Ph.D.
日期:1989 年 4 月 16 日
原文部分:Part IX: A TOP VIEW

TL;DR

本篇从 top level 观察 compiler,先用 Pascal 和 C 对比完整 program 的结构,再把前面零散构建的 parser 组织成完整 language 的骨架。

目录

章节说明
INTRODUCTION从局部 parser 回到完整 compiler
THE TOP LEVELcompiler 的 top-level 结构
THE STRUCTURE OF PASCALPascal program 的组成
FLESHING IT OUT将结构展开
DECLARATIONSdeclaration 部分
THE STRUCTURE OF CC 的 top-level 结构

INTRODUCTION

前几期一直在研究单独的 parser routine。现在应该退一步,从 top level 看整个 compiler:一个完整 program 如何组织,declaration、procedure 与 executable statement 如何彼此连接。

THE TOP LEVEL

Compiler 的核心工作仍然是把 input token 按 grammar 解析,并生成 object code。但完整 compiler 必须有一个 top-level:初始化 scanner,读取整个 source,处理 declaration,进入 executable part,并在结束时生成必要的收尾 code。

这一层的 grammar 往往比 expression grammar 简单:

text
<program> ::= <declarations> <statements> .

重要的是先确定 language 的整体结构,再把已有 routine 接入,而不是把所有功能堆进一个巨大 procedure。

THE STRUCTURE OF PASCAL

Pascal 的 program 通常由 program header、declaration 部分和 statement 部分构成。Declaration 可以包括 constant、type、variable、procedure 和 function;statement 部分则是一个 compound statement。

text
<program> ::= PROGRAM <name> ;
              <declarations>
              BEGIN <statement-list> END .

Pascal 把许多信息放在 declaration 中,compiler 可以在进入 executable statement 前建立 symbol table。这样做有利于静态检查,但也要求 compiler 明确区分 declaration phase 与 execution phase。

FLESHING IT OUT

把结构展开时,应为每个 grammar rule 写一个 procedure。Top-level procedure 负责调用更低层 routine,并验证它们返回时的 terminating token。语法的每个 keyword 都对应一个 match call;每个可重复部分都对应 loop;可选部分都对应 guarded IF。

这种方法与之前的 expression、control construct parser 完全相同,只是现在调用层次更高。

DECLARATIONS

Declaration 的实际内容取决于 language。最小 language 可以只支持 variable declaration:

text
<declarations> ::= [ <declaration> ]*
<declaration>  ::= VAR <identifier-list>
<identifier-list> ::= <identifier> [ , <identifier> ]*

Parser 看到 declaration 时,把 name 放入 symbol table,并记录 type、storage location 等信息。即使当前只生成 assembly code,也应把 symbol-table 操作隔离在独立 routine 中,为以后加入 type、scope 与 storage allocation 留出空间。

THE STRUCTURE OF C

C 的结构与 Pascal 不同。C 没有一个包住全部 executable code 的 BEGIN/END;function definition 本身就是 top-level unit,program 从 main function 开始。Declaration 可以出现在 file、function 或 block scope,statement 也可以混合 declaration。

这种结构让 C 的 grammar 更灵活,但也增加了 context 与 scope 的处理。对 compiler writer 来说,关键仍然是把 language 的 top-level grammar 写清楚,然后让每一层 parser 只负责自己的部分。

本篇的重点不是选择 Pascal 或 C,而是认识到:compiler construction 必须从 top-level architecture 开始,逐步连接已经验证过的 lower-level parser。

+### 原文代码块 1

text
begin
        solve the problem
     end

原文代码块 2

text
<program> ::= <program-header> <block> '.'

     <program-header> ::= PROGRAM <ident>

     <block> ::= <declarations> <statements>

原文代码块 3

text
-- ------------------------------------------------------------
-- Parse and translate a program
: prog ( -- )
        0 LOCAL name
        'p' match       \ Handles program header part 
        getname TO name
        name prolog
        '.' match
        name epilog ;
-- ------------------------------------------------------------

原文代码块 4

text
-- ------------------------------------------------------------
-- Write the prolog
: prolog ( char -- )
        S" CODE " ROT CHAR-APPEND emitln 
        S" rpush," emitln ;
-- ------------------------------------------------------------
-- Write the epilog
: epilog ( char -- )
        S" rpop,  ebx jmp," emitln 
        DROP S" END-CODE"   emitln ;
-- ------------------------------------------------------------

原文代码块 5

text
px.   (where x is any single letter, the program name)

原文代码块 6

text
-- ------------------------------------------------------------
-- Parse and translate a pascal block 
: doblock ( char -- ) prolog ;
-- ------------------------------------------------------------

原文代码块 7

text
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( char -- )
        0 LOCAL name
        'p' match       \ Handles program header part 
        getname TO name
        name doblock
        '.' match
        name epilog ;
-- ------------------------------------------------------------

原文代码块 8

text
-- ------------------------------------------------------------
-- Parse and translate a pascal block 
: doblock ( char -- )
        LOCAL name
        declarations 
        name prolog
        'OF name 1 prolog
        name postlabel
        statements ;
-- ------------------------------------------------------------

原文代码块 9

text
<declarations> ::= ( <label list>    |
                          <constant list> |
                          <type list>     |
                          <variable list> |
                          <procedure>     |
                          <function>         )*

原文代码块 10

text
-- ------------------------------------------------------------
-- Parse and translate the declaration part 
: declarations ( -- )
        BEGIN 
          Look 'l' = 
          Look 'c' = OR 
          Look 't' = OR
          Look 'v' = OR  
          Look 'p' = OR
          Look 'f' = OR
        WHILE   CASE Look
                 'l' OF  labels      ENDOF
                 'c' OF  constants   ENDOF
                 't' OF  types       ENDOF
                 'v' OF  variables   ENDOF
                 'p' OF  doprocedure ENDOF
                 'f' OF  dofunction  ENDOF
                ENDCASE 
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 11

text
-- ------------------------------------------------------------
-- Process label statement 
: labels ( -- ) 'l' match ;
-- ------------------------------------------------------------
-- Process const statement 
: constants ( -- ) 'c' match ;
-- ------------------------------------------------------------
-- Process type statement 
: types ( -- ) 't' match ;
-- ------------------------------------------------------------
-- Process var statement 
: variables ( -- ) 'v' match ;
-- ------------------------------------------------------------
-- Process procedure definition 
: doprocedure ( -- ) 'p' match ;
-- ------------------------------------------------------------
-- Process function definition 
: dofunction ( -- ) 'f' match ;
-- ------------------------------------------------------------

原文代码块 12

text
<statements> ::= <compound statement>

     <compound statement> ::= BEGIN <statement> (';' <statement>) END

原文代码块 13

text
-- ------------------------------------------------------------
-- Parse and translate the statement part
: statements ( -- )
        'b' match
        BEGIN  Look 'e' <>
        WHILE  getchar 
        REPEAT 
        'e' match ;
-- ------------------------------------------------------------

原文代码块 14

text
'pxbe.'

原文代码块 15

text
<statement> ::= <simple statement> | <structured statement>

    <simple statement> ::= <assignment> | <procedure call> | null

    <structured statement> ::= <compound statement> |
                               <if statement>       |
                               <case statement>     |
                               <while statement>    |
                               <repeat statement>   |
                               <for statement>      |
                               <with statement>

原文代码块 16

text
<program> ::= ( <global declaration> )*

     <global declaration> ::= <data declaration>  | <function>

原文代码块 17

text
<global declaration> ::= '#' <preprocessor command>  |
                              'int' <data list>           |
                              'char' <data list>          |
                              <ident> <function body>     |

原文代码块 18

text
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( -- )
        BEGIN   Look ^Z <>
        WHILE   CASE Look
                  '#' OF preproc  ENDOF
                  'i' OF intdecl  ENDOF
                  'c' OF chardecl ENDOF
                      int dofunction
                ENDCASE
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 19

text
<program> ::= ( <top-level decl> )*

     <top-level decl> ::= <function def> | <data decl>

     <data decl> ::= [<class>] <type> <decl-list>

     <function def> ::= [<class>] [<type>] <function decl>

原文代码块 20

text
<top-level decl> ::= [<class>] <decl>

     <decl> ::= <type> <typed decl> | <function decl>

     <typed decl> ::= <data list> | <function decl>

原文代码块 21

text
-- ------------------------------------------------------------
-- Main Program
: main ( -- )
        init
        BEGIN   
          Look ^Z <> 
        WHILE
          getclass
          gettype
          topdecl
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 22

text
0 VALUE class

原文代码块 23

text
-- ------------------------------------------------------------
-- Get a storage class specifier 
: getclass ( -- )
        Look 'a' =  Look 'x' = OR  Look 's' = OR
           IF Look TO class
              getchar
         ELSE 'a' TO class      
        ENDIF ;
-- ------------------------------------------------------------

原文代码块 24

text
-- ------------------------------------------------------------
-- Get a type specifier 
: gettype ( -- )
        BL TO typ
        Look 'u' 
         = IF   'u' TO sign
                'i' TO typ
                getchar
         ELSE   's' TO sign
        ENDIF
        Look 'i' = Look 'l' = OR  Look 'c' = OR
           IF   Look TO typ
                getchar
        ENDIF ;
-- ------------------------------------------------------------

原文代码块 25

text
-- ------------------------------------------------------------
-- Process a top-level declaration 
: topdecl ( -- )
        getname LOCAL Name
        Look '(' = IF  name dofunc 
                 ELSE  name dodata
                ENDIF ;
-- ------------------------------------------------------------

原文代码块 26

text
-- -------------------------------------------------------------
-- Process a function definition 
: dofunc ( char -- )
        LOCAL n
        '(' match
        ')' match
        '{' match
        '}' match
        typ BL = IF  'i' TO typ  ENDIF
        CR class EMIT SPACE sign EMIT SPACE typ EMIT 
           ."  function " n EMIT ;
-- -------------------------------------------------------------
-- Process a Data Declaration 
: dodata ( char -- )
        LOCAL n
        typ BL = IF  S" Type declaration" expected  ENDIF
        CR class EMIT SPACE sign EMIT SPACE typ EMIT 
           ."  data " n EMIT 
        BEGIN  Look ',' = 
        WHILE  ',' match
               getname TO n
               CR class EMIT SPACE sign EMIT SPACE typ EMIT 
                  ."  data " n EMIT 
        REPEAT ';' match ;
-- ------------------------------------------------------------

原文代码块 27

text
*****************************************************************
*                                                               *
*                        COPYRIGHT NOTICE                       *
*                                                               *
*   Copyright (C) 1989 Jack W. Crenshaw. All rights reserved.   *
*                                                               *
*****************************************************************

参考资料

版权说明:原文页面标注 Copyright (C) 1988 Jack W. Crenshaw. All rights reserved.

← 返回列表
← 上一篇 A little philosophy:为什么 compiler 可以保持简单 下一篇 → Introducing Tiny:构建一门小型语言

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论