タイガーブック(3)

ml-lexのレキサーを書いていた。

github.com

この方のがとてもわかりやすいと思う。 これの 2 章。

tiger.lexを書く。

%s COMMENT

正確には%stateらしい。

COMMENTという状態をあらかじめ定義しておく。

var type function break of end in nil let
do to for while else then if array
:= | & >= > <= < <> = / * - + { } ( ) [ ] . , ; :
abcdefg
12345
"ABCDEFG"
/* comment has started */

こんな感じのtiger(作るプログラミング言語の名前)のソースコードらしきものを用意しておく。

tiger.lexを修正して、

% sml
Standard ML of New Jersey v110.85 [built: Sat Dec 22 16:51:02 2018]
- CM.make "sources.cm";
略
- Parse.parse "test.tig";
VAR   2
TYPE   6
FUNCTION   11
BREAK   20
OF   26
END   29
IN   33
NIL   36
LET   40
DO   44
TO   47
FOR   50
WHILE   54
ELSE   60
THEN   65
IF   70
ARRAY   73
ASSIGN   80
OR   83
AND   85
GE   87
GT   90
LE   92
LT   95
NEQ   97
EQ   100
DIVIDE   102
TIMES   104
MINUS   106
PLUS   108
LBRACE   110
RBRACE   112
LPAREN   114
RPAREN   116
LBRACK   118
RBRACK   120
DOT   122
COMMA   124
SEMICOLON   126
COLON   128
ID(abcdefg)     130
INT(12345)   138
STRING("ABCDEFG")     144
skipping comment
skipping comment c
skipping comment o
skipping comment m
skipping comment m
skipping comment e
skipping comment n
skipping comment t
skipping comment
skipping comment h
skipping comment a
skipping comment s
skipping comment
skipping comment s
skipping comment t
skipping comment a
skipping comment r
skipping comment t
skipping comment e
skipping comment d
skipping comment
EOF   179
val it = () : unit

これで字句解析ができてそうなことを確認できた。 tokens.smlに関数は、定義されているので、tiger.lexを完成させればいいだけ。