-
Notifications
You must be signed in to change notification settings - Fork 3
/
mechc.ts
1948 lines (1823 loc) · 76.1 KB
/
mechc.ts
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs'
import {
Parser,
makeFailure,
succeed,
fail,
lazy,
alt,
seq,
seqMap,
lookahead,
string as s,
regex as r,
} from 'parsimmon'
//
// Parser
//
// Stages:
// 1. Tokenize with a regex
// 2. Parse into token tree with recursive descent
// 3. Parse into AST with precedence-climbing
// The conventional approach to parsing programming languages is 2 steps:
// 1. The tokenizer (aka lexer or scanner) takes source text as input,
// and outputs a sequence of tokens.
// 2. The parser takes the sequence of tokens as input, and outputs
// the AST (abstract syntax tree).
// Typically, they're implemented by writing them in DSLs (domain-specific
// languages) based on Backus-Naur Form, then using a tool like Jison,
// PEG.js, Chevrotain, or Ohm to compile them into executable code. Such
// tools are called "parser generators", or sometimes "compiler compilers".
// Usually one tool generates both steps, and both steps are written in
// similar DSLs, often in the same file, so the distinction just helps
// organize the lexing/parsing code written in the DSL.
//
// In contrast, Mechanical's parser is handwritten directly in executable
// JavaScript (technically, TypeScript). This probably sounds horrifying
// to anyone familiar with a conventional CS education, but actually by
// splitting parsing into 3 steps rather than the usual 2, the implementation
// is reasonably clean:
//
// Stage 1, the tokenizer, is just a regex to turn the source text string
// into a sequence of string tokens.
//
// Stage 2, the token tree parser, only parses the nesting of parentheses/
// brackets/braces and indentation, outputting a sequence of tokens and
// groups which contain a nested sequence of further tokens and groups.
// This is a simple top-down recursive-descent parser.
//
// Stage 3, the AST parser, doesn't need to deal with nesting because that's
// taken care of. It mainly deals with infix operators and their relative
// precedence, using straightforward bottom-up precedence-climbing.
//
// Note that by separating parsing nesting from parsing operator precedence,
// we can use a top-down procedure for one and bottom-up for the other.
//
// This approach has a few benefits over the conventional approach:
// - Good error messages are easier, because we can ensure we complain
// at the right time and provide the right information. The generality
// of parser generators often loses crucial information necessary to
// provide really excellent error messages.
// - It allows users to write macros to manipulate the token tree in a
// forward-compatible way, because the token tree format is more
// stable than the AST. This is why token trees were invented in the
// first place (by the Dylan language).
// - Mechanical's intentionally simple syntax lends itself to being
// parsed by simple, performant parsing code. Parser generators
// are generally designed to be able to parse arbitrarily-complex
// context-free grammars, much of which simple recursive-descent
// and simple precedence-climbing cannot parse.
//
// Misc. design note:
// - Conventionally, the tokenizer is responsible for discarding
// whitespace and comments, and attaching source location info to
// tokens. In CPython, it also inserts NEWLINE, INDENT, and DEDENT
// tokens. In Mechanical, the tokenizer is just a regex and doesn't
// discard any text. The token tree parser handles nested indentation
// grouping, generating newline tokens as well as unmatched brackets
// or dedents, and otherwise discarding whitespace and comments,
// as well as attaching source location info.
// Acknowledgements:
// - this way of structuring compilers was best described by @jneen, who
// calls our token tree a "skeleton tree":
// https://tech.trello.com/jeanine-adkisson-skeleton-trees/
// - they were inspired by the "D-expressions" paper, which introduced the
// skeleton syntax tree as a way for the Dylan language (which has
// conventional infix syntax) to provide macro facilities as convenient
// as Lisp (whose macro facilities are so convenient because of its
// S-expression syntax):
// https://people.eecs.berkeley.edu/~jrb/Projects/dexprs.pdf
// - since Mechanical's skeleton tree serves a similar role to a conventional
// tokenizer, I decided to call it a "token tree", like Rust:
// https://blog.rust-lang.org/2018/12/21/Procedural-Macros-in-Rust-2018.html#whats-inside-a-tokenstream
export namespace TokenTree {
export type Seq = ReadonlyArray<AnyToken | Group>
// token variants have to be split up like this for type narrowing to work
type AnyToken =
Token<'Ident'>
| Token<'Punct'>
| Token<'UnmatchedDelim', 'dedent' | '[' | ']' | '(' | ')' | '{' | '}'>
| Token<'Numeral'>
| Token<'StringLiteral'>
| Token<'FieldFunc'>
//| Token<'Hashtag'>
interface Token<T, Val = string> extends Span {
readonly type: T
readonly val: Val
}
interface Group extends Span {
readonly type: 'Group'
readonly delims: 'indent' | '()' | '[]' | '{}'
readonly nested: Seq
}
interface Span {
readonly i: number
readonly length: number
}
export function tokenize(source: string): string[] {
// TODO: decimals, E notation, numeric separators
return source.match(/( *(\/\/[^\n]*)?\n)+| +|\d+[\d_]*|"(\\"|[^"])*"|'(\\'|[^'])*'|\.\w+|\w+|\*\*|==|!=|<=|>=|=>|&&|\|\||\D/g) || []
// the \D is to match miscellaneous characters, since `.` doesn't
// match newline-like characters
}
type Mismatch = { open?: Token<'Punct' | 'UnmatchedDelim'>, close?: Token<'UnmatchedDelim'> }
type ParseResult = { tokens: Seq, n: number, srcN: number, mismatches: Mismatch[] }
function parseSeq(tokens: string[], i: number, srcI: number, indent: number, prevIndent: number, closeDelim: null | ')' | ']' | '}', openI: number, openSrcI: number): ParseResult {
const seq: Seq[number][] = []
const mismatches: Mismatch[] = []
let j = i, srcJ = srcI
while (j < tokens.length) {
const token = tokens[j]
// if this is the close-delim we're waiting for, return without consuming
if (token === closeDelim) break
// otherwise, any close-delimiter is an unmatched one
else if (token === ')' || token === ']' || token === '}') {
const unmatchedDelim =
{ type: 'UnmatchedDelim', val: token, i: srcJ, length: 1 } as const
mismatches.push({
open: isNaN(openI) ? undefined
: { type: 'Punct', val: tokens[openI], i: openSrcI, length: 1 },
close: unmatchedDelim })
seq.push(unmatchedDelim)
j += 1
srcJ += 1
continue
}
// if open-delimiter, then recurse
if (token === '(' || token === '[' || token === '{') {
const closeDelim = token === '(' ? ')' : token === '[' ? ']' : '}'
const { tokens: nested, n, srcN, mismatches: newMismatches } =
parseSeq(tokens, j + 1, srcJ + 1, indent, prevIndent, closeDelim, j, srcJ)
j += n + 1
srcJ += srcN + 1
const lookahead = tokens[j]
// if recursion ended because it encountered the close-delimiter,
// then consume it and emit group
if (lookahead === closeDelim) {
seq.push({ type: 'Group', delims: token + closeDelim as any, nested,
i: srcJ - srcN - 1, length: srcN + 2 })
j += 1
srcJ += 1
}
else { // else, recursion ended on dedent or EOF, so emit
// unmatched open-delim token and then nested tokens
const unmatchedDelim =
{ type: 'UnmatchedDelim', val: token, i: srcJ - srcN - 1, length: 1 } as const
seq.push(unmatchedDelim, ...nested)
mismatches.push({ open: unmatchedDelim })
}
mismatches.push(...newMismatches)
continue
}
const lastCh = token.charAt(token.length - 1)
// if newline, lookahead at indent of next line
if (lastCh === '\n') {
if (j + 1 >= tokens.length) break
let lookahead = tokens[j + 1]
let lookaheadIndent =
lookahead && lookahead.endsWith(' ') ? lookahead.length : 0
// if unchanged indent level from current, emit newline token
if (lookaheadIndent === indent) {
if (j > 0) { // ignore "virtual" newline (see parse())
seq.push({ type: 'Punct', val: '\n', i: srcJ, length: token.length })
}
j += 1 + (lookaheadIndent ? 1 : 0)
srcJ += token.length + lookaheadIndent
continue
}
// if deeper indent, recurse with new indent
if (lookaheadIndent > indent) {
j += 2
srcJ += token.length + lookaheadIndent
const { tokens: nested, n, srcN, mismatches: newMismatches } =
parseSeq(tokens, j, srcJ, lookaheadIndent, indent, closeDelim, openI, openSrcI)
seq.push({ type: 'Group', delims: 'indent', nested,
i: srcJ - lookaheadIndent, length: srcN + lookaheadIndent })
mismatches.push(...newMismatches)
j += n
srcJ += srcN
// if recursion ended in EOF, return
if (j + 1 >= tokens.length) break
// otherwise, recursion ended on a dedent, lookahead to it
lookahead = tokens[j + 1]
lookaheadIndent =
lookahead && lookahead.endsWith(' ') ? lookahead.length : 0
// if closing dedent is exactly the current indent,
// continue parsing at this indent level
if (lookaheadIndent === indent) {
const linebreakLength = tokens[j].length
j += 1 + (lookaheadIndent ? 1 : 0)
srcJ += linebreakLength + lookaheadIndent
continue
}
}
// if dedent to (or past) previous indent, return from current
// recursion without consuming newline or indent
if (lookaheadIndent <= prevIndent) break
// otherwise, must be dedent but only part-of-the-way to previous
// indent. Emit unmatched dedent token and update current indent
const unmatchedDedent = { type: 'UnmatchedDelim', val: 'dedent',
i: srcJ + token.length, length: lookaheadIndent } as const
seq.push(unmatchedDedent)
mismatches.push({ close: unmatchedDedent })
j += 2
srcJ += token.length + lookaheadIndent
indent = lookaheadIndent
continue
}
// if ordinary whitespace, skip
if (lastCh === ' ') {
j += 1
srcJ += token.length
continue
}
// otherwise, emit token
let type: AnyToken['type'] = 'Punct'
const ch = token.charAt(0), chCode = token.charCodeAt(0)
if (ch === '_'
|| (0x41 <= chCode && chCode <= 0x5A) // letters A-Z
|| (0x61 <= chCode && chCode <= 0x7A) // letters a-z
) {
type = 'Ident'
}
else if (0x30 <= chCode && chCode <= 0x39) { // digits 0-9
type = 'Numeral'
}
else if (token.length > 1) {
if (ch === '"' || ch === "'") type = 'StringLiteral'
else if (ch === '.') type = 'FieldFunc'
}
seq.push({ type, val: token, i: srcJ, length: token.length })
j += 1
srcJ += token.length
}
return { tokens: seq, n: j - i, srcN: srcJ - srcI, mismatches }
}
export function parse(source: string): { tokens: Seq, mismatches: Mismatch[] } {
// prefix with "virtual" newline to handle leading indent
return parseSeq(['\n'].concat(tokenize(source)), 0, -1, 0, NaN, null, NaN, NaN)
}
}
export namespace AST {
export type Expression = PrimaryExpr | FieldAccessExpr | CallExpr | UnaryExpr
| BinaryExpr | CompareChainExpr | CondExpr | ArrowFunc
export type PrimaryExpr = Numeral | StringLiteral | FieldFunc | Variable
| ArrayLiteral | RecordLiteral
export interface Numeral {
readonly type: 'Numeral'
readonly val: string
}
export interface StringLiteral {
readonly type: 'StringLiteral'
readonly val: string
}
export interface FieldFunc {
readonly type: 'FieldFunc'
readonly val: string
}
export interface Variable {
readonly type: 'Variable'
readonly name: string
}
export interface ArrayLiteral {
readonly type: 'ArrayLiteral'
readonly exprs: readonly Expression[]
}
export interface RecordLiteral {
readonly type: 'RecordLiteral'
readonly pairs: ReadonlyArray<{
readonly key: string
readonly val: Expression
}>
}
export interface FieldAccessExpr {
readonly type: 'FieldAccessExpr'
readonly record: Expression
readonly fieldName: string
}
export interface CallExpr {
readonly type: 'CallExpr'
readonly contextArg: Expression | null
readonly func: Expression
readonly args: ReadonlyArray<{
readonly label: string | null
readonly arg: Expression
}>
}
export interface UnaryExpr {
readonly type: 'UnaryExpr'
readonly op: '-' | '!'
readonly arg: Expression
}
export interface BinaryExpr {
readonly type: 'BinaryExpr'
readonly op: '**' | '*' | '/' | '%' | '+' | '-' | '!=' | '==' | '<' | '>' | '<='
| '>=' | '&&' | '||' // in order of precedence
readonly left: Expression
readonly right: Expression
}
export interface CompareChainExpr {
readonly type: 'CompareChainExpr'
readonly chain: readonly BinaryExpr[]
}
export interface CondExpr {
readonly type: 'CondExpr'
readonly test: Expression
readonly ifYes: Expression
readonly ifNo: Expression
}
export interface ArrowFunc {
readonly type: 'ArrowFunc'
readonly params: readonly string[]
readonly body: Expression | readonly Statement[]
}
export type Statement = ReturnStmt | EmitStmt | LetStmt | ChangeStmt
| DoStmt | GetDoStmt | FutureDoStmt | AfterGotStmt
export interface ReturnStmt {
readonly type: 'ReturnStmt'
readonly expr: Expression
}
export interface EmitStmt {
readonly type: 'EmitStmt'
readonly expr: Expression
}
export interface LetStmt {
readonly type: 'LetStmt'
readonly varName: string
readonly expr: Expression
}
export interface ChangeStmt {
readonly type: 'ChangeStmt'
readonly varName: string
readonly expr: Expression
}
export interface DoStmt {
readonly type: 'DoStmt'
readonly expr: Expression
}
export interface GetDoStmt {
readonly type: 'GetDoStmt'
readonly varName: string
readonly expr: Expression
}
export interface FutureDoStmt {
readonly type: 'FutureDoStmt'
readonly varName: string
readonly expr: Expression
}
export interface AfterGotStmt {
readonly type: 'AfterGotStmt'
readonly vars: readonly string[]
}
export interface StateDecl {
readonly type: 'StateDecl'
readonly varName: string
readonly expr: Expression
}
export interface WhenDecl {
readonly type: 'WhenDecl'
readonly event: Expression
readonly varName: string | null
readonly body: readonly Statement[]
}
export type TopLevel = StateDecl | WhenDecl | DoStmt | GetDoStmt
export function stripWhitespace(tokens: TokenTree.Seq): TokenTree.Seq {
const stripped = []
for (const token of tokens) {
if ((token.type === 'Punct' && token.val === '\n')
|| (token.type === 'UnmatchedDelim' && token.val === 'dedent')) {
continue
}
if (token.type === 'Group' && token.delims === 'indent') {
stripped.push(...stripWhitespace(token.nested))
}
else {
stripped.push(token)
}
}
return stripped
}
type ParseError = { i: number, length?: number, code: string, msg: string }
export function parseExpr(tokens: TokenTree.Seq, i: number): {
expr?: AST.Expression, n: number, errors: ParseError[]
} {
const result = (expr: AST.Expression, errors: ParseError[] = [], n = 1) =>
({ expr, n, errors })
const token = tokens[i]
switch (token.type) {
case 'Ident':
return result({ type: 'Variable', name: token.val })
case 'Numeral':
case 'StringLiteral':
case 'FieldFunc':
delete (token as any).i
delete (token as any).length
// ^ temporary, for tests, TODO: remove
return result(token)
case 'Group':
switch (token.delims) {
case '[]':
// accumulate exprs & errors by looping over nested token trees
const nested = stripWhitespace(token.nested)
const exprs: Expression[] = []
const errors: ParseError[] = []
let nestedI = 0
while (nestedI < nested.length) {
// parse item
const item = parseExpr(nested, nestedI)
nestedI += item.n
errors.push(...item.errors)
if (item.expr) exprs.push(item.expr)
// if no trailing comma, no problem
if (nestedI >= nested.length) break
// other than that, consume comma after each item
const next = nested[nestedI]
if (next.type === 'Punct' && next.val === ',') {
nestedI += 1
} else {
errors.push({ i: next.i, code: 'array_comma',
msg: 'Parsing array, just finished parsing array item, expected comma, got: ' + JSON.stringify(next) })
break
}
}
return result({ type: 'ArrayLiteral', exprs }, errors)
default:
throw `parseExpr() of Group with delims '${token.delims}' not yet implemented`
}
default:
throw `parseExpr() of token type '${token.type}' not yet implemented`
}
}
}
// who says you can't do left-recursion in a top-down parser? Come at me!
function leftRecur<Op, BinExpr>(
argParser: Parser<BinExpr>,
opParser: Parser<Op>,
map: (op: Op, left: BinExpr, right: BinExpr) => BinExpr
): Parser<BinExpr> {
return seqMap(argParser, seq(opParser, argParser).many(), (first, rest) =>
rest.reduce((left, [op, right]) => map(op, left, right), first as BinExpr))
}
// many <parser>'s separated by <separator>, with optional trailing <separator>
// Usage: <parser>.thru(sepByOptTrailing(<separator>))
function sepByOptTrailing<R>(separator: Parser<unknown>) {
return (parser: Parser<R>) => seqMap(
parser.skip(separator).many(),
parser.map(r => [r]).or(succeed([])),
(results, result) => results.concat(result)
)
}
// (some of the) Lexical Grammar
// Whitespace
const _ = r(/[ \n]*/) // optional whitespace
const __ = r(/[ \n]+/) // required whitespace
const _nonNL = r(/ */) // whitespace, no newlines
const _EOL = r(/ *(?:\/\/[^\n]*)?\n/).desc('end-of-line') // end-of-line,
// including optional whitespace and line comment
// Note that Tabs are banned, as are exotic whitespace \a\b\v\f\r, except
// in string literals. Just think of banned whitespace like control
// characters and non-printing characters.
// By convention, rules all start and end on non-whitespace, and expect
// the parent rule to deal with surrounding whitespace, EXCEPT that
// StatementIndentBlock expects leading indentation (so it must only be
// invoked immediately after a newline)
const Identifier = r(/[a-z](?:[a-z0-9]|_[a-z0-9])*/i) // TODO non-English letters etc
.desc('identifier (e.g. example_identifier)')
export function parserAtIndent(indent: string): {
Expression: Parser<AST.Expression>,
Statement: Parser<AST.Statement>,
StatementIndentBlock: Parser<AST.Statement[]>,
DoStmt: Parser<AST.DoStmt>,
GetDoStmt: Parser<AST.GetDoStmt>,
} {
//
// Expression Grammar (based on JS)
// https://tc39.es/ecma262/#sec-ecmascript-language-expressions
//
const Expression: Parser<AST.Expression> = lazy(() => alt(ArrowFunc, CondExpr))
const ParenGroup = s('(').then(Expression.trim(_)).skip(s(')'))
const Variable = Identifier.map(name => ({ type: 'Variable', name } as const))
const Numeral = r(/\d(?:\d|_\d)*/).desc('numeral (e.g. 123, 9_000)') // TODO decimals, exponential notation
.map(val => ({ type: 'Numeral', val } as const))
const FieldFunc = s('.').then(Identifier)
.map(name => ({ type: 'FieldFunc', val: '.' + name } as const))
.desc('field access function (e.g. .field_name)')
const StringLiteral = r(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/)
.desc(`string literal (e.g. "..." or '...')`)
.chain(str => {
let i = 0, errOffset = 0, errMsg = ''
const dedented = str.replace(/\n */g, prefix => {
i += 1
if (prefix.length - 1 >= indent.length) {
return '\n' + prefix.slice(1 + indent.length)
} else {
errOffset = str.split('\n').slice(0, i).join('\n').length
+ prefix.length
errMsg = `Multiline string improperly indented\n`
+ `Only indented ${prefix.length - 1} spaces, needs to be `
+ `indented ${indent.length} spaces`
return ''
}
})
if (errOffset) return Parser(() => makeFailure(errOffset, errMsg))
return succeed({ type: 'StringLiteral', val: dedented } as const)
})
const ArrayLiteral = s('[').then(
Expression.thru(sepByOptTrailing(s(',').trim(_))).trim(_)
.map(exprs => ({ type: 'ArrayLiteral', exprs } as const))
).skip(s(']'))
.desc('array literal (e.g. [ ... ])')
const RecordLiteral = s('{').then(
seqMap(Identifier, alt(s(':').trim(_).then(Expression), succeed(null)),
(key, val) => ({ key, val: val ?? { type: 'Variable', name: key } }))
.thru(sepByOptTrailing(s(',').trim(_))).trim(_)
.map(pairs => ({ type: 'RecordLiteral', pairs } as const))
).skip(s('}'))
.desc('record literal (e.g. { ... })')
const PrimaryExpr = alt( // in terms of operator precedence, "primary expressions"
// are the smallest units, which are either actual leaf nodes (variables,
// numberals, string literals) or delimited groups (parenthesized exprs,
// array literals, record literals, function calls, anonymous functions).
// They are the operands to the tightest-binding operator
ParenGroup,
Variable,
Numeral,
FieldFunc,
StringLiteral,
ArrayLiteral,
RecordLiteral,
)
const FieldAccessExpr = alt( // (tightest-binding operator)
seqMap(PrimaryExpr.skip(s('.').trim(_)), Identifier, (record, fieldName) =>
({ type: 'FieldAccessExpr', record, fieldName } as const)),
PrimaryExpr,
)
const CallExpr = alt( // as an exception to operator precedence, binds tighter
seqMap( // leftwards than FieldAccessExpr, because of how '.' is overloaded
PrimaryExpr.skip(_),
s('.').then(Identifier.trim(_)).or(succeed(null)),
s('(').then(
seqMap(Identifier.skip(s(':').trim(_)).or(succeed(null)), Expression,
(label, arg) => ({ label, arg })).sepBy(s(',').trim(_)).trim(_)
).skip(s(')')),
(expr, infixIdent, args) => ({
type: 'CallExpr',
contextArg: (infixIdent === null ? null : expr),
func: (infixIdent === null ? expr
: { type: 'Variable', name: infixIdent } as const),
args,
} as const)
),
FieldAccessExpr,
)
const UnaryExpr = alt(
seqMap(r(/[-!]/).skip(_) as Parser<'-' | '!'>, CallExpr,
(op, arg) => ({ type: 'UnaryExpr', op, arg } as const)),
CallExpr,
)
const ExponentExpr = alt(
seqMap(CallExpr.skip(s('**').trim(_)), UnaryExpr,
(left, right) => ({ type: 'BinaryExpr', op: '**', left, right } as const)),
// Note 1: as a special exception to typical operator precedence,
// exponents binds equally tightly leftwards as UnaryExpr, to avoid the
// ambiguity of whether -2**2 is (-2)**2 = 4 or -(2**2) = -4
// https://tc39.es/ecma262/#sec-exp-operator
// In Chrome, -2**2 throws:
// Uncaught SyntaxError: Unary operator used immediately before
// exponentiation expression. Parenthesis must be used to disambiguate
// operator precedence
//
// Note 2: in a breaking change from JS, Mechanical also prohibits
// chaining of exponents because it's not associative, i.e. it's
// ambiguous whether 2**3**2 is (2**3)**2 = 64 or 2**(3**2) = 512.
// In JS it's right-associative (so the answer is 512), which I think
// is confusing because the other non-associative operators are
// left-associative, e.g. 2/3/4 = (2/3)/4 and not 2/(3/4)
UnaryExpr,
)
const MultExpr = leftRecur(
ExponentExpr, r(/[*/%]/).trim(_) as Parser<'*' | '/' | '%'>,
(op, left, right) => ({ type: 'BinaryExpr', op, left, right } as const)
)
const AddExpr = leftRecur(
MultExpr, r(/[+-]/).trim(_) as Parser<'+' | '-'>,
(op, left, right) => ({ type: 'BinaryExpr', op, left, right } as const)
)
const InequalityExpr = seqMap( // mutually
// exclusive precedence with other comparisons and cannot be chained,
// because (1 != 2 != 1) == #yes could be surprising, but anything else
// would require quadratic comparisons
AddExpr.skip(s('!=').trim(_)), AddExpr,
(left, right) => ({ type: 'BinaryExpr', op: '!=', left, right } as const)
)
const CompareChainExpr: Parser<AST.Expression> = seqMap(
AddExpr,
seqMap(
seq(s<string>('==').trim(_), AddExpr).many(), // we need to special-case
// the leading =='s because alt() requires failure to fall-through to the
// next alternative, and when parsing "a == b > c" the first alternative
// won't fail, rather it succeeds parsing '== b', but the overall parser
// then fails on '>'
alt(
seq(r(/<=?|==/).trim(_), AddExpr).atLeast(1),
seq(r(/>=?|==/).trim(_), AddExpr).atLeast(1),
succeed([]),
),
(undirected, directed) => undirected.concat(directed)
),
(first, rest) => rest.length == 0
? first
: rest.length === 1
? {
type: 'BinaryExpr',
op: rest[0][0] as AST.BinaryExpr['op'],
left: first,
right: rest[0][1],
} as const
: ({
type: 'CompareChainExpr',
chain: rest.map(([op, arg], i) => ({
type: 'BinaryExpr',
op: op as AST.BinaryExpr['op'],
left: i ? rest[i-1][1] : first,
right: arg,
} as const)),
})
)
const CompareExpr = alt(InequalityExpr, CompareChainExpr)
const AndExpr = leftRecur( // conventionally higher precedence than OrExpr
CompareExpr, s('&&').trim(_),
(op, left, right) => ({ type: 'BinaryExpr', op, left, right } as const)
)
const OrExpr = leftRecur( // conventionally lower precedence than AndExpr
AndExpr, s('||').trim(_),
(op, left, right) => ({ type: 'BinaryExpr', op, left, right } as const)
)
const CondExpr = alt(
seqMap(
OrExpr.skip(s('?').trim(_)), Expression.skip(s(':').trim(_)), Expression,
(test, ifYes, ifNo) => ({ type: 'CondExpr', test, ifYes, ifNo } as const)
),
OrExpr,
)
const ArrowFunc = lazy<AST.ArrowFunc>(() => seqMap(
alt(
Identifier.map(param => [param]),
s('(').then(Identifier.sepBy1(s(',').trim(_)).trim(_)).skip(s(')')),
)
.skip(s('=>').trim(_)),
alt<AST.Expression | AST.Statement[]>(
lookahead(/[^{]/).then(Expression), // negative lookahead to prohibit
// record literals, same as JS, even though our statement syntax is
// actually restrictive enough that it's not ambiguous, unlike JS.
// It's still nice to reduce visual ambiguity, i.e. syntax that
// visually looks similar and you would have to look closely to
// disambiguate. Same reasoning for indentation-sensitivity
// TODO: reconsider this, we could just let syntax highlighting
// ameliorate any visual ambiguity
StatementBraceBlock,
),
(params, body) => ({ type: 'ArrowFunc', params, body } as const)
))
//
// Statements
// allowed in the body of an event handler declaration, or in a cmd {} block
//
const ReturnStmt = s('Return').then(__).then(Expression)
.map(expr => ({ type: 'ReturnStmt', expr } as const))
const EmitStmt = s('Emit').then(__).then(Expression)
.map(expr => ({ type: 'EmitStmt', expr } as const))
const LetStmt = seqMap(
s('Let').then(__).then(Identifier), s('=').trim(_).then(Expression),
(varName, expr) => ({ type: 'LetStmt', varName, expr } as const),
)
const ChangeStmt = seqMap(
s('Change').then(__).then(Identifier), s('to').trim(_).then(Expression),
(varName, expr) => ({ type: 'ChangeStmt', varName, expr } as const)
)
const DoStmt = s('Do').then(__).then(Expression)
.map<AST.DoStmt>(expr => ({ type: 'DoStmt', expr } as const))
const GetDoStmt = seqMap(
s('Get').then(__).then(Identifier),
s('=').trim(_).then(s('Do')).then(_).then(Expression),
(varName, expr) => ({ type: 'GetDoStmt', varName, expr } as const)
)
const FutureDoStmt = seqMap(
s('Future').then(__).then(Identifier),
s('=').trim(_).then(s('Do')).then(_).then(Expression),
(varName, expr) => ({ type: 'FutureDoStmt', varName, expr } as const)
)
const AfterGotStmt = r(/~* *After +got +/).then(
Identifier.sepBy1(s(',').trim(_))
.desc('at least one variable required in "After got ..." statement')
).skip(r(/ *~*/)).map(vars => ({ type: 'AfterGotStmt', vars } as const))
const Statement = alt<AST.Statement>(ReturnStmt, EmitStmt, LetStmt,
ChangeStmt, DoStmt, GetDoStmt, FutureDoStmt, AfterGotStmt)
const StatementIndentBlock = _EOL.many().then(_nonNL).chain(newIndent => {
if (newIndent.length > indent.length) {
const { Statement } = parserAtIndent(newIndent)
return Statement.sepBy1(_EOL.atLeast(1).then(_nonNL).chain(nextIndent => {
if (nextIndent.length === newIndent.length) return succeed('')
return fail(`Statement improperly indented\n`
+ `Indented ${nextIndent.length} spaces, needs to be indented `
+ `exactly ${newIndent.length} spaces`)
// XXX TODO: if the line clearly does parse correctly as a statement,
// forgiving parser should clearly explain that indentation
// is the reason for error (currently, indentation is listed
// as one of many possible reasons, because an expression
// continuation is also possible, as in '1\n+ 2', so it's
// like, expected proper indent *or* '+' or '-' etc).
// Forgiving parser-based error message isn't the only
// solution, line continuations should probably be indented
})).map(stmts => stmts.filter(Boolean))
}
return fail(`Statement block improperly indented\n`
+ `Only indented ${newIndent.length} spaces, needs to be indented `
+ `>${indent.length} spaces`)
})
const StatementBraceBlock = s('{').then(
alt(
Statement.sepBy1(s(';').trim(_nonNL)).trim(_nonNL),
StatementIndentBlock.trim(_EOL).skip(s(indent)),
)
).skip(s('}'))
return { Expression, Statement, StatementIndentBlock, DoStmt, GetDoStmt }
}
export const parser = parserAtIndent('')
//
// Top-Level Declarations
// all exported
//
const StateDecl = seqMap(
s('State').then(__).then(Identifier), s('=').trim(_).then(parser.Expression),
(varName, expr) => ({ type: 'StateDecl', varName, expr } as const)
)
const WhenDecl = seqMap(
s('When').then(__).then(parser.Expression),
alt(s('with').trim(__).then(Identifier), succeed(null))
.skip(_).skip(s(':')).skip(_EOL),
parser.StatementIndentBlock,
(event, varName, body) => ({ type: 'WhenDecl', event, varName, body } as const)
)
export const TopLevel =
alt<AST.TopLevel>(StateDecl, WhenDecl, parser.DoStmt, parser.GetDoStmt)
export const ProgramParser = s('Mechanical v0.0.1\n').then(
alt(TopLevel, _nonNL.result(null))
.sepBy(_EOL.desc('Top-level declarations cannot be indented'))
).map((decls => decls.filter(Boolean)) as <T>(decl: T[]) => Exclude<T, null>[])
//
// Type System
//
export namespace Types {
// Anything and Nothing are the top and bottom types, aka the universal and empty types
export type Type = NontrivialType | 'Anything' | 'Nothing'
export type NontrivialType = PrimitiveType | CompositeType | Func
// None is the unit type
export type PrimitiveType = 'None' | Err | ScalarType
export type ScalarType = bool | num | str
export type CompositeType = Arr | Product | Sum // | SumOfProducts
export interface Err {
readonly species: 'Error'
readonly error: Sum
readonly nullable?: true
}
interface Errorable {
readonly nullable?: true
readonly error?: Sum
}
// scalars
export interface bool extends Errorable { readonly species: 'boolean' }
export interface num extends Errorable { readonly species: 'number' }
export interface str extends Errorable { readonly species: 'string' }
// array/list/vector
export interface Arr extends Errorable {
readonly species: 'Array'
readonly ItemType: NontrivialType
}
// simple product type, aka a record
export interface Product extends Errorable {
readonly species: 'Product'
readonly fields: { readonly [name: string]: NontrivialType }
}
// sum type, aka hashtagged union, aka tagged union, aka discriminated union,
// aka disjoint union, aka variant type, aka coproduct
export interface Sum extends Errorable {
readonly species: 'Sum'
readonly variants: { readonly [tag: string]: NontrivialType | null }
//readonly opaque?: true // TODO: implement
}
// TODO: not implemented yet
//
// sum-of-products, disjoint union of product types
// (i.e. a union of disjoint record types)
//
// Recursive, tree-shaped.
// For example, consider a function that returns:
// { x: #simple, foo: 1}
// { x: #complex, y: #a, z: #a, bar: 1 }
// { x: #complex, y: #a, z: #b, baz: 1 }
// { x: #complex, y: #b, z: #a, qux: 1 }
// { x: #complex, y: #b, z: #b, zot: 1 }
//
// Then the inferred sum-of-products type will be:
// {
// species: 'SumOfProducts',
// discriminant: 'x',
// variants: {
// 'simple': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'simple': null } },
// 'foo': { species: 'number' },
// },
// },
// 'complex': {
// species: 'SumOfProduct',
// discriminant: 'y',
// variants: {
// 'a' : {
// species: 'SumOfProduct',
// discriminant: 'z',
// variants: {
// 'a': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'complex': null } },
// 'y': { species: 'Sum', variants: { 'a': null } },
// 'z': { species: 'Sum', variants: { 'a': null } },
// 'bar': { species: 'number' },
// },
// },
// 'b': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'complex': null } },
// 'y': { species: 'Sum', variants: { 'a': null } },
// 'z': { species: 'Sum', variants: { 'b': null } },
// 'baz': { species: 'number' },
// },
// },
// },
// },
// 'b' : {
// species: 'SumOfProduct',
// discriminant: 'z',
// variants: {
// 'a': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'complex': null } },
// 'y': { species: 'Sum', variants: { 'b': null } },
// 'z': { species: 'Sum', variants: { 'a': null } },
// 'qux': { species: 'number' },
// },
// },
// 'b': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'complex': null } },
// 'y': { species: 'Sum', variants: { 'b': null } },
// 'z': { species: 'Sum', variants: { 'b': null } },
// 'zot': { species: 'number' },
// },
// },
// },
// },
// },
// },
// },
// }
// Note that while 'x' must necessarily be at the highest level, the order
// of 'y' and 'z' is arbitrarily enforced to be lexicographic.
// The issue of having to arbitrarily choose the order of discriminant fields
// can only occur when, at a particular level, multiple fields are shared by
// every record subtype.
//
// What if no one field is shared by every record subtype? Consider:
// { x: #a, y: #a, foo: 1 }
// { x: #b, z: #a, bar: 1 }
// { y: #b, z: #b, qux: 1 }
//
// The fields are sorted by which are shared by the most record subtypes,
// then lexicographically:
// {
// species: 'SumOfProducts',
// discriminant: 'x',
// variants: {
// 'a': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'a': null }},
// 'y': { species: 'Sum', variants: { 'a': null }},
// 'foo': { species: 'number' },
// },
// },
// 'b': {
// species: 'Product',
// fields: {
// 'x': { species: 'Sum', variants: { 'b': null }},
// 'z': { species: 'Sum', variants: { 'a': null }},
// 'bar': { species: 'number' },
// },
// },
// },
// others: [
// {
// species: 'Product',
// fields: {
// 'y': { species: 'Sum', variants: { 'b': null }},
// 'z': { species: 'Sum', variants: { 'b': null }},
// 'qux': { species: 'number' },
// },
// }
// ],
// }
//
// When determining whether another type is disjoint, it will be necessary
// to compare with both the relevant variant subtype and all the subtypes
// in `others`. Consider: