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

Introducing Tiny:构建一门小型语言

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

LET'S BUILD A COMPILER!

作者:Jack W. Crenshaw, Ph.D.
原文部分:Part 10: TINY LANGUAGE

TL;DR

本篇围绕 Tiny language 展开,沿用前文的 parser、scanner、symbol table 与 code generation 方法。

说明

本篇译稿正在按原文各章节整理,专用术语、代码标识符与 syntax 保留原样。完整章节结构如下:

  • INTRODUCTION
  • THE BASICS
  • DECLARATIONS
  • EXECUTABLE STATEMENTS
  • CONCLUSION

正文的核心是把前面已经验证过的 compiler technique 组合起来,并明确 grammar、token、scope、storage 与 calling convention 等边界。

INTRODUCTION

本篇继续扩展 Tiny compiler。前文的 parser 已经能够处理 expression、Boolean、control construct 与 lexical scanning;现在需要处理更高层的 language feature,并保持各模块之间的清晰接口。

THE BASICS

实现新 feature 时,先定义 syntax,再为每条 grammar rule 编写 procedure。Scanner 提供 token,parser 验证结构,symbol table 保存名字与属性,code generator 负责输出 object code。各层不应把其他层的内部细节扩散出去。

DECLARATIONS

Declaration 阶段建立 symbol,并记录后续 code generation 所需的属性。遇到非法、重复或未定义的 name 时,应在能够准确定位的位置报告 error。

EXECUTABLE STATEMENTS

Executable statement 由统一的 block parser 分派。每种 statement 都消费自己的 keyword、argument 与 terminator;控制流通过唯一 label 和 branch 生成。

CONCLUSION

本篇把 compiler 从已有基础继续推进到更完整的 language 结构。后续实现仍然可以沿用相同的 syntax-directed translation 方法。

GETTING STARTED

Tiny 的目标是一门足够小、但能够编写实际 program 的 language。实现从已有 cradle 开始,先确定 declarations、statements 与 expression 的边界,再逐步接入 code generation。

DECLARATIONS

Tiny 的 declaration 语法负责创建 variable 与常量。Declaration parser 将 identifier 放入 symbol table,并在需要时处理 initializer。

DECLARATIONS AND SYMBOLS

Symbol table 记录 name、kind、type 和 storage。即使当前只有一种 data type,也应把 lookup、insert 与 duplicate-check 封装起来。

INITIALIZERS

Initializer 在 declaration phase 处理。常量可以直接进入 data area,变量则生成初始化 code;这与运行时 assignment 必须区分。

THE SYMBOL TABLE

所有 identifier reference 都要经过 symbol table。未声明的 name 应报告 error,重复 declaration 也应拒绝。

EXECUTABLE STATEMENTS

Statement parser 处理 assignment、procedure call 和 control construct。每个 routine 消费自己的 token,并把 code generation 留给对应的 translator。

BOOLEANS

Boolean expression 的 value 与 condition flags 都要满足 control construct 的要求。Tiny 继续使用 0 表示 false、非零表示 true 的约定。

CONTROL STRUCTURES

把 IF、WHILE、LOOP、REPEAT、FOR、DO 和 BREAK 接入 Tiny keyword。Label 与 block nesting 仍沿用前文设计。

LEXICAL SCANNING

Scanner 识别 keyword、identifier、number、operator 与 newline;parser 只接收 token,不再依赖 single-character placeholder。

MULTI-CHARACTER VARIABLE NAMES

GetName 收集完整 identifier,再查询 keyword table。非 keyword 的 token 作为 variable name 保存。

MORE RELOPS

加入 <=、>=、<> 等 relational operator。Scanner 必须处理 lookahead,Relation parser 再选择对应的 SETcc 或 branch。

INPUT/OUTPUT

I/O statement 可以先生成对 runtime support routine 的 call。这样 compiler 只负责 syntax 与参数组织。

CONCLUSION

Tiny 已经从实验性 parser 组合成完整 language 的骨架;后续将继续修正 scanner 与实现细节。

+### 原文代码块 1

text
<program> ::= PROGRAM <top-level decl> <main> '.'

原文代码块 2

text
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( -- )
        'p' match
        header
        prolog
        '.' match
        epilog ;
-- ------------------------------------------------------------

原文代码块 3

text
-- ------------------------------------------------------------
-- Write header info
: header ( -- ) 
        S" -- DATA section --------" emitdln 
        S" " emitdln ;
-- ------------------------------------------------------------

原文代码块 4

text
-- ------------------------------------------------------------
-- Write the prolog 
: prolog ( -- ) 
        S" " emitln 
        S" -- CODE section --------" emitdln 
        S" "          emitdln 
        S" CODE main" emitdln  
        S" rpush,"    emitln
        newlabel postlabel ;
-- ------------------------------------------------------------
-- Write the epilog 
: epilog ( -- ) 
        S" rpop,  ebx jmp," emitln
        S" END-CODE"        emitdln ;
-- ------------------------------------------------------------

原文代码块 5

text
-- -------------------------------------------------------------------------
: tiny10 ( -- )
        init prog
        Look ^M <> IF  S" Unexpected data after " S" ." name.aborts  ENDIF ;
-- -------------------------------------------------------------------------

原文代码块 6

text
-- abort, reporting offending item
: name.aborts ( c-addr1 u1 char ) 
        >R S"  `" $+ R> CHAR-APPEND &' CHAR-APPEND aborts ;

原文代码块 7

text
PROGRAM .   (or 'p.' in our shorthand.)

原文代码块 8

text
<main> ::= BEGIN <block> END

原文代码块 9

text
BEGIN <name>
     END <name>

原文代码块 10

text
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( -- )
        'p' match
        header
        main
        '.' match ;
-- ------------------------------------------------------------

原文代码块 11

text
-- ------------------------------------------------------------
-- Parse and translate a main program 
: main ( -- )
        'b' match
        prolog
        'e' match
        epilog ;
-- ------------------------------------------------------------

原文代码块 12

text
PROGRAM BEGIN END . (or 'pbe.')

原文代码块 13

text
<top-level decls> ::= ( <data declaration> )*

     <data declaration> ::= VAR <var-list>

原文代码块 14

text
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( -- )
        'p' match
        header
        topdecls
        main
        '.' match ;
-- ------------------------------------------------------------

原文代码块 15

text
-- ------------------------------------------------------------
-- Process a data declaration 
: decl ( -- )
        'v' match
        getchar ;
-- ------------------------------------------------------------
-- Parse and translate global declarations 
: topdecls ( -- )
        BEGIN   Look 'b' <> 
        WHILE   CASE Look
                 'v' OF decl  ENDOF
                     S" Unrecognized keyword " Look name.aborts
                ENDCASE
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 16

text
-- ------------------------------------------------------------
-- Parse and translate a data declaration
: decl ( -- )
        'v' match
        getname alloc ;
-- ------------------------------------------------------------

原文代码块 17

text
-- ------------------------------------------------------------
-- Allocate storage for a variable 
: alloc ( char -- )  
        S" CREATE " ROT CHAR-APPEND S"  0 , " $+ emitdln ;
-- ------------------------------------------------------------

原文代码块 18

text
pvxvyvzbe.

原文代码块 19

text
<var-list> ::= <ident> (, <ident>)*

原文代码块 20

text
-- ------------------------------------------------------------
-- Parse and translate a data declaration
: decl ( -- )
        'v' match
        getname alloc
        BEGIN  Look ',' =  
        WHILE  getchar getname alloc  
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 21

text
<var-list> ::= <var> ( <var> )*

     <var> ::= <ident> [ = <integer> ]

原文代码块 22

text
-- ------------------------------------------------------------
-- Allocate storage for a variable 
: alloc ( char -- )
        S" CREATE " ROT CHAR-APPEND BL CHAR-APPEND
        Look '=' = IF   '=' match 
                        getnum (.)
                 ELSE   S" 0"
                ENDIF   $+
        S"  ," $+ emitln ;
-- ------------------------------------------------------------

原文代码块 23

text
-- ------------------------------------------------------------
-- Get a Number
: getnum ( -- val )
        Look digit? 0= IF  S" Integer" expected  ENDIF
        0 >R
        BEGIN   Look digit? 
        WHILE   R> #10 *  Look '0' - +  >R  
                getchar
        REPEAT  R> ;
-- ------------------------------------------------------------

原文代码块 24

text
-- ------------------------------------------------------------
-- Allocate storage for a variable 
: alloc ( char -- )
        S" CREATE " ROT CHAR-APPEND BL CHAR-APPEND
        Look '=' = IF   '=' match 
                        Look '-' = IF '-' match S" -" $+ ENDIF
                        getnum (.)
                 ELSE   S" 0"
                ENDIF   $+
        S"  ," $+ emitln ;

-- ------------------------------------------------------------

原文代码块 25

text
pvavavabe.

原文代码块 26

text
CREATE ST  26 CHARS ALLOT

原文代码块 27

text
-- ------------------------------------------------------------
-- Look for symbol in table 
: intable ( char -- tf ) 'A' - ST + C@  0<> ;
-- ------------------------------------------------------------

原文代码块 28

text
begin
        ST 26 ERASE
   ...

原文代码块 29

text
( n) DUP intable IF  S" Duplicate variable name" ROT name.aborts  ENDIF
        'v' OVER 'A' - ST + C!

原文代码块 30

text
<main> ::= BEGIN <block> END

原文代码块 31

text
<block> ::= (Assignment)*

原文代码块 32

text
-- ------------------------------------------------------------
-- Parse and translate an assignment statement
: assignment ( -- ) getchar ;
-- ------------------------------------------------------------
-- Parse and translate a block of statements
: block ( -- )
        BEGIN  Look 'e' <>
        WHILE  assignment 
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 33

text
-- ------------------------------------------------------------
-- Parse and translate a main program 
: main ( -- )
        'b' match
        prolog
        block
        'e' match
        epilog ;
-- ------------------------------------------------------------

原文代码块 34

text
-- -----------------------------------------------------------------------------------------------------------------------
-- Load/store primary register with a constant/variable
: loadconstant  ( u -- ) (.) S"  d# -> eax  mov," $+ emitln ;

: loadvariable  ( char -- ) 
        DUP intable 0= IF  .undefined  ENDIF
        S"  dword-ptr -> eax  mov," ROT CHAR-PREPEND emitln ;

: storevariable ( char -- ) 
        DUP intable 0= IF  .undefined  ENDIF
        S" eax -> " ROT CHAR-APPEND S"  dword-ptr  mov," $+ emitln ;

-- Allocate storage for a static variable
: allocatestorage ( char c-addr u -- )  
        ROT
        S" CREATE " ROT CHAR-APPEND BL CHAR-APPEND 
        2SWAP $+ S"  , " $+ emitdln ;

: callfunction  ( char -- ) S"  offset NEAR call," ROT CHAR-PREPEND emitln ;    -- call a function

: _negate ( -- ) S" eax  neg,"   emitln ;                                       -- negate primary
: _not    ( -- ) S" eax  not,"   emitln ;                                       -- not primary
: _push   ( -- ) S" eax  push,"  emitln ;                                       -- push primary to stack
: _pop    ( -- ) S" eax  pop,"   emitln ;                                       -- pop primary from stack
: _decr   ( -- ) S" 1 b# -> eax sub," emitln ;                                  -- decrement primary
: _incr   ( -- ) S" 1 b# -> eax add," emitln ;                                  -- increment primary
: _decSP  ( -- ) S" [esp -4 +] -> esp lea," emitln ;                            -- drop 1 stack item
: _incSP  ( -- ) S" [esp  4 +] -> esp lea," emitln ;                            -- restore stack item
: _popadd ( -- ) S" [esp] -> eax  add,  [esp 4 +] -> esp lea," emitln ;         -- add TOS to primary
: _popsub ( -- ) S" [esp] -> eax  sub,  [esp 4 +] -> esp lea," emitln _negate ; -- subtract TOS from primary
: _popor  ( -- ) S" [esp] -> eax  or,   [esp 4 +] -> esp lea," emitln ;         -- or TOS to primary
: _popxor ( -- ) S" [esp] -> eax  xor,  [esp 4 +] -> esp lea," emitln ;         -- xor TOS to primary
: _popand ( -- ) S" [esp] -> eax  and,  [esp 4 +] -> esp lea," emitln ;         -- xor TOS to primary
: _popcmp ( -- ) S" [esp] -> eax  cmp,  [esp 4 +] -> esp lea," emitln ;         -- compare TOS to primary
: _sete   ( -- ) S" al  sete,   al -> eax  movsx," emitln ;                     -- set primary if equal
: _setne  ( -- ) S" al  setne,  al -> eax  movsx," emitln ;                     -- set primary if NOT equal
: _setg   ( -- ) S" al  setl,   al -> eax  movsx," emitln ;                     -- set primary if greater
: _setl   ( -- ) S" al  setg,   al -> eax  movsx," emitln ;                     -- set primary if less
: _setge  ( -- ) S" al  setle,  al -> eax  movsx," emitln ;                     -- set primary if greater or equal
: _setle  ( -- ) S" al  setge,  al -> eax  movsx," emitln ;                     -- set primary if less or equal

-- jump always; jump if eax 0
: _branch    ( c-addr u -- ) S"  offset NEAR  jmp," $+ emitln ;    
: _pcmp+b0>  ( c-addr u -- ) _popcmp S"  offset NEAR  jg,"  $+ emitln ;
: _branch0   ( c-addr u -- ) S" eax -> eax or,  " 2SWAP $+ S"  offset NEAR  je,"  $+ emitln ;
: _branch<>0 ( c-addr u -- ) S" eax -> eax or,  " 2SWAP $+ S"  offset NEAR  jnz," $+ emitln ;

-- multiply TOS and primary; divide primary by TOS
: _popmul ( -- ) S" [esp] dword mul, [esp 4 +] -> esp lea," emitln ;
: _popdiv ( -- ) S" ecx pop, ecx -> eax xchg, eax -> edx mov, #31 b# -> edx sar, ebx idiv," emitln ;
-- -----------------------------------------------------------------------------------------------------------------------

原文代码块 35

text
-- ------------------------------------------------------------------
-- Report an undefined identifier 
: .undefined ( char -- ) 
   S" Undefined identifier `" ROT CHAR-APPEND &' CHAR-APPEND aborts ;
-- ------------------------------------------------------------------

原文代码块 36

text
<assignment> ::= <ident> = <expression>

     <expression> ::= <first term> ( <addop> <term> )*

     <first term> ::= <first factor> <rest>

     <term> ::= <factor> <rest>

     <rest> ::= ( <mulop> <factor> )*

     <first factor> ::= [ <addop> ] <factor>

     <factor> ::= <var> | <number> | ( <expression> )

原文代码块 37

text
-- -------------------------------------------------------------
-- Parse and Translate a Math Factor 

DEFER expression

: factor ( -- )
   Look '(' =  IF  '(' match expression ')' match EXIT  ENDIF
   Look alpha? IF  getname loadvariable 
             ELSE  getnum  loadconstant 
            ENDIF ; 
-- ------------------------------------------------------------
-- Parse and translate a negative factor
: negfactor ( -- )
   '-' match
   Look digit? IF  getnum NEGATE loadconstant EXIT  ENDIF
   factor _negate ;
-- ------------------------------------------------------------
-- Parse and translate a leading factor 
: firstfactor ( -- )
   CASE Look
     '+' OF  '+' match factor ENDOF
     '-' OF   negfactor       ENDOF
              factor
   ENDCASE ;
-- ------------------------------------------------------------
-- Recognize and translate a multiply
: multiply ( -- ) '*' match factor _popmul ;
-- ------------------------------------------------------------
-- Recognize and translate a divide
: divide ( -- ) '/' match factor _popdiv ;
-- ------------------------------------------------------------
-- Common code used by term and firstterm
: term1 ( -- )
   BEGIN Look mulop?
   WHILE _push
         CASE Look 
          '*' OF multiply ENDOF
          '/' OF divide   ENDOF
         ENDCASE
   REPEAT ;
-- ------------------------------------------------------------
-- Parse and translate a math term 
: term ( -- ) factor term1 ;
-- ------------------------------------------------------------
-- Parse and translate a leading term 
: firstterm ( -- ) firstfactor term1 ;
-- ------------------------------------------------------------
-- Recognize and translate an add 
: add ( -- ) '+' match term _popadd ;
-- ------------------------------------------------------------
-- Recognize and translate a subtract
: subtract ( -- ) '-' match term _popsub ;
-- ------------------------------------------------------------
-- Parse and translate an expression
:NONAME ( -- )
   firstterm
   BEGIN Look addop?
   WHILE _push
         CASE Look
          '+' OF Add      ENDOF
          '-' OF Subtract ENDOF
         ENDCASE 
   REPEAT ; IS expression
-- ------------------------------------------------------------
-- Parse and translate an assignment statement
: assignment ( -- )
   getname LOCAL name
   '=' match
   expression
   name storevariable ;
-- ------------------------------------------------------------

原文代码块 38

text
-- ------------------------------------------------------------
-- Recognize a boolean Orop 
: orop? ( char -- tf ) DUP '|' = SWAP '~' = OR ;
-- ------------------------------------------------------------
-- Recognize a relop 
: relop? ( char -- tf )  
        DUP  '=' = 
        OVER '#' = OR  
        OVER '<' = OR
        SWAP '>' = OR ;
-- ------------------------------------------------------------

原文代码块 39

text
<bool-expr> ::= <bool-term> ( <orop> <bool-term> )*

     <bool-term> ::= <not-factor> ( <andop> <not-factor> )*

     <not-factor> ::= [ '!' ] <relation>

     <relation> ::= <expression> [ <relop> <expression> ]

原文代码块 40

text
#define TRUE -1
     #define FALSE 0

原文代码块 41

text
-- -------------------------------------------------------------
-- Recognize and translate a relational "equals" 
: equals ( -- ) '=' match expression _popcmp _sete ;
-- -------------------------------------------------------------
-- Recognize and translate a relational "not equals" 
: notequals ( -- ) '#' match expression _popcmp _setne ;
-- -------------------------------------------------------------
-- Recognize and translate a relational "less than" 
: less ( -- ) '<' match expression _popcmp _setl ;
-- -------------------------------------------------------------
-- Recognize and translate a relational "greater than" 
: greater ( -- ) '>' match expression _popcmp _setg ;
-- -------------------------------------------------------------
-- Parse and translate a relation 
: relation ( -- )
   expression
   Look relop? 0= ?EXIT 
   _push
   CASE Look 
    '=' OF equals    ENDOF
    '#' OF notequals ENDOF
    '<' OF less      ENDOF
    '>' OF greater   ENDOF
   ENDCASE ;
-- -------------------------------------------------------------
-- Parse and translate a boolean factor with leading NOT 
: notfactor ( -- )
   Look '!' <> IF  relation  EXIT  ENDIF
   '!' match  relation _not ;
-- -------------------------------------------------------------
-- Parse and translate a boolean term 
: boolterm ( -- )
   notfactor 
   BEGIN  Look '&' =
   WHILE  _push  '&' match  notfactor  _popand
   REPEAT ;
-- ------------------------------------------------------------
-- Recognize and translate a boolean OR 
: boolOR ( -- ) '|' match boolterm _popor ;
-- ------------------------------------------------------------
-- Recognize and translate an EXCLUSIVE OR 
: boolXOR ( -- ) '~' match boolterm _popxor ;
-- ------------------------------------------------------------
-- Parse and translate a boolean expression 
:NONAME ( -- ) 
   boolterm
   BEGIN Look orop? 
   WHILE _push
         CASE Look
          '|' OF boolor ENDOF
          '~' OF boolxor ENDOF
         ENDCASE
   REPEAT ; IS boolexpression
-- ------------------------------------------------------------

原文代码块 42

text
pvx,y,zbx=z>ye.

原文代码块 43

text
PROGRAM
     VAR X,Y,Z
     BEGIN
     X = Z > Y
     END.

原文代码块 44

text
<if> ::= IF <bool-expression> <block> [ ELSE <block>] ENDIF

     <while> ::= WHILE <bool-expression> <block> ENDWHILE

原文代码块 45

text
end { loop }

原文代码块 46

text
end { if }

原文代码块 47

text
<bool-expression> and <block>

原文代码块 48

text
-- -------------------------------------------------------------
-- Recognize and translate an IF Construct 

DEFER block ( -- )

: doIF ( -- )
        0 0 LOCALS| L2 L1 |
        'i' match
        boolexpression
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        L1 COUNT DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
        L1 COUNT _branch0
        block
        Look 'l'  = IF  L2 FREE ?ALLOCATE
                        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
                        L2 COUNT _branch
                        L1 COUNT postlabel
                        block
                 ENDIF
        L2 COUNT postlabel
        'e' match
        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;
-- ------------------------------------------------------------
-- Parse and translate a WHILE Statement 
: doWHILE ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
        'w' match
        L1 COUNT postlabel
        boolexpression
        L2 COUNT _branch0
        block
        'e' match
        L1 COUNT _branch
        L2 COUNT postlabel
        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;
-- ------------------------------------------------------------

原文代码块 49

text
<block> ::= ( <statement> )*

原文代码块 50

text
<statement> ::= <if> | <while> | <assignment>

原文代码块 51

text
-- ------------------------------------------------------------
-- Parse and translate a block of statements
:NONAME BEGIN  Look 'e' <> 
               Look 'l' <> AND
        WHILE  CASE Look
                'i' OF  doIF      ENDOF
                'w' OF  doWHILE   ENDOF
                        assignment
               ENDCASE
        REPEAT ; IS block
-- ------------------------------------------------------------

原文代码块 52

text
-- ------------------------------------------------------------
-- Skip over an end-of-line
: newline ( -- )
   BEGIN Look ^M = 
   WHILE getchar 
         Look ^J = IF  getchar  ENDIF
         skipwhite
   REPEAT ;
-- ------------------------------------------------------------

原文代码块 53

text
-- ------------------------------------------------------------
-- Type declarations 
  8 =: /symbol
100 =: maxentry
-- ------------------------------------------------------------
-- Variable declarations 
0 VALUE token                  -- encoded token   
CREATE token$ 16 CHARS ALLOT   -- unencoded token 
-- ------------------------------------------------------------
-- Definition of keywords and token types 
-- helper to build symbol tables
: $, ( c-addr u size -- ) 
        >S S MIN >R  
        R@ C, R@ 0 ?DO  C@+ C,  LOOP DROP 
        S> R> - CHARS ALLOT ; 
-- Symboltable builder itself
: SYMTAB ( size -- ) 
        CREATE  DUP 0< IF  0 , ABS DUP , 
                           1+ maxentry * ALLOT   
                     ELSE  HERE >R
                           0 ,  ( #items )
                           DUP >S ,  ( itemsize )
                           BEGIN  BL <WORD> DUP  
                           WHILE  S $, 1 R@ +!  
                           REPEAT 2DROP -R -S
                    ENDIF
        DOES>   CELL+ @+ 1+ ROT * + ( ix -- addr ) ; 

/symbol SYMTAB KWlist IF ELSE ENDIF WHILE ENDWHILE VAR BEGIN END PROGRAM

: KW->token ( kw_index -- ) 2+ C" xilewevbep" + C@ TO token ;
-- ------------------------------------------------------------

原文代码块 54

text
-- ------------------------------------------------------------
-- Table Lookup 
: lookup ( c-addr u 'table -- n2 | -1 )
        0 0 LOCALS| /symbol n table sz addr |
        table 2 CELLS - @+ TO n  @ TO /symbol
        n 0<= IF  -1 EXIT  ENDIF
           0 n DO 
                  /symbol 1+ I * table + COUNT  
                  addr sz COMPARE 0= IF  I UNLOOP EXIT  ENDIF
         -1 +LOOP 
        -1 ;
-- ------------------------------------------------------------
.
.
-- ------------------------------------------------------------
-- Get an identifier and scan it for keywords
: scan ( -- ) getname 0 KWlist lookup KW->token ;
-- ------------------------------------------------------------
-- Match a specific input string 
: matchstring ( c-addr u -- )
        token$ COUNT 2OVER 
        COMPARE IF  &` CHAR-PREPEND &' CHAR-APPEND expected
              ELSE  2DROP
             ENDIF ;
-- ------------------------------------------------------------

原文代码块 55

text
-- ------------------------------------------------------------
-- Get an identifier 
: getname ( -- c-addr u )
        newline
        Look alpha? 0= IF  S" Name" expected  ENDIF
        token$ C0!
        BEGIN   Look alnum?
        WHILE   Look >UPC token$ char+!  getchar
        REPEAT  
        token$ COUNT  skipwhite ;
-- ------------------------------------------------------------

原文代码块 56

text
-- -------------------------------------------------------------
-- Parse and translate a math factor 

DEFER boolexpression ( -- )

: factor ( -- ) 
        Look '('  = IF  '(' match  boolexpression  ')' match EXIT  ENDIF
        Look alpha? IF  getname DROP C@ loadvariable         EXIT  ENDIF
        getnum loadconstant ;
-- ------------------------------------------------------------
.
.
-- ------------------------------------------------------------
-- Parse and translate an assignment statement
: assignment ( -- )
        token$ COUNT DUP 1+ ALLOCATE ?ALLOCATE DUP LOCAL name PACK DROP
        '=' match 
        boolexpression
        name COUNT DROP C@ storevariable
        name FREE ?ALLOCATE ;
-- ------------------------------------------------------------
.
.
-- ------------------------------------------------------------
-- Parse and translate a data declaration
: decl ( -- )
        getname DROP C@ alloc
        BEGIN  Look ',' =  
        WHILE  ',' match  getname DROP C@ alloc  
        REPEAT ;
-- ------------------------------------------------------------

原文代码块 57

text
-- -------------------------------------------------------------
-- Recognize and translate an IF construct 

DEFER block

: doIF ( -- )
        0 0 LOCALS| L2 L1 |
        boolexpression
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        L1 COUNT DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
        L1 COUNT _branch0
        block
        token 'l' = IF  L2 FREE ?ALLOCATE
                        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
                        L2 COUNT _branch
                        L1 COUNT postlabel
                        block
                 ENDIF
        L2 COUNT postlabel
        S" ENDIF" matchstring

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;
-- ------------------------------------------------------------
-- Parse and translate a WHILE statement 
: doWHILE ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP

        L1 COUNT postlabel
        boolexpression
        L2 COUNT _branch0
        block
        L1 COUNT _branch
        L2 COUNT postlabel
        S" ENDWHILE" matchstring

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;
-- ------------------------------------------------------------
-- Parse and translate a block of statements 
:NONAME ( label -- )
        LOCAL L
        scan
        BEGIN  token 'e' <> 
               token 'l' <> AND
        WHILE  CASE token
                'i' OF  doIF      ENDOF
                'w' OF  doWHILE   ENDOF
                        assignment
               ENDCASE
               scan
        REPEAT ; IS block
-- ------------------------------------------------------------
-- Parse and Translate Global Declarations 
: topdecls ( -- )
        scan
        BEGIN   token 'b' <> 
        WHILE   CASE token
                 'v' OF decl  ENDOF
                     S" Unrecognized keyword " 
                     token$ COUNT name.aborts
                ENDCASE
                scan
        REPEAT ;
-- ------------------------------------------------------------
-- Parse and translate a main program 
: doprogram ( -- )
        S" BEGIN" matchstring
        prolog
        block
        S" END" matchstring
        epilog ;
-- ------------------------------------------------------------
-- Parse and translate a program 
: prog ( -- )
        S" PROGRAM" matchstring 
        getname prog$ PACK DROP
        header
        topdecls
        doprogram
        '.' match ;
-- ------------------------------------------------------------
-- Initialize 
: init ( -- ) 
        CLEAR Lcount
        ST 26 CHARS ERASE
        CR getchar scan ; 
-- ------------------------------------------------------------

原文代码块 58

text
0 ST    2 CELLS - =: [cnt]ST
      0 SType 2 CELLS - =: [cnt]SType

原文代码块 59

text
100 =: maxentry
.
.
/symbol  NEGATE SYMTAB ST
=CELL 1- NEGATE SYMTAB SType

原文代码块 60

text
-- ------------------------------------------------------------
-- Look for symbol in table 
: intable ( c-addr u -- tf ) 0 ST lookup 0>= ;
-- ------------------------------------------------------------

原文代码块 61

text
-- ------------------------------------------------------------
-- Add a new entry to the symbol table 
: addentry ( c-addr u type -- )
        [cnt]ST LOCALS| #entries T sz addr |
        addr sz intable IF  S" Duplicate identifier " addr sz name.aborts  ENDIF
        #entries @ maxentry = IF  S" Symbol table full" aborts  ENDIF
        1 #entries +!
        addr sz  #entries @ ST    PACK DROP 
        T        #entries @ SType C! ;
-- ------------------------------------------------------------

原文代码块 62

text
-- ------------------------------------------------------------
-- Allocate storage for a variable 
: alloc ( c-addr u -- )
        LOCALS| sz addr |
        addr sz intable IF  S" Duplicate variable name " 
                            addr sz name.aborts  
                     ENDIF
        addr sz 'v' addentry
.
.
.
-- ------------------------------------------------------------

原文代码块 63

text
-- ------------------------------------------------------------
-- Initialize 
: init ( -- ) 
        CLEAR Lcount
        [cnt]ST    OFF
        [cnt]SType OFF
        CR getchar scan ; 
-- ------------------------------------------------------------

原文代码块 64

text
-- -------------------------------------------------------------
-- Recognize and translate a relational "less than or equal" 
: lessorequal ( -- )  '=' match  expression _popcmp _setle ;
-- -------------------------------------------------------------
-- Recognize and Translate a Relational "Not Equals" 
: notequals   ( -- )  '>' match  expression _popcmp _setne ;
-- -------------------------------------------------------------
-- recognize and translate a relational "less than"
: less ( -- ) 
        '<' match 
        Look '=' = IF  lessorequal EXIT  ENDIF
        Look '>' = IF  notequals   EXIT  ENDIF
        expression _popcmp _setl ;
-- -------------------------------------------------------------
-- recognize and translate a relational "greater than"
: greater ( -- ) 
        '>' match  
        Look '=' = IF   '=' match expression _popcmp _setge 
                        EXIT  
                ENDIF
        expression _popcmp _setg ;
-- -------------------------------------------------------------

原文代码块 65

text
-- -------------------------------------------------------------
-- read to primary register and store in variable
: readvar  ( c-addr u -- ) S" READ" callfunction  storevariable ; 
-- -------------------------------------------------------------
-- write from primary register
: writevar ( -- ) S" WRITE" callfunction ;

原文代码块 66

text
-- ------------------------------------------------------------
-- Write header info 
: header ( -- ) 
        S" -- DATA section --------" emitdln 
        S" NEEDS -tinylib" emitdln
        S" " emitdln ;
-- ------------------------------------------------------------

原文代码块 67

text
-- ------------------------------------------------------------
-- Definition of keywords and token types 
/symbol SYMTAB KWlist IF ELSE ENDIF WHILE ENDWHILE READ WRITE VAR BEGIN END PROGRAM

: KW->token ( kw_index -- ) 2+ C" xileweRWvbep" + C@ TO token ;
-- ------------------------------------------------------------

原文代码块 68

text
-- ------------------------------------------------------------
-- Process a read statement 
: doread ( -- )
        '(' match
        getname readvar
        BEGIN  Look ',' = 
        WHILE  ',' match getname readvar
        REPEAT 
        ')' match ;
-- -------------------------------------------------------------
-- Process a write statement
: dowrite ( -- )
        '(' match 
        expression writevar
        BEGIN  Look ',' = 
        WHILE  ',' match expression writevar
        REPEAT 
        ')' match ;
-- ------------------------------------------------------------

原文代码块 69

text
-- ------------------------------------------------------------
-- Parse and translate a block of statements 
:NONAME ( -- )
        scan
        BEGIN  token 'e' <> 
               token 'l' <> AND
        WHILE  CASE token
                'i' OF  doIF      ENDOF
                'w' OF  doWHILE   ENDOF
                'R' OF  doread    ENDOF
                'W' OF  dowrite   ENDOF
                        assignment
               ENDCASE
               scan
        REPEAT ; IS block
-- ------------------------------------------------------------

原文代码块 70

text
-- Variable declarations --------------------------------------------------------------------------------------------------

-1 =: unknown

0 VALUE Lcount                          -- label counter
0 VALUE Look                            -- lookahead character 
0 VALUE token                           -- encoded token

#100 =: maxentry

CREATE token$  0 C, #256 CHARS ALLOT    -- unencoded token
CREATE prog$   0 C, #256 CHARS ALLOT    -- program name

-- Symbol tables and Labels ----------------------------------------------------------------------------------------------------------

-- helper to build symbol tables
: $, ( c-addr u size -- ) 
        >S S MIN >R  
        R@ C, R@ 0 ?DO  C@+ C,  LOOP DROP 
        S> R> - CHARS ALLOT ; 

-- Type declarations  
: SYMTAB ( size -- ) 
        CREATE  DUP 0< IF  0 , ABS DUP , 
                           1+ maxentry * ALLOT   
                     ELSE  HERE >R
                           0 ,  ( #items )
                           DUP >S ,  ( itemsize )
                           BEGIN  BL <WORD> DUP  
                           WHILE  2DUP S" \" COMPARE 
                                  0= IF  2DROP REFILL DROP
                                   ELSE  S $, 1 R@ +!  
                                  ENDIF
                           REPEAT 2DROP -R -S
                    ENDIF
        DOES>   CELL+ @+ 1+ ROT * + ( ix -- addr ) ; 

-- Definition of keywords and token types

8 CHARS =: /symbol

/symbol SYMTAB KWlist   IF ELSE ENDIF   \ 
                        WHILE ENDWHILE  \ 
                        DO ENDDO        \
                        LOOP ENDLOOP    \ 
                        REPEAT UNTIL    \
                        FOR TO ENDFOR   \
                        BREAK           \
                        READ WRITE      \ 
                        VAR BEGIN END PROGRAM

: KW->token ( kw_index -- ) 2+ C" xilewedeLerufteBRWvbep" + C@ TO token ;
 
        /symbol  NEGATE SYMTAB ST
        =CELL 1- NEGATE SYMTAB SType

0 ST    2 CELLS - =: [cnt]ST
0 SType 2 CELLS - =: [cnt]SType

: lookup ( c-addr u 'table -- n2|unknown )
        0 0 LOCALS| /symbol n table sz addr |
        table 2 CELLS - @+ TO n  @ TO /symbol
        n 0<= IF  unknown EXIT  ENDIF
           0 n DO 
                  /symbol 1+ I * table + COUNT  
                  addr sz COMPARE 0= IF  I UNLOOP EXIT  ENDIF
         -1 +LOOP 
        unknown ;

-- Locate a symbol in table 
-- Returns the index of the entry.  (unknown) -1 if not present.
: locate ( c-addr u -- ix ) 0 ST lookup ;

-- Look for symbol in table
: intable ( c-addr u -- tf )
        0 ST lookup 0>= ;

-- Dump the symbol tabel
: .symbols ( -- )
        [cnt]ST @ 0= IF  CR ." No symbols defined." EXIT  ENDIF
        CR ." -- type --.-------- name ---------" 
        CR
        [cnt]ST @ 0 ?DO  CR   2 HTAB   I 1+ SType C@ EMIT 
                              #14 HTAB I 1+ ST    .$ 
                   LOOP ;

-- Tools ------------------------------------------------------------------------------------------------------------------

: getchar  ( -- )          EKEY TO Look ;                       -- read new character from input stream 
: error    ( c-addr u -- ) CR ^G EMIT ." Error: " TYPE ." ." ;  -- report an error 
: aborts   ( c-addr u -- ) error ABORT ;                        -- report error and halt 
: expected ( c-addr u -- ) S"  Expected" $+ aborts ;            -- report what was expected 
: alpha?   ( char -- tf )  >UPC 'A' 'Z' 1+ WITHIN ;             -- recognize an alpha character 
: digit?   ( char -- tf )  '0' '9' 1+ WITHIN ;                  -- recognize a decimal digit
: alnum?   ( char -- tf )  DUP alpha? SWAP digit? OR ;          -- recognize alphanumeric
: white?   ( char -- tf )  DUP Tab =  SWAP BL  =  OR ;          -- recognize white space
: orop?    ( char -- tf )  DUP '|' =  SWAP '~' =  OR ;          -- recognize an OR operand
: addop?   ( char -- tf )  DUP '+' =  SWAP '-' =  OR ;          -- test for AddOp
: mulop?   ( char -- tf )  DUP '*' =  SWAP '/' =  OR ;          -- test for MulOp
: emits    ( c-addr u -- ) Tab EMIT TYPE ;                      -- output a string with tab 
: emitdln  ( c-addr u -- ) CR TYPE ;                            -- output a string without tab, +crlf
: emitln   ( c-addr u -- ) CR emits ;                           -- output a string with tab and crlf 

-- abort, reporting offending item
: name.aborts ( c-addr1 u1 c-addr2 u2 ) 
        &` CHAR-PREPEND &' CHAR-APPEND $+ aborts ;

: .undefined ( c-addr u -- )
        S" Undefined identifier " 2SWAP name.aborts ;

-- generate a unique label
: newlabel ( -- c-addr u ) S" @" Lcount U>D <# #S #> $+  1 +TO Lcount ;

-- post a label to output 
: postlabel ( c-addr u -- ) CR TYPE ':' EMIT ;

-- Recognize a relop
: relop? ( char -- tf )  
        DUP  '=' = 
        OVER '#' = OR  
        OVER '<' = OR
        SWAP '>' = OR ;

: char+!   ( c addr -- )   DUP >S COUNT + C!  1 S> C+! ;

-- skip white space
: skipwhite ( -- ) 
        BEGIN  Look white? 
        WHILE  getchar 
        REPEAT ;

-- skip cr+lf
: fin ( -- )
        Look ^M = IF getchar ENDIF
        Look ^J = IF getchar ENDIF 
        skipwhite ;

: newline ( -- ) BEGIN  Look ^M = WHILE  fin  REPEAT ;

-- match a specific input character 
: match ( char -- )
        DUP Look = IF  DROP getchar skipwhite 
                 ELSE  S" `" ROT CHAR-APPEND &' CHAR-APPEND expected 
                ENDIF ;

-- get an identifier. 
: getname ( -- c-addr u )
        newline
        Look alpha? 0= IF  S" Name" expected  ENDIF
        token$ C0!
        BEGIN   Look alnum?
        WHILE   Look >UPC token$ char+!  getchar
        REPEAT  
        token$ COUNT  skipwhite ;

-- get a number 
: getnum ( -- val )
        newline
        Look digit? 0= IF  S" Integer" expected  ENDIF
        0 >R
        BEGIN   Look digit? 
        WHILE   R> #10 *  Look '0' - +  >R  
                getchar
        REPEAT  '#' TO token
        R>  skipwhite ;

-- Get an identifier and scan it for keywords
: scan ( -- ) getname 0 KWlist lookup KW->token ;

-- Add a new entry to symbol table 
: addentry ( c-addr u type -- )
        [cnt]ST LOCALS| #entries T sz addr |
        addr sz intable IF  S" Duplicate identifier " addr sz name.aborts  ENDIF
        #entries @ maxentry = IF  S" Symbol table full" aborts  ENDIF
        1 #entries +!
        addr sz  #entries @ ST  PACK DROP 
        T #entries @ SType C! ;

-- Match a specific input string 
: matchstring ( c-addr u -- )
        token$ COUNT 2OVER 
        COMPARE IF  &` CHAR-PREPEND &' CHAR-APPEND expected
              ELSE  2DROP
             ENDIF ;

-- Code generation -------------------------------------------------------------------------------------------------------

-- Load/store primary register with a constant/variable
: loadconstant  ( u -- ) (.) S"  d# -> eax  mov," $+ emitln ;

: loadvariable  ( c-addr u -- ) 
        2DUP intable 0= IF  .undefined  ENDIF
        S"  dword-ptr -> eax  mov," $+ emitln ;

: storevariable ( c-addr u -- ) 
        2DUP intable 0= IF  .undefined  ENDIF
        S" eax -> " 2SWAP $+ S"  dword-ptr  mov," $+ emitln ;

-- Allocate storage for a static variable
: allocatestorage ( c-addr1 u1 c-addr2 u2 -- )  
        S" CREATE " 2ROT $+ BL CHAR-APPEND 2SWAP $+ S"  , " $+ emitdln ;

: callfunction  ( c-addr u -- ) S"  offset NEAR call," $+ emitln ;              -- call a function

: _negate ( -- ) S" eax  neg,"   emitln ;                                       -- negate primary
: _not    ( -- ) S" eax  not,"   emitln ;                                       -- not primary
: _push   ( -- ) S" eax  push,"  emitln ;                                       -- push primary to stack
: _pop    ( -- ) S" eax  pop,"   emitln ;                                       -- pop primary from stack
: _decr   ( -- ) S" 1 b# -> eax sub," emitln ;                                  -- decrement primary
: _incr   ( -- ) S" 1 b# -> eax add," emitln ;                                  -- increment primary
: _decSP  ( -- ) S" [esp -4 +] -> esp lea," emitln ;                            -- drop 1 stack item
: _incSP  ( -- ) S" [esp  4 +] -> esp lea," emitln ;                            -- restore stack item
: _popadd ( -- ) S" [esp] -> eax  add,  [esp 4 +] -> esp lea," emitln ;         -- add TOS to primary
: _popsub ( -- ) S" [esp] -> eax  sub,  [esp 4 +] -> esp lea," emitln _negate ; -- subtract TOS from primary
: _popor  ( -- ) S" [esp] -> eax  or,   [esp 4 +] -> esp lea," emitln ;         -- or TOS to primary
: _popxor ( -- ) S" [esp] -> eax  xor,  [esp 4 +] -> esp lea," emitln ;         -- xor TOS to primary
: _popand ( -- ) S" [esp] -> eax  and,  [esp 4 +] -> esp lea," emitln ;         -- xor TOS to primary
: _popcmp ( -- ) S" [esp] -> eax  cmp,  [esp 4 +] -> esp lea," emitln ;         -- compare TOS to primary
: _sete   ( -- ) S" al  sete,   al -> eax  movsx," emitln ;                     -- set primary if equal
: _setne  ( -- ) S" al  setne,  al -> eax  movsx," emitln ;                     -- set primary if NOT equal
: _setg   ( -- ) S" al  setl,   al -> eax  movsx," emitln ;                     -- set primary if greater
: _setl   ( -- ) S" al  setg,   al -> eax  movsx," emitln ;                     -- set primary if less
: _setge  ( -- ) S" al  setle,  al -> eax  movsx," emitln ;                     -- set primary if greater or equal
: _setle  ( -- ) S" al  setge,  al -> eax  movsx," emitln ;                     -- set primary if less or equal

-- jump always; jump if eax 0
: _branch    ( c-addr u -- ) S"  offset NEAR  jmp," $+ emitln ;    
: _pcmp+b0>  ( c-addr u -- ) _popcmp S"  offset NEAR  jg,"  $+ emitln ;
: _branch0   ( c-addr u -- ) S" eax -> eax or,  " 2SWAP $+ S"  offset NEAR  je,"  $+ emitln ;
: _branch<>0 ( c-addr u -- ) S" eax -> eax or,  " 2SWAP $+ S"  offset NEAR  jnz," $+ emitln ;

-- multiply TOS and primary; divide primary by TOS
: _popmul ( -- ) S" [esp] dword mul, [esp 4 +] -> esp lea," emitln ;
: _popdiv ( -- ) S" ecx pop, ecx -> eax xchg, eax -> edx mov, #31 b# -> edx sar, ebx idiv," emitln ;

-- read to primary register and store in variable
: readvar  ( c-addr u -- ) S" READ" callfunction  storevariable ; 

-- write from primary register
: writevar ( -- ) S" WRITE" callfunction ; 

-- Write assembler header info; epilogue, and prologue
: header ( -- ) 
        S" -- DATA section --------" emitdln 
        S" " emitdln ;

: prolog ( -- ) 
        S" " emitln 
        S" -- CODE section --------" emitdln 
        S" "          emitdln 
        S" CODE " prog$ COUNT $+ emitdln  
        S" rpush,"    emitln
        newlabel postlabel ;

: epilog ( -- ) 
        S" rpop,  ebx jmp," emitln
        S" END-CODE"        emitdln ;

-- Expressions -----------------------------------------------------------------------------------------------------------

-- parse and translate an identifier.
-- Note that we need to store getname locally because parsing a call's 
-- parameterlist may clobber it.
: ident ( -- )
        getname DUP 1+ ALLOCATE ?ALLOCATE DUP LOCAL name PACK DROP
        Look '(' = IF   '(' match ')' match 
                        name COUNT callfunction
                 ELSE   name COUNT loadvariable
                ENDIF
        name FREE ?ALLOCATE ;

DEFER expression
DEFER boolexpression

-- parse and translate a math factor
: factor ( -- ) 
        Look '('  = IF  '(' match  boolexpression  ')' match EXIT  ENDIF
        Look alpha? IF  getname loadvariable  EXIT  ENDIF
        getnum loadconstant ;

-- parse and translate the first math factor
: signedfactor ( -- ) 
        Look '+'  = IF  getchar       ENDIF
        Look '-' <> IF  factor  EXIT  ENDIF
        getchar skipwhite
        Look digit? IF  getnum NEGATE loadconstant
                  ELSE  factor _negate
                 ENDIF ;

-- recognize and translate multiply / divide 
: multiply  ( -- ) '*' match  factor _popmul ;  
: divide    ( -- ) '/' match  factor _popdiv ;

-- parse and translate a math term
: term ( -- ) 
        signedfactor 
        BEGIN Look mulop?
        WHILE   _push
                CASE Look
                  '*' OF multiply  ENDOF
                  '/' OF divide    ENDOF
                         S" Mulop" expected
                ENDCASE 
        REPEAT ;

-- recognize and translate add / subtract
: add       ( -- ) '+' match  term   _popadd ; 
: subtract  ( -- ) '-' match  term   _popsub ;

-- parse and translate an expression
:NONAME ( -- ) 
        term
        BEGIN   Look addop? 
        WHILE   _push
                CASE Look
                  '+' OF add      ENDOF
                  '-' OF subtract ENDOF
                         S" Addop" expected
                ENDCASE 
        REPEAT ; IS expression

-- recognize and translate a relational "equals"
: equals      ( -- )  '=' match  expression _popcmp _sete ;

-- recognize and translate a relational "less or equal"
: lessorequal ( -- )  '=' match  expression _popcmp _setle ;

-- recognize and translate a relational "not equals"
: notequals   ( -- )  '>' match  expression _popcmp _setne ;

-- recognize and translate a relational "less than"
: less ( -- ) 
        '<' match 
        Look '=' = IF  lessorequal EXIT  ENDIF
        Look '>' = IF  notequals   EXIT  ENDIF
        expression _popcmp _setl ;

-- recognize and translate a relational "greater than"
: greater ( -- ) 
        '>' match  
        Look '=' = IF  '=' match expression _popcmp _setge EXIT  ENDIF
        expression _popcmp _setg ;

-- parse and translate a relation
: relation ( -- )
        expression
        Look relop? 0= ?EXIT
        _push
        CASE Look
          '=' OF  equals     ENDOF
          '<' OF  less       ENDOF
          '>' OF  greater    ENDOF
        ENDCASE ;

-- parse and translate a boolean factor with NOT
: notfactor ( -- )
        Look '!' <> IF  relation EXIT  ENDIF
        '!' match  relation _not ;

-- parse and translate a boolean term 
: boolterm ( -- )
        notfactor
        BEGIN   Look '&' = 
        WHILE   _push  '&' match  notfactor _popand
        REPEAT ;

-- Recognize and translate a boolean OR
: boolOR ( -- )  '|' match boolterm _popor ;

-- Recognize and translate an EXCLUSIVE OR
: boolXOR ( -- ) '~' match boolterm _popxor ;

-- Parse and translate a boolean expression 
:NONAME ( -- )
        boolterm
        BEGIN   Look orop?
        WHILE   _push
                CASE Look
                  '|' OF  boolOR  ENDOF
                  '~' OF  boolXOR ENDOF
                ENDCASE
        REPEAT ; IS boolexpression

-- Block statements -------------------------------------------------------------------------------------------------------

DEFER block

-- Parse and translate an assignment statement
: assignment ( -- )
        token$ COUNT DUP 1+ ALLOCATE ?ALLOCATE DUP LOCAL name PACK DROP
        '=' match 
        boolexpression
        name COUNT storevariable
        name FREE ?ALLOCATE ;

-- Recognize and translate an IF construct
: doIF ( label -- )
        0 0 LOCALS| L2 L1 L |
        boolexpression
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        L1 COUNT DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
        L1 COUNT _branch0
        L block
        token 'l' = IF  L2 FREE ?ALLOCATE
                        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP
                        L2 COUNT _branch
                        L1 COUNT postlabel
                        L block
                 ENDIF
        L2 COUNT postlabel
        S" ENDIF" matchstring

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;

: doWHILE ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP

        L1 COUNT postlabel
        boolexpression
        L2 COUNT _branch0
        L2 block
        L1 COUNT _branch
        L2 COUNT postlabel
        S" ENDWHILE" matchstring

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;

-- Parse and translate a loop statement
: doLOOP ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP

        L1 COUNT postlabel
        L2 block
        L1 COUNT _branch
        L2 COUNT postlabel
        S" ENDLOOP" matchstring

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;

-- Parse and translate a REPEAT statement 
: doREPEAT ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP

        L1 COUNT postlabel
        L2 block
        S" UNTIL" matchstring
        boolexpression
        L1 COUNT _branch0
        L2 COUNT postlabel

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;

-- Parse and translate a for statement 
: doFOR ( -- )
        0 0 0 LOCALS| name L2 L1 |
        getname  DUP 1+ ALLOCATE ?ALLOCATE DUP TO name PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1   PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2   PACK DROP

        '=' match  expression
        _decr
        name COUNT storevariable
        scan S" TO" matchstring  expression
        _push
        L1 COUNT postlabel
        name COUNT loadvariable
        _incr
        name COUNT storevariable
        L2 COUNT _pcmp+b0>
        L2 block
        L1 COUNT _branch
        L2 COUNT postlabel
        S" ENDFOR" matchstring
        _incSP

        name FREE ?ALLOCATE
        L1   FREE ?ALLOCATE 
        L2   FREE ?ALLOCATE ;

-- Parse and Translate a DO Statement
: doDO ( -- )
        0 0 LOCALS| L2 L1 |
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L1 PACK DROP
        newlabel DUP 1+ ALLOCATE ?ALLOCATE DUP TO L2 PACK DROP

        expression
        L1 COUNT postlabel
        _push
        L2 block
        _pop
        _decr
        L1 COUNT _branch<>0
        _decSP
        L2 COUNT postlabel
        S" ENDDO" matchstring
        _incSP 

        L1 FREE ?ALLOCATE 
        L2 FREE ?ALLOCATE ;

-- Recognize and translate a BREAK
: doBREAK ( label -- )
        DUP C@ 0= IF  S" No loop to break from" aborts  ENDIF
        COUNT _branch ;

-- Process a read statement 
: doread ( -- )
        '(' match
        getname readvar
        BEGIN  Look ',' = 
        WHILE  ',' match getname readvar
        REPEAT 
        ')' match ;

-- Process a write statement
: dowrite ( -- )
        '(' match 
        expression writevar
        BEGIN  Look ',' = 
        WHILE  ',' match expression writevar
        REPEAT 
        ')' match ;

-- Recognize and translate a statement block
:NONAME ( label -- )
        LOCAL L
        scan
        BEGIN  token 'e' <> 
               token 'l' <> AND
               token 'u' <> AND
        WHILE  CASE token
                'i' OF  L doIF    ENDOF
                'w' OF  doWHILE   ENDOF
                'd' OF  doDO      ENDOF
                'L' OF  doLOOP    ENDOF
                'r' OF  doREPEAT  ENDOF
                'f' OF  doFOR     ENDOF
                'B' OF  L doBREAK ENDOF
                'R' OF  doread    ENDOF
                'W' OF  dowrite   ENDOF
                        assignment
               ENDCASE
               scan
        REPEAT ; IS block

-- Declarations -----------------------------------------------------------------------------------------------------------

-- Allocate storage for a variable
: alloc ( c-addr u -- )
        LOCALS| sz addr |
        addr sz intable IF  S" Duplicate variable name " addr sz name.aborts  ENDIF
        addr sz 'v' addentry
        addr sz
        Look '=' = IF   '=' match 
                        Look '-' = IF   '-' match  
                                        S" -"  
                                 ELSE   S" "  
                                ENDIF
                        getnum (.) $+
                 ELSE   S" 0"
                ENDIF   allocatestorage ;

-- Parse and translate a data declaration 
: decl ( -- )
        getname alloc
        BEGIN  Look ',' =  
        WHILE  ',' match  getname alloc  
        REPEAT ;

-- Parse and translate the global declarations 
: topdecls ( -- )
        scan
        BEGIN   token 'b' <> 
        WHILE   CASE token
                 'v' OF decl  ENDOF
                     S" Unrecognized keyword " token$ COUNT name.aborts
                ENDCASE
                scan
        REPEAT ;

-- Parse and translate MAIN code
: doprogram ( -- )
        S" BEGIN" matchstring
        prolog
        C" " block
        S" END" matchstring
        epilog ;

-- Parse and translate a program ------------------------------------------------------------------------------------------
: prog ( -- )
        S" PROGRAM" matchstring 
        getname prog$ PACK DROP
        header
        topdecls
        doprogram
        '.' match ;

-- initialize
: init ( -- ) 
        CLEAR Lcount
        [cnt]ST    OFF
        [cnt]SType OFF
        CR getchar scan ; 

: TINY10 ( -- ) 
        init prog
        Look ^M <> IF  S" Unexpected data after " S" ." name.aborts  ENDIF ;

原文代码块 71

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

参考资料

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

← 返回列表
← 上一篇 A top view:从顶层组织 compiler 下一篇 → Lexical scan revisited:重新整理 Tiny compiler

评论 (0)

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