Procedures:procedure、parameter 与 local variable
LET'S BUILD A COMPILER!
作者:Jack W. Crenshaw, Ph.D.
原文部分:Part 13: PROCEDURE、PARAMETER 与 LOCAL VARIABLE
TL;DR
本篇围绕 procedure、parameter 与 local variable 展开,沿用前文的 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 方法。
ONE LAST DIGRESSION
Procedure 会引入 calling convention、stack frame、parameter semantics 和 scope。这些设计必须先明确,不能只增加一条 CALL instruction。
THE BASICS
Procedure declaration 创建 name、parameter 和 local-variable 的 symbol。Body 是独立 block,compiler 保存入口 label,并在结束处生成 return。
A BASIS FOR EXPERIMENTS
先实现没有 parameter 的 procedure:声明时输出 label,body 结束时输出 return,调用处输出 CALL。验证 control transfer 后再加入参数。
DECLARING A PROCEDURE
Declaration parser 读取 PROCEDURE、name、parameter list 与 body。Symbol table 要支持前置声明、递归调用以及 procedure/function 的区别。
CALLING THE PROCEDURE
Call parser 查找 procedure,检查 argument 数量,并按 calling convention 生成 argument code 与 CALL。Function 的 return value 通常通过 EAX 等约定位置返回。
PASSING PARAMETERS
参数可以通过 stack、register 或固定 memory 传递。Stack 对递归最灵活,但 caller 与 callee 必须共享一致的布局和清理规则。
THE SEMANTICS OF PARAMETERS
Argument 与 parameter 不是同一个对象。Compiler 必须区分传 value、传 address,还是传可修改的 storage reference。
PASS-BY-VALUE
Pass-by-value 在 call 时计算 argument 并复制 value。Callee 修改 parameter 不会改变 caller 的原始 variable。
WHAT'S WRONG?
只使用 pass-by-value 无法修改 caller 的 variable,也不适合复制大型 object。某些场景需要共享 storage。
CALL-BY-REFERENCE
Call-by-reference 传递 variable 的 address。Callee 通过 address 访问 caller storage,因此 assignment 会修改原 variable;parser 必须区分 lvalue 与普通 expression。
LOCAL VARIABLES
Local variable 属于一次 procedure invocation。递归调用不能共享固定 global storage,因此需要 stack frame,并通过 frame pointer 或 offset 定位。
CONCLUSION
Procedure 是从 expression/statement parser 走向完整 language 的关键一步。先确定 calling convention 与 parameter semantics,再实现 parser 和 code generator。
+### 原文代码块 1
<ident> = <ident>
原文代码块 2
-- ------------------------------------------------------------
-- Variable declarations --------------------------------------
0 VALUE Look -- lookahead character
CREATE ST #26 CHARS ALLOT -- symbol table
-- Get type of symbol
: typeof ( char -- ) 'A' - ST + C@ ;
-- Look for symbol in table
: intable ( char -- ) typeof 0<> ;
-- 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 BL = SWAP Tab = OR ; -- Recognize white space
: emits ( c-addr u -- ) Tab EMIT TYPE ; -- output a string with tab
: emitdln ( c-addr u -- ) CR TYPE ; -- output a string with crlf
: emitln ( c-addr u -- ) CR emits ; -- output a string with tab and crlf
-- Skip over EOL
: fin ( -- ) Look ^M = IF getchar Look ^J = IF getchar ENDIF ENDIF ;
-- Skip a comment field
: skipcomment RECURSIVE ( -- )
BEGIN Look '}' <>
WHILE getchar
Look '{' = IF skipcomment ENDIF
REPEAT getchar ;
-- Skip white space
: skipwhite ( -- )
BEGIN Look white?
WHILE Look '{' = IF skipcomment ELSE getchar ENDIF
REPEAT ;
-- Abort, reporting an offending item
: name.aborts ( c-addr1 u1 char )
S" " ROT CHAR-APPEND &' CHAR-APPEND S" `" 2SWAP $+ $+ aborts ;
: .undefined ( char -- ) >S S" Undefined identifier" S> name.aborts ;
: .duplicate ( char -- ) >S S" Duplicate identifier" S> name.aborts ;
-- Is identifier in the symbol table?
: checktable ( char -- )
DUP intable IF DROP EXIT ENDIF .undefined ;
-- Is identifier already in symbol table?
: checkdup ( char -- )
DUP intable 0= IF DROP EXIT ENDIF .duplicate ;
-- Add a new entry to symbol table
: addentry ( char type -- )
OVER checkdup
SWAP 'A' - ST + C! ;
: checkvar ( char -- )
DUP checktable
typeof 'v' <> IF >S S" ' is not a variable" S" `"
S> CHAR-APPEND 2SWAP $+ aborts
ENDIF ;
-- 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 ( -- char )
Look alpha? 0= IF S" Identifier" expected ENDIF
Look >UPC getchar skipwhite ;
-- Get a number
: getnum ( -- num )
Look digit? 0= IF S" Number" expected ENDIF
Look getchar skipwhite ;
-- Code generation --------------------------------------------
-- Load primary register from variable
: loadvariable ( char -- )
DUP checkvar
S" " ROT CHAR-APPEND S" dword-ptr -> eax mov," $+ emitln ;
-- Store primary register in variable
: storevariable ( char -- )
DUP checkvar
S" eax -> " ROT CHAR-APPEND S" dword-ptr mov," $+ emitln ;
-- Expressions ------------------------------------------------
-- Parse and translate an expression
: expression ( -- ) getname loadvariable ;
-- Parse and translate an assignment statement
: assignment ( -- ) getname >R '=' match expression R> storevariable ;
-- Block statements -------------------------------------------
: doblock ( -- ) BEGIN Look 'e' <> WHILE assignment fin REPEAT ;
: beginblock ( -- ) 'b' match fin doblock 'e' match fin ;
-- Declarations -----------------------------------------------
-- Allocate storage for a variable
: alloc ( char -- )
>R R@ 'v' addentry
S" CREATE " R> CHAR-APPEND S" 0 ," $+ emitdln ;
: decl ( -- ) 'v' match getname alloc ;
-- Parse and translate the global declarations
: topdecls ( -- )
BEGIN Look 'b' <>
WHILE CASE Look
'v' OF decl ENDOF
S" Unrecognized keyword" Look name.aborts
ENDCASE
fin
REPEAT ;
-- Parse and translate a program ------------------------------
-- Initialize everything
: init ( -- ) ST #26 ERASE CR getchar skipwhite ;
: calls ( -- ) init topdecls beginblock ;
-- ------------------------------------------------------------
原文代码块 3
va (for VAR A)
vb (for VAR B)
vc (for VAR C)
b (for BEGIN)
a=b
b=c
e. (for END.)
原文代码块 4
PROGRAM FOO;
.
.
PROCEDURE BAR; BAR:
BEGIN .
. .
. .
END; ret,
BEGIN { MAIN PROGRAM } MAIN:
. .
. .
BAR; BAR offset NEAR call,
. .
. .
END. END MAIN
原文代码块 5
<declaration> ::= <data decl> | <procedure>
原文代码块 6
<procedure> ::= PROCEDURE <ident> <begin-block>
原文代码块 7
-- ------------------------------------------------------------
-- Parse and translate a procedure declaration
: doProc ( -- )
'p' match
getname >R fin
R@ 'p' addentry
R> procheader
beginblock
_ret ;
-- ------------------------------------------------------------
原文代码块 8
'p' OF doProc ENDOF
原文代码块 9
doVars
doProcs
doMain
原文代码块 10
-- ------------------------------------------------------------
-- Parse and translate a main program
: doMain ( -- )
'b' match fin
prolog doBlock epilog ;
-- ------------------------------------------------------------
.
.
.
-- ------------------------------------------------------------
-- Main Program
: TINY ( -- ) init topdecls doMain ;
-- ------------------------------------------------------------
原文代码块 11
BEGIN { of MAIN }
原文代码块 12
<declaration> ::= <data decl> | <procedure> | <main program>
<procedure> ::= PROCEDURE <ident> <begin-block>
<main program> ::= PROGRAM <ident> <begin-block>
原文代码块 13
-- ------------------------------------------------------------
-- Parse and translate a main program
: doMain ( -- )
'P' match
getname prog$ char-place fin
prolog
beginblock ;
-- ------------------------------------------------------------
.
.
.
-- ------------------------------------------------------------
-- Parse and translate global declarations
: topdecls ( -- )
BEGIN Look '.' <>
WHILE CASE Look
'v' OF Decl ENDOF
'p' OF DoProc ENDOF
'P' OF DoMain ENDOF
S" Unrecognized keyword' Look name.aborts
ENDCASE
fin
REPEAT ;
-- ------------------------------------------------------------
-- Main Program
: TINY ( -- ) init topdecls epilog ;
-- ------------------------------------------------------------
原文代码块 14
<proc_call> ::= <identifier>
原文代码块 15
<assignment> ::= <identifier> '=' <expression>
原文代码块 16
-- ------------------------------------------------------------
-- Parse and translate an assignment statement
: assignment ( char -- )
>R
'=' match expression
R> storevariable ;
-- ------------------------------------------------------------
-- Decide if a statement is an assignment or procedure call
: assignorproc ( -- )
getname >R
CASE R@ typeof
0 OF R> .undefined ENDOF
'v' OF R> assignment ENDOF
'p' OF R> callproc ENDOF
S" Identifier " R> CHAR-APPEND
S" cannot be used here" $+ aborts
ENDCASE ;
-- ------------------------------------------------------------
-- Parse and translate a block of statements
: doBlock ( -- )
BEGIN Look 'e' <>
WHILE assignorproc
fin
REPEAT ;
-- ------------------------------------------------------------
原文代码块 17
-- --------------------------------------------------------------------
-- Call a procedure
: callproc ( char -- ) S" offset NEAR call, " ROT CHAR-PREPEND emitln ;
-- --------------------------------------------------------------------
原文代码块 18
PROCEDURE FOO(X, Y, Z)
原文代码块 19
<procedure> ::= PROCEDURE <ident>
'(' <param-list> ')' <begin-block>
<param_list> ::= <parameter> ( ',' <parameter> )* | null
原文代码块 20
<proc call> ::= <ident> '(' <param-list> ')'
原文代码块 21
initialize; ,
原文代码块 22
-- ------------------------------------------------------------
-- Process the formal parameter list of a procedure
: formallist ( -- )
'(' match
Look ')' <>
IF formalparam
BEGIN Look ',' =
WHILE ',' match formalparam
REPEAT
ENDIF
')' match ;
-- ------------------------------------------------------------
原文代码块 23
-- ------------------------------------------------------------
-- Parse and translate a procedure declaration
: doProc ( -- )
'p' match
getname >R
formallist
fin
R@ 'p' addentry
R> procheader
beginblock
_ret ;
-- ------------------------------------------------------------
原文代码块 24
-- ------------------------------------------------------------
-- Process a formal parameter
: formalparam ( -- ) getname DROP ;
-- ------------------------------------------------------------
原文代码块 25
-- ------------------------------------------------------------
-- Process an actual parameter
: param ( -- ) getname DROP ;
-- ------------------------------------------------------------
-- Process the actual parameter list for a procedure call
: paramlist ( -- )
'(' match
Look ')' <>
IF param
BEGIN Look ',' =
WHILE ',' match param
REPEAT
ENDIF
')' match ;
-- ------------------------------------------------------------
-- Process a procedure call
: callproc ( char -- )
paramlist _call ;
-- ------------------------------------------------------------
原文代码块 26
SUBROUTINE FOO(X, Y, N)
原文代码块 27
CALL FOO(A, B, J + 1)
原文代码块 28
K = J + 1
CALL FOO(A, B, K)
原文代码块 29
CALL FOO(A, B, 4)
原文代码块 30
FOO(X, Y)
原文代码块 31
X dword-ptr push, ; Push X
Y dword-ptr push, ; Push Y
FOO offset NEAR call, ; Call FOO
原文代码块 32
.
.
Value of X (4 bytes)
Value of Y (4 bytes)
return address (4 bytes)
ESP --> [ ..... ]
原文代码块 33
X: 8(SP)
Y: 4(SP)
原文代码块 34
PROCEDURE FOO(A, B)
BEGIN
A = B
END
原文代码块 35
FOO: [esp 4 +] -> eax mov,
eax -> [esp 8 +] mov,
ret,
原文代码块 36
CREATE params 26 CHARS ALLOT
原文代码块 37
0 VALUE #params
原文代码块 38
-- ------------------------------------------------------------
-- Initialize parameter table to null
: clearparams ( -- )
params 26 CHARS ERASE
CLEAR #params ;
-- ------------------------------------------------------------
原文代码块 39
-- ------------------------------------------------------------
-- Initialize
: init ( -- )
CLEAR Lcount
clearST
clearparams
CR getchar skipwhite ;
-- ------------------------------------------------------------
.
.
.
-- ------------------------------------------------------------
-- Parse and translate a procedure declaration
: doProc ( -- )
'p' match
getname >R
formallist
fin
R@ 'p' addentry
R> procheader
beginblock
_ret
clearparams ;
-- ------------------------------------------------------------
原文代码块 40
-- ------------------------------------------------------------
-- Find the parameter number
: paramnumber ( char -- u ) 'A' - params + C@ ;
-- ------------------------------------------------------------
-- See if an identifier is a parameter
: param? ( char -- tf ) 'A' - params + C@ 0<> ;
-- ------------------------------------------------------------
-- Add a new parameter to table
: addparam ( char -- )
DUP param? IF .duplicate ENDIF
1 +TO #params
#params SWAP 'A' - params + C! ;
-- ------------------------------------------------------------
原文代码块 41
-- ------------------------------------------------------------
-- Load a parameter to the primary register
: loadparameter ( index -- )
#params SWAP - 1+ CELLS ( offset ) >R
S" [esp " R> (.) $+ S" +] -> eax mov," $+ emitln ;
-- ------------------------------------------------------------
-- Store a parameter from the primary register
: storeparameter ( index -- )
#params SWAP - 1+ CELLS ( offset ) >R
S" eax -> [esp " R> (.) $+ S" +] mov," $+ emitln ;
-- ------------------------------------------------------------
-- Push the primary register to the stack
: _push ( -- ) S" eax push," emitln ;
-- ------------------------------------------------------------
原文代码块 42
-- ------------------------------------------------------------
-- Process a formal parameter
: formalparam ( -- ) getname addparam ;
-- ------------------------------------------------------------
原文代码块 43
-- ------------------------------------------------------------------
-- Get type of symbol
: typeof ( char -- ) DUP param? IF DROP 'f' ELSE ST[n] C@ ENDIF ;
-- ------------------------------------------------------------------
原文代码块 44
-- ------------------------------------------------------------
-- Decide if a statement is an assignment or procedure call
: assignorproc ( -- )
getname >R
CASE R@ typeof
0 OF R> .undefined ENDOF
'v' OF R> assignment ENDOF
'f' OF R> assignment ENDOF
'p' OF R> callproc ENDOF
S" Identifier `" R> CHAR-APPEND
S" ' cannot be used here" $+ aborts
ENDCASE ;
-- ------------------------------------------------------------
原文代码块 45
-- ------------------------------------------------------------
-- Parse and translate an expression
-- Vestigial version
getname
DUP param? IF paramnumber loadparameter
ELSE loadvariable
ENDIF ;
-- ------------------------------------------------------------
-- Parse and translate an assignment statement
: assignment ( char -- )
>R '=' match expression R>
DUP param? IF paramnumber storeparameter
ELSE storevariable
ENDIF ;
-- ------------------------------------------------------------
原文代码块 46
-- ------------------------------------------------------------
-- Process an actual parameter
: param ( -- ) expression _push ;
-- ------------------------------------------------------------
原文代码块 47
-- ------------------------------------------------------------
-- Process the parameter list for a procedure call
: paramlist ( -- #bytes )
0 LOCAL N
'(' match
Look ')' <>
IF param 1 +TO N
BEGIN Look ',' =
WHILE ',' match param 1 +TO N
REPEAT
ENDIF
')' match
N CELLS ;
-- ------------------------------------------------------------
Procedure
CallProc
then uses this to clean up the stack:
-- ------------------------------------------------------------
-- Process a procedure call
: callproc ( char -- ) paramlist >R _call R> _cleanstack ;
-- ------------------------------------------------------------
原文代码块 48
-- ------------------------------------------------------------
-- Adjust the stack pointer upwards by n bytes
: _cleanstack ( #bytes -- )
?DUP IF (.) S" d# -> esp add," $+ emitln ENDIF ;
-- ------------------------------------------------------------
原文代码块 49
PROCEDURE FOO(A, B)
BEGIN
A = A + B
END
原文代码块 50
FOO: [esp 8 +] -> eax mov, ; fetch a
eax push, ; push it
[esp 4 +] -> eax mov, ; fetch b
[esp] -> eax add, ; add a
eax -> [esp 8 +] mov, ; store a
ret,
原文代码块 51
FOO: 0 0 enter,
[ebp 12 +] -> eax mov, ; fetch a
eax push, ; push it
[ebp 8 +] -> eax mov, ; fetch b
[esp] -> eax add, ; add a
eax -> [ebp 12 +] mov, ; store a
leave,
ret,
原文代码块 52
-- ------------------------------------------------------------
-- Write the prolog for a procedure
: procprolog ( char -- )
S" SUBROUTINE " ROT CHAR-APPEND emitdln
S" 0 0 enter," emitln ;
-- ------------------------------------------------------------
-- Write the epilog for a procedure
: procepilog ( -- )
S" leave," emitln
S" ret," emitln ;
-- ------------------------------------------------------------
原文代码块 53
-- ------------------------------------------------------------
-- Parse and translate a procedure declaration
: doProc ( -- )
'p' match
getname >R
formallist
fin
R@ 'p' addentry
R> procprolog
beginblock
procepilog
clearparams ;
-- ------------------------------------------------------------
原文代码块 54
-- ------------------------------------------------------------
-- Load a parameter to the primary register
: loadparameter ( index -- )
#params SWAP - 2+ CELLS ( offset ) >R
S" [ebp " R> (.) $+ S" +] -> eax mov," $+ emitln ;
-- ------------------------------------------------------------
-- Store a parameter from the primary register
: storeparameter ( index -- )
#params SWAP - 2+ CELLS ( offset ) >R
S" eax -> [ebp " R> (.) $+ S" +] mov," $+ emitln ;
-- ------------------------------------------------------------
原文代码块 55
FOO(X, Y)
原文代码块 56
X d# push, ; Push the address of X
Y d# push, ; Push the address of Y
FOO offset NEAR call, ; Call FOO
原文代码块 57
-- ------------------------------------------------------------
-- Process an actual parameter
: param ( -- ) S" d# push," getname CHAR-PREPEND emitln ;
-- ------------------------------------------------------------
原文代码块 58
FOO: 0 0 enter,
[ebp 12 +] -> eax mov, ; fetch address of A
[eax] -> eax mov, ; fetch A
eax push, ; push it
[ebp 8 +] -> eax mov, ; fetch address of B
[eax] -> eax mov, ; fetch B
[esp] -> eax add,
[ebp 12 +] -> ebx mov, ; get address of A
eax -> [ebx] mov, ; store A
leave,
ret,
原文代码块 59
-- ------------------------------------------------------------
-- Load a parameter to the primary register
: loadparameter ( index -- )
#params SWAP - 2+ CELLS ( offset ) >R
S" [ebp " R> (.) $+ S" +] -> ebx mov," $+ emitln
S" [ebx] -> eax mov," emitln ;
-- ------------------------------------------------------------
-- Store a parameter from the primary register
: storeparameter ( index -- )
#params SWAP - 2+ CELLS ( offset ) >R
S" [ebp " R> (.) $+ S" +] -> ebx mov," $+ emitln
S" eax -> [ebx] mov," emitln ;
-- ------------------------------------------------------------
原文代码块 60
[ebp 8 +] -> eax mov,
原文代码块 61
X dword-ptr -> eax mov, .
原文代码块 62
0 VALUE lbase
原文代码块 63
-- ------------------------------------------------------------
-- Load a parameter to the primary register
: loadparameter ( index -- )
lbase SWAP - 2+ CELLS ( offset ) >R
S" [ebp " R> (.) $+ S" +] -> eax mov," $+ emitln ;
-- ------------------------------------------------------------
-- Store a parameter from the primary register (call by value)
: storeparameter ( index -- )
lbase SWAP - 2+ CELLS ( offset ) >R
S" eax -> [ebp " R> (.) $+ S" +] mov," $+ emitln ;
-- ------------------------------------------------------------
原文代码块 64
-- ------------------------------------------------------------
-- Process the formal parameter list of a procedure
: formallist ( -- )
'(' match
Look ')' <>
IF formalparam
BEGIN Look ',' =
WHILE ',' match formalparam
REPEAT
ENDIF
')' match fin
#params TO lbase
2 +TO #params ;
-- ------------------------------------------------------------
原文代码块 65
-- ------------------------------------------------------------
-- Parse and translate a local data declaration
: locdecl ( -- ) 'v' match getname addparam fin ;
-- ------------------------------------------------------------
-- Parse and translate local declarations
: locdecls ( -- n )
0
BEGIN Look 'v' =
WHILE locdecl 1+
REPEAT ;
-- ------------------------------------------------------------
原文代码块 66
-- ------------------------------------------------------------
-- Parse and translate a procedure declaration
: doProc ( -- )
'p' match
getname >R
R@ 'p' addentry
formallist
locdecls ( #formals )
R> SWAP ( name #formals ) procprolog
beginblock
procepilog
clearparams ;
-- ------------------------------------------------------------
原文代码块 67
-- ------------------------------------------------------------
-- Write the prolog for a procedure
: procprolog ( char #formals -- )
>R S" SUBROUTINE " ROT CHAR-APPEND emitdln
R> CELLS (.) S" 0 enter," $+ emitln ;
-- ------------------------------------------------------------
原文代码块 68
*****************************************************************
* *
* COPYRIGHT NOTICE *
* *
* Copyright (C) 1989 Jack W. Crenshaw. All rights reserved. *
* *
*****************************************************************
参考资料
版权说明:原文页面标注 Copyright (C) 1988 Jack W. Crenshaw. All rights reserved.
评论 (0)