-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.fs
More file actions
634 lines (542 loc) · 21.7 KB
/
Copy pathParser.fs
File metadata and controls
634 lines (542 loc) · 21.7 KB
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
module Parser
type ParserState =
{ Line: int
Column: int
Tokens: Lexer.TokenType list }
type Root = ASTNode list
and GoImport =
{ ModuleName: string
Alias: string option }
and GoferImport = { ModuleName: string }
and LogicBlock = ASTNode list
and RecordField = Identifier * TypeDeclaration
and RecordDefinition = { Fields: RecordField list }
and RecordLiteral = (Identifier * ASTNode) list
and Identifier =
{ Name: string
Mutable': bool
Public': bool }
and TypedIdentifier =
{ Name: string
Type: TypeDeclaration
Mutable': bool
Public': bool }
and IdentifierType =
| Identifier of Identifier
| TypedIdentifier of TypedIdentifier
| ArrayDestructure of Identifier list
| RecordDestructure of Identifier list
| TupleDestructure of Identifier list
and TypeDeclaration =
{ Name: string
Module: string option
Pointer: bool
Slice: bool }
and LetStatement =
{ Left: IdentifierType; Right: ASTNode }
and AssignStatement = { Left: ASTNode; Right: ASTNode }
and Assignment =
| Let of LetStatement
| Assign of AssignStatement
and Assign = { Left: ASTNode; Right: ASTNode }
and ScopedFunctionArg =
{ Name: string
Type: string
ScopedName: string }
and FunctionArg =
| ScopedArg of ScopedFunctionArg
| TypedArg of TypedIdentifier
| Arg of Identifier
| Null
and FunctionDefinition =
{ Name: string
Args: FunctionArg list
ReturnType: TypeDeclaration option
Body: ASTNode
Struct: (string * ASTNode) option }
and FunctionCall = { Name: string; Args: ASTNode list }
and ASTNode =
| Root of Root
| GoImport of GoImport
| Import of GoferImport
| FuncDef of FunctionDefinition
| FunctionStatement of FunctionDefinition // Top level function definitions
| AssignmentStatement of Assignment
| Block of LogicBlock
| AssignExpression of Assign
| IndexExpression of ASTNode
| TypeLiteral of TypeDeclaration
| TypeDefinition of string * ASTNode
| ParenExpression of ASTNode
| ArrayLiteral of ASTNode list
| RecordLiteral of RecordLiteral
| TupleLiteral of TypeDeclaration list
| RecordType of RecordDefinition
| PubDeclaration of ASTNode
| StringLiteral of string
| NumberLiteral of string
| PipeExpression of ASTNode list
| IdentifierLiteral of IdentifierType
| ReturnExpression of ASTNode option
| FunctionCallExpression of FunctionCall
| NoOp
type ParseDelimiter =
| FuncDelim of (Lexer.TokenType list -> bool)
| NoDelimiter
let filterNoOp x =
match x with
| NoOp -> false
| _ -> true
let unexpectedTokenError token =
match token with
| Some t ->
let msg = $"Unexpected token: {t}"
Error msg
| None -> Error "Unexpected end of input"
exception ParseException of (Option<Lexer.TokenType> * int * int * string)
let raiseParserError state msg =
raise (
ParseException(
(List.tryHead state.Tokens),
state.Line,
state.Column,
$"Parse error: {msg} at line {state.Line} column {state.Column}"
)
)
let updateState (token: Lexer.Token) tokens =
{ Line = token.Line
Column = token.Column
Tokens = tokens }
let rec ignoreNewlines tokens =
match tokens with
| [] -> []
| Lexer.NewLine _ :: tail -> ignoreNewlines tail
| _ -> tokens
let rec parseImport state =
match state.Tokens with
| Lexer.String x :: Lexer.NewLine _ :: tail -> (updateState x tail), GoImport { ModuleName = x.Value; Alias = None }
| Lexer.Identifier x :: Lexer.String y :: Lexer.NewLine tok :: tail ->
(updateState tok tail),
GoImport
{ ModuleName = x.Value
Alias = Some y.Value }
| Lexer.Identifier x :: Lexer.NewLine tok :: tail -> (updateState tok tail), Import { ModuleName = x.Value }
| _ -> raiseParserError state "Invalid import statement"
and parseParenExpression state =
let delim =
FuncDelim(fun x ->
match x with
| Lexer.RParen _ :: _ -> true
| _ -> false)
parseTree state delim
and parseBraceExpression state =
match ignoreNewlines state.Tokens with
| Lexer.Identifier _ :: Lexer.Colon _ :: _ -> parseRecord state []
| _ ->
let delim =
FuncDelim(fun x ->
match x with
| Lexer.RBrace _ :: _ -> true
| _ -> false)
let newState, nodes = recParseTree state delim []
newState, Block nodes
and [<TailCall>] parseRecord state properties =
match ignoreNewlines state.Tokens with
| [] -> state, RecordLiteral properties
| Lexer.Comma x :: tail -> parseRecord (updateState x tail) properties
| Lexer.RBrace x :: tail' -> (updateState x tail'), RecordLiteral properties
| Lexer.Identifier x :: Lexer.Colon y :: tail ->
let newState, node = matchToken <| updateState y tail
parseRecord
newState
(({ Name = x.Value
Mutable' = false
Public' = false },
node)
:: properties)
| _ -> raiseParserError state "Invalid record literal"
and parseRecordType state' =
let checkForComma previousWasComma property =
match previousWasComma, property with
| false, Some _ -> true
| _ -> false
let rec parse previousWasComma state fields =
match state.Tokens with
| [] -> state, List.rev fields
| Lexer.NewLine x :: remaining -> parse previousWasComma (updateState x remaining) fields
| Lexer.Comma x :: remaining ->
if checkForComma previousWasComma (List.tryHead fields) then
parse true (updateState x remaining) fields
else
raiseParserError state "Unexpected comma parsing record type"
| Lexer.RBrace x :: tail -> ((updateState x tail), (List.rev fields))
| Lexer.Pub _ :: Lexer.Identifier x :: Lexer.Colon _ :: remaining ->
let newState, t = parseTypeLiteral <| updateState x remaining
parse false newState
<| ({ Name = x.Value
Mutable' = false
Public' = true },
t)
:: fields
| Lexer.Pub _ :: Lexer.Mut _ :: Lexer.Identifier x :: Lexer.Colon _ :: remaining ->
let newState, t = parseTypeLiteral <| updateState x remaining
parse false newState
<| ({ Name = x.Value
Mutable' = true
Public' = true },
t)
:: fields
| Lexer.Mut _ :: Lexer.Identifier x :: Lexer.Colon _ :: remaining ->
let newState, t = parseTypeLiteral <| updateState x remaining
parse false newState
<| ({ Name = x.Value
Mutable' = true
Public' = false },
t)
:: fields
| Lexer.Identifier head :: Lexer.Colon _ :: remaining ->
let newState, typeDec = parseTypeLiteral <| updateState head remaining
parse
false
newState
(({ Name = head.Value
Mutable' = false
Public' = false },
typeDec)
:: fields)
| _ ->
printfn "Tokens: %A\n\n" <| state.Tokens
raiseParserError state "Invalid record type"
parse false state' []
and parseTupleLiteral state items =
match state.Tokens with
| Lexer.RParen x :: tail -> (updateState x tail), TupleLiteral items
| _ -> raiseParserError state "Not implemented"
and parseTypeLiteral state =
let (isSlice, tail') =
match state.Tokens with
| Lexer.LBracket _ :: Lexer.RBracket _ :: tail' -> true, tail'
| _ -> false, state.Tokens
let (isPointer, tail'') =
match tail' with
| Lexer.Deref _ :: tail'' -> true, tail''
| _ -> false, tail'
match tail'' with
| Lexer.Identifier x :: Lexer.Dot _ :: Lexer.Identifier y :: remaining ->
((updateState y remaining),
{ Name = x.Value
Module = Some(y.Value)
Pointer = isPointer
Slice = isSlice })
| Lexer.Identifier x :: Lexer.Comma _ :: remaining
| Lexer.Identifier x :: remaining ->
((updateState x remaining),
{ Name = x.Value
Module = None
Pointer = isPointer
Slice = isSlice })
| _ -> raiseParserError state "Invalid type declaration"
and parseTypeDec ident state =
match ignoreNewlines state.Tokens with
| Lexer.LBrace x :: tail' ->
let newState, typeDecs = parseRecordType (updateState x tail')
newState, TypeDefinition(ident, RecordType { Fields = typeDecs })
| _ ->
let newState, t = parseTypeLiteral state
newState, TypeDefinition(ident, TypeLiteral t)
and parseArrayLiteral state =
let delim =
FuncDelim(fun x ->
match x with
| Lexer.RBracket _ :: _ -> true
| _ -> false)
let newState, nodes = recParseTree state delim []
(newState, ArrayLiteral nodes)
and parseFunctionArgs state =
let rec parse' previousWasComma mut state args =
match (state.Tokens, (previousWasComma || (List.length args) < 1)) with
| Lexer.RParen x :: tail, _ -> (updateState x tail), args
| Lexer.Mut x :: tail, true -> parse' previousWasComma true (updateState x tail) args
| Lexer.Identifier x :: Lexer.Colon _ :: tail, true ->
let newState, t = parseTypeLiteral <| updateState x tail
parse' false false newState
<| TypedArg
{ Name = x.Value
Type = t
Mutable' = mut
Public' = false }
:: args
| Lexer.Identifier x :: tail, true ->
parse' false false (updateState x tail)
<| Arg
{ Name = x.Value
Mutable' = mut
Public' = false }
:: args
| Lexer.Comma x :: tail, false -> parse' true false (updateState x tail) args
| _ -> raiseParserError state "Invalid function argument"
parse' false false state []
and parseStructMethodDefinition state =
match state.Tokens with
| Lexer.Identifier x :: tail ->
let newState, t = parseTypeDec x.Value <| updateState x tail
let newState' =
{ newState with
Tokens =
match newState.Tokens with
| Lexer.RParen _ :: tail -> tail
| _ -> raiseParserError newState "Invalid struct method definition" }
newState', (x.Value, t)
| _ -> raiseParserError state "Invalid struct method definition"
and parseFunction state =
let matchReturnType state =
match state.Tokens with
| Lexer.ReturnType x :: tail ->
parseTypeLiteral <| updateState x tail
||> fun newState returnType -> newState, Some returnType
| _ -> state, None
let rec parse' structInfo state =
match state.Tokens with
| Lexer.LParen x :: tail ->
try
let newState, structInfo = parseStructMethodDefinition <| updateState x tail
parse' (Some structInfo) newState
with ParseException _ ->
match structInfo with
| Some _ -> raiseParserError state "Invalid struct method definition"
| None ->
let newState, args = parseFunctionArgs <| updateState x tail
let newState', returnType = matchReturnType newState
match newState'.Tokens with
| Lexer.LBrace x :: tail' ->
parseBraceExpression <| updateState x tail'
||> fun newState' body ->
newState',
FuncDef
{ Name = ""
Args = List.rev args
ReturnType = returnType
Body = body
Struct = None }
| _ -> raiseParserError newState "Invalid function definition"
| Lexer.Identifier x :: Lexer.LParen _ :: tail ->
let newState, args = parseFunctionArgs <| updateState x tail
let newState', returnType = matchReturnType newState
match newState'.Tokens with
| Lexer.LBrace brace :: tail' ->
let newState', body = parseBraceExpression <| updateState brace tail'
newState',
FuncDef
{ Name = x.Value
Args = args
ReturnType = returnType
Body = body
Struct = structInfo }
| _ -> raiseParserError newState "Invalid function definition"
| _ -> raiseParserError state "Invalid function definition"
parse' None state
and parseLetExpression state =
let rec parseDestructure delim t' args state' =
match state'.Tokens with
| Lexer.Identifier x :: Lexer.Comma c :: remaining ->
parseDestructure
delim
t'
({ Name = x.Value
Mutable' = false
Public' = false }
:: args)
(updateState c remaining)
| Lexer.Identifier x :: t :: Lexer.Assign a :: remaining when delim t ->
(updateState a remaining),
(t' (
{ Name = x.Value
Public' = false
Mutable' = false }
:: args
))
| _ -> raiseParserError state "Invalid array destructure"
let parseArrayDestructure =
parseDestructure
(fun x ->
match x with
| Lexer.RBracket _ -> true
| _ -> false)
ArrayDestructure
[]
let parseRecordDestructure =
parseDestructure
(fun x ->
match x with
| Lexer.RBrace _ -> true
| _ -> false)
RecordDestructure
[]
let parseTupleDestructure =
parseDestructure
(fun x ->
match x with
| Lexer.RParen _ -> true
| _ -> false)
TupleDestructure
[]
let parseLeft state =
match state.Tokens with
| Lexer.Identifier x :: Lexer.Colon y :: tail ->
parseTypeLiteral <| updateState y tail
||> fun newState type' ->
newState,
TypedIdentifier
{ Name = x.Value
Type = type'
Mutable' = false
Public' = false }
| Lexer.Identifier x :: Lexer.Assign y :: tail ->
updateState y tail,
Identifier
{ Name = x.Value
Mutable' = false
Public' = false }
| Lexer.LParen x :: tail -> parseTupleDestructure <| updateState x tail
| Lexer.LBrace x :: tail -> parseRecordDestructure <| updateState x tail
| Lexer.LBracket x :: tail -> parseArrayDestructure <| updateState x tail
| _ -> raiseParserError state "Invalid left field on assign"
let newState, left = parseLeft state
let newState', right =
matchToken (
match newState.Tokens with
| Lexer.Assign x :: tail -> updateState x tail
| _ -> newState
)
newState', AssignmentStatement <| Let { Left = left; Right = right }
and parseFunctionCall (tok: Lexer.Token) state =
let rec parseArgs state args =
match state.Tokens with
| Lexer.RParen x :: tail -> (updateState x tail), args
| Lexer.Comma x :: tail -> parseArgs (updateState x tail) args
| _ -> matchToken state ||> fun newState node -> parseArgs newState (node :: args)
let newState, args = parseArgs state []
newState, FunctionCallExpression { Name = tok.Value; Args = args }
and parseRecordAccess state = state, NoOp
and parseIndexAccess state = state, NoOp
and parseIdentifier (tok: Lexer.Token) state =
match state.Tokens with
| Lexer.LParen x :: tail -> parseFunctionCall tok <| updateState x tail
| Lexer.Dot x :: tail -> parseRecordAccess <| updateState x tail
| Lexer.LBracket x :: tail -> parseIndexAccess <| updateState x tail
| _ ->
state,
IdentifierLiteral
<| Identifier
{ Name = tok.Value
Mutable' = false
Public' = false }
and parsePipe state node =
let rec parse previousWasPipe state' nodes =
match previousWasPipe, state'.Tokens with
| false, Lexer.Pipe x :: tail -> parse true (updateState x tail) nodes
| false, _ -> state', nodes
| true, _ -> matchToken state' ||> fun newState node -> parse false newState (node :: nodes)
let newState, nodes = parse false state []
newState, PipeExpression(node :: (List.rev nodes))
and parseReturn state =
match state.Tokens with
| Lexer.NewLine x :: tail -> updateState x tail, ReturnExpression None
| _ -> matchToken state ||> fun newState node -> newState, ReturnExpression(Some node)
and parseSuffix state node =
let rec parse' assigned state node =
match ignoreNewlines state.Tokens with
| Lexer.Pipe x :: tail -> parse' assigned <|| parsePipe (updateState x tail) node
| Lexer.Dot x :: tail -> parse' assigned <|| parseRecordAccess (updateState x tail)
| Lexer.Assign x :: tail ->
if assigned then
raiseParserError state "Invalid assignment"
else
let newState', right = matchToken <| updateState x tail
parse' true newState' (AssignExpression { Left = node; Right = right })
| Lexer.LBracket x :: tail ->
// TODO: Fix this to use IndexExpression
let newState', right = matchToken <| updateState x tail
parse' assigned newState' (AssignExpression { Left = node; Right = right })
| Lexer.LParen x :: tail ->
let newState', right = matchToken <| updateState x tail
parse' assigned newState' (FunctionCallExpression { Name = ""; Args = [ node; right ] })
| _ -> state, node
parse' false state node
and parseComment state =
match state.Tokens with
| [] as x -> matchToken { state with Tokens = x }
| Lexer.NewLine x :: tail -> matchToken <| updateState x tail
| _ :: tail -> parseComment { state with Tokens = tail }
and matchToken state =
parseSuffix
<|| match state.Tokens with
| [] -> (state, NoOp)
| Lexer.Import x :: tail -> parseImport <| updateState x tail
| Lexer.NewLine x :: tail -> ((updateState x tail), NoOp)
| Lexer.LBrace x :: tail -> parseBraceExpression <| updateState x tail
| Lexer.LParen x :: tail -> parseParenExpression <| updateState x tail
| Lexer.LBracket x :: tail -> parseArrayLiteral <| updateState x tail
| Lexer.Function x :: tail -> parseFunction <| updateState x tail
| Lexer.Let x :: tail -> parseLetExpression <| updateState x tail
| Lexer.Identifier x :: tail -> parseIdentifier x <| updateState x tail
| Lexer.String x :: tail -> updateState x tail, StringLiteral x.Value
| Lexer.Number x :: tail -> updateState x tail, NumberLiteral x.Value
| Lexer.Pub x :: tail -> updateState x tail, NoOp
| Lexer.Return x :: tail -> parseReturn <| updateState x tail
| Lexer.Comment x :: tail -> updateState x tail, NoOp
| Lexer.TypeKeyword _ :: tail ->
match ignoreNewlines tail with
| Lexer.Identifier ident :: Lexer.Assign x :: tail -> parseTypeDec ident.Value <| updateState x tail
| _ -> raiseParserError state "Invalid type declaration"
| _ ->
printfn "%A" <| state.Tokens
raiseParserError state "Invalid token"
and parseTree state delimiter =
match delimiter, state.Tokens with
| _, [] -> (state, NoOp)
| NoDelimiter, _ -> matchToken state
| FuncDelim f, _ when not (f state.Tokens) -> matchToken state
| _, _ -> (state, NoOp)
and filterTokensUntilDelimiter delimiter tokens =
match delimiter, tokens with
| _, [] -> []
| NoDelimiter, _ -> ignoreNewlines tokens
| FuncDelim f, _ ->
match tokens with
| [] -> []
| head :: tail when f [ head ] -> tail
| head :: tail -> head :: filterTokensUntilDelimiter delimiter tail
and [<TailCall>] recParseTree state delimiter children =
match delimiter, state.Tokens with
| _, [] ->
let filtered = List.filter filterNoOp children |> List.rev
({ state with
Tokens = filterTokensUntilDelimiter delimiter state.Tokens },
filtered)
| FuncDelim f, _ when not (f state.Tokens) ->
let state, child = parseTree state delimiter
recParseTree state delimiter (child :: children)
| NoDelimiter, _ ->
let state, child = parseTree state delimiter
recParseTree state delimiter (child :: children)
| _, _ ->
let filtered = List.filter filterNoOp children |> List.rev
({ state with
Tokens = filterTokensUntilDelimiter delimiter state.Tokens },
filtered)
and [<TailCall>] recursiveParse state astList =
match state.Tokens with
| [] -> [], List.filter filterNoOp astList |> List.rev
| Lexer.EOF _ :: _ -> [], List.filter filterNoOp astList |> List.rev
| _ ->
let newState, child = parseTree state NoDelimiter
recursiveParse newState (child :: astList)
let parse tokens =
let _, ast =
recursiveParse
{ Line = 0
Column = 0
Tokens = tokens }
[]
Root ast