1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
|
fun $ (x, y) = x y
infixr 0 $
fun printLn s = (print s; print "\n")
datatype token =
Invalid |
Number of string |
Id of string |
CharConst of string * int |
kwBreak |
kwCase |
kwChar |
kwConst |
kwContinue |
kwDefault |
kwDouble |
kwElse |
kwEnum |
kwExtern |
kwFloat |
kwFor |
kwGoto |
kwInt |
kwLong |
kwRegister |
kwReturn |
kwShort |
kwSigned |
kwSizeof |
kwStruct |
kwSwitch |
kwTypedef |
kwUnion |
kwUnsigned |
kwVoid |
kwVolatile |
OParen |
CParen |
Plus |
DoublePlus|
Minus |
DoubleMinus |
Semicolon |
EqualSign |
DoubleEqualSign |
ExclMark |
ExclMarkEqualSign |
QuestionMark |
Colon |
Hash |
DoubleHash |
CppInclude |
CppDefine
val kwPrefix = #"@"
val cppPrefix = #"$"
val tokenRepr =
let
fun & repr = str kwPrefix ^ repr
fun % repr = str cppPrefix ^ repr
in
[
(OParen, "("),
(CParen, ")"),
(kwBreak, &"break"),
(kwCase, &"case"),
(kwChar, &"char"),
(kwConst, &"const"),
(kwContinue, &"continue"),
(kwDefault, &"default"),
(kwDouble, &"double"),
(kwElse, &"else"),
(kwEnum, &"enum"),
(kwExtern, &"extern"),
(kwFloat, &"float"),
(kwFor, &"for"),
(kwGoto, &"goto"),
(kwInt, &"int"),
(kwLong, &"long"),
(kwRegister, &"register"),
(kwReturn, &"return"),
(kwShort, &"short"),
(kwSigned, &"signed"),
(kwSizeof, &"sizeof"),
(kwStruct, &"struct"),
(kwSwitch, &"switch"),
(kwTypedef, &"typedef"),
(kwUnion, &"union"),
(kwUnsigned, &"unsigned"),
(kwVoid, &"void"),
(kwVolatile, &"volatile"),
(Plus, "+"),
(DoublePlus, "++"),
(Minus, "-"),
(DoubleMinus, "--"),
(Semicolon, ";"),
(EqualSign, "="),
(DoubleEqualSign, "=="),
(ExclMark, "!"),
(ExclMarkEqualSign, "!="),
(QuestionMark, "?"),
(Colon, ":"),
(Hash, "#"),
(DoubleHash, "##"),
(CppInclude, % "include"),
(CppDefine, % "define")
]
end
exception TokenWithoutRepr
val printToken = fn
(Number s) => printLn $ "Num: " ^ s
| (Id s) => printLn $ "Id: " ^ s
| (CharConst (repr, _)) => printLn repr
| v =>
case List.find (fn (x, _) => x = v) tokenRepr of
SOME (_, repr) => printLn repr
| NONE => raise TokenWithoutRepr
type fileId = int
type fileOffset = int
type pos = fileId * fileOffset
type fullToken = pos * token
type stream = {
(* list of file ids, file names and file contents *)
allFiles: (fileId * string * string) list,
(* stack of file ids, file offsets and file contents *)
stack: (fileId * fileOffset * string) list
}
exception EndOfStream
exception EndOfFile
exception InvalidStream
exception InvalidStreamAdvance
fun calcFilePos s offset =
let
fun calc s cur offset (line, col) =
if cur = offset then
(line, col)
else
calc s (cur + 1) offset
(if String.sub (s, cur) = #"\n" then (line + 1, 1)
else (line, col + 1))
in
calc s 0 offset (1, 1)
end
fun printPos fileList (id, pos) =
let
val triple = List.find (fn (fid, _, _) => fid = id) fileList
in
case triple of
NONE => raise InvalidStream
| SOME (_, fname, contents) =>
let
val (line, col) = calcFilePos contents pos
val line = Int.toString line
val col = Int.toString col
in
print $ fname ^ ":" ^ line ^ ":" ^ col ^ ": "
end
end
fun readFile fname =
let
open TextIO
val h = openIn fname
val s = inputAll h
val () = closeIn h
in
s
end
fun getchar
({ stack = (id, off, contents) :: rest, allFiles }: stream)
: (char * stream) =
if off < String.size contents then
(String.sub (contents, off),
{ stack = (id, off + 1, contents) :: rest, allFiles })
else
raise EndOfFile
| getchar _ = raise EndOfStream
fun ungetc
({ stack = (id, off, contents) :: rest, allFiles }) =
if off = 0 then
raise InvalidStream
else
{ stack = (id, off - 1, contents) :: rest, allFiles }
| ungetc _ = raise InvalidStream
fun getOffset ({ stack = (_, off, _) :: _, ... }: stream) = off
| getOffset _ = raise InvalidStream
fun getPosAfterCharRead
({ stack = (id, off, _) :: _, ... }: stream) = (id, off - 1)
| getPosAfterCharRead _ = raise InvalidStream
fun getPos ({ stack = (id, off, _) :: _, ... }: stream) = (id, off)
| getPos _ = raise InvalidStream
fun getSubstr startOff endOff
({ stack = (_, _, contents) :: _, ... }: stream) =
String.substring (contents, startOff, endOff - startOff)
| getSubstr _ _ _ = raise InvalidStream
fun advanceToNewFile
({ stack = (_, off, contents) :: rest, allFiles }: stream) =
if off = String.size contents then
{ stack = rest, allFiles }
else
raise InvalidStreamAdvance
| advanceToNewFile _ = raise InvalidStreamAdvance
fun streamInit fname =
let
val contents = readFile fname
in
{ allFiles = [(0, fname, contents)], stack = [(0, 0, contents)] }
end
fun isSpace c = c = #" " orelse c = #"\t" orelse c = #"\n"
fun isLetter c =
ord c >= ord #"a" andalso ord c <= ord #"z" orelse
ord c >= ord #"A" andalso ord c <= ord #"Z"
fun isIdStart c = c = #"_" orelse isLetter c
fun isDigit c = ord c >= ord #"0" andalso ord c <= ord #"9"
fun isIdBody c = isIdStart c orelse isDigit c
(* FSM for parsing symbols *)
val maxStates = 16
exception FsmTableIsTooSmall
exception FsmTableIsTooLarge of int
fun fsmInsert (nextState, buf) curState tk (c :: cs) =
let
open Array
val (_, row) = sub (buf, curState)
val potNextState = sub (row, ord c)
in
if potNextState <> ~1 then
fsmInsert (nextState, buf) potNextState tk cs
else (
update (row, ord c, !nextState);
nextState := !nextState + 1;
fsmInsert (nextState, buf) (!nextState - 1) tk cs
)
end
| fsmInsert (_, buf) curState tk [] =
let
open Array
val (_, row) = sub (buf, curState)
in
update (buf, curState, (tk, row))
end
fun isStartForFsmGen () =
let
open Array
val lookupTable = array (128, false)
fun firstChr s = ord $ String.sub (s, 0)
val () = List.app
(fn (_, repr) => update (lookupTable, firstChr repr, true))
$ List.filter
(fn (_, repr) =>
let
val c = String.sub (repr, 0)
in
c <> kwPrefix andalso c <> cppPrefix
end)
tokenRepr
in
fn c => sub (lookupTable, ord c)
end
val isStartForFsm = isStartForFsmGen ()
fun fsmTableCreate () =
let
open Array
val T as (nextState, buf) =
(ref 1, array (maxStates, (Invalid, array (128, ~1))))
val r = ref 1
fun filterNeeded [] acc = acc
| filterNeeded ((T as (tk, repr)) :: tks) acc =
filterNeeded tks
(if isStartForFsm $ String.sub (repr, 0) then
(printToken tk; T :: acc)
else
acc)
val tokenRepr = filterNeeded tokenRepr []
fun fsmInsert' T curState tk repr = fsmInsert T curState tk repr handle
Subscript => raise FsmTableIsTooSmall
in
while !r < length buf do (
update (buf, !r, (Invalid, array(128, ~1)));
r := !r + 1
);
List.app (fn (v, p) => fsmInsert' T 0 v $ explode p) tokenRepr;
if !nextState <> maxStates then
raise FsmTableIsTooLarge $ !nextState
else ();
T
end
val fsmTable = fsmTableCreate ()
fun fsmEat stream =
let
open Array
val stream = ungetc stream
val pos = getPos stream
fun get curState stream =
let
val (c, stream) = (fn (c, s) => (SOME c, s)) $ getchar stream handle
_ => (NONE, stream)
in
case c of
NONE => (#1 $ sub (#2 fsmTable, curState), stream)
| SOME c =>
let
val (tk, row) = sub (#2 fsmTable, curState)
val nextState = sub (row, ord c)
in
if nextState = ~1 then
(tk, ungetc stream)
else
get nextState stream
end
end
in
(fn (tk, stream) => ((pos, tk), stream)) $ get 0 stream
end
exception UnexpectedCharacter of char
fun isFirstOnLine (tk: fullToken) (stream: stream) =
let
val (id, offset) = #1 tk
in
case List.find (fn (fid, _, _) => id = fid) (#allFiles stream) of
NONE => raise InvalidStream
| SOME (_, _, contents) =>
let
fun returnToNL ~1 = true
| returnToNL offset =
let
val chr = String.sub (contents, offset)
in
if chr = #"\n" then
true
else if isSpace chr then
returnToNL (offset - 1)
else
false
end
in
returnToNL (offset - 1)
end
end
fun parseGeneric stream parser acc =
let
val stream = ungetc stream
val P as (_, startOff) = getPos stream
fun parse' stream acc = let
val (c, stream) = (fn (c, s) => (SOME c, s)) $ getchar stream handle
_ => (NONE, stream)
val (acc, tk, stream) = parser acc (stream, startOff) c
in
case tk of
NONE => parse' stream acc
| _ => (valOf tk, stream)
end
val (tk, stream) = parse' stream acc
in
((P, tk): fullToken, stream)
end
fun finishSeqRead startOff stream =
let
val (_, endOff) = getPos stream
val s = getSubstr startOff endOff stream
in
s
end
fun findKeyword s =
case List.find
(fn (_, repr) =>
String.sub (repr, 0) = kwPrefix andalso
String.extract (repr, 1, NONE) = s)
tokenRepr
of
SOME (tk, _) => tk
| NONE => Id s
fun idParser () (stream, startOff) c =
let
fun finalize stream =
let
val s = finishSeqRead startOff stream
val tk = findKeyword s
in
((), SOME tk, stream)
end
in
case c of
NONE => finalize stream
| SOME c =>
if isIdBody c then
((), NONE, stream)
else
finalize (ungetc stream)
end
val formCppDirExn = Fail $ "Expected cpp direcive\n"
fun formCppDir (Id s) tkl =
let
open String
fun conv tk = ((#1 $ hd tkl, tk) :: tl tkl)
in
case List.find
(fn (_, repr) =>
sub (repr, 0) = cppPrefix andalso
extract (repr, 1, NONE) = s)
tokenRepr
of
SOME (tk, _) => conv tk
| NONE => raise formCppDirExn
end
| formCppDir _ _ = raise formCppDirExn
fun numParser () (stream, startOff) c =
let
fun finalize stream =
((), SOME $ Number (finishSeqRead startOff stream), stream)
in
case c of
NONE => finalize stream
| SOME c =>
if isDigit c then
((), NONE, stream)
else
finalize (ungetc stream)
end
exception IncompleteEsqSeq
fun eatEscSeq stream =
let
val (c, stream) = getchar stream handle
_ => raise IncompleteEsqSeq
in
(case c of
#"\\" => #"\\"
| #"t" => #"\t"
| #"n" => #"\n"
| c => c,
stream)
end
datatype CharParseState = ChInit | ChStart | ChValue of int | ChTerm
exception CharConstExn of string
val chExnExpValue = CharConstExn "expected value after '"
val chExnExpTerm = CharConstExn "expected ' after value"
val chExnStart = CharConstExn "can not start parsing (unreachable)"
val chExnAfterTerm = CharConstExn "can not finish parsing (unreachable)"
fun charParser ChInit (stream, _) (SOME c) =
if c = #"'" then
(ChStart, NONE, stream)
else
raise chExnStart
| charParser ChStart (stream, _) (SOME c) =
if c <> #"'" then
let
val (c, stream) =
if c <> #"\\" then (c, stream) else eatEscSeq stream
in
(ChValue $ ord c, NONE, stream)
end
else
raise chExnExpValue
| charParser (ChValue v) (stream, startOff) (SOME c) =
if c = #"'" then
(ChTerm,
SOME $ CharConst (finishSeqRead startOff stream, v), stream)
else
raise chExnExpTerm
| charParser ChTerm _ (SOME _) =
raise chExnAfterTerm
| charParser state (_, _) NONE =
raise case state of
ChInit => chExnStart
| ChStart => chExnExpValue
| ChValue _ => chExnExpTerm
| ChTerm => chExnAfterTerm
fun tokenize stream tkl =
let
fun getcharSkipEof stream = getchar stream handle
EndOfFile => getcharSkipEof (advanceToNewFile stream)
val (c, stream) = (fn (c, s) => (SOME c, s)) $ getcharSkipEof stream
handle
EndOfStream => (NONE, stream)
fun cont (tk, stream) = tokenize stream (tk :: tkl)
fun @-> parser acc = cont $ parseGeneric stream parser acc
in
case c of
NONE => (rev tkl, #allFiles stream)
| SOME c =>
if isSpace c then
tokenize stream tkl
else if isIdStart c then
let
val isCppDir = (fn Hash => true | _ => false) (#2 $ hd tkl)
handle Empty => false
val (tk, stream) = parseGeneric stream idParser ()
in
tokenize stream
(if isCppDir then (formCppDir (#2 tk) tkl) else (tk :: tkl))
end
else if isDigit c then
@-> numParser ()
else if c = #"'" then
@-> charParser ChInit
else if isStartForFsm c then
cont $ fsmEat stream
else
raise UnexpectedCharacter c
end
fun main [fname] =
let
val stream = streamInit fname
val (tkl, fileList) = tokenize stream []
in
List.app (fn (p, x) => (printPos fileList p; printToken x)) tkl
end
| main _ = printLn "Expected a signle argument: file name"
val () = main $ CommandLine.arguments ()
|