mhs-lang 2.2.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parser.js ADDED
@@ -0,0 +1,1523 @@
1
+ /**
2
+ * Parser AST untuk Bahasa .mhs (mendukung sintaks Rust-safe & Pythonic).
3
+ */
4
+
5
+ const { groupLogicalLines, tokenize } = require('./lexer');
6
+
7
+ const TYPE_ALIASES = {
8
+ int: 'bulat',
9
+ i64: 'bulat',
10
+ i32: 'bulat',
11
+ isize: 'bulat',
12
+ usize: 'bulat',
13
+ bulat: 'bulat',
14
+ float: 'desimal',
15
+ f64: 'desimal',
16
+ f32: 'desimal',
17
+ desimal: 'desimal',
18
+ angka: 'angka',
19
+ str: 'teks',
20
+ String: 'teks',
21
+ teks: 'teks',
22
+ bool: 'bool',
23
+ logika: 'bool',
24
+ bytes: 'bytes',
25
+ None: 'Unit',
26
+ Kosong: 'Unit',
27
+ Nihil: 'Unit',
28
+ Unit: 'Unit',
29
+ list: 'Daftar',
30
+ List: 'Daftar',
31
+ daftar: 'Daftar',
32
+ Daftar: 'Daftar',
33
+ dict: 'Kamus',
34
+ Dict: 'Kamus',
35
+ kamus: 'Kamus',
36
+ Kamus: 'Kamus',
37
+ set: 'Himpunan',
38
+ Set: 'Himpunan',
39
+ himpunan: 'Himpunan',
40
+ Himpunan: 'Himpunan',
41
+ tuple: 'Tupel',
42
+ Tuple: 'Tupel',
43
+ tupel: 'Tupel',
44
+ Tupel: 'Tupel',
45
+ Optional: 'Opsi',
46
+ Opsi: 'Opsi',
47
+ Hasil: 'Hasil',
48
+ Callable: 'Fungsi',
49
+ Fungsi: 'Fungsi',
50
+ Any: 'ApaSaja',
51
+ ApaSaja: 'ApaSaja',
52
+ };
53
+
54
+ function canonicalTypeName(name) {
55
+ return TYPE_ALIASES[name] || name;
56
+ }
57
+
58
+ function parseTypeAnnotation(tokens, startIdx = 0) {
59
+ let i = startIdx;
60
+ if (i >= tokens.length) return { type: null, nextIdx: i };
61
+
62
+ // &T atau &ubah T atau pinjam T / pinjam_ubah T
63
+ if (tokens[i].value === '&' || tokens[i].value === 'pinjam') {
64
+ i++;
65
+ let mutable = false;
66
+ if (tokens[i] && tokens[i].value === 'ubah') {
67
+ mutable = true;
68
+ i++;
69
+ }
70
+ const inner = parseTypeAnnotation(tokens, i);
71
+ return {
72
+ type: {
73
+ kind: mutable ? 'PinjamUbah' : 'Pinjam',
74
+ inner: inner.type || { kind: 'Named', name: 'ApaSaja', args: [] },
75
+ },
76
+ nextIdx: inner.nextIdx,
77
+ };
78
+ }
79
+ if (tokens[i].value === 'pinjam_ubah') {
80
+ i++;
81
+ const inner = parseTypeAnnotation(tokens, i);
82
+ return {
83
+ type: {
84
+ kind: 'PinjamUbah',
85
+ inner: inner.type || { kind: 'Named', name: 'ApaSaja', args: [] },
86
+ },
87
+ nextIdx: inner.nextIdx,
88
+ };
89
+ }
90
+
91
+ // Unit type ()
92
+ if (tokens[i].value === '(' && tokens[i + 1] && tokens[i + 1].value === ')') {
93
+ return {
94
+ type: { kind: 'Named', name: 'Unit', args: [] },
95
+ nextIdx: i + 2,
96
+ };
97
+ }
98
+
99
+ const head = tokens[i];
100
+ if (!head || (head.type !== 'IDENT' && head.type !== 'KEYWORD')) {
101
+ return { type: null, nextIdx: i };
102
+ }
103
+
104
+ let name = head.value;
105
+ i++;
106
+ while (tokens[i] && tokens[i].value === '.' && tokens[i + 1]) {
107
+ name += '.' + tokens[i + 1].value;
108
+ i += 2;
109
+ }
110
+
111
+ const canonical = canonicalTypeName(name);
112
+ const args = [];
113
+ if (tokens[i] && tokens[i].value === '[') {
114
+ i++;
115
+ while (i < tokens.length && tokens[i].value !== ']') {
116
+ const sub = parseTypeAnnotation(tokens, i);
117
+ if (sub.type) {
118
+ args.push(sub.type);
119
+ i = sub.nextIdx;
120
+ } else {
121
+ i++;
122
+ }
123
+ if (tokens[i] && tokens[i].value === ',') i++;
124
+ }
125
+ if (tokens[i] && tokens[i].value === ']') i++;
126
+ }
127
+
128
+ return {
129
+ type: { kind: 'Named', name: canonical, rawName: name, args },
130
+ nextIdx: i,
131
+ };
132
+ }
133
+
134
+ function formatType(t) {
135
+ if (!t) return 'TidakDiketahui';
136
+ if (t.kind === 'Pinjam') return `&${formatType(t.inner)}`;
137
+ if (t.kind === 'PinjamUbah') return `&ubah ${formatType(t.inner)}`;
138
+ if (t.kind === 'Named') {
139
+ if (t.args && t.args.length > 0) {
140
+ return `${t.name}[${t.args.map(formatType).join(', ')}]`;
141
+ }
142
+ return t.name;
143
+ }
144
+ return String(t);
145
+ }
146
+
147
+ function isSym(t) {
148
+ return !!t && t.type !== 'STRING' && t.type !== 'FSTRING' && t.type !== 'NUMBER';
149
+ }
150
+
151
+ function symEq(t, val) {
152
+ return isSym(t) && t.value === val;
153
+ }
154
+
155
+ /**
156
+ * Parser ekspresi rekursif-turun dari array token.
157
+ */
158
+ class ExprParser {
159
+ constructor(tokens) {
160
+ this.tokens = tokens;
161
+ this.pos = 0;
162
+ }
163
+
164
+ peek(offset = 0) {
165
+ return this.tokens[this.pos + offset] || null;
166
+ }
167
+
168
+ peekSym(offset = 0) {
169
+ const t = this.tokens[this.pos + offset] || null;
170
+ return isSym(t) ? t : null;
171
+ }
172
+
173
+ consume() {
174
+ return this.tokens[this.pos++] || null;
175
+ }
176
+
177
+ matchValue(val) {
178
+ const t = this.peekSym();
179
+ if (t && t.value === val) {
180
+ this.pos++;
181
+ return t;
182
+ }
183
+ return null;
184
+ }
185
+
186
+ span(startTok, endTok) {
187
+ const s = startTok || { line: 1, col: 1 };
188
+ const e = endTok || s;
189
+ return { line: s.line, col: s.col, endCol: e.endCol || s.endCol || s.col + 1 };
190
+ }
191
+
192
+ parseExpr() {
193
+ if (!this.peek()) return null;
194
+ return this.parseLambda();
195
+ }
196
+
197
+ parseLambda() {
198
+ const t = this.peekSym();
199
+ if (t && (t.value === 'anonim' || t.value === 'lambda')) {
200
+ this.consume();
201
+ const params = [];
202
+ while (this.peek() && !symEq(this.peek(), ':')) {
203
+ if (this.peek().type === 'IDENT' || this.peek().type === 'KEYWORD') {
204
+ params.push(this.consume().value);
205
+ } else {
206
+ this.consume();
207
+ }
208
+ this.matchValue(',');
209
+ }
210
+ this.matchValue(':');
211
+ const body = this.parseExpr();
212
+ return { kind: 'Lambda', params, body, ...this.span(t, this.tokens[this.pos - 1]) };
213
+ }
214
+ return this.parseTernary();
215
+ }
216
+
217
+ parseTernary() {
218
+ const expr = this.parseOr();
219
+ const t = this.peekSym();
220
+ if (t && (t.value === 'jika' || t.value === 'if')) {
221
+ const saved = this.pos;
222
+ this.consume();
223
+ const cond = this.parseOr();
224
+ const next = this.peekSym();
225
+ if (next && (next.value === 'selain_itu' || next.value === 'else' || next.value === 'lainnya')) {
226
+ this.consume();
227
+ const alt = this.parseTernary();
228
+ return {
229
+ kind: 'Ternary',
230
+ consequent: expr,
231
+ cond,
232
+ alternate: alt,
233
+ ...this.span(expr, alt),
234
+ };
235
+ }
236
+ this.pos = saved;
237
+ }
238
+ return expr;
239
+ }
240
+
241
+ parseOr() {
242
+ let left = this.parseAnd();
243
+ while (this.peekSym() && (this.peekSym().value === 'atau' || this.peekSym().value === 'or' || this.peekSym().value === '||')) {
244
+ const op = this.consume();
245
+ const right = this.parseAnd();
246
+ left = { kind: 'Binary', op: 'atau', left, right, ...this.span(left, right || op) };
247
+ }
248
+ return left;
249
+ }
250
+
251
+ parseAnd() {
252
+ let left = this.parseNot();
253
+ while (this.peekSym() && (this.peekSym().value === 'dan' || this.peekSym().value === 'and' || this.peekSym().value === '&&')) {
254
+ const op = this.consume();
255
+ const right = this.parseNot();
256
+ left = { kind: 'Binary', op: 'dan', left, right, ...this.span(left, right || op) };
257
+ }
258
+ return left;
259
+ }
260
+
261
+ parseNot() {
262
+ const t = this.peekSym();
263
+ if (t && (t.value === 'bukan' || t.value === 'not' || t.value === '!')) {
264
+ if (!(t.value === 'not' && symEq(this.peek(1), 'in'))) {
265
+ this.consume();
266
+ const operand = this.parseNot();
267
+ return { kind: 'Unary', op: 'bukan', operand, ...this.span(t, operand || t) };
268
+ }
269
+ }
270
+ return this.parseCompare();
271
+ }
272
+
273
+ parseCompare() {
274
+ let left = this.parseRange();
275
+ while (this.peekSym()) {
276
+ const t = this.peekSym();
277
+ let op = null;
278
+ if (['==', '!=', '<', '<=', '>', '>=', 'dalam', 'in', 'adalah', 'bukan_adalah', 'is'].includes(t.value)) {
279
+ if (t.value === 'is' && symEq(this.peek(1), 'not')) {
280
+ this.consume();
281
+ this.consume();
282
+ op = 'bukan_adalah';
283
+ } else {
284
+ op = this.consume().value;
285
+ }
286
+ } else if (t.value === 'not' && symEq(this.peek(1), 'in')) {
287
+ this.consume();
288
+ this.consume();
289
+ op = 'bukan_dalam';
290
+ } else if (t.value === 'bukan' && symEq(this.peek(1), 'dalam')) {
291
+ this.consume();
292
+ this.consume();
293
+ op = 'bukan_dalam';
294
+ } else {
295
+ break;
296
+ }
297
+ const right = this.parseRange();
298
+ left = { kind: 'Binary', op, left, right, ...this.span(left, right || t) };
299
+ }
300
+ return left;
301
+ }
302
+
303
+ parseRange() {
304
+ let left = this.parseBitOr();
305
+ if (this.peekSym() && (this.peekSym().value === '..' || this.peekSym().value === '..=')) {
306
+ const op = this.consume();
307
+ const right = this.parseBitOr();
308
+ return {
309
+ kind: 'Range',
310
+ inclusive: op.value === '..=',
311
+ start: left,
312
+ end: right,
313
+ ...this.span(left, right || op),
314
+ };
315
+ }
316
+ return left;
317
+ }
318
+
319
+ parseBitOr() {
320
+ let left = this.parseBitXor();
321
+ while (symEq(this.peek(), '|')) {
322
+ const op = this.consume();
323
+ const right = this.parseBitXor();
324
+ left = { kind: 'Binary', op: '|', left, right, ...this.span(left, right || op) };
325
+ }
326
+ return left;
327
+ }
328
+
329
+ parseBitXor() {
330
+ let left = this.parseBitAnd();
331
+ while (symEq(this.peek(), '^')) {
332
+ const op = this.consume();
333
+ const right = this.parseBitAnd();
334
+ left = { kind: 'Binary', op: '^', left, right, ...this.span(left, right || op) };
335
+ }
336
+ return left;
337
+ }
338
+
339
+ parseBitAnd() {
340
+ let left = this.parseShift();
341
+ while (symEq(this.peek(), '&')) {
342
+ const op = this.consume();
343
+ const right = this.parseShift();
344
+ left = { kind: 'Binary', op: '&', left, right, ...this.span(left, right || op) };
345
+ }
346
+ return left;
347
+ }
348
+
349
+ parseShift() {
350
+ let left = this.parseAdd();
351
+ while (this.peekSym() && (this.peekSym().value === '<<' || this.peekSym().value === '>>')) {
352
+ const op = this.consume();
353
+ const right = this.parseAdd();
354
+ left = { kind: 'Binary', op: op.value, left, right, ...this.span(left, right || op) };
355
+ }
356
+ return left;
357
+ }
358
+
359
+ parseAdd() {
360
+ let left = this.parseMul();
361
+ while (this.peekSym() && (this.peekSym().value === '+' || this.peekSym().value === '-')) {
362
+ const op = this.consume();
363
+ const right = this.parseMul();
364
+ left = { kind: 'Binary', op: op.value, left, right, ...this.span(left, right || op) };
365
+ }
366
+ return left;
367
+ }
368
+
369
+ parseMul() {
370
+ let left = this.parseUnary();
371
+ while (this.peekSym() && ['*', '/', '//', '%'].includes(this.peekSym().value)) {
372
+ const op = this.consume();
373
+ const right = this.parseUnary();
374
+ left = { kind: 'Binary', op: op.value, left, right, ...this.span(left, right || op) };
375
+ }
376
+ return left;
377
+ }
378
+
379
+ parseUnary() {
380
+ const t = this.peekSym();
381
+ if (!t) return this.parsePower();
382
+
383
+ if (t.value === '&' || t.value === 'pinjam') {
384
+ this.consume();
385
+ let mutable = false;
386
+ if (symEq(this.peek(), 'ubah')) {
387
+ mutable = true;
388
+ this.consume();
389
+ }
390
+ const target = this.parseUnary();
391
+ return { kind: 'Borrow', mutable, target, ...this.span(t, target || t) };
392
+ }
393
+ if (t.value === 'pinjam_ubah') {
394
+ this.consume();
395
+ const target = this.parseUnary();
396
+ return { kind: 'Borrow', mutable: true, target, ...this.span(t, target || t) };
397
+ }
398
+ if (t.value === 'pindah') {
399
+ this.consume();
400
+ const target = this.parseUnary();
401
+ return { kind: 'Move', target, ...this.span(t, target || t) };
402
+ }
403
+ if (t.value === '*') {
404
+ this.consume();
405
+ const target = this.parseUnary();
406
+ return { kind: 'DerefOrSpread', target, ...this.span(t, target || t) };
407
+ }
408
+ if (t.value === '**') {
409
+ this.consume();
410
+ const target = this.parseUnary();
411
+ return { kind: 'KwSpread', target, ...this.span(t, target || t) };
412
+ }
413
+ if (t.value === 'await') {
414
+ this.consume();
415
+ const target = this.parseUnary();
416
+ return { kind: 'Await', target, ...this.span(t, target || t) };
417
+ }
418
+ if (t.value === '-' || t.value === '+' || t.value === '~') {
419
+ this.consume();
420
+ const operand = this.parseUnary();
421
+ return { kind: 'Unary', op: t.value, operand, ...this.span(t, operand || t) };
422
+ }
423
+ return this.parsePower();
424
+ }
425
+
426
+ parsePower() {
427
+ let left = this.parsePostfix();
428
+ if (symEq(this.peek(), '**')) {
429
+ const op = this.consume();
430
+ const right = this.parseUnary();
431
+ return { kind: 'Binary', op: '**', left, right, ...this.span(left, right || op) };
432
+ }
433
+ return left;
434
+ }
435
+
436
+ parsePostfix() {
437
+ let node = this.parsePrimary();
438
+ if (!node) return null;
439
+
440
+ while (this.peekSym()) {
441
+ const t = this.peekSym();
442
+ if (t.value === '(') {
443
+ this.consume();
444
+ const args = [];
445
+ const kwargs = [];
446
+
447
+ if (this.peek() && !symEq(this.peek(), ')')) {
448
+ const first = this.parseCallArg();
449
+ if (this.peekSym() && (this.peekSym().value === 'untuk' || this.peekSym().value === 'for')) {
450
+ const clauses = this.parseComprehensionClauses();
451
+ this.matchValue(')');
452
+ node = {
453
+ kind: 'Call',
454
+ callee: node,
455
+ args: [{ kind: 'GeneratorComp', body: first.value, clauses, ...this.span(first.value, this.tokens[this.pos - 1]) }],
456
+ kwargs: [],
457
+ ...this.span(node, this.tokens[this.pos - 1]),
458
+ };
459
+ continue;
460
+ }
461
+ if (first.kwargName) kwargs.push(first);
462
+ else args.push(first.value);
463
+
464
+ while (this.matchValue(',')) {
465
+ if (this.peek() && symEq(this.peek(), ')')) break;
466
+ const arg = this.parseCallArg();
467
+ if (arg.kwargName) kwargs.push(arg);
468
+ else args.push(arg.value);
469
+ }
470
+ }
471
+ const closeTok = this.matchValue(')') || t;
472
+ node = { kind: 'Call', callee: node, args, kwargs, ...this.span(node, closeTok) };
473
+ } else if (t.value === '.') {
474
+ this.consume();
475
+ const propTok = this.consume();
476
+ node = {
477
+ kind: 'Member',
478
+ object: node,
479
+ property: propTok ? propTok.value : '',
480
+ ...this.span(node, propTok || t),
481
+ };
482
+ } else if (t.value === '[') {
483
+ this.consume();
484
+ let hasColon = false;
485
+ let start = null;
486
+ let end = null;
487
+ let step = null;
488
+
489
+ if (this.peek() && !symEq(this.peek(), ':') && !symEq(this.peek(), ']')) {
490
+ start = this.parseExpr();
491
+ }
492
+ if (this.matchValue(':')) {
493
+ hasColon = true;
494
+ if (this.peek() && !symEq(this.peek(), ':') && !symEq(this.peek(), ']')) {
495
+ end = this.parseExpr();
496
+ }
497
+ if (this.matchValue(':')) {
498
+ if (this.peek() && !symEq(this.peek(), ']')) {
499
+ step = this.parseExpr();
500
+ }
501
+ }
502
+ }
503
+ const closeTok = this.matchValue(']') || t;
504
+ if (hasColon) {
505
+ node = { kind: 'Slice', object: node, start, end, step, ...this.span(node, closeTok) };
506
+ } else {
507
+ node = { kind: 'Index', object: node, index: start, ...this.span(node, closeTok) };
508
+ }
509
+ } else if (t.value === '?') {
510
+ this.consume();
511
+ node = { kind: 'TryPropagate', expr: node, ...this.span(node, t) };
512
+ } else {
513
+ break;
514
+ }
515
+ }
516
+ return node;
517
+ }
518
+
519
+ parseCallArg() {
520
+ const t0 = this.peek();
521
+ const t1 = this.peek(1);
522
+ if (t0 && (t0.type === 'IDENT' || t0.type === 'KEYWORD') && symEq(t1, '=')) {
523
+ this.consume();
524
+ this.consume();
525
+ const val = this.parseExpr();
526
+ return { kwargName: t0.value, value: val };
527
+ }
528
+ return { kwargName: null, value: this.parseExpr() };
529
+ }
530
+
531
+ parseComprehensionClauses() {
532
+ const clauses = [];
533
+ while (this.peekSym() && (this.peekSym().value === 'untuk' || this.peekSym().value === 'for')) {
534
+ this.consume();
535
+ const targets = [];
536
+ while (this.peek() && !symEq(this.peek(), 'dalam') && !symEq(this.peek(), 'in')) {
537
+ if (this.peek().type === 'IDENT' || this.peek().type === 'KEYWORD') {
538
+ targets.push(this.consume().value);
539
+ } else {
540
+ this.consume();
541
+ }
542
+ this.matchValue(',');
543
+ }
544
+ if (symEq(this.peek(), 'dalam') || symEq(this.peek(), 'in')) {
545
+ this.consume();
546
+ }
547
+ const iter = this.parseOr();
548
+ let cond = null;
549
+ if (symEq(this.peek(), 'jika') || symEq(this.peek(), 'if')) {
550
+ this.consume();
551
+ cond = this.parseOr();
552
+ }
553
+ clauses.push({ targets, iter, cond });
554
+ }
555
+ return clauses;
556
+ }
557
+
558
+ parsePrimary() {
559
+ const t = this.peek();
560
+ if (!t) return null;
561
+
562
+ if (t.type === 'NUMBER') {
563
+ this.consume();
564
+ return {
565
+ kind: 'Literal',
566
+ litType: t.isFloat ? 'desimal' : 'bulat',
567
+ value: Number(t.value),
568
+ raw: t.value,
569
+ ...this.span(t, t),
570
+ };
571
+ }
572
+
573
+ if (t.type === 'STRING' || t.type === 'FSTRING') {
574
+ const parseSingleStr = (tok) => {
575
+ if (tok.type === 'STRING') {
576
+ return {
577
+ kind: 'Literal',
578
+ litType: tok.prefix.includes('b') ? 'bytes' : 'teks',
579
+ value: tok.value,
580
+ quote: tok.quote,
581
+ ...this.span(tok, tok),
582
+ };
583
+ }
584
+ const embeddedAsts = [];
585
+ for (const exprText of tok.exprs) {
586
+ try {
587
+ const { tokens } = tokenize(exprText);
588
+ const clean = tokens.filter((tk) => tk.type !== 'LINE_START' && tk.type !== 'NEWLINE' && tk.type !== 'EOF');
589
+ if (clean.length > 0) {
590
+ const parsed = new ExprParser(clean).parseExpr();
591
+ if (parsed) embeddedAsts.push(parsed);
592
+ }
593
+ } catch {
594
+ // Biarkan jika ekspresi kompleks
595
+ }
596
+ }
597
+ return {
598
+ kind: 'FString',
599
+ value: tok.value,
600
+ quote: tok.quote,
601
+ embeddedAsts,
602
+ ...this.span(tok, tok),
603
+ };
604
+ };
605
+
606
+ let node = parseSingleStr(this.consume());
607
+ while (this.peek() && (this.peek().type === 'STRING' || this.peek().type === 'FSTRING')) {
608
+ const nextNode = parseSingleStr(this.consume());
609
+ node = {
610
+ kind: 'Binary',
611
+ op: '+',
612
+ left: node,
613
+ right: nextNode,
614
+ ...this.span(node, nextNode),
615
+ };
616
+ }
617
+ return node;
618
+ }
619
+
620
+ if (['Benar', 'benar', 'True', 'Salah', 'salah', 'False'].includes(t.value)) {
621
+ this.consume();
622
+ return {
623
+ kind: 'Literal',
624
+ litType: 'bool',
625
+ value: ['Benar', 'benar', 'True'].includes(t.value),
626
+ ...this.span(t, t),
627
+ };
628
+ }
629
+
630
+ if (['Kosong', 'kosong', 'None'].includes(t.value)) {
631
+ this.consume();
632
+ return {
633
+ kind: 'NullLiteral',
634
+ raw: t.value,
635
+ ...this.span(t, t),
636
+ };
637
+ }
638
+
639
+ if (t.value === 'TidakAda') {
640
+ this.consume();
641
+ return { kind: 'OptionNone', ...this.span(t, t) };
642
+ }
643
+
644
+ if (t.value === '(') {
645
+ this.consume();
646
+ if (this.matchValue(')')) {
647
+ return { kind: 'Tuple', items: [], ...this.span(t, this.tokens[this.pos - 1]) };
648
+ }
649
+ const first = this.parseExpr();
650
+ if (symEq(this.peek(), 'untuk') || symEq(this.peek(), 'for')) {
651
+ const clauses = this.parseComprehensionClauses();
652
+ const endTok = this.matchValue(')') || t;
653
+ return { kind: 'GeneratorComp', body: first, clauses, ...this.span(t, endTok) };
654
+ }
655
+ if (this.matchValue(',')) {
656
+ const items = [first];
657
+ while (this.peek() && !symEq(this.peek(), ')')) {
658
+ items.push(this.parseExpr());
659
+ if (!this.matchValue(',')) break;
660
+ }
661
+ const endTok = this.matchValue(')') || t;
662
+ return { kind: 'Tuple', items, ...this.span(t, endTok) };
663
+ }
664
+ this.matchValue(')');
665
+ return first;
666
+ }
667
+
668
+ if (t.value === '[') {
669
+ this.consume();
670
+ if (this.matchValue(']')) {
671
+ return { kind: 'List', items: [], ...this.span(t, this.tokens[this.pos - 1]) };
672
+ }
673
+ const first = this.parseExpr();
674
+ if (symEq(this.peek(), 'untuk') || symEq(this.peek(), 'for')) {
675
+ const clauses = this.parseComprehensionClauses();
676
+ const endTok = this.matchValue(']') || t;
677
+ return { kind: 'ListComp', body: first, clauses, ...this.span(t, endTok) };
678
+ }
679
+ const items = [first];
680
+ while (this.matchValue(',')) {
681
+ if (this.peek() && symEq(this.peek(), ']')) break;
682
+ items.push(this.parseExpr());
683
+ }
684
+ const endTok = this.matchValue(']') || t;
685
+ return { kind: 'List', items, ...this.span(t, endTok) };
686
+ }
687
+
688
+ if (t.value === '{') {
689
+ this.consume();
690
+ if (this.matchValue('}')) {
691
+ return { kind: 'Dict', entries: [], ...this.span(t, this.tokens[this.pos - 1]) };
692
+ }
693
+ const firstKey = this.parseExpr();
694
+ if (this.matchValue(':')) {
695
+ const firstVal = this.parseExpr();
696
+ if (symEq(this.peek(), 'untuk') || symEq(this.peek(), 'for')) {
697
+ const clauses = this.parseComprehensionClauses();
698
+ const endTok = this.matchValue('}') || t;
699
+ return { kind: 'DictComp', key: firstKey, value: firstVal, clauses, ...this.span(t, endTok) };
700
+ }
701
+ const entries = [{ key: firstKey, value: firstVal }];
702
+ while (this.matchValue(',')) {
703
+ if (this.peek() && symEq(this.peek(), '}')) break;
704
+ const k = this.parseExpr();
705
+ this.matchValue(':');
706
+ const v = this.parseExpr();
707
+ entries.push({ key: k, value: v });
708
+ }
709
+ const endTok = this.matchValue('}') || t;
710
+ return { kind: 'Dict', entries, ...this.span(t, endTok) };
711
+ } else {
712
+ // Set literal
713
+ const items = [firstKey];
714
+ while (this.matchValue(',')) {
715
+ if (this.peek() && symEq(this.peek(), '}')) break;
716
+ items.push(this.parseExpr());
717
+ }
718
+ const endTok = this.matchValue('}') || t;
719
+ return { kind: 'Set', items, ...this.span(t, endTok) };
720
+ }
721
+ }
722
+
723
+ if (t.type === 'IDENT' || t.type === 'KEYWORD') {
724
+ this.consume();
725
+ return { kind: 'Ident', name: t.value, ...this.span(t, t) };
726
+ }
727
+
728
+ this.consume();
729
+ return null;
730
+ }
731
+ }
732
+
733
+ function parseExpression(tokens) {
734
+ if (!tokens || tokens.length === 0) return null;
735
+ return new ExprParser(tokens).parseExpr();
736
+ }
737
+
738
+ function findTopLevelToken(tokens, predicate) {
739
+ let depth = 0;
740
+ for (let i = 0; i < tokens.length; i++) {
741
+ if (!isSym(tokens[i])) continue;
742
+ const v = tokens[i].value;
743
+ if (v === '(' || v === '[' || v === '{') depth++;
744
+ else if (v === ')' || v === ']' || v === '}') depth = Math.max(0, depth - 1);
745
+ else if (depth === 0 && predicate(tokens[i], i, tokens)) return i;
746
+ }
747
+ return -1;
748
+ }
749
+
750
+ function parseParams(tokens) {
751
+ const params = [];
752
+ let i = 0;
753
+ while (i < tokens.length) {
754
+ if (tokens[i].value === ',') { i++; continue; }
755
+
756
+ let isStar = false;
757
+ let isDoubleStar = false;
758
+ if (tokens[i].value === '**') { isDoubleStar = true; i++; }
759
+ else if (tokens[i].value === '*') { isStar = true; i++; }
760
+
761
+ let isBorrow = false;
762
+ let isMut = false;
763
+ if (tokens[i]?.value === '&' || tokens[i]?.value === 'pinjam') {
764
+ isBorrow = true;
765
+ i++;
766
+ if (tokens[i]?.value === 'ubah') {
767
+ isMut = true;
768
+ i++;
769
+ }
770
+ } else if (tokens[i]?.value === 'pinjam_ubah') {
771
+ isBorrow = true;
772
+ isMut = true;
773
+ i++;
774
+ } else if (tokens[i]?.value === 'ubah') {
775
+ isMut = true;
776
+ i++;
777
+ }
778
+
779
+ const nameTok = tokens[i];
780
+ if (!nameTok) break;
781
+ const name = nameTok.value;
782
+ i++;
783
+
784
+ let type = null;
785
+ if (tokens[i] && tokens[i].value === ':') {
786
+ i++;
787
+ const parsed = parseTypeAnnotation(tokens, i);
788
+ type = parsed.type;
789
+ i = parsed.nextIdx;
790
+ }
791
+
792
+ // Jika parameter ditulis `&x` tanpa `:`, tandai pinjaman pada tipenya
793
+ if (isBorrow && type && type.kind !== 'Pinjam' && type.kind !== 'PinjamUbah') {
794
+ type = { kind: isMut ? 'PinjamUbah' : 'Pinjam', inner: type };
795
+ } else if (isBorrow && !type) {
796
+ type = { kind: isMut ? 'PinjamUbah' : 'Pinjam', inner: { kind: 'Named', name: 'TidakDiketahui', args: [] } };
797
+ }
798
+
799
+ let defaultExpr = null;
800
+ if (tokens[i] && tokens[i].value === '=') {
801
+ i++;
802
+ const defStart = i;
803
+ let depth = 0;
804
+ while (i < tokens.length) {
805
+ const v = tokens[i].value;
806
+ if (v === '(' || v === '[' || v === '{') depth++;
807
+ else if (v === ')' || v === ']' || v === '}') depth = Math.max(0, depth - 1);
808
+ else if (depth === 0 && v === ',') break;
809
+ i++;
810
+ }
811
+ defaultExpr = parseExpression(tokens.slice(defStart, i));
812
+ }
813
+
814
+ params.push({
815
+ name,
816
+ type,
817
+ isBorrow,
818
+ isMut,
819
+ isStar,
820
+ isDoubleStar,
821
+ defaultExpr,
822
+ line: nameTok.line,
823
+ col: nameTok.col,
824
+ endCol: nameTok.endCol,
825
+ });
826
+ }
827
+ return params;
828
+ }
829
+
830
+ function parseImportItems(tokens) {
831
+ const items = [];
832
+ let i = 0;
833
+ if (tokens[0]?.value === '(') {
834
+ tokens = tokens.slice(1, tokens[tokens.length - 1]?.value === ')' ? -1 : undefined);
835
+ }
836
+ while (i < tokens.length) {
837
+ if (tokens[i].value === ',') { i++; continue; }
838
+ const name = tokens[i].value;
839
+ i++;
840
+ let alias = name;
841
+ if (tokens[i] && (tokens[i].value === 'sebagai' || tokens[i].value === 'as')) {
842
+ i++;
843
+ if (tokens[i]) {
844
+ alias = tokens[i].value;
845
+ i++;
846
+ }
847
+ }
848
+ items.push({ name, alias });
849
+ }
850
+ return items;
851
+ }
852
+
853
+ /**
854
+ * Mengurai daftar baris logis menjadi AST program bertingkat.
855
+ */
856
+ function parseProgram(source) {
857
+ const { lines, rawLines } = groupLogicalLines(source);
858
+ const directives = new Set();
859
+
860
+ // Validasi indentasi lebih awal supaya konsisten dengan error transpiler/LSP
861
+ const indentStack = [0];
862
+ for (let idx = 0; idx < lines.length; idx++) {
863
+ const ln = lines[idx];
864
+ while (ln.indent < indentStack[indentStack.length - 1]) {
865
+ indentStack.pop();
866
+ }
867
+ if (ln.indent !== indentStack[indentStack.length - 1]) {
868
+ throw new SyntaxError(`Kesalahan indentasi pada baris ${ln.line}: "${ln.rawText.trim()}"`);
869
+ }
870
+ const lastTok = ln.tokens[ln.tokens.length - 1];
871
+ const opensBlock = symEq(lastTok, ':');
872
+ if (opensBlock) {
873
+ const nextLn = lines[idx + 1];
874
+ if (!nextLn || nextLn.indent <= ln.indent) {
875
+ throw new SyntaxError(`Blok setelah baris ${ln.line} ("${ln.rawText.trim()}") harus memiliki indentasi lebih dalam.`);
876
+ }
877
+ indentStack.push(nextLn.indent);
878
+ }
879
+ }
880
+
881
+ let cursor = 0;
882
+
883
+ function parseBlock(expectedIndent) {
884
+ const stmts = [];
885
+ let pendingDecorators = [];
886
+
887
+ while (cursor < lines.length) {
888
+ const ln = lines[cursor];
889
+ if (ln.indent < expectedIndent) break;
890
+ if (ln.indent > expectedIndent) {
891
+ throw new SyntaxError(`Kesalahan indentasi pada baris ${ln.line}: "${ln.rawText.trim()}"`);
892
+ }
893
+
894
+ const toks = ln.tokens;
895
+ const t0 = toks[0];
896
+ const tLast = toks[toks.length - 1];
897
+
898
+ // Directive `#![kotak_pasir]` (dikomentari `#`, tetapi cek rawText di baris awal)
899
+ if (t0.value === '@') {
900
+ pendingDecorators.push({
901
+ name: toks[1]?.value || '',
902
+ tokens: toks.slice(1),
903
+ line: ln.line,
904
+ });
905
+ cursor++;
906
+ continue;
907
+ }
908
+
909
+ const decorators = pendingDecorators;
910
+ pendingDecorators = [];
911
+
912
+ // Cek `tidak_aman impor ...` atau `tidak_aman dari ...`
913
+ let unsafePrefix = false;
914
+ let sToks = toks;
915
+ if (t0.value === 'tidak_aman' && toks[1] && ['impor', 'impor_py', 'dari', 'dari_py'].includes(toks[1].value)) {
916
+ unsafePrefix = true;
917
+ sToks = toks.slice(1);
918
+ }
919
+
920
+ const head = sToks[0];
921
+
922
+ // 1. Impor
923
+ if (['impor', 'impor_py', 'import'].includes(head.value)) {
924
+ cursor++;
925
+ const modTok = sToks[1];
926
+ let target = modTok?.value || '';
927
+ let i = 2;
928
+ if (modTok?.type !== 'STRING') {
929
+ while (sToks[i] && sToks[i].value === '.' && sToks[i + 1]) {
930
+ target += '.' + sToks[i + 1].value;
931
+ i += 2;
932
+ }
933
+ }
934
+ let alias = null;
935
+ if (sToks[i] && (sToks[i].value === 'sebagai' || sToks[i].value === 'as') && sToks[i + 1]) {
936
+ alias = sToks[i + 1].value;
937
+ }
938
+ if (!alias) {
939
+ const base = target.replace(/\.(mhs|py)$/i, '').split(/[\\/]/).pop();
940
+ alias = base.split('.')[0].replace(/[^A-Za-z0-9_]/g, '_');
941
+ }
942
+ stmts.push({
943
+ kind: 'ImportStmt',
944
+ isPyImport: head.value === 'impor_py',
945
+ isUnsafe: unsafePrefix,
946
+ target,
947
+ targetIsString: modTok?.type === 'STRING',
948
+ alias,
949
+ line: ln.line,
950
+ col: head.col,
951
+ endCol: tLast.endCol,
952
+ });
953
+ continue;
954
+ }
955
+
956
+ // 2. Dari ... impor ...
957
+ if (['dari', 'dari_py', 'from'].includes(head.value)) {
958
+ cursor++;
959
+ const modTok = sToks[1];
960
+ let target = modTok?.value || '';
961
+ let i = 2;
962
+ if (modTok?.type !== 'STRING') {
963
+ while (sToks[i] && sToks[i].value === '.' && sToks[i + 1]) {
964
+ target += '.' + sToks[i + 1].value;
965
+ i += 2;
966
+ }
967
+ }
968
+ if (sToks[i] && (sToks[i].value === 'impor' || sToks[i].value === 'import')) i++;
969
+ const items = parseImportItems(sToks.slice(i));
970
+ stmts.push({
971
+ kind: 'FromImportStmt',
972
+ isPyImport: head.value === 'dari_py',
973
+ isUnsafe: unsafePrefix,
974
+ target,
975
+ targetIsString: modTok?.type === 'STRING',
976
+ items,
977
+ line: ln.line,
978
+ col: head.col,
979
+ endCol: tLast.endCol,
980
+ });
981
+ continue;
982
+ }
983
+
984
+ // 3. Fungsi / Asinkron fungsi
985
+ if (
986
+ ((head.value === 'fungsi' || head.value === 'def') ||
987
+ ((head.value === 'asinkron' || head.value === 'async') && (sToks[1]?.value === 'fungsi' || sToks[1]?.value === 'def'))) &&
988
+ tLast.value === ':'
989
+ ) {
990
+ const isAsync = head.value === 'asinkron' || head.value === 'async';
991
+ const fnIdx = isAsync ? 2 : 1;
992
+ const nameTok = sToks[fnIdx];
993
+ const openParen = sToks.findIndex((t) => t.value === '(');
994
+ let closeParen = -1;
995
+ let depth = 0;
996
+ if (openParen !== -1) {
997
+ for (let k = openParen; k < sToks.length; k++) {
998
+ if (sToks[k].value === '(') depth++;
999
+ else if (sToks[k].value === ')') {
1000
+ depth--;
1001
+ if (depth === 0) { closeParen = k; break; }
1002
+ }
1003
+ }
1004
+ }
1005
+ const params = openParen !== -1 && closeParen !== -1
1006
+ ? parseParams(sToks.slice(openParen + 1, closeParen))
1007
+ : [];
1008
+ let returnType = null;
1009
+ if (closeParen !== -1 && sToks[closeParen + 1]?.value === '->') {
1010
+ const parsedRet = parseTypeAnnotation(sToks, closeParen + 2);
1011
+ returnType = parsedRet.type;
1012
+ }
1013
+ cursor++;
1014
+ const childIndent = lines[cursor].indent;
1015
+ const body = parseBlock(childIndent);
1016
+ stmts.push({
1017
+ kind: 'FunctionDecl',
1018
+ isAsync,
1019
+ name: nameTok?.value || '',
1020
+ params,
1021
+ returnType,
1022
+ decorators,
1023
+ body,
1024
+ line: ln.line,
1025
+ col: nameTok?.col || head.col,
1026
+ endCol: nameTok?.endCol || head.endCol,
1027
+ });
1028
+ continue;
1029
+ }
1030
+
1031
+ // 4. Struktur / Kelas
1032
+ if ((head.value === 'struktur' || head.value === 'kelas' || head.value === 'class') && tLast.value === ':') {
1033
+ const nameTok = sToks[1];
1034
+ let baseClass = null;
1035
+ if (sToks[2]?.value === '(' && sToks[3]) {
1036
+ baseClass = sToks[3].value;
1037
+ }
1038
+ cursor++;
1039
+ const childIndent = lines[cursor].indent;
1040
+ const body = parseBlock(childIndent);
1041
+ stmts.push({
1042
+ kind: head.value === 'struktur' ? 'StructDecl' : 'ClassDecl',
1043
+ name: nameTok?.value || '',
1044
+ baseClass,
1045
+ decorators,
1046
+ body,
1047
+ line: ln.line,
1048
+ col: nameTok?.col || head.col,
1049
+ endCol: nameTok?.endCol || head.endCol,
1050
+ });
1051
+ continue;
1052
+ }
1053
+
1054
+ // 5. Pilihan Tipe (Enum)
1055
+ if ((head.value === 'pilihan_tipe' || head.value === 'enum') && tLast.value === ':') {
1056
+ const nameTok = sToks[1];
1057
+ cursor++;
1058
+ const childIndent = lines[cursor].indent;
1059
+ const variantLines = [];
1060
+ while (cursor < lines.length && lines[cursor].indent >= childIndent) {
1061
+ const vln = lines[cursor];
1062
+ const vt = vln.tokens;
1063
+ const vName = vt[0]?.value;
1064
+ const fields = [];
1065
+ if (vt[1]?.value === '(') {
1066
+ const closeIdx = vt.findIndex((t) => t.value === ')');
1067
+ const inner = vt.slice(2, closeIdx === -1 ? vt.length : closeIdx);
1068
+ const parsedFields = parseParams(inner);
1069
+ for (const pf of parsedFields) {
1070
+ fields.push({ name: pf.name, type: pf.type });
1071
+ }
1072
+ }
1073
+ variantLines.push({ name: vName, fields, line: vln.line, col: vt[0]?.col || 1 });
1074
+ cursor++;
1075
+ }
1076
+ stmts.push({
1077
+ kind: 'EnumDecl',
1078
+ name: nameTok?.value || '',
1079
+ variants: variantLines,
1080
+ line: ln.line,
1081
+ col: nameTok?.col || head.col,
1082
+ endCol: nameTok?.endCol || head.endCol,
1083
+ });
1084
+ continue;
1085
+ }
1086
+
1087
+ // 6. Implementasi (impl)
1088
+ if ((head.value === 'implementasi' || head.value === 'impl') && tLast.value === ':') {
1089
+ let traitName = null;
1090
+ let targetName = sToks[1]?.value || '';
1091
+ if (sToks[2]?.value === 'untuk' && sToks[3]) {
1092
+ traitName = targetName;
1093
+ targetName = sToks[3].value;
1094
+ }
1095
+ cursor++;
1096
+ const childIndent = lines[cursor].indent;
1097
+ const body = parseBlock(childIndent);
1098
+ stmts.push({
1099
+ kind: 'ImplDecl',
1100
+ traitName,
1101
+ targetName,
1102
+ body,
1103
+ line: ln.line,
1104
+ col: head.col,
1105
+ endCol: tLast.endCol,
1106
+ });
1107
+ continue;
1108
+ }
1109
+
1110
+ // 7. Tidak aman block
1111
+ if (head.value === 'tidak_aman' && tLast.value === ':') {
1112
+ cursor++;
1113
+ const childIndent = lines[cursor].indent;
1114
+ const body = parseBlock(childIndent);
1115
+ stmts.push({
1116
+ kind: 'UnsafeBlock',
1117
+ body,
1118
+ line: ln.line,
1119
+ col: head.col,
1120
+ endCol: tLast.endCol,
1121
+ });
1122
+ continue;
1123
+ }
1124
+
1125
+ // 8. Cocok (Pattern Matching)
1126
+ if ((head.value === 'cocok' || head.value === 'match') && tLast.value === ':') {
1127
+ const target = parseExpression(sToks.slice(1, -1));
1128
+ cursor++;
1129
+ const armIndent = lines[cursor].indent;
1130
+ const arms = [];
1131
+ while (cursor < lines.length && lines[cursor].indent >= armIndent) {
1132
+ const aln = lines[cursor];
1133
+ if (aln.indent > armIndent) {
1134
+ throw new SyntaxError(`Kesalahan indentasi pada cabang cocok baris ${aln.line}`);
1135
+ }
1136
+ const arrowIdx = findTopLevelToken(aln.tokens, (t) => t.value === '=>');
1137
+ if (arrowIdx === -1) {
1138
+ throw new SyntaxError(`Cabang 'cocok' pada baris ${aln.line} wajib menggunakan '=>'`);
1139
+ }
1140
+ const leftToks = aln.tokens.slice(0, arrowIdx);
1141
+ const guardIdx = findTopLevelToken(leftToks, (t) => t.value === 'jika' || t.value === 'if');
1142
+ const patToks = guardIdx === -1 ? leftToks : leftToks.slice(0, guardIdx);
1143
+ const guard = guardIdx === -1 ? null : parseExpression(leftToks.slice(guardIdx + 1));
1144
+ const rightToks = aln.tokens.slice(arrowIdx + 1);
1145
+
1146
+ let armBody = [];
1147
+ if (rightToks.length === 1 && rightToks[0].value === ':') {
1148
+ cursor++;
1149
+ const bodyIndent = lines[cursor].indent;
1150
+ armBody = parseBlock(bodyIndent);
1151
+ } else {
1152
+ cursor++;
1153
+ // Buat pseudo-statement untuk inline arm body
1154
+ armBody = parseInlineArmBody(rightToks, aln.line, aln.rawText);
1155
+ }
1156
+
1157
+ arms.push({
1158
+ pattern: parsePattern(patToks),
1159
+ guard,
1160
+ body: armBody,
1161
+ line: aln.line,
1162
+ col: aln.tokens[0]?.col || 1,
1163
+ });
1164
+ }
1165
+ stmts.push({
1166
+ kind: 'MatchStmt',
1167
+ target,
1168
+ arms,
1169
+ line: ln.line,
1170
+ col: head.col,
1171
+ endCol: tLast.endCol,
1172
+ });
1173
+ continue;
1174
+ }
1175
+
1176
+ // 9. Jika / jika cocok / selama / untuk / coba / dengan
1177
+ if ((head.value === 'jika' || head.value === 'if') && tLast.value === ':') {
1178
+ const branches = [];
1179
+ // Cabang utama
1180
+ const condSlice = sToks.slice(1, -1);
1181
+ const isIfLet = condSlice[0]?.value === 'cocok';
1182
+ if (isIfLet) {
1183
+ const eqIdx = findTopLevelToken(condSlice, (t) => t.value === '=');
1184
+ const pat = parsePattern(condSlice.slice(1, eqIdx));
1185
+ const expr = parseExpression(condSlice.slice(eqIdx + 1));
1186
+ cursor++;
1187
+ const body = parseBlock(lines[cursor].indent);
1188
+ branches.push({ isIfLet: true, pattern: pat, expr, cond: null, body, line: ln.line });
1189
+ } else {
1190
+ cursor++;
1191
+ const body = parseBlock(lines[cursor].indent);
1192
+ branches.push({ isIfLet: false, cond: parseExpression(condSlice), body, line: ln.line });
1193
+ }
1194
+
1195
+ while (cursor < lines.length && lines[cursor].indent === expectedIndent) {
1196
+ const nln = lines[cursor];
1197
+ const nh = nln.tokens[0]?.value;
1198
+ const nl = nln.tokens[nln.tokens.length - 1]?.value;
1199
+ if ((nh === 'atau_jika' || nh === 'jika_tidak' || nh === 'elif') && nl === ':') {
1200
+ const cSlice = nln.tokens.slice(1, -1);
1201
+ cursor++;
1202
+ const b = parseBlock(lines[cursor].indent);
1203
+ branches.push({ isIfLet: false, cond: parseExpression(cSlice), body: b, line: nln.line });
1204
+ } else if ((nh === 'selain_itu' || nh === 'lainnya' || nh === 'else') && nl === ':') {
1205
+ cursor++;
1206
+ const b = parseBlock(lines[cursor].indent);
1207
+ branches.push({ isElse: true, cond: null, body: b, line: nln.line });
1208
+ break;
1209
+ } else {
1210
+ break;
1211
+ }
1212
+ }
1213
+ stmts.push({ kind: 'IfStmt', branches, line: ln.line, col: head.col });
1214
+ continue;
1215
+ }
1216
+
1217
+ if ((head.value === 'selama' || head.value === 'while') && tLast.value === ':') {
1218
+ const cond = parseExpression(sToks.slice(1, -1));
1219
+ cursor++;
1220
+ const body = parseBlock(lines[cursor].indent);
1221
+ stmts.push({ kind: 'WhileStmt', cond, body, line: ln.line, col: head.col });
1222
+ continue;
1223
+ }
1224
+
1225
+ if ((head.value === 'untuk' || head.value === 'for') && tLast.value === ':') {
1226
+ let i = 1;
1227
+ let isMut = false;
1228
+ if (sToks[i]?.value === 'ubah') {
1229
+ isMut = true;
1230
+ i++;
1231
+ }
1232
+ const inIdx = findTopLevelToken(sToks, (t) => t.value === 'dalam' || t.value === 'in');
1233
+ const targetToks = inIdx !== -1 ? sToks.slice(i, inIdx) : [];
1234
+ const targets = targetToks
1235
+ .filter((t) => t.type === 'IDENT' || t.type === 'KEYWORD')
1236
+ .map((t) => ({ name: t.value, line: t.line, col: t.col, endCol: t.endCol }));
1237
+ const iter = inIdx !== -1 ? parseExpression(sToks.slice(inIdx + 1, -1)) : null;
1238
+ cursor++;
1239
+ const body = parseBlock(lines[cursor].indent);
1240
+ stmts.push({ kind: 'ForStmt', isMut, targets, iter, body, line: ln.line, col: head.col });
1241
+ continue;
1242
+ }
1243
+
1244
+ if ((head.value === 'coba' || head.value === 'try') && tLast.value === ':') {
1245
+ cursor++;
1246
+ const tryBody = parseBlock(lines[cursor].indent);
1247
+ const catches = [];
1248
+ let finallyBody = null;
1249
+ while (cursor < lines.length && lines[cursor].indent === expectedIndent) {
1250
+ const nln = lines[cursor];
1251
+ const nh = nln.tokens[0]?.value;
1252
+ const nl = nln.tokens[nln.tokens.length - 1]?.value;
1253
+ if ((nh === 'tangkap' || nh === 'except') && nl === ':') {
1254
+ const inner = nln.tokens.slice(1, -1);
1255
+ let errVar = null;
1256
+ if (inner.length === 1) errVar = inner[0].value;
1257
+ else if (inner.length >= 3 && (inner[inner.length - 2].value === 'sebagai' || inner[inner.length - 2].value === 'as')) {
1258
+ errVar = inner[inner.length - 1].value;
1259
+ }
1260
+ cursor++;
1261
+ const cBody = parseBlock(lines[cursor].indent);
1262
+ catches.push({ errVar, body: cBody, line: nln.line });
1263
+ } else if ((nh === 'akhirnya' || nh === 'finally') && nl === ':') {
1264
+ cursor++;
1265
+ finallyBody = parseBlock(lines[cursor].indent);
1266
+ break;
1267
+ } else {
1268
+ break;
1269
+ }
1270
+ }
1271
+ stmts.push({ kind: 'TryStmt', tryBody, catches, finallyBody, line: ln.line, col: head.col });
1272
+ continue;
1273
+ }
1274
+
1275
+ if ((head.value === 'dengan' || head.value === 'with') && tLast.value === ':') {
1276
+ const asIdx = findTopLevelToken(sToks, (t) => t.value === 'sebagai' || t.value === 'as');
1277
+ const ctxExpr = parseExpression(asIdx === -1 ? sToks.slice(1, -1) : sToks.slice(1, asIdx));
1278
+ const asVar = asIdx !== -1 && sToks[asIdx + 1] ? sToks[asIdx + 1].value : null;
1279
+ cursor++;
1280
+ const body = parseBlock(lines[cursor].indent);
1281
+ stmts.push({ kind: 'WithStmt', ctxExpr, asVar, body, line: ln.line, col: head.col });
1282
+ continue;
1283
+ }
1284
+
1285
+ // 10. Pernyataan tunggal
1286
+ cursor++;
1287
+ stmts.push(parseSingleStmt(sToks, ln.line, ln.rawText));
1288
+ }
1289
+
1290
+ return stmts;
1291
+ }
1292
+
1293
+ // Cek direktif komentar `#![...]` di baris awal sebelum kode
1294
+ for (const raw of rawLines) {
1295
+ const trimmed = raw.trim();
1296
+ if (!trimmed) continue;
1297
+ if (trimmed.startsWith('#![')) {
1298
+ const m = trimmed.match(/^#!\[([A-Za-z_]\w*)\]/);
1299
+ if (m) directives.add(m[1]);
1300
+ } else if (!trimmed.startsWith('#')) {
1301
+ break;
1302
+ }
1303
+ }
1304
+
1305
+ const body = parseBlock(0);
1306
+ return { kind: 'Program', directives, body, rawLines };
1307
+ }
1308
+
1309
+ function parseInlineArmBody(tokens, line, rawText) {
1310
+ if (!tokens || tokens.length === 0) return [];
1311
+ return [parseSingleStmt(tokens, line, rawText)];
1312
+ }
1313
+
1314
+ function parseSingleStmt(sToks, line, rawText) {
1315
+ const head = sToks[0];
1316
+ const tLast = sToks[sToks.length - 1];
1317
+
1318
+ if (head.value === 'kembalikan' || head.value === 'return') {
1319
+ return {
1320
+ kind: 'ReturnStmt',
1321
+ expr: sToks.length > 1 ? parseExpression(sToks.slice(1)) : null,
1322
+ line,
1323
+ col: head.col,
1324
+ };
1325
+ }
1326
+ if (head.value === 'hasilkan' || head.value === 'yield') {
1327
+ return {
1328
+ kind: 'YieldStmt',
1329
+ expr: sToks.length > 1 ? parseExpression(sToks.slice(1)) : null,
1330
+ line,
1331
+ col: head.col,
1332
+ };
1333
+ }
1334
+ if (head.value === 'berhenti' || head.value === 'break') {
1335
+ return { kind: 'BreakStmt', line, col: head.col };
1336
+ }
1337
+ if (head.value === 'lanjut' || head.value === 'continue') {
1338
+ return { kind: 'ContinueStmt', line, col: head.col };
1339
+ }
1340
+ if (head.value === 'lewat' || head.value === 'pass') {
1341
+ return { kind: 'PassStmt', line, col: head.col };
1342
+ }
1343
+ if (head.value === 'lempar' || head.value === 'raise') {
1344
+ return {
1345
+ kind: 'RaiseStmt',
1346
+ expr: parseExpression(sToks.slice(1)),
1347
+ line,
1348
+ col: head.col,
1349
+ endCol: tLast.endCol,
1350
+ };
1351
+ }
1352
+ if (head.value === 'pastikan' || head.value === 'assert') {
1353
+ const commaIdx = findTopLevelToken(sToks, (t) => t.value === ',');
1354
+ const cond = parseExpression(commaIdx === -1 ? sToks.slice(1) : sToks.slice(1, commaIdx));
1355
+ const msg = commaIdx === -1 ? null : parseExpression(sToks.slice(commaIdx + 1));
1356
+ return { kind: 'AssertStmt', cond, msg, line, col: head.col };
1357
+ }
1358
+ if (head.value === 'umum' || head.value === 'global') {
1359
+ const names = sToks.slice(1).filter((t) => t.type === 'IDENT').map((t) => t.value);
1360
+ return { kind: 'GlobalStmt', names, line, col: head.col };
1361
+ }
1362
+
1363
+ // Deklarasi konst / tetap / ubah
1364
+ if (head.value === 'konst' || head.value === 'tetap' || head.value === 'ubah') {
1365
+ const eqIdx = findTopLevelToken(sToks, (t) => t.value === '=');
1366
+ const leftSlice = eqIdx === -1 ? sToks.slice(1) : sToks.slice(1, eqIdx);
1367
+ const colonIdx = findTopLevelToken(leftSlice, (t) => t.value === ':');
1368
+ const namePart = colonIdx === -1 ? leftSlice : leftSlice.slice(0, colonIdx);
1369
+ const type = colonIdx === -1 ? null : parseTypeAnnotation(leftSlice, colonIdx + 1).type;
1370
+ const names = namePart
1371
+ .filter((t) => t.type === 'IDENT' || t.type === 'KEYWORD')
1372
+ .map((t) => ({ name: t.value, line: t.line, col: t.col, endCol: t.endCol }));
1373
+ const value = eqIdx === -1 ? null : parseExpression(sToks.slice(eqIdx + 1));
1374
+ return {
1375
+ kind: 'VarDecl',
1376
+ qualifier: head.value,
1377
+ names,
1378
+ type,
1379
+ value,
1380
+ line,
1381
+ col: head.col,
1382
+ endCol: tLast.endCol,
1383
+ };
1384
+ }
1385
+
1386
+ // Assignment biasa / augmented (+=, -=, dst.) / type-annotated field or var (`x: T = val`)
1387
+ const assignIdx = findTopLevelToken(
1388
+ sToks,
1389
+ (t) => ['=', '+=', '-=', '*=', '/=', '%=', '//=', '**='].includes(t.value)
1390
+ );
1391
+ if (assignIdx !== -1) {
1392
+ const opTok = sToks[assignIdx];
1393
+ const leftSlice = sToks.slice(0, assignIdx);
1394
+ const colonIdx = opTok.value === '=' ? findTopLevelToken(leftSlice, (t) => t.value === ':') : -1;
1395
+ const targetSlice = colonIdx === -1 ? leftSlice : leftSlice.slice(0, colonIdx);
1396
+ const type = colonIdx === -1 ? null : parseTypeAnnotation(leftSlice, colonIdx + 1).type;
1397
+ const target = parseExpression(targetSlice);
1398
+ const value = parseExpression(sToks.slice(assignIdx + 1));
1399
+ return {
1400
+ kind: 'AssignStmt',
1401
+ op: opTok.value,
1402
+ target,
1403
+ type,
1404
+ value,
1405
+ line,
1406
+ col: head.col,
1407
+ endCol: tLast.endCol,
1408
+ };
1409
+ }
1410
+
1411
+ // Deklarasi field bertipe tanpa nilai awal (mis. `id_produk: str` di dalam `kelas`/`struktur`)
1412
+ const colonIdx = findTopLevelToken(sToks, (t) => t.value === ':');
1413
+ if (colonIdx === 1 && (sToks[0].type === 'IDENT' || sToks[0].type === 'KEYWORD')) {
1414
+ const parsed = parseTypeAnnotation(sToks, 2);
1415
+ return {
1416
+ kind: 'FieldDecl',
1417
+ name: sToks[0].value,
1418
+ type: parsed.type,
1419
+ line,
1420
+ col: sToks[0].col,
1421
+ endCol: tLast.endCol,
1422
+ };
1423
+ }
1424
+
1425
+ return {
1426
+ kind: 'ExprStmt',
1427
+ expr: parseExpression(sToks),
1428
+ rawText,
1429
+ line,
1430
+ col: head.col,
1431
+ endCol: tLast.endCol,
1432
+ };
1433
+ }
1434
+
1435
+ function parsePattern(tokens) {
1436
+ if (!tokens || tokens.length === 0) return { kind: 'Wildcard' };
1437
+ let isMut = false;
1438
+ if (symEq(tokens[0], 'ubah') && tokens.length >= 2) {
1439
+ isMut = true;
1440
+ tokens = tokens.slice(1);
1441
+ }
1442
+ const t0 = tokens[0];
1443
+
1444
+ if (tokens.length === 1) {
1445
+ if (t0.type === 'NUMBER') {
1446
+ return { kind: 'Literal', litType: t0.isFloat ? 'desimal' : 'bulat', value: Number(t0.value), line: t0.line, col: t0.col };
1447
+ }
1448
+ if (t0.type === 'STRING') {
1449
+ return { kind: 'Literal', litType: 'teks', value: t0.value, line: t0.line, col: t0.col };
1450
+ }
1451
+ if (t0.value === '_') return { kind: 'Wildcard', line: t0.line, col: t0.col };
1452
+ if (t0.value === 'TidakAda') return { kind: 'Variant', name: 'TidakAda', args: [], line: t0.line, col: t0.col };
1453
+ if (t0.value === 'Benar' || t0.value === 'benar' || t0.value === 'True') {
1454
+ return { kind: 'Literal', litType: 'bool', value: true, line: t0.line, col: t0.col };
1455
+ }
1456
+ if (t0.value === 'Salah' || t0.value === 'salah' || t0.value === 'False') {
1457
+ return { kind: 'Literal', litType: 'bool', value: false, line: t0.line, col: t0.col };
1458
+ }
1459
+ // Bisa berupa nama varian unit enum atau pengikatan variabel (ditentukan analyzer/transpiler)
1460
+ return { kind: 'IdentOrUnitVariant', name: t0.value, isMut, line: t0.line, col: t0.col };
1461
+ }
1462
+
1463
+ // Range pattern `1..10` atau `1..=10`
1464
+ if (tokens.length === 3 && (tokens[1].value === '..' || tokens[1].value === '..=')) {
1465
+ return {
1466
+ kind: 'Range',
1467
+ inclusive: tokens[1].value === '..=',
1468
+ start: parseExpression([tokens[0]]),
1469
+ end: parseExpression([tokens[2]]),
1470
+ line: t0.line,
1471
+ col: t0.col,
1472
+ };
1473
+ }
1474
+
1475
+ // Variant tuple pattern: `Ada(x)`, `Ok(v)`, `Galat(e)`, `Tertunda(alasan)` atau `Status.Aktif`
1476
+ if (tokens[1]?.value === '.' && tokens[2]) {
1477
+ const rest = tokens.slice(2);
1478
+ const sub = parsePattern(rest);
1479
+ return {
1480
+ kind: 'QualifiedVariant',
1481
+ enumName: t0.value,
1482
+ variantName: sub.name || tokens[2].value,
1483
+ args: sub.args || [],
1484
+ line: t0.line,
1485
+ col: t0.col,
1486
+ };
1487
+ }
1488
+
1489
+ if (tokens[1]?.value === '(') {
1490
+ const closeIdx = tokens.length - 1;
1491
+ const innerToks = tokens.slice(2, tokens[closeIdx]?.value === ')' ? closeIdx : tokens.length);
1492
+ const args = [];
1493
+ let start = 0;
1494
+ let depth = 0;
1495
+ for (let i = 0; i <= innerToks.length; i++) {
1496
+ if (i === innerToks.length || (depth === 0 && innerToks[i].value === ',')) {
1497
+ const slice = innerToks.slice(start, i);
1498
+ if (slice.length > 0) args.push(parsePattern(slice));
1499
+ start = i + 1;
1500
+ } else if (innerToks[i].value === '(') depth++;
1501
+ else if (innerToks[i].value === ')') depth = Math.max(0, depth - 1);
1502
+ }
1503
+ return {
1504
+ kind: 'Variant',
1505
+ name: t0.value,
1506
+ args,
1507
+ line: t0.line,
1508
+ col: t0.col,
1509
+ };
1510
+ }
1511
+
1512
+ return { kind: 'ExprPattern', expr: parseExpression(tokens), line: t0.line, col: t0.col };
1513
+ }
1514
+
1515
+ module.exports = {
1516
+ TYPE_ALIASES,
1517
+ canonicalTypeName,
1518
+ parseTypeAnnotation,
1519
+ formatType,
1520
+ parseExpression,
1521
+ parseProgram,
1522
+ parsePattern,
1523
+ };