mhs-lang 2.3.0 → 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.
Files changed (60) hide show
  1. package/README.md +47 -134
  2. package/bin/mhs.js +89 -81
  3. package/examples/demo_lengkap.mhs +12 -9
  4. package/examples/halo.mhs +7 -7
  5. package/examples/python_native.mhs +5 -4
  6. package/examples/rumus_elektronika.mhs +6 -6
  7. package/examples/tes_semua_modul.mhs +7 -7
  8. package/examples/utama_impor.mhs +8 -7
  9. package/package.json +6 -7
  10. package/src/index.js +84 -28
  11. package/src/language_server.js +58 -28
  12. package/src/lexer.js +444 -0
  13. package/src/modules/data_json.js +16 -4
  14. package/src/modules/index.js +0 -18
  15. package/src/parser.js +1523 -0
  16. package/src/py_modules/data_json.py +13 -2
  17. package/src/py_transpiler.js +1279 -202
  18. package/src/rust_runtime.js +443 -0
  19. package/src/safety_analyzer.js +2139 -0
  20. package/src/stdlib.js +123 -77
  21. package/src/transpiler.js +813 -337
  22. package/LICENSE +0 -21
  23. package/assets/mhs-file-icons.vsix +0 -0
  24. package/assets/mhs.ico +0 -0
  25. package/assets/mhs.svg +0 -3
  26. package/examples/__pycache__/alat_py.cpython-312.pyc +0 -0
  27. package/examples/tes_modul_baru.mhs +0 -44
  28. package/scripts/postinstall.js +0 -276
  29. package/src/modules/antrian.js +0 -37
  30. package/src/modules/arsip.js +0 -31
  31. package/src/modules/basis_data.js +0 -47
  32. package/src/modules/iterasi.js +0 -136
  33. package/src/modules/jalur.js +0 -77
  34. package/src/modules/proses.js +0 -43
  35. package/src/modules/statistika.js +0 -79
  36. package/src/modules/tabel.js +0 -83
  37. package/src/py_modules/__pycache__/antrian.cpython-312.pyc +0 -0
  38. package/src/py_modules/__pycache__/basis_data.cpython-312.pyc +0 -0
  39. package/src/py_modules/__pycache__/berkas.cpython-312.pyc +0 -0
  40. package/src/py_modules/__pycache__/data_json.cpython-312.pyc +0 -0
  41. package/src/py_modules/__pycache__/iterasi.cpython-312.pyc +0 -0
  42. package/src/py_modules/__pycache__/jalur.cpython-312.pyc +0 -0
  43. package/src/py_modules/__pycache__/jaringan.cpython-312.pyc +0 -0
  44. package/src/py_modules/__pycache__/koleksi.cpython-312.pyc +0 -0
  45. package/src/py_modules/__pycache__/kripto.cpython-312.pyc +0 -0
  46. package/src/py_modules/__pycache__/matematika.cpython-312.pyc +0 -0
  47. package/src/py_modules/__pycache__/modul_acak.cpython-312.pyc +0 -0
  48. package/src/py_modules/__pycache__/pola.cpython-312.pyc +0 -0
  49. package/src/py_modules/__pycache__/sistem.cpython-312.pyc +0 -0
  50. package/src/py_modules/__pycache__/statistika.cpython-312.pyc +0 -0
  51. package/src/py_modules/__pycache__/uji.cpython-312.pyc +0 -0
  52. package/src/py_modules/__pycache__/waktu.cpython-312.pyc +0 -0
  53. package/src/py_modules/antrian.py +0 -20
  54. package/src/py_modules/arsip.py +0 -37
  55. package/src/py_modules/basis_data.py +0 -29
  56. package/src/py_modules/iterasi.py +0 -37
  57. package/src/py_modules/jalur.py +0 -47
  58. package/src/py_modules/proses.py +0 -35
  59. package/src/py_modules/statistika.py +0 -29
  60. package/src/py_modules/tabel.py +0 -29
@@ -0,0 +1,2139 @@
1
+ /**
2
+ * Penganalisis Keamanan Statis ala Rust untuk Bahasa .mhs
3
+ * Menegakkan: Immutability by default, Ownership/Move/Borrow Checker (NLL),
4
+ * Static Type Checking, Null-safety (Opsi/Hasil/?), Exhaustive `cocok`,
5
+ * serta batas `tidak_aman` dan `--sandbox`.
6
+ */
7
+
8
+ const { parseProgram, formatType, canonicalTypeName } = require('./parser');
9
+
10
+ const COPY_TYPES = new Set(['bulat', 'desimal', 'angka', 'bool', 'Unit', 'bytes']);
11
+ const UNSAFE_HOST_MODULES = new Set([
12
+ 'os', 'sys', 'subprocess', 'ctypes', 'shutil', 'socket', 'importlib',
13
+ 'fs', 'child_process', 'vm', 'net', 'dgram', 'cluster', 'worker_threads',
14
+ 'process', 'http', 'https',
15
+ ]);
16
+ const SANDBOX_FORBIDDEN_MODULES = new Set([
17
+ ...UNSAFE_HOST_MODULES,
18
+ 'berkas', 'jaringan', 'sistem', 'pathlib', 'getpass', 'urllib', 'requests', 'asyncio',
19
+ ]);
20
+
21
+ const BUILTIN_BORROWING_FUNCS = new Set([
22
+ 'cetak', 'print', 'panjang', 'len', 'tipe', 'type', 'mengandung',
23
+ 'jumlah', 'sum', 'urutkan', 'sorted', 'balik', 'reversed',
24
+ 'min_nilai', 'min', 'maks_nilai', 'max', 'semua', 'all',
25
+ 'ada_yang', 'any', 'enumerasi', 'enumerate', 'pasangkan', 'zip',
26
+ 'kunci', 'nilai', 'salin', 'isinstance', 'hasattr', 'getattr',
27
+ 'teks', 'str', 'bulat', 'int', 'desimal', 'float', 'angka',
28
+ 'masukan', 'input',
29
+ 'huruf_besar', 'huruf_kecil', 'potong', 'ganti', 'pisah', 'gabung',
30
+ 'dari_kosong', 'ambil_indeks', 'ambil_kunci', 'asdict', 'repr',
31
+ 'round', 'bulatkan', 'mutlak', 'abs', 'akar', 'pangkat', 'pow',
32
+ 'bawah', 'atas',
33
+ ]);
34
+
35
+ const MUTATING_METHODS = new Set([
36
+ 'append', 'extend', 'insert', 'pop', 'remove', 'clear', 'sort', 'reverse',
37
+ 'update', 'setdefault', 'add', 'discard', 'push', 'splice', 'shift', 'unshift',
38
+ ]);
39
+
40
+ const MUTATING_STDLIB_FUNCS = new Set(['tambah', 'hapus', 'kocok']);
41
+
42
+ const KNOWN_BUILTINS = new Set([
43
+ ...BUILTIN_BORROWING_FUNCS,
44
+ ...MUTATING_STDLIB_FUNCS,
45
+ 'masukan', 'input', 'rentang', 'range', 'daftar', 'list', 'kamus', 'dict',
46
+ 'himpunan', 'set', 'tupel', 'tuple', 'petakan', 'map', 'saring', 'filter',
47
+ 'acak', 'waktu_sekarang', 'tunggu', 'buka', 'open', 'bekukan',
48
+ 'Ada', 'TidakAda', 'Ok', 'Galat', 'panik',
49
+ 'urai_bulat', 'urai_desimal', 'tambah_aman', 'kurang_aman', 'kali_aman', 'bagi_aman',
50
+ '__name__', '__file__', 'super', 'bytes', 'bool', 'Exception', 'Error', 'ValueError',
51
+ 'TypeError', 'KeyError', 'IndexError', 'RuntimeError',
52
+ 'True', 'False', 'None', 'Benar', 'Salah', 'Kosong',
53
+ ]);
54
+
55
+ const BUILTIN_MODULES = new Set([
56
+ 'matematika', 'modul_acak', 'acak', 'waktu', 'berkas', 'sistem',
57
+ 'data_json', 'json_id', 'pola', 'koleksi', 'kripto', 'jaringan', 'uji',
58
+ ]);
59
+
60
+ class MhsSafetyError extends Error {
61
+ constructor(diagnostics, rawLines = [], filename = '<mhs>') {
62
+ const formatted = diagnostics.map((d) => formatDiagnostic(d, rawLines, filename)).join('\n\n');
63
+ super(formatted);
64
+ this.name = 'MhsSafetyError';
65
+ this.diagnostics = diagnostics;
66
+ this.primary = diagnostics[0];
67
+ }
68
+ }
69
+
70
+ function formatDiagnostic(diag, rawLines = [], filename = '<mhs>') {
71
+ const lineIdx = Math.max(0, (diag.line || 1) - 1);
72
+ const lineText = rawLines[lineIdx] || '';
73
+ const col = Math.max(1, diag.col || 1);
74
+ const len = Math.max(1, (diag.endCol ? diag.endCol - col : 1));
75
+ const lineLabel = String(diag.line || 1);
76
+ const pad = ' '.repeat(lineLabel.length);
77
+ const caretPad = ' '.repeat(Math.max(0, col - 1));
78
+ const carets = '^'.repeat(Math.min(len, Math.max(1, lineText.length - col + 1)));
79
+
80
+ const lines = [
81
+ `${diag.severity === 'warning' ? 'peringatan' : 'galat'}[${diag.code}]: ${diag.message}`,
82
+ ` --> ${filename}:${diag.line || 1}:${col}`,
83
+ ` ${pad} |`,
84
+ ` ${lineLabel} | ${lineText}`,
85
+ ` ${pad} | ${caretPad}${carets}`,
86
+ ];
87
+ if (diag.note) {
88
+ lines.push(` ${pad} = catatan: ${diag.note}`);
89
+ }
90
+ if (diag.hint) {
91
+ lines.push(` ${pad} = bantuan: ${diag.hint}`);
92
+ }
93
+ return lines.join('\n');
94
+ }
95
+
96
+ function makeType(name, args = []) {
97
+ return { kind: 'Named', name: canonicalTypeName(name), args };
98
+ }
99
+
100
+ const T_UNKNOWN = makeType('TidakDiketahui');
101
+ const T_ANY = makeType('ApaSaja');
102
+ const T_UNIT = makeType('Unit');
103
+ const T_INT = makeType('bulat');
104
+ const T_FLOAT = makeType('desimal');
105
+ const T_NUM = makeType('angka');
106
+ const T_STR = makeType('teks');
107
+ const T_BOOL = makeType('bool');
108
+ const T_BYTES = makeType('bytes');
109
+
110
+ function isUnknownOrAny(t) {
111
+ return !t || (t.kind === 'Named' && (t.name === 'TidakDiketahui' || t.name === 'ApaSaja'));
112
+ }
113
+
114
+ function isCopyType(t) {
115
+ if (!t) return true;
116
+ if (t.kind === 'Pinjam') return true;
117
+ if (t.kind === 'PinjamUbah') return false;
118
+ if (t.kind === 'Named') {
119
+ if (COPY_TYPES.has(t.name)) return true;
120
+ if (t.name === 'Tupel' || t.name === 'Opsi' || t.name === 'Hasil') {
121
+ if (!t.args || t.args.length === 0) return true;
122
+ return t.args.every(isCopyType);
123
+ }
124
+ if (t.name === 'Fungsi') return true;
125
+ // teks, Daftar, Kamus, Himpunan, struct, class, enum dengan data -> Move type
126
+ if (t.name === 'TidakDiketahui' || t.name === 'ApaSaja') return true;
127
+ return false;
128
+ }
129
+ return false;
130
+ }
131
+
132
+ function typesCompatible(expected, actual) {
133
+ if (isUnknownOrAny(expected) || isUnknownOrAny(actual)) return true;
134
+ if (expected.kind === 'Pinjam' && (actual.kind === 'Pinjam' || actual.kind === 'PinjamUbah')) {
135
+ return typesCompatible(expected.inner, actual.inner);
136
+ }
137
+ if (expected.kind === 'PinjamUbah' && actual.kind === 'PinjamUbah') {
138
+ return typesCompatible(expected.inner, actual.inner);
139
+ }
140
+ if (expected.kind !== actual.kind) return false;
141
+ if (expected.name === 'angka' && (actual.name === 'bulat' || actual.name === 'desimal' || actual.name === 'angka')) {
142
+ return true;
143
+ }
144
+ if (expected.name === 'desimal' && actual.name === 'bulat') {
145
+ // Promosi implisit bulat ke desimal saat anotasi eksplisit desimal? Di Rust tidak implisit,
146
+ // tapi angka/float di Python sering bercampur — cek ketat kecuali target `angka`.
147
+ return false;
148
+ }
149
+ if (expected.name !== actual.name) return false;
150
+ if (expected.args && actual.args && expected.args.length > 0 && actual.args.length > 0) {
151
+ const len = Math.min(expected.args.length, actual.args.length);
152
+ for (let i = 0; i < len; i++) {
153
+ if (!typesCompatible(expected.args[i], actual.args[i])) return false;
154
+ }
155
+ }
156
+ return true;
157
+ }
158
+
159
+ /**
160
+ * Mengumpulkan semua baris di mana setiap variabel dipakai di dalam daftar statement (untuk NLL).
161
+ */
162
+ function collectUsesInExpr(expr, map) {
163
+ if (!expr) return;
164
+ switch (expr.kind) {
165
+ case 'Ident': {
166
+ const prev = map.get(expr.name) || 0;
167
+ if (expr.line > prev) map.set(expr.name, expr.line);
168
+ break;
169
+ }
170
+ case 'FString':
171
+ for (const sub of expr.embeddedAsts || []) collectUsesInExpr(sub, map);
172
+ break;
173
+ case 'Unary':
174
+ collectUsesInExpr(expr.operand, map);
175
+ break;
176
+ case 'Borrow':
177
+ case 'Move':
178
+ case 'DerefOrSpread':
179
+ case 'KwSpread':
180
+ case 'Await':
181
+ collectUsesInExpr(expr.target, map);
182
+ break;
183
+ case 'TryPropagate':
184
+ collectUsesInExpr(expr.expr, map);
185
+ break;
186
+ case 'Binary':
187
+ collectUsesInExpr(expr.left, map);
188
+ collectUsesInExpr(expr.right, map);
189
+ break;
190
+ case 'Range':
191
+ collectUsesInExpr(expr.start, map);
192
+ collectUsesInExpr(expr.end, map);
193
+ break;
194
+ case 'Ternary':
195
+ collectUsesInExpr(expr.consequent, map);
196
+ collectUsesInExpr(expr.cond, map);
197
+ collectUsesInExpr(expr.alternate, map);
198
+ break;
199
+ case 'Call':
200
+ collectUsesInExpr(expr.callee, map);
201
+ for (const a of expr.args || []) collectUsesInExpr(a, map);
202
+ for (const kw of expr.kwargs || []) collectUsesInExpr(kw.value, map);
203
+ break;
204
+ case 'Member':
205
+ collectUsesInExpr(expr.object, map);
206
+ break;
207
+ case 'Index':
208
+ collectUsesInExpr(expr.object, map);
209
+ collectUsesInExpr(expr.index, map);
210
+ break;
211
+ case 'Slice':
212
+ collectUsesInExpr(expr.object, map);
213
+ collectUsesInExpr(expr.start, map);
214
+ collectUsesInExpr(expr.end, map);
215
+ collectUsesInExpr(expr.step, map);
216
+ break;
217
+ case 'List':
218
+ case 'Tuple':
219
+ case 'Set':
220
+ for (const it of expr.items || []) collectUsesInExpr(it, map);
221
+ break;
222
+ case 'Dict':
223
+ for (const e of expr.entries || []) {
224
+ collectUsesInExpr(e.key, map);
225
+ collectUsesInExpr(e.value, map);
226
+ }
227
+ break;
228
+ case 'ListComp':
229
+ case 'GeneratorComp':
230
+ collectUsesInExpr(expr.body, map);
231
+ for (const cl of expr.clauses || []) {
232
+ collectUsesInExpr(cl.iter, map);
233
+ collectUsesInExpr(cl.cond, map);
234
+ }
235
+ break;
236
+ case 'DictComp':
237
+ collectUsesInExpr(expr.key, map);
238
+ collectUsesInExpr(expr.value, map);
239
+ for (const cl of expr.clauses || []) {
240
+ collectUsesInExpr(cl.iter, map);
241
+ collectUsesInExpr(cl.cond, map);
242
+ }
243
+ break;
244
+ case 'Lambda':
245
+ collectUsesInExpr(expr.body, map);
246
+ break;
247
+ }
248
+ }
249
+
250
+ function collectLastUses(stmts, map = new Map()) {
251
+ for (const st of stmts) {
252
+ switch (st.kind) {
253
+ case 'VarDecl':
254
+ collectUsesInExpr(st.value, map);
255
+ break;
256
+ case 'AssignStmt':
257
+ collectUsesInExpr(st.target, map);
258
+ collectUsesInExpr(st.value, map);
259
+ break;
260
+ case 'ExprStmt':
261
+ case 'ReturnStmt':
262
+ case 'YieldStmt':
263
+ case 'RaiseStmt':
264
+ collectUsesInExpr(st.expr, map);
265
+ break;
266
+ case 'AssertStmt':
267
+ collectUsesInExpr(st.cond, map);
268
+ collectUsesInExpr(st.msg, map);
269
+ break;
270
+ case 'IfStmt':
271
+ for (const br of st.branches) {
272
+ collectUsesInExpr(br.cond, map);
273
+ collectUsesInExpr(br.expr, map);
274
+ collectLastUses(br.body, map);
275
+ }
276
+ break;
277
+ case 'WhileStmt':
278
+ collectUsesInExpr(st.cond, map);
279
+ collectLastUses(st.body, map);
280
+ break;
281
+ case 'ForStmt':
282
+ collectUsesInExpr(st.iter, map);
283
+ collectLastUses(st.body, map);
284
+ break;
285
+ case 'MatchStmt':
286
+ collectUsesInExpr(st.target, map);
287
+ for (const arm of st.arms) {
288
+ collectUsesInExpr(arm.guard, map);
289
+ collectLastUses(arm.body, map);
290
+ }
291
+ break;
292
+ case 'UnsafeBlock':
293
+ collectLastUses(st.body, map);
294
+ break;
295
+ case 'TryStmt':
296
+ collectLastUses(st.tryBody, map);
297
+ for (const c of st.catches) collectLastUses(c.body, map);
298
+ if (st.finallyBody) collectLastUses(st.finallyBody, map);
299
+ break;
300
+ case 'WithStmt':
301
+ collectUsesInExpr(st.ctxExpr, map);
302
+ collectLastUses(st.body, map);
303
+ break;
304
+ }
305
+ }
306
+ return map;
307
+ }
308
+
309
+ function analyzeSafety(source, options = {}) {
310
+ const { filename = '<mhs>', sandbox: optSandbox = false, isRepl = false } = options;
311
+ const program = parseProgram(source);
312
+ const sandbox = optSandbox || program.directives.has('kotak_pasir');
313
+ const diagnostics = [];
314
+
315
+ const functions = new Map();
316
+ const structs = new Map(); // name -> { fields: Map, methods: Map, hasDrop: bool, isClass: bool }
317
+ const enums = new Map(); // name -> { variants: Map<vName, fields>, methods: Map, hasDrop: bool }
318
+ const variantToEnum = new Map();
319
+ const usesTanyaInFn = new Set(); // line keys of functions using `?`
320
+ const mutBorrowedBindings = new Set(); // "line:name" of variables that get &ubah borrowed
321
+ const droppableVars = new Map(); // blockKey -> Set of varNames
322
+
323
+ function addError(code, line, col, endCol, message, hint = null, note = null, severity = 'error') {
324
+ diagnostics.push({ code, line, col, endCol, message, hint, note, severity });
325
+ }
326
+
327
+ // Registrasi fungsi bawaan yang punya tipe pengembalian jelas
328
+ functions.set('urai_bulat', {
329
+ params: [{ name: 's', type: makeType('Pinjam', [T_STR]), isBorrow: true }],
330
+ returnType: makeType('Hasil', [T_INT, T_STR]),
331
+ isBuiltin: true,
332
+ });
333
+ functions.set('urai_desimal', {
334
+ params: [{ name: 's', type: makeType('Pinjam', [T_STR]), isBorrow: true }],
335
+ returnType: makeType('Hasil', [T_FLOAT, T_STR]),
336
+ isBuiltin: true,
337
+ });
338
+ functions.set('ambil_indeks', {
339
+ params: [{ name: 'k', type: makeType('Pinjam', [T_ANY]), isBorrow: true }, { name: 'i', type: T_INT }],
340
+ returnType: makeType('Opsi', [T_ANY]),
341
+ isBuiltin: true,
342
+ });
343
+ functions.set('ambil_kunci', {
344
+ params: [{ name: 'k', type: makeType('Pinjam', [T_ANY]), isBorrow: true }, { name: 'kunci', type: T_STR }],
345
+ returnType: makeType('Opsi', [T_ANY]),
346
+ isBuiltin: true,
347
+ });
348
+ functions.set('dari_kosong', {
349
+ params: [{ name: 'v', type: T_ANY }],
350
+ returnType: makeType('Opsi', [T_ANY]),
351
+ isBuiltin: true,
352
+ });
353
+ functions.set('tambah_aman', {
354
+ params: [{ name: 'a', type: T_INT }, { name: 'b', type: T_INT }],
355
+ returnType: makeType('Hasil', [T_INT, T_STR]),
356
+ isBuiltin: true,
357
+ });
358
+ functions.set('kurang_aman', {
359
+ params: [{ name: 'a', type: T_INT }, { name: 'b', type: T_INT }],
360
+ returnType: makeType('Hasil', [T_INT, T_STR]),
361
+ isBuiltin: true,
362
+ });
363
+ functions.set('kali_aman', {
364
+ params: [{ name: 'a', type: T_INT }, { name: 'b', type: T_INT }],
365
+ returnType: makeType('Hasil', [T_INT, T_STR]),
366
+ isBuiltin: true,
367
+ });
368
+ functions.set('bagi_aman', {
369
+ params: [{ name: 'a', type: T_NUM }, { name: 'b', type: T_NUM }],
370
+ returnType: makeType('Hasil', [T_FLOAT, T_STR]),
371
+ isBuiltin: true,
372
+ });
373
+
374
+ // Scope class
375
+ class Scope {
376
+ constructor(parent = null, kind = 'block', depth = 0) {
377
+ this.parent = parent;
378
+ this.kind = kind; // 'module' | 'function' | 'block' | 'class'
379
+ this.depth = depth;
380
+ this.bindings = new Map();
381
+ this.borrows = []; // active borrows created in or visible to this scope
382
+ }
383
+
384
+ lookup(name) {
385
+ if (this.bindings.has(name)) return this.bindings.get(name);
386
+ return this.parent ? this.parent.lookup(name) : null;
387
+ }
388
+
389
+ lookupOwn(name) {
390
+ return this.bindings.get(name) || null;
391
+ }
392
+
393
+ cloneStates() {
394
+ const snap = new Map();
395
+ let cur = this;
396
+ while (cur) {
397
+ for (const [k, b] of cur.bindings) {
398
+ if (!snap.has(k)) snap.set(k, b.state);
399
+ }
400
+ cur = cur.parent;
401
+ }
402
+ return snap;
403
+ }
404
+
405
+ restoreStates(snap) {
406
+ let cur = this;
407
+ while (cur) {
408
+ for (const [k, b] of cur.bindings) {
409
+ if (snap.has(k)) b.state = snap.get(k);
410
+ }
411
+ cur = cur.parent;
412
+ }
413
+ }
414
+ }
415
+
416
+ // Pass 1: Hoist top-level declarations (functions, structs, classes, enums, impls)
417
+ function hoistDeclarations(stmts) {
418
+ for (const st of stmts) {
419
+ if (st.kind === 'FunctionDecl') {
420
+ functions.set(st.name, {
421
+ params: st.params,
422
+ returnType: st.returnType || T_UNIT,
423
+ hasExplicitReturn: !!st.returnType,
424
+ decorators: st.decorators,
425
+ node: st,
426
+ });
427
+ } else if (st.kind === 'StructDecl' || st.kind === 'ClassDecl') {
428
+ const fields = new Map();
429
+ const methods = new Map();
430
+ let hasDrop = false;
431
+ for (const item of st.body) {
432
+ if (item.kind === 'FieldDecl') {
433
+ fields.set(item.name, item.type || T_UNKNOWN);
434
+ } else if (item.kind === 'AssignStmt' && item.target?.kind === 'Ident') {
435
+ fields.set(item.target.name, item.type || T_UNKNOWN);
436
+ } else if (item.kind === 'FunctionDecl') {
437
+ methods.set(item.name, item);
438
+ if (item.name === 'lepas') hasDrop = true;
439
+ if ((item.name === '__init__' || item.name === '__inisialisasi__') && st.kind === 'ClassDecl') {
440
+ for (const bStmt of item.body) {
441
+ if (
442
+ bStmt.kind === 'AssignStmt' &&
443
+ bStmt.target?.kind === 'Member' &&
444
+ bStmt.target.object?.kind === 'Ident' &&
445
+ (bStmt.target.object.name === 'diri' || bStmt.target.object.name === 'self')
446
+ ) {
447
+ if (!fields.has(bStmt.target.property)) {
448
+ fields.set(bStmt.target.property, bStmt.type || T_UNKNOWN);
449
+ }
450
+ }
451
+ }
452
+ }
453
+ }
454
+ }
455
+ structs.set(st.name, { fields, methods, hasDrop, isClass: st.kind === 'ClassDecl', node: st });
456
+ } else if (st.kind === 'EnumDecl') {
457
+ const variants = new Map();
458
+ for (const v of st.variants) {
459
+ variants.set(v.name, v.fields);
460
+ variantToEnum.set(v.name, st.name);
461
+ }
462
+ enums.set(st.name, { variants, methods: new Map(), hasDrop: false, node: st });
463
+ } else if (st.kind === 'ImplDecl') {
464
+ const targetInfo = structs.get(st.targetName) || enums.get(st.targetName);
465
+ if (targetInfo) {
466
+ if (st.traitName === 'Lepas' || st.traitName === 'Drop') {
467
+ targetInfo.hasDrop = true;
468
+ }
469
+ for (const item of st.body) {
470
+ if (item.kind === 'FunctionDecl') {
471
+ targetInfo.methods.set(item.name, item);
472
+ if (item.name === 'lepas') targetInfo.hasDrop = true;
473
+ }
474
+ }
475
+ }
476
+ }
477
+ }
478
+ }
479
+
480
+ hoistDeclarations(program.body);
481
+
482
+ const rootScope = new Scope(null, 'module', 0);
483
+ // Masukkan simbol yang di-hoist ke rootScope
484
+ for (const [fnName] of functions) {
485
+ rootScope.bindings.set(fnName, {
486
+ name: fnName, type: makeType('Fungsi'), mutable: false, isConst: false,
487
+ state: 'owned', scopeDepth: 0, isHoisted: true, declLine: 1,
488
+ });
489
+ }
490
+ for (const [sName] of structs) {
491
+ rootScope.bindings.set(sName, {
492
+ name: sName, type: makeType('Tipe'), mutable: false, isConst: false,
493
+ state: 'owned', scopeDepth: 0, isHoisted: true, declLine: 1,
494
+ });
495
+ }
496
+ for (const [eName, eInfo] of enums) {
497
+ rootScope.bindings.set(eName, {
498
+ name: eName, type: makeType('Tipe'), mutable: false, isConst: false,
499
+ state: 'owned', scopeDepth: 0, isHoisted: true, declLine: 1,
500
+ });
501
+ for (const [vName] of eInfo.variants) {
502
+ rootScope.bindings.set(vName, {
503
+ name: vName, type: makeType(eName), mutable: false, isConst: false,
504
+ state: 'owned', scopeDepth: 0, isHoisted: true, declLine: 1,
505
+ });
506
+ }
507
+ }
508
+
509
+ function isRootBorrowAlive(binding, currentLine, lastUses) {
510
+ // Cek semua borrow aktif pada binding
511
+ const active = [];
512
+ for (const br of binding.borrows || []) {
513
+ const holderLastUse = br.holderVar ? (lastUses.get(br.holderVar) || br.declaredLine) : br.declaredLine;
514
+ if (holderLastUse >= currentLine && br.declaredLine <= currentLine) {
515
+ active.push(br);
516
+ }
517
+ }
518
+ return active;
519
+ }
520
+
521
+ function checkAndRecordMove(identName, line, col, endCol, scope, ctx, reason = 'dipindahkan') {
522
+ const binding = scope.lookup(identName);
523
+ if (!binding || binding.isHoisted || KNOWN_BUILTINS.has(identName)) return;
524
+
525
+ if (binding.state === 'moved') {
526
+ addError(
527
+ 'E0382', line, col, endCol,
528
+ `penggunaan nilai yang sudah dipindahkan: \`${identName}\``,
529
+ `gunakan \`salin(${identName})\` jika ingin menyalinnya, atau pinjam dengan \`&${identName}\``,
530
+ binding.movedAt ? `nilai dipindahkan sebelumnya pada baris ${binding.movedAt.line}` : null
531
+ );
532
+ return;
533
+ }
534
+ if (binding.state === 'maybe_moved') {
535
+ addError(
536
+ 'E0382', line, col, endCol,
537
+ `penggunaan variabel \`${identName}\` yang kemungkinan sudah dipindahkan di salah satu cabang`,
538
+ `gunakan \`salin(${identName})\` atau pastikan semua cabang mengembalikan nilai`
539
+ );
540
+ return;
541
+ }
542
+
543
+ if (isCopyType(binding.type)) return;
544
+
545
+ // Cek apakah sedang dipinjam
546
+ const activeBorrows = isRootBorrowAlive(binding, line, ctx.lastUses);
547
+ if (activeBorrows.length > 0) {
548
+ addError(
549
+ 'E0505', line, col, endCol,
550
+ `tidak dapat memindahkan \`${identName}\` karena sedang dipinjam`,
551
+ 'pastikan pinjaman tidak lagi digunakan setelah pemindahan kepemilikan',
552
+ `pinjaman aktif dibuat pada baris ${activeBorrows[0].declaredLine}`
553
+ );
554
+ return;
555
+ }
556
+
557
+ binding.state = 'moved';
558
+ binding.movedAt = { line, col, reason };
559
+ }
560
+
561
+ function checkBorrow(targetExpr, mutable, holderVar, line, col, endCol, scope, ctx, isInlineCall = false) {
562
+ if (!targetExpr || targetExpr.kind !== 'Ident') return T_UNKNOWN;
563
+ const name = targetExpr.name;
564
+ const binding = scope.lookup(name);
565
+ if (!binding) {
566
+ if (!KNOWN_BUILTINS.has(name)) {
567
+ addError('E0425', line, col, endCol, `variabel \`${name}\` tidak ditemukan di cakupan ini`);
568
+ }
569
+ return T_UNKNOWN;
570
+ }
571
+
572
+ if (binding.state === 'moved' || binding.state === 'maybe_moved') {
573
+ addError(
574
+ 'E0382', line, col, endCol,
575
+ `tidak dapat meminjam \`${name}\` karena nilainya sudah dipindahkan`,
576
+ `gunakan \`salin(${name})\` sebelum memindahkannya`,
577
+ binding.movedAt ? `dipindahkan pada baris ${binding.movedAt.line}` : null
578
+ );
579
+ return mutable ? { kind: 'PinjamUbah', inner: binding.type } : { kind: 'Pinjam', inner: binding.type };
580
+ }
581
+
582
+ if (mutable && !binding.mutable) {
583
+ addError(
584
+ 'E0596', line, col, endCol,
585
+ `tidak dapat meminjam \`${name}\` sebagai dapat diubah (\`&ubah\`), karena dideklarasikan tetap`,
586
+ `ubah deklarasinya menjadi \`ubah ${name} = ...\``
587
+ );
588
+ }
589
+
590
+ const active = isRootBorrowAlive(binding, line, ctx.lastUses);
591
+ if (mutable) {
592
+ const existingMut = active.find((b) => b.mutable);
593
+ if (existingMut) {
594
+ addError(
595
+ 'E0499', line, col, endCol,
596
+ `tidak dapat meminjam \`${name}\` sebagai \`&ubah\` lebih dari satu kali pada saat yang bersamaan`,
597
+ 'selesaikan penggunaan pinjaman ubah pertama sebelum membuat pinjaman ubah baru',
598
+ `pinjaman ubah pertama aktif sejak baris ${existingMut.declaredLine}`
599
+ );
600
+ } else {
601
+ const existingShared = active.find((b) => !b.mutable);
602
+ if (existingShared) {
603
+ addError(
604
+ 'E0502', line, col, endCol,
605
+ `tidak dapat meminjam \`${name}\` sebagai \`&ubah\` karena sedang dipinjam sebagai tetap (\`&\`)`,
606
+ 'jangan gunakan pinjaman tetap setelah baris peminjaman ubah dimulai',
607
+ `pinjaman tetap aktif sejak baris ${existingShared.declaredLine}`
608
+ );
609
+ }
610
+ }
611
+ } else {
612
+ const existingMut = active.find((b) => b.mutable);
613
+ if (existingMut) {
614
+ addError(
615
+ 'E0502', line, col, endCol,
616
+ `tidak dapat meminjam \`${name}\` sebagai tetap (\`&\`) karena sedang dipinjam sebagai \`&ubah\``,
617
+ 'selesaikan penggunaan pinjaman ubah sebelum meminjam sebagai tetap',
618
+ `pinjaman ubah aktif sejak baris ${existingMut.declaredLine}`
619
+ );
620
+ }
621
+ }
622
+
623
+ if (!binding.borrows) binding.borrows = [];
624
+ binding.borrows.push({
625
+ holderVar: isInlineCall ? null : holderVar,
626
+ mutable,
627
+ declaredLine: line,
628
+ scopeDepth: binding.scopeDepth,
629
+ });
630
+ if (mutable) {
631
+ mutBorrowedBindings.add(`${binding.declLine}:${name}`);
632
+ }
633
+
634
+ return mutable ? { kind: 'PinjamUbah', inner: binding.type } : { kind: 'Pinjam', inner: binding.type };
635
+ }
636
+
637
+ function checkReadUse(identName, line, col, endCol, scope, ctx) {
638
+ if (KNOWN_BUILTINS.has(identName)) return;
639
+ const binding = scope.lookup(identName);
640
+ if (!binding) {
641
+ if (!ctx.inComprehensionVars?.has(identName)) {
642
+ addError('E0425', line, col, endCol, `simbol \`${identName}\` tidak ditemukan di cakupan ini`);
643
+ }
644
+ return;
645
+ }
646
+ if (binding.state === 'moved') {
647
+ addError(
648
+ 'E0382', line, col, endCol,
649
+ `penggunaan nilai yang sudah dipindahkan: \`${identName}\``,
650
+ `gunakan \`salin(${identName})\` atau pinjam dengan \`&${identName}\``,
651
+ binding.movedAt ? `nilai dipindahkan pada baris ${binding.movedAt.line}` : null
652
+ );
653
+ } else if (binding.state === 'maybe_moved') {
654
+ addError(
655
+ 'E0382', line, col, endCol,
656
+ `penggunaan variabel \`${identName}\` yang kemungkinan sudah dipindahkan`,
657
+ `gunakan \`salin(${identName})\` sebelum percabangan`
658
+ );
659
+ }
660
+ }
661
+
662
+ function inferAndCheckExpr(expr, scope, ctx, optionsExpr = {}) {
663
+ if (!expr) return T_UNKNOWN;
664
+ const {
665
+ consumeMove = false,
666
+ holderVar = null,
667
+ isBorrowArg = false,
668
+ expectType = null,
669
+ inCallStmt = false,
670
+ } = optionsExpr;
671
+
672
+ switch (expr.kind) {
673
+ case 'Literal':
674
+ return makeType(expr.litType);
675
+
676
+ case 'NullLiteral':
677
+ if (!ctx.inUnsafe) {
678
+ addError(
679
+ 'E0701', expr.line, expr.col, expr.endCol,
680
+ `nilai \`${expr.raw}\` (null) dilarang di kode aman`,
681
+ 'gunakan tipe `Opsi` (`Ada(nilai)` / `TidakAda`) atau bungkus operasi FFI dengan `tidak_aman:`'
682
+ );
683
+ }
684
+ return T_ANY;
685
+
686
+ case 'OptionNone':
687
+ return makeType('Opsi', [T_UNKNOWN]);
688
+
689
+ case 'FString':
690
+ for (const sub of expr.embeddedAsts || []) {
691
+ inferAndCheckExpr(sub, scope, ctx, { consumeMove: false, isBorrowArg: true });
692
+ }
693
+ return T_STR;
694
+
695
+ case 'Ident': {
696
+ const b = scope.lookup(expr.name);
697
+ if (!b) {
698
+ if (!KNOWN_BUILTINS.has(expr.name) && !ctx.inComprehensionVars?.has(expr.name)) {
699
+ addError('E0425', expr.line, expr.col, expr.endCol, `simbol \`${expr.name}\` tidak ditemukan di cakupan ini`);
700
+ }
701
+ return T_UNKNOWN;
702
+ }
703
+ if (consumeMove && !isBorrowArg) {
704
+ checkAndRecordMove(expr.name, expr.line, expr.col, expr.endCol, scope, ctx);
705
+ } else {
706
+ checkReadUse(expr.name, expr.line, expr.col, expr.endCol, scope, ctx);
707
+ }
708
+ return b.type || T_UNKNOWN;
709
+ }
710
+
711
+ case 'Borrow': {
712
+ return checkBorrow(
713
+ expr.target, expr.mutable, holderVar,
714
+ expr.line, expr.col, expr.endCol, scope, ctx,
715
+ !holderVar
716
+ );
717
+ }
718
+
719
+ case 'Move': {
720
+ if (expr.target?.kind === 'Ident') {
721
+ const b = scope.lookup(expr.target.name);
722
+ if (b && isCopyType(b.type)) {
723
+ // `pindah x` eksplisit tetap memindahkan variabel agar semantik eksplisit terjaga
724
+ const active = isRootBorrowAlive(b, expr.line, ctx.lastUses);
725
+ if (active.length > 0) {
726
+ addError('E0505', expr.line, expr.col, expr.endCol, `tidak dapat memindahkan \`${expr.target.name}\` karena sedang dipinjam`);
727
+ } else if (b.state === 'moved') {
728
+ addError('E0382', expr.line, expr.col, expr.endCol, `penggunaan nilai yang sudah dipindahkan: \`${expr.target.name}\``);
729
+ } else {
730
+ b.state = 'moved';
731
+ b.movedAt = { line: expr.line, col: expr.col, reason: 'pindah eksplisit' };
732
+ }
733
+ return b.type;
734
+ }
735
+ }
736
+ return inferAndCheckExpr(expr.target, scope, ctx, { consumeMove: true });
737
+ }
738
+
739
+ case 'DerefOrSpread': {
740
+ const innerT = inferAndCheckExpr(expr.target, scope, ctx, { consumeMove: false });
741
+ if (innerT?.kind === 'Pinjam' || innerT?.kind === 'PinjamUbah') {
742
+ return innerT.inner;
743
+ }
744
+ return innerT;
745
+ }
746
+
747
+ case 'KwSpread':
748
+ return inferAndCheckExpr(expr.target, scope, ctx, { consumeMove: false });
749
+
750
+ case 'Await':
751
+ return inferAndCheckExpr(expr.target, scope, ctx, { consumeMove });
752
+
753
+ case 'TryPropagate': {
754
+ if (!ctx.currentFn) {
755
+ addError(
756
+ 'E0277', expr.line, expr.col, expr.endCol,
757
+ 'operator `?` hanya dapat digunakan di dalam fungsi',
758
+ 'pindahkan logika ini ke dalam `fungsi` yang mengembalikan `Hasil` atau `Opsi`'
759
+ );
760
+ } else {
761
+ usesTanyaInFn.add(`${ctx.currentFn.line}:${ctx.currentFn.name}`);
762
+ const retName = ctx.currentFn.returnType?.name;
763
+ if (!ctx.currentFn.returnType || (retName !== 'Hasil' && retName !== 'Opsi' && !isUnknownOrAny(ctx.currentFn.returnType))) {
764
+ addError(
765
+ 'E0277', expr.line, expr.col, expr.endCol,
766
+ `operator \`?\` tidak cocok dengan tipe kembali fungsi \`${ctx.currentFn.returnType ? formatType(ctx.currentFn.returnType) : 'Unit ()'}\``,
767
+ 'tambahkan tipe kembali `-> Hasil[T, E]` atau `-> Opsi[T]` pada deklarasi fungsi'
768
+ );
769
+ }
770
+ }
771
+ const innerT = inferAndCheckExpr(expr.expr, scope, ctx, { consumeMove: true });
772
+ if (innerT?.kind === 'Named' && (innerT.name === 'Hasil' || innerT.name === 'Opsi')) {
773
+ return innerT.args?.[0] || T_UNKNOWN;
774
+ }
775
+ return T_UNKNOWN;
776
+ }
777
+
778
+ case 'Unary': {
779
+ const opT = inferAndCheckExpr(expr.operand, scope, ctx, { consumeMove: false });
780
+ if (expr.op === 'bukan') return T_BOOL;
781
+ return opT;
782
+ }
783
+
784
+ case 'Range': {
785
+ inferAndCheckExpr(expr.start, scope, ctx, { consumeMove: false });
786
+ inferAndCheckExpr(expr.end, scope, ctx, { consumeMove: false });
787
+ return makeType('Daftar', [T_INT]);
788
+ }
789
+
790
+ case 'Binary': {
791
+ const lt = inferAndCheckExpr(expr.left, scope, ctx, { consumeMove: false });
792
+ const rt = inferAndCheckExpr(expr.right, scope, ctx, { consumeMove: false });
793
+
794
+ if ((expr.op === '/' || expr.op === '//' || expr.op === '%') &&
795
+ expr.right?.kind === 'Literal' && expr.right.value === 0) {
796
+ addError(
797
+ 'E0710', expr.right.line, expr.right.col, expr.right.endCol,
798
+ 'pembagian atau sisa bagi dengan nol terdeteksi pada waktu kompilasi',
799
+ 'gunakan pembagi bukan nol atau `bagi_aman(a, b)` yang mengembalikan `Hasil`'
800
+ );
801
+ }
802
+
803
+ if (['==', '!=', '<', '<=', '>', '>=', 'dalam', 'in', 'bukan_dalam', 'adalah', 'bukan_adalah', 'is', 'dan', 'atau'].includes(expr.op)) {
804
+ if (['<', '<=', '>', '>='].includes(expr.op) && !isUnknownOrAny(lt) && !isUnknownOrAny(rt)) {
805
+ const lNum = ['bulat', 'desimal', 'angka'].includes(lt.name);
806
+ const rNum = ['bulat', 'desimal', 'angka'].includes(rt.name);
807
+ if ((lNum && rt.name === 'teks') || (lt.name === 'teks' && rNum)) {
808
+ addError(
809
+ 'E0369', expr.line, expr.col, expr.endCol,
810
+ `perbandingan \`${expr.op}\` tidak valid antara tipe \`${formatType(lt)}\` dan \`${formatType(rt)}\``
811
+ );
812
+ }
813
+ }
814
+ return T_BOOL;
815
+ }
816
+
817
+ if (['+', '-', '*', '/', '//', '%', '**'].includes(expr.op) && !isUnknownOrAny(lt) && !isUnknownOrAny(rt)) {
818
+ const lNum = ['bulat', 'desimal', 'angka'].includes(lt.name);
819
+ const rNum = ['bulat', 'desimal', 'angka'].includes(rt.name);
820
+ if ((lNum && rt.name === 'teks') || (lt.name === 'teks' && rNum && expr.op !== '*')) {
821
+ addError(
822
+ 'E0369', expr.line, expr.col, expr.endCol,
823
+ `operasi \`${expr.op}\` tidak valid antara \`${formatType(lt)}\` dan \`${formatType(rt)}\``,
824
+ 'konversi tipe secara eksplisit dengan `teks(...)` atau `urai_bulat(...)`'
825
+ );
826
+ }
827
+ if (expr.op === '-' || expr.op === '/' || expr.op === '//' || expr.op === '%') {
828
+ if (lt.name === 'teks' || rt.name === 'teks') {
829
+ addError(
830
+ 'E0369', expr.line, expr.col, expr.endCol,
831
+ `operasi aritmatika \`${expr.op}\` tidak didukung untuk tipe \`teks\``
832
+ );
833
+ }
834
+ }
835
+ if (lt.name === 'desimal' || rt.name === 'desimal' || expr.op === '/') return T_FLOAT;
836
+ if (lt.name === 'bulat' && rt.name === 'bulat') return T_INT;
837
+ if (lt.name === 'teks' && rt.name === 'teks' && expr.op === '+') return T_STR;
838
+ }
839
+ return lt && !isUnknownOrAny(lt) ? lt : rt;
840
+ }
841
+
842
+ case 'Ternary': {
843
+ inferAndCheckExpr(expr.cond, scope, ctx, { consumeMove: false });
844
+ const ct = inferAndCheckExpr(expr.consequent, scope, ctx, { consumeMove });
845
+ const at = inferAndCheckExpr(expr.alternate, scope, ctx, { consumeMove });
846
+ return !isUnknownOrAny(ct) ? ct : at;
847
+ }
848
+
849
+ case 'List': {
850
+ let elemType = T_UNKNOWN;
851
+ for (const it of expr.items) {
852
+ const t = inferAndCheckExpr(it, scope, ctx, { consumeMove: true });
853
+ if (isUnknownOrAny(elemType) && !isUnknownOrAny(t)) elemType = t;
854
+ }
855
+ return makeType('Daftar', [elemType]);
856
+ }
857
+
858
+ case 'Tuple': {
859
+ const ts = expr.items.map((it) => inferAndCheckExpr(it, scope, ctx, { consumeMove: true }));
860
+ return makeType('Tupel', ts);
861
+ }
862
+
863
+ case 'Set': {
864
+ let elemType = T_UNKNOWN;
865
+ for (const it of expr.items) {
866
+ const t = inferAndCheckExpr(it, scope, ctx, { consumeMove: true });
867
+ if (isUnknownOrAny(elemType)) elemType = t;
868
+ }
869
+ return makeType('Himpunan', [elemType]);
870
+ }
871
+
872
+ case 'Dict': {
873
+ let kt = T_UNKNOWN;
874
+ let vt = T_UNKNOWN;
875
+ for (const e of expr.entries) {
876
+ const k = inferAndCheckExpr(e.key, scope, ctx, { consumeMove: true });
877
+ const v = inferAndCheckExpr(e.value, scope, ctx, { consumeMove: true });
878
+ if (isUnknownOrAny(kt)) kt = k;
879
+ if (isUnknownOrAny(vt)) vt = v;
880
+ }
881
+ return makeType('Kamus', [kt, vt]);
882
+ }
883
+
884
+ case 'ListComp':
885
+ case 'GeneratorComp':
886
+ case 'DictComp': {
887
+ const compVars = new Set(ctx.inComprehensionVars || []);
888
+ for (const cl of expr.clauses || []) {
889
+ inferAndCheckExpr(cl.iter, scope, { ...ctx, inComprehensionVars: compVars }, { consumeMove: false });
890
+ for (const tgt of cl.targets) compVars.add(tgt);
891
+ if (cl.cond) {
892
+ inferAndCheckExpr(cl.cond, scope, { ...ctx, inComprehensionVars: compVars }, { consumeMove: false });
893
+ }
894
+ }
895
+ const subCtx = { ...ctx, inComprehensionVars: compVars };
896
+ if (expr.kind === 'DictComp') {
897
+ const kt = inferAndCheckExpr(expr.key, scope, subCtx, { consumeMove: false });
898
+ const vt = inferAndCheckExpr(expr.value, scope, subCtx, { consumeMove: false });
899
+ return makeType('Kamus', [kt, vt]);
900
+ }
901
+ const bt = inferAndCheckExpr(expr.body, scope, subCtx, { consumeMove: false });
902
+ return makeType('Daftar', [bt]);
903
+ }
904
+
905
+ case 'Lambda': {
906
+ const fnScope = new Scope(scope, 'function', scope.depth + 1);
907
+ for (const p of expr.params) {
908
+ fnScope.bindings.set(p, {
909
+ name: p, type: T_UNKNOWN, mutable: false, isConst: false,
910
+ state: 'owned', scopeDepth: fnScope.depth, declLine: expr.line,
911
+ });
912
+ }
913
+ inferAndCheckExpr(expr.body, fnScope, ctx, { consumeMove: false });
914
+ return makeType('Fungsi');
915
+ }
916
+
917
+ case 'Member': {
918
+ const objT = inferAndCheckExpr(expr.object, scope, ctx, { consumeMove: false });
919
+ const unwrapped = (objT?.kind === 'Pinjam' || objT?.kind === 'PinjamUbah') ? objT.inner : objT;
920
+ if (unwrapped?.kind === 'Named' && structs.has(unwrapped.name)) {
921
+ const sInfo = structs.get(unwrapped.name);
922
+ if (sInfo.fields.has(expr.property)) {
923
+ return sInfo.fields.get(expr.property);
924
+ }
925
+ }
926
+ return T_UNKNOWN;
927
+ }
928
+
929
+ case 'Index': {
930
+ const objT = inferAndCheckExpr(expr.object, scope, ctx, { consumeMove: false });
931
+ inferAndCheckExpr(expr.index, scope, ctx, { consumeMove: false });
932
+ const unwrapped = (objT?.kind === 'Pinjam' || objT?.kind === 'PinjamUbah') ? objT.inner : objT;
933
+ if (unwrapped?.kind === 'Named') {
934
+ if (unwrapped.name === 'Daftar' && unwrapped.args[0]) return unwrapped.args[0];
935
+ if (unwrapped.name === 'Kamus' && unwrapped.args[1]) return unwrapped.args[1];
936
+ if (unwrapped.name === 'teks') return T_STR;
937
+ }
938
+ return T_UNKNOWN;
939
+ }
940
+
941
+ case 'Slice': {
942
+ const objT = inferAndCheckExpr(expr.object, scope, ctx, { consumeMove: false });
943
+ if (expr.start) inferAndCheckExpr(expr.start, scope, ctx, { consumeMove: false });
944
+ if (expr.end) inferAndCheckExpr(expr.end, scope, ctx, { consumeMove: false });
945
+ if (expr.step) inferAndCheckExpr(expr.step, scope, ctx, { consumeMove: false });
946
+ return objT;
947
+ }
948
+
949
+ case 'Call': {
950
+ return analyzeCall(expr, scope, ctx, { inCallStmt });
951
+ }
952
+ }
953
+ return T_UNKNOWN;
954
+ }
955
+
956
+ function analyzeCall(expr, scope, ctx, { inCallStmt = false } = {}) {
957
+ const callee = expr.callee;
958
+
959
+ // 1. Cek unsafe builtins (`eval`, `exec`, `compile`, `__import__`)
960
+ if (callee?.kind === 'Ident') {
961
+ const fnName = callee.name;
962
+
963
+ if (['eval', 'exec', 'compile', '__import__', 'Function'].includes(fnName) && !ctx.inUnsafe) {
964
+ addError(
965
+ 'E0133', expr.line, expr.col, expr.endCol,
966
+ `pemanggilan \`${fnName}()\` bersifat tidak aman dan dilarang di kode aman`,
967
+ 'bungkus operasi ini dalam blok `tidak_aman:` atau gunakan fungsi aman yang terverifikasi'
968
+ );
969
+ }
970
+
971
+ if (sandbox && (fnName === 'buka' || fnName === 'open')) {
972
+ addError(
973
+ 'E0134', expr.line, expr.col, expr.endCol,
974
+ `akses berkas lewat \`${fnName}()\` dilarang dalam mode kotak pasir (--sandbox)`
975
+ );
976
+ }
977
+
978
+ // `salin(x)`: meminjam &x secara aman lalu menghasilkan salinan baru
979
+ if (fnName === 'salin') {
980
+ if (expr.args.length !== 1) {
981
+ addError('E0061', expr.line, expr.col, expr.endCol, '`salin()` membutuhkan tepat 1 argumen');
982
+ return T_UNKNOWN;
983
+ }
984
+ return inferAndCheckExpr(expr.args[0], scope, ctx, { consumeMove: false, isBorrowArg: true });
985
+ }
986
+
987
+ // `Ada(x)`, `Ok(x)`, `Galat(e)`
988
+ if (fnName === 'Ada') {
989
+ const inner = expr.args[0] ? inferAndCheckExpr(expr.args[0], scope, ctx, { consumeMove: true }) : T_UNKNOWN;
990
+ return makeType('Opsi', [inner]);
991
+ }
992
+ if (fnName === 'Ok') {
993
+ const inner = expr.args[0] ? inferAndCheckExpr(expr.args[0], scope, ctx, { consumeMove: true }) : T_UNIT;
994
+ return makeType('Hasil', [inner, T_UNKNOWN]);
995
+ }
996
+ if (fnName === 'Galat') {
997
+ const inner = expr.args[0] ? inferAndCheckExpr(expr.args[0], scope, ctx, { consumeMove: true }) : T_STR;
998
+ return makeType('Hasil', [T_UNKNOWN, inner]);
999
+ }
1000
+
1001
+ // Fungsi mutasi stdlib seperti `tambah(daftar, item)` / `hapus(daftar, idx)` / `kocok(daftar)`
1002
+ if (MUTATING_STDLIB_FUNCS.has(fnName)) {
1003
+ const target = expr.args[0];
1004
+ if (target?.kind === 'Ident') {
1005
+ const b = scope.lookup(target.name);
1006
+ if (b && !b.mutable && !b.isHoisted) {
1007
+ addError(
1008
+ 'E0384', expr.line, target.col, target.endCol,
1009
+ `tidak dapat memutasi variabel tetap \`${target.name}\` dengan \`${fnName}()\``,
1010
+ `ubah deklarasi \`${target.name}\` menjadi \`ubah ${target.name} = ...\``
1011
+ );
1012
+ }
1013
+ if (b) {
1014
+ const active = isRootBorrowAlive(b, expr.line, ctx.lastUses);
1015
+ if (active.length > 0) {
1016
+ addError('E0506', expr.line, target.col, target.endCol, `tidak dapat mengubah \`${target.name}\` karena sedang dipinjam`);
1017
+ }
1018
+ }
1019
+ } else if (target?.kind === 'DerefOrSpread' && target.target?.kind === 'Ident') {
1020
+ const rb = scope.lookup(target.target.name);
1021
+ if (rb?.type?.kind === 'Pinjam') {
1022
+ addError('E0594', expr.line, target.col, target.endCol, `tidak dapat memutasi nilai melalui pinjaman tetap \`${target.target.name}\``);
1023
+ }
1024
+ }
1025
+ for (let i = 0; i < expr.args.length; i++) {
1026
+ inferAndCheckExpr(expr.args[i], scope, ctx, { consumeMove: i > 0, isBorrowArg: i === 0 });
1027
+ }
1028
+ return T_UNKNOWN;
1029
+ }
1030
+
1031
+ // Fungsi yang meminjam argumen secara otomatis (cetak, panjang, dll.)
1032
+ if (BUILTIN_BORROWING_FUNCS.has(fnName)) {
1033
+ for (const a of expr.args) {
1034
+ inferAndCheckExpr(a, scope, ctx, { consumeMove: false, isBorrowArg: true });
1035
+ }
1036
+ for (const kw of expr.kwargs) {
1037
+ inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: false, isBorrowArg: true });
1038
+ }
1039
+ if (fnName === 'panjang' || fnName === 'len') return T_INT;
1040
+ if (fnName === 'teks' || fnName === 'str' || fnName === 'masukan' || fnName === 'input' || fnName === 'huruf_besar' || fnName === 'huruf_kecil' || fnName === 'potong' || fnName === 'ganti' || fnName === 'gabung') return T_STR;
1041
+ if (fnName === 'bulat' || fnName === 'int' || fnName === 'waktu_sekarang') return T_INT;
1042
+ if (fnName === 'desimal' || fnName === 'float' || fnName === 'akar') return T_FLOAT;
1043
+ if (fnName === 'mengandung' || fnName === 'semua' || fnName === 'all' || fnName === 'ada_yang' || fnName === 'any' || fnName === 'isinstance') return T_BOOL;
1044
+ if (fnName === 'cetak' || fnName === 'print') return T_UNIT;
1045
+ return T_UNKNOWN;
1046
+ }
1047
+
1048
+ // Konstruktor Enum Variant (`Tertunda(...)`)
1049
+ if (variantToEnum.has(fnName)) {
1050
+ const enumName = variantToEnum.get(fnName);
1051
+ const eInfo = enums.get(enumName);
1052
+ const fields = eInfo.variants.get(fnName) || [];
1053
+ if (expr.args.length !== fields.length) {
1054
+ addError(
1055
+ 'E0061', expr.line, expr.col, expr.endCol,
1056
+ `varian \`${enumName}.${fnName}\` mengharapkan ${fields.length} argumen, tetapi diberi ${expr.args.length}`
1057
+ );
1058
+ }
1059
+ for (let i = 0; i < expr.args.length; i++) {
1060
+ const argT = inferAndCheckExpr(expr.args[i], scope, ctx, { consumeMove: true });
1061
+ if (fields[i]?.type && !typesCompatible(fields[i].type, argT)) {
1062
+ addError(
1063
+ 'E0308', expr.args[i].line, expr.args[i].col, expr.args[i].endCol,
1064
+ `ketidakcocokan tipe argumen varian \`${fnName}\`: diharapkan \`${formatType(fields[i].type)}\`, ditemukan \`${formatType(argT)}\``
1065
+ );
1066
+ }
1067
+ }
1068
+ return makeType(enumName);
1069
+ }
1070
+
1071
+ // Konstruktor Struct / Class
1072
+ if (structs.has(fnName)) {
1073
+ const sInfo = structs.get(fnName);
1074
+ const initFn = sInfo.methods.get('__init__') || sInfo.methods.get('__inisialisasi__');
1075
+ if (initFn) {
1076
+ const userParams = initFn.params.filter((p) => p.name !== 'diri' && p.name !== 'self');
1077
+ checkCallParamsAndArgs(fnName, userParams, expr, scope, ctx);
1078
+ } else if (sInfo.fields.size > 0) {
1079
+ // Dataclass / struktur konstruktor
1080
+ const fieldNames = Array.from(sInfo.fields.keys());
1081
+ for (let i = 0; i < expr.args.length; i++) {
1082
+ const argT = inferAndCheckExpr(expr.args[i], scope, ctx, { consumeMove: true });
1083
+ const expectedT = sInfo.fields.get(fieldNames[i]);
1084
+ if (expectedT && !typesCompatible(expectedT, argT)) {
1085
+ addError(
1086
+ 'E0308', expr.args[i].line, expr.args[i].col, expr.args[i].endCol,
1087
+ `ketidakcocokan tipe field \`${fieldNames[i]}\` pada \`${fnName}\`: diharapkan \`${formatType(expectedT)}\`, ditemukan \`${formatType(argT)}\``
1088
+ );
1089
+ }
1090
+ }
1091
+ for (const kw of expr.kwargs) {
1092
+ const argT = inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: true });
1093
+ const expectedT = sInfo.fields.get(kw.kwargName);
1094
+ if (expectedT && !typesCompatible(expectedT, argT)) {
1095
+ addError(
1096
+ 'E0308', kw.value.line, kw.value.col, kw.value.endCol,
1097
+ `ketidakcocokan tipe field \`${kw.kwargName}\` pada \`${fnName}\`: diharapkan \`${formatType(expectedT)}\`, ditemukan \`${formatType(argT)}\``
1098
+ );
1099
+ }
1100
+ }
1101
+ } else {
1102
+ for (const a of expr.args) inferAndCheckExpr(a, scope, ctx, { consumeMove: true });
1103
+ for (const kw of expr.kwargs) inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: true });
1104
+ }
1105
+ return makeType(fnName);
1106
+ }
1107
+
1108
+ // Fungsi user / builtin terdefinisi di `functions`
1109
+ if (functions.has(fnName)) {
1110
+ const fnInfo = functions.get(fnName);
1111
+ checkCallParamsAndArgs(fnName, fnInfo.params, expr, scope, ctx, !!fnInfo.isBuiltin);
1112
+ return fnInfo.returnType || T_UNKNOWN;
1113
+ }
1114
+
1115
+ // Cek apakah nama fungsi ada di scope (mis. parameter/variabel fungsi atau modul)
1116
+ checkReadUse(fnName, expr.line, callee.col, callee.endCol, scope, ctx);
1117
+ for (const a of expr.args) inferAndCheckExpr(a, scope, ctx, { consumeMove: false });
1118
+ for (const kw of expr.kwargs) inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: false });
1119
+ return T_UNKNOWN;
1120
+ }
1121
+
1122
+ // 2. Method call `obj.method(...)`
1123
+ if (callee?.kind === 'Member') {
1124
+ const methodName = callee.property;
1125
+
1126
+ // `.buka_tanpa_cek()` memerlukan `tidak_aman`
1127
+ if (methodName === 'buka_tanpa_cek' && !ctx.inUnsafe) {
1128
+ addError(
1129
+ 'E0133', expr.line, expr.col, expr.endCol,
1130
+ 'pemanggilan `.buka_tanpa_cek()` tidak aman karena dapat memicu panik jika kosong/galat',
1131
+ 'gunakan `cocok`, `.buka_atau(...)`, `?`, atau bungkus dengan `tidak_aman:`'
1132
+ );
1133
+ }
1134
+
1135
+ const objT = inferAndCheckExpr(callee.object, scope, ctx, { consumeMove: false });
1136
+ const unwrappedObjT = (objT?.kind === 'Pinjam' || objT?.kind === 'PinjamUbah') ? objT.inner : objT;
1137
+
1138
+ // Cek pemanggilan method pada struct/class/enum
1139
+ if (unwrappedObjT?.kind === 'Named') {
1140
+ const typeInfo = structs.get(unwrappedObjT.name) || enums.get(unwrappedObjT.name);
1141
+ if (typeInfo && typeInfo.methods.has(methodName)) {
1142
+ const mNode = typeInfo.methods.get(methodName);
1143
+ const selfParam = mNode.params[0];
1144
+ const needsMutSelf = selfParam && (selfParam.isMut || (selfParam.type?.kind === 'PinjamUbah'));
1145
+ if (needsMutSelf && callee.object?.kind === 'Ident') {
1146
+ const objBind = scope.lookup(callee.object.name);
1147
+ if (objBind && !objBind.mutable && objBind.type?.kind !== 'PinjamUbah') {
1148
+ addError(
1149
+ 'E0596', expr.line, callee.object.col, callee.object.endCol,
1150
+ `tidak dapat memanggil method pengubah \`${methodName}()\` pada variabel tetap \`${callee.object.name}\``,
1151
+ `ubah deklarasi \`${callee.object.name}\` menjadi \`ubah ${callee.object.name} = ...\``
1152
+ );
1153
+ }
1154
+ }
1155
+ const userParams = mNode.params.filter((p) => p.name !== 'diri' && p.name !== 'self');
1156
+ checkCallParamsAndArgs(`${unwrappedObjT.name}.${methodName}`, userParams, expr, scope, ctx);
1157
+ return mNode.returnType || T_UNKNOWN;
1158
+ }
1159
+ }
1160
+
1161
+ // Cek mutating method list/dict/set bawaan
1162
+ if (MUTATING_METHODS.has(methodName)) {
1163
+ if (callee.object?.kind === 'Ident') {
1164
+ const b = scope.lookup(callee.object.name);
1165
+ if (b && !b.mutable && !b.isHoisted && b.type?.kind !== 'PinjamUbah') {
1166
+ addError(
1167
+ 'E0384', expr.line, callee.object.col, callee.object.endCol,
1168
+ `tidak dapat memanggil method pengubah \`.${methodName}()\` pada variabel tetap \`${callee.object.name}\``,
1169
+ `ubah deklarasi menjadi \`ubah ${callee.object.name} = ...\``
1170
+ );
1171
+ }
1172
+ if (b) {
1173
+ const active = isRootBorrowAlive(b, expr.line, ctx.lastUses);
1174
+ if (active.length > 0) {
1175
+ addError('E0506', expr.line, callee.object.col, callee.object.endCol, `tidak dapat memutasi \`${callee.object.name}\` karena sedang dipinjam`);
1176
+ }
1177
+ }
1178
+ } else if (callee.object?.kind === 'Member' && callee.object.object?.kind === 'Ident') {
1179
+ const rootName = callee.object.object.name;
1180
+ if (rootName === 'diri' || rootName === 'self') {
1181
+ if (ctx.currentFn && !ctx.currentFnSelfMut && !ctx.inInitMethod) {
1182
+ addError(
1183
+ 'E0596', expr.line, callee.object.col, callee.object.endCol,
1184
+ `tidak dapat memutasi \`diri.${callee.object.property}\` di dalam method tanpa \`&ubah diri\``,
1185
+ `ubah parameter pertama method menjadi \`&ubah diri\``
1186
+ );
1187
+ }
1188
+ }
1189
+ }
1190
+ }
1191
+
1192
+ const isMutMethod = MUTATING_METHODS.has(methodName);
1193
+ for (const a of expr.args) inferAndCheckExpr(a, scope, ctx, { consumeMove: isMutMethod });
1194
+ for (const kw of expr.kwargs) inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: isMutMethod });
1195
+
1196
+ if (methodName === 'ambil' || methodName === 'ambil_opsi' || methodName === 'nilai_ok' || methodName === 'nilai_galat') {
1197
+ return makeType('Opsi', [T_UNKNOWN]);
1198
+ }
1199
+ if (methodName === 'ke_hasil') {
1200
+ return makeType('Hasil', [T_UNKNOWN, T_UNKNOWN]);
1201
+ }
1202
+ if (methodName === 'apakah_ada' || methodName === 'apakah_tidak_ada' || methodName === 'apakah_ok' || methodName === 'apakah_galat' || methodName === 'isdigit') {
1203
+ return T_BOOL;
1204
+ }
1205
+ if (methodName === 'strip' || methodName === 'upper' || methodName === 'lower' || methodName === 'hex') {
1206
+ return T_STR;
1207
+ }
1208
+ return T_UNKNOWN;
1209
+ }
1210
+
1211
+ inferAndCheckExpr(callee, scope, ctx, { consumeMove: false });
1212
+ for (const a of expr.args) inferAndCheckExpr(a, scope, ctx, { consumeMove: false });
1213
+ for (const kw of expr.kwargs) inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: false });
1214
+ return T_UNKNOWN;
1215
+ }
1216
+
1217
+ function checkCallParamsAndArgs(fnName, params, callExpr, scope, ctx, isBuiltin = false) {
1218
+ const hasVarargs = params.some((p) => p.isStar || p.isDoubleStar);
1219
+ const requiredCount = params.filter((p) => !p.defaultExpr && !p.isStar && !p.isDoubleStar).length;
1220
+ const totalProvided = callExpr.args.length + callExpr.kwargs.length;
1221
+
1222
+ if (!hasVarargs && (totalProvided < requiredCount || totalProvided > params.length)) {
1223
+ addError(
1224
+ 'E0061', callExpr.line, callExpr.col, callExpr.endCol,
1225
+ `fungsi \`${fnName}\` mengharapkan ${requiredCount === params.length ? requiredCount : `${requiredCount}..${params.length}`} argumen, tetapi diberi ${totalProvided}`
1226
+ );
1227
+ }
1228
+
1229
+ // Catat konflik pinjaman intra-call (`f(&ubah x, &ubah x)` atau `f(&x, &ubah x)`)
1230
+ const callBorrowMap = new Map();
1231
+ const recordCallBorrow = (argNode, isMut) => {
1232
+ const targetName = argNode?.kind === 'Borrow' && argNode.target?.kind === 'Ident'
1233
+ ? argNode.target.name
1234
+ : null;
1235
+ if (!targetName) return;
1236
+ const prev = callBorrowMap.get(targetName) || { shared: 0, mut: 0 };
1237
+ if (isMut) {
1238
+ if (prev.mut > 0) {
1239
+ addError('E0499', argNode.line, argNode.col, argNode.endCol, `tidak dapat meminjam \`${targetName}\` sebagai \`&ubah\` dua kali di pemanggilan yang sama`);
1240
+ } else if (prev.shared > 0) {
1241
+ addError('E0502', argNode.line, argNode.col, argNode.endCol, `konflik pinjaman \`${targetName}\` (& dan &ubah bersamaan) di pemanggilan yang sama`);
1242
+ }
1243
+ prev.mut++;
1244
+ } else {
1245
+ if (prev.mut > 0) {
1246
+ addError('E0502', argNode.line, argNode.col, argNode.endCol, `konflik pinjaman \`${targetName}\` (& dan &ubah bersamaan) di pemanggilan yang sama`);
1247
+ }
1248
+ prev.shared++;
1249
+ }
1250
+ callBorrowMap.set(targetName, prev);
1251
+ };
1252
+
1253
+ for (let i = 0; i < callExpr.args.length; i++) {
1254
+ const arg = callExpr.args[i];
1255
+ const param = params[i];
1256
+ const expectsBorrow = param && (param.isBorrow || param.type?.kind === 'Pinjam' || param.type?.kind === 'PinjamUbah');
1257
+ const expectsMutBorrow = param && ((param.isMut && param.isBorrow) || param.type?.kind === 'PinjamUbah');
1258
+
1259
+ if (arg?.kind === 'Borrow') {
1260
+ recordCallBorrow(arg, arg.mutable);
1261
+ }
1262
+
1263
+ const argT = inferAndCheckExpr(arg, scope, ctx, {
1264
+ consumeMove: !expectsBorrow,
1265
+ isBorrowArg: expectsBorrow,
1266
+ });
1267
+
1268
+ if (expectsMutBorrow && arg?.kind === 'Borrow' && !arg.mutable) {
1269
+ addError(
1270
+ 'E0308', arg.line, arg.col, arg.endCol,
1271
+ `parameter \`${param.name}\` mengharapkan pinjaman ubah (\`&ubah\`), tetapi diberi pinjaman tetap (\`&\`)`,
1272
+ `gunakan \`&ubah ...\``
1273
+ );
1274
+ }
1275
+
1276
+ if (param?.type && !typesCompatible(param.type, argT)) {
1277
+ // Literal string & builtin helper boleh langsung dipinjam sebagai `&teks` / `&T`
1278
+ const isAutoBorrowAllowed =
1279
+ expectsBorrow && !expectsMutBorrow &&
1280
+ (isBuiltin || arg?.kind === 'Literal' || arg?.kind === 'FString') &&
1281
+ typesCompatible(param.type.inner, argT);
1282
+
1283
+ if (isAutoBorrowAllowed) {
1284
+ continue;
1285
+ }
1286
+ if (expectsBorrow && arg?.kind !== 'Borrow' && typesCompatible(param.type.inner, argT)) {
1287
+ addError(
1288
+ 'E0308', arg.line, arg.col, arg.endCol,
1289
+ `parameter \`${param.name}\` mengharapkan pinjaman \`${formatType(param.type)}\`, tetapi diberi nilai milik \`${formatType(argT)}\``,
1290
+ `pinjamkan nilainya dengan \`&${expectsMutBorrow ? 'ubah ' : ''}...\``
1291
+ );
1292
+ } else {
1293
+ addError(
1294
+ 'E0308', arg.line, arg.col, arg.endCol,
1295
+ `ketidakcocokan tipe untuk parameter \`${param.name}\` pada \`${fnName}\`: diharapkan \`${formatType(param.type)}\`, ditemukan \`${formatType(argT)}\``
1296
+ );
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ for (const kw of callExpr.kwargs) {
1302
+ const param = params.find((p) => p.name === kw.kwargName);
1303
+ const expectsBorrow = param && (param.isBorrow || param.type?.kind === 'Pinjam' || param.type?.kind === 'PinjamUbah');
1304
+ const argT = inferAndCheckExpr(kw.value, scope, ctx, { consumeMove: !expectsBorrow, isBorrowArg: expectsBorrow });
1305
+ if (param?.type && !typesCompatible(param.type, argT)) {
1306
+ addError(
1307
+ 'E0308', kw.value.line, kw.value.col, kw.value.endCol,
1308
+ `ketidakcocokan tipe untuk argumen \`${kw.kwargName}\`: diharapkan \`${formatType(param.type)}\`, ditemukan \`${formatType(argT)}\``
1309
+ );
1310
+ }
1311
+ }
1312
+ }
1313
+
1314
+ function isExhaustiveMatch(matchStmt, targetT) {
1315
+ const arms = matchStmt.arms;
1316
+ let hasCatchAll = false;
1317
+ let sawAda = false;
1318
+ let sawTidakAda = false;
1319
+ let sawOk = false;
1320
+ let sawGalat = false;
1321
+ let sawTrue = false;
1322
+ let sawFalse = false;
1323
+ const coveredVariants = new Set();
1324
+
1325
+ for (const arm of arms) {
1326
+ if (arm.guard) continue; // Guarded arms tidak menjamin exhaustiveness
1327
+ const p = arm.pattern;
1328
+ if (p.kind === 'Wildcard') {
1329
+ hasCatchAll = true;
1330
+ } else if (p.kind === 'IdentOrUnitVariant') {
1331
+ if (p.name === 'TidakAda') sawTidakAda = true;
1332
+ else if (variantToEnum.has(p.name)) coveredVariants.add(p.name);
1333
+ else hasCatchAll = true; // Pengikatan variabel tanpa guard
1334
+ } else if (p.kind === 'Variant') {
1335
+ if (p.name === 'Ada') sawAda = true;
1336
+ else if (p.name === 'TidakAda') sawTidakAda = true;
1337
+ else if (p.name === 'Ok') sawOk = true;
1338
+ else if (p.name === 'Galat') sawGalat = true;
1339
+ else coveredVariants.add(p.name);
1340
+ } else if (p.kind === 'QualifiedVariant') {
1341
+ coveredVariants.add(p.variantName);
1342
+ } else if (p.kind === 'Literal' && p.litType === 'bool') {
1343
+ if (p.value === true) sawTrue = true;
1344
+ else sawFalse = true;
1345
+ }
1346
+ }
1347
+
1348
+ if (hasCatchAll) return null;
1349
+
1350
+ const unwrapped = (targetT?.kind === 'Pinjam' || targetT?.kind === 'PinjamUbah') ? targetT.inner : targetT;
1351
+ const tName = unwrapped?.name;
1352
+
1353
+ if (tName === 'Opsi' || sawAda || sawTidakAda) {
1354
+ const missing = [];
1355
+ if (!sawAda) missing.push('Ada(...)');
1356
+ if (!sawTidakAda) missing.push('TidakAda');
1357
+ return missing.length ? missing : null;
1358
+ }
1359
+
1360
+ if (tName === 'Hasil' || sawOk || sawGalat) {
1361
+ const missing = [];
1362
+ if (!sawOk) missing.push('Ok(...)');
1363
+ if (!sawGalat) missing.push('Galat(...)');
1364
+ return missing.length ? missing : null;
1365
+ }
1366
+
1367
+ if (tName === 'bool' || sawTrue || sawFalse) {
1368
+ const missing = [];
1369
+ if (!sawTrue) missing.push('Benar');
1370
+ if (!sawFalse) missing.push('Salah');
1371
+ return missing.length ? missing : null;
1372
+ }
1373
+
1374
+ let enumName = tName && enums.has(tName) ? tName : null;
1375
+ if (!enumName && coveredVariants.size > 0) {
1376
+ const firstVar = coveredVariants.values().next().value;
1377
+ enumName = variantToEnum.get(firstVar) || null;
1378
+ }
1379
+ if (enumName && enums.has(enumName)) {
1380
+ const allVars = Array.from(enums.get(enumName).variants.keys());
1381
+ const missing = allVars.filter((v) => !coveredVariants.has(v));
1382
+ return missing.length ? missing : null;
1383
+ }
1384
+
1385
+ return ['_'];
1386
+ }
1387
+
1388
+ function bindPatternVars(pattern, targetT, scope, line) {
1389
+ const unwrapped = (targetT?.kind === 'Pinjam' || targetT?.kind === 'PinjamUbah') ? targetT.inner : targetT;
1390
+ if (pattern.kind === 'IdentOrUnitVariant') {
1391
+ if (pattern.name !== 'TidakAda' && !variantToEnum.has(pattern.name)) {
1392
+ scope.bindings.set(pattern.name, {
1393
+ name: pattern.name, type: unwrapped || T_UNKNOWN, mutable: !!pattern.isMut, isConst: false,
1394
+ state: 'owned', scopeDepth: scope.depth, declLine: line, borrows: [],
1395
+ });
1396
+ }
1397
+ } else if (pattern.kind === 'Variant' || pattern.kind === 'QualifiedVariant') {
1398
+ const vName = pattern.variantName || pattern.name;
1399
+ for (let i = 0; i < (pattern.args || []).length; i++) {
1400
+ let argT = T_UNKNOWN;
1401
+ if (vName === 'Ada' || vName === 'Ok') argT = unwrapped?.args?.[0] || T_UNKNOWN;
1402
+ else if (vName === 'Galat') argT = unwrapped?.args?.[1] || T_STR;
1403
+ else if (variantToEnum.has(vName)) {
1404
+ const eInfo = enums.get(variantToEnum.get(vName));
1405
+ const fields = eInfo?.variants.get(vName) || [];
1406
+ argT = fields[i]?.type || T_UNKNOWN;
1407
+ }
1408
+ bindPatternVars(pattern.args[i], argT, scope, line);
1409
+ }
1410
+ }
1411
+ }
1412
+
1413
+ function containsBreak(stmts) {
1414
+ for (const st of stmts) {
1415
+ if (st.kind === 'BreakStmt') return true;
1416
+ if (st.kind === 'IfStmt' && st.branches.some((b) => containsBreak(b.body))) return true;
1417
+ if (st.kind === 'MatchStmt' && st.arms.some((a) => containsBreak(a.body))) return true;
1418
+ if (st.kind === 'TryStmt' && (containsBreak(st.tryBody) || st.catches.some((c) => containsBreak(c.body)))) return true;
1419
+ }
1420
+ return false;
1421
+ }
1422
+
1423
+ function blockAlwaysExits(stmts) {
1424
+ for (const st of stmts) {
1425
+ if (st.kind === 'ReturnStmt') return true;
1426
+ if (st.kind === 'ExprStmt' && st.expr?.kind === 'Call' && st.expr.callee?.name === 'panik') return true;
1427
+ if (st.kind === 'WhileStmt' && st.cond?.kind === 'Literal' && st.cond.value === true && !containsBreak(st.body)) {
1428
+ return true;
1429
+ }
1430
+ if (st.kind === 'IfStmt') {
1431
+ const hasElse = st.branches.some((b) => b.isElse);
1432
+ if (hasElse && st.branches.every((b) => blockAlwaysExits(b.body))) return true;
1433
+ }
1434
+ if (st.kind === 'MatchStmt') {
1435
+ if (st.arms.length > 0 && st.arms.every((a) => blockAlwaysExits(a.body))) return true;
1436
+ }
1437
+ }
1438
+ return false;
1439
+ }
1440
+
1441
+ function isTypeDroppable(t) {
1442
+ if (!t || t.kind !== 'Named') return false;
1443
+ const info = structs.get(t.name) || enums.get(t.name);
1444
+ return !!(info && info.hasDrop);
1445
+ }
1446
+
1447
+ function analyzeBlock(stmts, scope, ctx, blockKey = 'root') {
1448
+ const localLastUses = collectLastUses(stmts);
1449
+ const mergedLastUses = new Map(ctx.lastUses);
1450
+ for (const [k, v] of localLastUses) {
1451
+ mergedLastUses.set(k, Math.max(mergedLastUses.get(k) || 0, v));
1452
+ }
1453
+ const blockCtx = { ...ctx, lastUses: mergedLastUses };
1454
+
1455
+ for (const st of stmts) {
1456
+ switch (st.kind) {
1457
+ case 'ImportStmt':
1458
+ case 'FromImportStmt': {
1459
+ const baseMod = st.target.replace(/\.(mhs|py)$/i, '').split('.')[0];
1460
+ const isPyFile = st.target.endsWith('.py');
1461
+ const needsUnsafe = st.isPyImport || isPyFile || UNSAFE_HOST_MODULES.has(baseMod);
1462
+
1463
+ if (sandbox && (SANDBOX_FORBIDDEN_MODULES.has(baseMod) || st.isPyImport || isPyFile)) {
1464
+ addError(
1465
+ 'E0134', st.line, st.col, st.endCol,
1466
+ `impor \`${st.target}\` dilarang dalam mode kotak pasir (--sandbox)`
1467
+ );
1468
+ } else if (needsUnsafe && !ctx.inUnsafe && !st.isUnsafe) {
1469
+ addError(
1470
+ 'E0133', st.line, st.col, st.endCol,
1471
+ `impor FFI/modul sistem \`${st.target}\` bersifat tidak aman`,
1472
+ `gunakan \`tidak_aman impor ${st.targetIsString ? `"${st.target}"` : st.target}\` atau letakkan di dalam blok \`tidak_aman:\``
1473
+ );
1474
+ }
1475
+
1476
+ if (st.kind === 'ImportStmt') {
1477
+ scope.bindings.set(st.alias, {
1478
+ name: st.alias, type: makeType('Modul'), mutable: false, isConst: false,
1479
+ state: 'owned', scopeDepth: scope.depth, isHoisted: true, declLine: st.line,
1480
+ });
1481
+ } else {
1482
+ for (const it of st.items) {
1483
+ scope.bindings.set(it.alias, {
1484
+ name: it.alias, type: T_UNKNOWN, mutable: false, isConst: false,
1485
+ state: 'owned', scopeDepth: scope.depth, isHoisted: true, declLine: st.line,
1486
+ });
1487
+ }
1488
+ }
1489
+ break;
1490
+ }
1491
+
1492
+ case 'VarDecl': {
1493
+ const isConst = st.qualifier === 'konst';
1494
+ const isMut = st.qualifier === 'ubah';
1495
+
1496
+ if (isConst && !st.value) {
1497
+ addError('E0384', st.line, st.col, st.endCol, `konstanta \`${st.names[0]?.name}\` wajib langsung diberi nilai`);
1498
+ }
1499
+
1500
+ let holder = st.names.length === 1 ? st.names[0].name : null;
1501
+ const inferred = st.value
1502
+ ? inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true, holderVar: holder })
1503
+ : T_UNKNOWN;
1504
+
1505
+ if (st.type && st.value && !typesCompatible(st.type, inferred)) {
1506
+ addError(
1507
+ 'E0308', st.line, st.col, st.endCol,
1508
+ `ketidakcocokan tipe untuk \`${holder || 'variabel'}\`: diharapkan \`${formatType(st.type)}\`, ditemukan \`${formatType(inferred)}\``
1509
+ );
1510
+ }
1511
+
1512
+ const finalType = st.type || inferred;
1513
+ for (const n of st.names) {
1514
+ const existing = scope.lookup(n.name);
1515
+ if (existing && existing.isConst) {
1516
+ addError('E0384', st.line, n.col, n.endCol, `tidak dapat mendeklarasikan ulang atau menutupi konstanta \`${n.name}\``);
1517
+ }
1518
+ const ownExisting = scope.lookupOwn(n.name);
1519
+ const shadowCount = ownExisting ? (ownExisting.shadowCount || 0) + 1 : 0;
1520
+
1521
+ scope.bindings.set(n.name, {
1522
+ name: n.name,
1523
+ type: finalType,
1524
+ mutable: isMut,
1525
+ isConst,
1526
+ state: 'owned',
1527
+ scopeDepth: scope.depth,
1528
+ declLine: st.line,
1529
+ declCol: n.col,
1530
+ shadowCount,
1531
+ borrows: [],
1532
+ });
1533
+ if (isTypeDroppable(finalType)) {
1534
+ if (!droppableVars.has(blockKey)) droppableVars.set(blockKey, new Set());
1535
+ droppableVars.get(blockKey).add(n.name);
1536
+ }
1537
+ }
1538
+ break;
1539
+ }
1540
+
1541
+ case 'AssignStmt': {
1542
+ // Field/Index assignment (`x.prop = v`, `x[i] = v`, `*r = v`)
1543
+ if (st.target?.kind === 'DerefOrSpread') {
1544
+ if (st.target.target?.kind === 'Ident') {
1545
+ const rName = st.target.target.name;
1546
+ const rb = scope.lookup(rName);
1547
+ if (!rb) {
1548
+ addError('E0425', st.line, st.col, st.endCol, `referensi \`${rName}\` tidak ditemukan`);
1549
+ } else if (rb.type?.kind === 'Pinjam') {
1550
+ addError(
1551
+ 'E0594', st.line, st.col, st.endCol,
1552
+ `tidak dapat mengubah nilai melalui pinjaman tetap \`*${rName}\``,
1553
+ 'gunakan pinjaman ubah (`&ubah`) untuk mengizinkan perubahan melalui referensi'
1554
+ );
1555
+ }
1556
+ const valT = inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true });
1557
+ if (rb?.type?.inner && !typesCompatible(rb.type.inner, valT)) {
1558
+ addError('E0308', st.line, st.col, st.endCol, `ketidakcocokan tipe penugasan \`*${rName}\``);
1559
+ }
1560
+ }
1561
+ break;
1562
+ }
1563
+
1564
+ if (st.target?.kind === 'Member') {
1565
+ const obj = st.target.object;
1566
+ if (obj?.kind === 'Ident') {
1567
+ const b = scope.lookup(obj.name);
1568
+ if (obj.name === 'diri' || obj.name === 'self') {
1569
+ if (ctx.currentFn && !ctx.currentFnSelfMut && !ctx.inInitMethod) {
1570
+ addError(
1571
+ 'E0596', st.line, st.col, st.endCol,
1572
+ `tidak dapat mengubah \`diri.${st.target.property}\` di method tanpa \`&ubah diri\``,
1573
+ 'tambahkan `&ubah diri` sebagai parameter pertama method'
1574
+ );
1575
+ }
1576
+ } else if (b && !b.mutable && b.type?.kind !== 'PinjamUbah') {
1577
+ addError(
1578
+ 'E0384', st.line, st.col, st.endCol,
1579
+ `tidak dapat mengubah properti pada variabel tetap \`${obj.name}\``,
1580
+ `ubah deklarasi \`${obj.name}\` menjadi \`ubah ${obj.name} = ...\``
1581
+ );
1582
+ } else if (b) {
1583
+ const active = isRootBorrowAlive(b, st.line, blockCtx.lastUses);
1584
+ if (active.length > 0) {
1585
+ addError('E0506', st.line, st.col, st.endCol, `tidak dapat mengubah \`${obj.name}\` karena sedang dipinjam`);
1586
+ }
1587
+ }
1588
+ }
1589
+ const fieldT = inferAndCheckExpr(st.target, scope, blockCtx, { consumeMove: false });
1590
+ const valT = inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true });
1591
+ if (fieldT && !typesCompatible(fieldT, valT)) {
1592
+ addError(
1593
+ 'E0308', st.line, st.col, st.endCol,
1594
+ `ketidakcocokan tipe field \`${st.target.property}\`: diharapkan \`${formatType(fieldT)}\`, ditemukan \`${formatType(valT)}\``
1595
+ );
1596
+ }
1597
+ break;
1598
+ }
1599
+
1600
+ if (st.target?.kind === 'Index') {
1601
+ if (st.target.object?.kind === 'Ident') {
1602
+ const name = st.target.object.name;
1603
+ const b = scope.lookup(name);
1604
+ if (b && !b.mutable && b.type?.kind !== 'PinjamUbah') {
1605
+ addError(
1606
+ 'E0384', st.line, st.col, st.endCol,
1607
+ `tidak dapat mengubah elemen pada variabel tetap \`${name}\``,
1608
+ `ubah deklarasi menjadi \`ubah ${name} = ...\``
1609
+ );
1610
+ } else if (b) {
1611
+ const active = isRootBorrowAlive(b, st.line, blockCtx.lastUses);
1612
+ if (active.length > 0) {
1613
+ addError('E0506', st.line, st.col, st.endCol, `tidak dapat mengubah \`${name}\` karena sedang dipinjam`);
1614
+ }
1615
+ }
1616
+ }
1617
+ inferAndCheckExpr(st.target.object, scope, blockCtx, { consumeMove: false });
1618
+ inferAndCheckExpr(st.target.index, scope, blockCtx, { consumeMove: false });
1619
+ inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true });
1620
+ break;
1621
+ }
1622
+
1623
+ // Assignment ke Ident / Tuple
1624
+ const targetNames = st.target?.kind === 'Tuple'
1625
+ ? st.target.items.filter((it) => it.kind === 'Ident').map((it) => it.name)
1626
+ : st.target?.kind === 'Ident' ? [st.target.name] : [];
1627
+
1628
+ if (targetNames.length === 1) {
1629
+ const name = targetNames[0];
1630
+ const existing = scope.lookup(name);
1631
+
1632
+ if (!existing) {
1633
+ // Deklarasi implisit pertama di cakupan saat ini = `tetap` (immutable by default!)
1634
+ if (st.op !== '=') {
1635
+ addError('E0425', st.line, st.col, st.endCol, `variabel \`${name}\` belum dideklarasikan sebelum operator \`${st.op}\``);
1636
+ break;
1637
+ }
1638
+ const valT = inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true, holderVar: name });
1639
+ if (st.type && !typesCompatible(st.type, valT)) {
1640
+ addError(
1641
+ 'E0308', st.line, st.col, st.endCol,
1642
+ `ketidakcocokan tipe untuk \`${name}\`: diharapkan \`${formatType(st.type)}\`, ditemukan \`${formatType(valT)}\``
1643
+ );
1644
+ }
1645
+ const finalT = st.type || valT;
1646
+ scope.bindings.set(name, {
1647
+ name,
1648
+ type: finalT,
1649
+ mutable: false, // Rust-first: implicit declaration is immutable!
1650
+ isConst: false,
1651
+ state: 'owned',
1652
+ scopeDepth: scope.depth,
1653
+ declLine: st.line,
1654
+ declCol: st.col,
1655
+ shadowCount: 0,
1656
+ borrows: [],
1657
+ });
1658
+ if (isTypeDroppable(finalT)) {
1659
+ if (!droppableVars.has(blockKey)) droppableVars.set(blockKey, new Set());
1660
+ droppableVars.get(blockKey).add(name);
1661
+ }
1662
+ } else {
1663
+ // Reassignment pada variabel yang sudah ada!
1664
+ if (existing.isConst) {
1665
+ addError('E0384', st.line, st.col, st.endCol, `tidak dapat mengubah konstanta \`${name}\``);
1666
+ } else if (!existing.mutable) {
1667
+ addError(
1668
+ 'E0384', st.line, st.col, st.endCol,
1669
+ `tidak dapat menugaskan ulang variabel tetap \`${name}\``,
1670
+ `gunakan \`ubah ${name} = ...\` saat deklarasi agar variabel dapat diubah, atau \`tetap ${name} = ...\` untuk shadowing`
1671
+ );
1672
+ } else {
1673
+ // Cek active borrows & dangling lifetime
1674
+ const active = isRootBorrowAlive(existing, st.line, blockCtx.lastUses);
1675
+ if (active.length > 0) {
1676
+ addError(
1677
+ 'E0506', st.line, st.col, st.endCol,
1678
+ `tidak dapat mengubah \`${name}\` karena sedang dipinjam`,
1679
+ null,
1680
+ `pinjaman aktif sejak baris ${active[0].declaredLine}`
1681
+ );
1682
+ }
1683
+ if (st.value?.kind === 'Borrow' && st.value.target?.kind === 'Ident') {
1684
+ const targetB = scope.lookup(st.value.target.name);
1685
+ if (targetB && targetB.scopeDepth > existing.scopeDepth) {
1686
+ addError(
1687
+ 'E0597', st.line, st.col, st.endCol,
1688
+ `\`${st.value.target.name}\` tidak hidup cukup lama untuk dipinjam oleh \`${name}\``,
1689
+ 'pastikan variabel yang dipinjam memiliki cakupan hidup yang lebih panjang atau sama'
1690
+ );
1691
+ }
1692
+ }
1693
+ }
1694
+
1695
+ const valT = inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true, holderVar: name });
1696
+ if (existing.mutable && !typesCompatible(existing.type, valT)) {
1697
+ addError(
1698
+ 'E0308', st.line, st.col, st.endCol,
1699
+ `tidak dapat mengubah tipe variabel \`${name}\` dari \`${formatType(existing.type)}\` menjadi \`${formatType(valT)}\``
1700
+ );
1701
+ }
1702
+ if (existing.mutable) {
1703
+ existing.state = 'owned';
1704
+ existing.movedAt = null;
1705
+ if (isUnknownOrAny(existing.type) && !isUnknownOrAny(valT)) existing.type = valT;
1706
+ }
1707
+ }
1708
+ } else {
1709
+ const valT = inferAndCheckExpr(st.value, scope, blockCtx, { consumeMove: true });
1710
+ for (const name of targetNames) {
1711
+ const ex = scope.lookup(name);
1712
+ if (ex && !ex.mutable) {
1713
+ addError('E0384', st.line, st.col, st.endCol, `tidak dapat menugaskan ulang variabel tetap \`${name}\``);
1714
+ } else if (!ex) {
1715
+ scope.bindings.set(name, {
1716
+ name, type: T_UNKNOWN, mutable: false, isConst: false,
1717
+ state: 'owned', scopeDepth: scope.depth, declLine: st.line, borrows: [],
1718
+ });
1719
+ }
1720
+ }
1721
+ }
1722
+ break;
1723
+ }
1724
+
1725
+ case 'ExprStmt': {
1726
+ const resT = inferAndCheckExpr(st.expr, scope, blockCtx, { consumeMove: false, inCallStmt: true });
1727
+ // `#[must_use]` untuk nilai kembalian Hasil atau Opsi yang dibuang begitu saja!
1728
+ if (
1729
+ st.expr?.kind === 'Call' &&
1730
+ resT?.kind === 'Named' &&
1731
+ (resT.name === 'Hasil' || resT.name === 'Opsi')
1732
+ ) {
1733
+ addError(
1734
+ 'E0702', st.line, st.col, st.endCol,
1735
+ `nilai bertipe \`${formatType(resT)}\` wajib ditangani dan tidak boleh diabaikan`,
1736
+ 'tangani dengan `cocok`, operator `?`, `.buka_atau(...)`, atau simpan ke variabel'
1737
+ );
1738
+ }
1739
+ break;
1740
+ }
1741
+
1742
+ case 'ReturnStmt': {
1743
+ const retT = st.expr
1744
+ ? inferAndCheckExpr(st.expr, scope, blockCtx, { consumeMove: true })
1745
+ : T_UNIT;
1746
+ // Cek dangling return reference ke variabel lokal!
1747
+ if (st.expr?.kind === 'Borrow' && st.expr.target?.kind === 'Ident' && ctx.currentFn) {
1748
+ const tb = scope.lookup(st.expr.target.name);
1749
+ if (tb && tb.scopeDepth >= ctx.fnScopeDepth && !tb.isParam) {
1750
+ addError(
1751
+ 'E0515', st.line, st.col, st.endCol,
1752
+ `tidak dapat mengembalikan referensi ke variabel lokal \`${st.expr.target.name}\``,
1753
+ 'kembalikan nilai kepemilikannya langsung tanpa `&`'
1754
+ );
1755
+ }
1756
+ }
1757
+ if (ctx.currentFn?.returnType && !typesCompatible(ctx.currentFn.returnType, retT)) {
1758
+ // Khusus jika fungsi pakai `?` dan `kembalikan Ok(val)` / `kembalikan Ada(val)`:
1759
+ addError(
1760
+ 'E0308', st.line, st.col, st.col + 10,
1761
+ `ketidakcocokan tipe kembalian fungsi \`${ctx.currentFn.name}\`: diharapkan \`${formatType(ctx.currentFn.returnType)}\`, ditemukan \`${formatType(retT)}\``
1762
+ );
1763
+ }
1764
+ break;
1765
+ }
1766
+
1767
+ case 'YieldStmt':
1768
+ if (st.expr) inferAndCheckExpr(st.expr, scope, blockCtx, { consumeMove: true });
1769
+ break;
1770
+
1771
+ case 'RaiseStmt':
1772
+ if (!ctx.inUnsafe) {
1773
+ addError(
1774
+ 'E0703', st.line, st.col, st.endCol,
1775
+ '`lempar` (exception) dilarang di kode aman ala Rust',
1776
+ 'kembalikan `Galat(...)` untuk error yang ditangani, gunakan `panik(...)` untuk kegagalan fatal, atau bungkus dalam `tidak_aman:`'
1777
+ );
1778
+ }
1779
+ if (st.expr) inferAndCheckExpr(st.expr, scope, blockCtx, { consumeMove: true });
1780
+ break;
1781
+
1782
+ case 'AssertStmt':
1783
+ inferAndCheckExpr(st.cond, scope, blockCtx, { consumeMove: false });
1784
+ if (st.msg) inferAndCheckExpr(st.msg, scope, blockCtx, { consumeMove: false });
1785
+ break;
1786
+
1787
+ case 'GlobalStmt':
1788
+ for (const g of st.names) {
1789
+ const b = scope.lookup(g);
1790
+ if (b) b.mutable = true;
1791
+ }
1792
+ break;
1793
+
1794
+ case 'IfStmt': {
1795
+ const initialSnap = scope.cloneStates();
1796
+ const postBranchSnaps = [];
1797
+
1798
+ for (const br of st.branches) {
1799
+ scope.restoreStates(initialSnap);
1800
+ const brScope = new Scope(scope, 'block', scope.depth + 1);
1801
+ if (br.isIfLet) {
1802
+ const exprT = inferAndCheckExpr(br.expr, scope, blockCtx, { consumeMove: false });
1803
+ bindPatternVars(br.pattern, exprT, brScope, br.line);
1804
+ } else if (br.cond) {
1805
+ inferAndCheckExpr(br.cond, scope, blockCtx, { consumeMove: false });
1806
+ }
1807
+ analyzeBlock(br.body, brScope, blockCtx, `if_${br.line}`);
1808
+ if (!blockAlwaysExits(br.body)) {
1809
+ postBranchSnaps.push(scope.cloneStates());
1810
+ }
1811
+ }
1812
+
1813
+ // Gabungkan status move dari semua cabang yang tidak return/break
1814
+ const hasElse = st.branches.some((b) => b.isElse);
1815
+ if (!hasElse) {
1816
+ postBranchSnaps.push(initialSnap);
1817
+ }
1818
+ if (postBranchSnaps.length > 0) {
1819
+ for (const [k] of initialSnap) {
1820
+ const states = postBranchSnaps.map((s) => s.get(k));
1821
+ if (states.every((s) => s === 'moved')) {
1822
+ const b = scope.lookup(k);
1823
+ if (b) b.state = 'moved';
1824
+ } else if (states.some((s) => s === 'moved' || s === 'maybe_moved')) {
1825
+ const b = scope.lookup(k);
1826
+ if (b) b.state = 'maybe_moved';
1827
+ } else {
1828
+ const b = scope.lookup(k);
1829
+ if (b) b.state = initialSnap.get(k);
1830
+ }
1831
+ }
1832
+ }
1833
+ break;
1834
+ }
1835
+
1836
+ case 'WhileStmt': {
1837
+ inferAndCheckExpr(st.cond, scope, blockCtx, { consumeMove: false });
1838
+ const preSnap = scope.cloneStates();
1839
+ const loopScope = new Scope(scope, 'block', scope.depth + 1);
1840
+ analyzeBlock(st.body, loopScope, blockCtx, `while_${st.line}`);
1841
+ // Cek ulang iterasi ke-2 jika ada variabel luar yang dipindahkan dalam loop
1842
+ const postSnap = scope.cloneStates();
1843
+ const movedInLoop = [];
1844
+ for (const [k, s] of postSnap) {
1845
+ if (preSnap.get(k) === 'owned' && (s === 'moved' || s === 'maybe_moved')) {
1846
+ movedInLoop.push(k);
1847
+ }
1848
+ }
1849
+ if (movedInLoop.length > 0) {
1850
+ const usesInLoop = collectLastUses(st.body);
1851
+ for (const mk of movedInLoop) {
1852
+ if (usesInLoop.has(mk)) {
1853
+ addError(
1854
+ 'E0382', st.line, st.col, st.col + 6,
1855
+ `nilai \`${mk}\` dipindahkan di dalam perulangan \`selama\` dan tidak dapat dipakai pada iterasi berikutnya`,
1856
+ `gunakan \`salin(${mk})\` atau pinjam dengan \`&${mk}\``
1857
+ );
1858
+ }
1859
+ }
1860
+ }
1861
+ break;
1862
+ }
1863
+
1864
+ case 'ForStmt': {
1865
+ const isBorrowIter = st.iter?.kind === 'Borrow';
1866
+ const iterT = inferAndCheckExpr(st.iter, scope, blockCtx, {
1867
+ consumeMove: !isBorrowIter,
1868
+ isBorrowArg: isBorrowIter,
1869
+ });
1870
+ const preSnap = scope.cloneStates();
1871
+ const loopScope = new Scope(scope, 'block', scope.depth + 1);
1872
+ const unwrappedIter = (iterT?.kind === 'Pinjam' || iterT?.kind === 'PinjamUbah') ? iterT.inner : iterT;
1873
+ let itemT = T_UNKNOWN;
1874
+ if (unwrappedIter?.kind === 'Named' && unwrappedIter.args?.[0]) {
1875
+ itemT = unwrappedIter.args[0];
1876
+ }
1877
+ for (const tgt of st.targets) {
1878
+ loopScope.bindings.set(tgt.name, {
1879
+ name: tgt.name,
1880
+ type: st.targets.length === 1 ? itemT : T_UNKNOWN,
1881
+ mutable: st.isMut,
1882
+ isConst: false,
1883
+ state: 'owned',
1884
+ scopeDepth: loopScope.depth,
1885
+ declLine: st.line,
1886
+ borrows: [],
1887
+ });
1888
+ }
1889
+ analyzeBlock(st.body, loopScope, blockCtx, `for_${st.line}`);
1890
+ const postSnap = scope.cloneStates();
1891
+ const movedInLoop = [];
1892
+ for (const [k, s] of postSnap) {
1893
+ if (preSnap.get(k) === 'owned' && (s === 'moved' || s === 'maybe_moved')) {
1894
+ movedInLoop.push(k);
1895
+ }
1896
+ }
1897
+ if (movedInLoop.length > 0) {
1898
+ const usesInLoop = collectLastUses(st.body);
1899
+ for (const mk of movedInLoop) {
1900
+ if (usesInLoop.has(mk)) {
1901
+ addError(
1902
+ 'E0382', st.line, st.col, st.col + 5,
1903
+ `nilai \`${mk}\` dipindahkan di dalam perulangan \`untuk\` dan tidak dapat dipakai pada iterasi berikutnya`,
1904
+ `gunakan \`salin(${mk})\` atau pinjam dengan \`&${mk}\``
1905
+ );
1906
+ }
1907
+ }
1908
+ }
1909
+ break;
1910
+ }
1911
+
1912
+ case 'MatchStmt': {
1913
+ const targetT = inferAndCheckExpr(st.target, scope, blockCtx, { consumeMove: true });
1914
+ const missing = isExhaustiveMatch(st, targetT);
1915
+ if (missing) {
1916
+ addError(
1917
+ 'E0004', st.line, st.col, st.endCol,
1918
+ `pola \`cocok\` tidak lengkap: kasus belum ditangani (${missing.join(', ')})`,
1919
+ `tambahkan cabang untuk ${missing.join(', ')} atau cabang catch-all \`_ => ...\``
1920
+ );
1921
+ }
1922
+ const initialSnap = scope.cloneStates();
1923
+ for (const arm of st.arms) {
1924
+ scope.restoreStates(initialSnap);
1925
+ const armScope = new Scope(scope, 'block', scope.depth + 1);
1926
+ bindPatternVars(arm.pattern, targetT, armScope, arm.line);
1927
+ if (arm.guard) {
1928
+ inferAndCheckExpr(arm.guard, armScope, blockCtx, { consumeMove: false });
1929
+ }
1930
+ analyzeBlock(arm.body, armScope, blockCtx, `match_${arm.line}`);
1931
+ }
1932
+ break;
1933
+ }
1934
+
1935
+ case 'UnsafeBlock': {
1936
+ if (sandbox) {
1937
+ addError(
1938
+ 'E0134', st.line, st.col, st.endCol,
1939
+ 'blok `tidak_aman:` dilarang dalam mode kotak pasir (--sandbox)'
1940
+ );
1941
+ }
1942
+ const uScope = new Scope(scope, 'block', scope.depth + 1);
1943
+ analyzeBlock(st.body, uScope, { ...blockCtx, inUnsafe: true }, `unsafe_${st.line}`);
1944
+ break;
1945
+ }
1946
+
1947
+ case 'TryStmt': {
1948
+ const tScope = new Scope(scope, 'block', scope.depth + 1);
1949
+ analyzeBlock(st.tryBody, tScope, blockCtx, `try_${st.line}`);
1950
+ for (const c of st.catches) {
1951
+ const cScope = new Scope(scope, 'block', scope.depth + 1);
1952
+ if (c.errVar) {
1953
+ cScope.bindings.set(c.errVar, {
1954
+ name: c.errVar, type: makeType('GalatRuntime'), mutable: false, isConst: false,
1955
+ state: 'owned', scopeDepth: cScope.depth, declLine: c.line, borrows: [],
1956
+ });
1957
+ }
1958
+ analyzeBlock(c.body, cScope, blockCtx, `catch_${c.line}`);
1959
+ }
1960
+ if (st.finallyBody) {
1961
+ const fScope = new Scope(scope, 'block', scope.depth + 1);
1962
+ analyzeBlock(st.finallyBody, fScope, blockCtx, `finally_${st.line}`);
1963
+ }
1964
+ break;
1965
+ }
1966
+
1967
+ case 'WithStmt': {
1968
+ if (sandbox && st.ctxExpr?.kind === 'Call' && ['buka', 'open'].includes(st.ctxExpr.callee?.name)) {
1969
+ addError('E0134', st.line, st.col, st.endCol, 'membuka berkas lewat `dengan buka(...)` dilarang dalam mode kotak pasir (--sandbox)');
1970
+ }
1971
+ inferAndCheckExpr(st.ctxExpr, scope, blockCtx, { consumeMove: false });
1972
+ const wScope = new Scope(scope, 'block', scope.depth + 1);
1973
+ if (st.asVar) {
1974
+ wScope.bindings.set(st.asVar, {
1975
+ name: st.asVar, type: T_UNKNOWN, mutable: true, isConst: false,
1976
+ state: 'owned', scopeDepth: wScope.depth, declLine: st.line, borrows: [],
1977
+ });
1978
+ }
1979
+ analyzeBlock(st.body, wScope, blockCtx, `with_${st.line}`);
1980
+ break;
1981
+ }
1982
+
1983
+ case 'FunctionDecl': {
1984
+ if (!scope.lookupOwn(st.name)) {
1985
+ scope.bindings.set(st.name, {
1986
+ name: st.name, type: makeType('Fungsi'), mutable: false, isConst: false,
1987
+ state: 'owned', scopeDepth: scope.depth, isHoisted: true, declLine: st.line,
1988
+ });
1989
+ }
1990
+ analyzeFunction(st, scope, blockCtx, null);
1991
+ break;
1992
+ }
1993
+
1994
+ case 'StructDecl':
1995
+ case 'ClassDecl': {
1996
+ const sInfo = structs.get(st.name);
1997
+ const classScope = new Scope(scope, 'class', scope.depth + 1);
1998
+ for (const item of st.body) {
1999
+ if (item.kind === 'FunctionDecl') {
2000
+ analyzeFunction(item, classScope, blockCtx, st.name);
2001
+ }
2002
+ }
2003
+ break;
2004
+ }
2005
+
2006
+ case 'ImplDecl': {
2007
+ const targetInfo = structs.get(st.targetName) || enums.get(st.targetName);
2008
+ if (!targetInfo) {
2009
+ addError('E0425', st.line, st.col, st.endCol, `tipe \`${st.targetName}\` untuk \`implementasi\` tidak ditemukan`);
2010
+ break;
2011
+ }
2012
+ const implScope = new Scope(scope, 'class', scope.depth + 1);
2013
+ for (const item of st.body) {
2014
+ if (item.kind === 'FunctionDecl') {
2015
+ analyzeFunction(item, implScope, blockCtx, st.targetName);
2016
+ }
2017
+ }
2018
+ break;
2019
+ }
2020
+
2021
+ case 'EnumDecl':
2022
+ break;
2023
+ }
2024
+ }
2025
+ }
2026
+
2027
+ function analyzeFunction(fnNode, parentScope, ctx, ownerTypeName) {
2028
+ const fnScope = new Scope(parentScope, 'function', parentScope.depth + 1);
2029
+ const hasDecorators = fnNode.decorators && fnNode.decorators.length > 0;
2030
+ const isInit = fnNode.name === '__init__' || fnNode.name === '__inisialisasi__';
2031
+ let selfIsMut = false;
2032
+
2033
+ for (let i = 0; i < fnNode.params.length; i++) {
2034
+ const p = fnNode.params[i];
2035
+ const isSelf = i === 0 && ownerTypeName && (p.name === 'diri' || p.name === 'self');
2036
+ if (isSelf) {
2037
+ selfIsMut = p.isMut || p.type?.kind === 'PinjamUbah' || isInit;
2038
+ const selfType = p.isBorrow
2039
+ ? { kind: selfIsMut ? 'PinjamUbah' : 'Pinjam', inner: makeType(ownerTypeName) }
2040
+ : makeType(ownerTypeName);
2041
+ fnScope.bindings.set(p.name, {
2042
+ name: p.name, type: selfType, mutable: selfIsMut, isConst: false,
2043
+ state: 'owned', scopeDepth: fnScope.depth, declLine: p.line, isParam: true, borrows: [],
2044
+ });
2045
+ continue;
2046
+ }
2047
+
2048
+ if (!p.type && !isRepl && !ctx.inUnsafe && !p.isStar && !p.isDoubleStar && !hasDecorators) {
2049
+ addError(
2050
+ 'E0704', p.line, p.col, p.endCol,
2051
+ `parameter \`${p.name}\` pada fungsi \`${fnNode.name}\` wajib memiliki anotasi tipe ala Rust`,
2052
+ `tambahkan tipe seperti \`${p.name}: bulat\` atau \`${p.name}: &teks\``
2053
+ );
2054
+ }
2055
+
2056
+ let paramType = p.type || T_UNKNOWN;
2057
+ if (p.defaultExpr) {
2058
+ const defT = inferAndCheckExpr(p.defaultExpr, parentScope, ctx, { consumeMove: false });
2059
+ if (p.type && !typesCompatible(p.type, defT)) {
2060
+ addError('E0308', p.line, p.col, p.endCol, `nilai default parameter \`${p.name}\` tidak cocok dengan tipenya`);
2061
+ }
2062
+ }
2063
+
2064
+ fnScope.bindings.set(p.name, {
2065
+ name: p.name,
2066
+ type: paramType,
2067
+ mutable: p.isMut || paramType.kind === 'PinjamUbah',
2068
+ isConst: false,
2069
+ state: 'owned',
2070
+ scopeDepth: fnScope.depth,
2071
+ declLine: p.line,
2072
+ isParam: true,
2073
+ borrows: [],
2074
+ });
2075
+ }
2076
+
2077
+ const fnCtx = {
2078
+ ...ctx,
2079
+ currentFn: fnNode,
2080
+ currentFnSelfMut: selfIsMut,
2081
+ inInitMethod: isInit,
2082
+ fnScopeDepth: fnScope.depth,
2083
+ };
2084
+
2085
+ analyzeBlock(fnNode.body, fnScope, fnCtx, `fn_${fnNode.line}_${fnNode.name}`);
2086
+
2087
+ if (fnNode.returnType && fnNode.returnType.name !== 'Unit' && !isUnknownOrAny(fnNode.returnType)) {
2088
+ if (!blockAlwaysExits(fnNode.body)) {
2089
+ addError(
2090
+ 'E0308', fnNode.line, fnNode.col, fnNode.endCol,
2091
+ `fungsi \`${fnNode.name}\` menjanjikan nilai kembali \`${formatType(fnNode.returnType)}\`, tetapi tidak semua jalur mengembalikan nilai`,
2092
+ 'pastikan setiap cabang diakhiri dengan `kembalikan ...` atau `panik(...)`'
2093
+ );
2094
+ }
2095
+ }
2096
+ }
2097
+
2098
+ analyzeBlock(program.body, rootScope, {
2099
+ inUnsafe: false,
2100
+ lastUses: new Map(),
2101
+ currentFn: null,
2102
+ currentFnSelfMut: false,
2103
+ inInitMethod: false,
2104
+ fnScopeDepth: 0,
2105
+ }, 'root');
2106
+
2107
+ const errors = diagnostics.filter((d) => d.severity !== 'warning');
2108
+ return {
2109
+ program,
2110
+ diagnostics,
2111
+ errors,
2112
+ metadata: {
2113
+ sandbox,
2114
+ usesTanyaInFn,
2115
+ mutBorrowedBindings,
2116
+ droppableVars,
2117
+ enums,
2118
+ structs,
2119
+ variantToEnum,
2120
+ },
2121
+ };
2122
+ }
2123
+
2124
+ function assertSafe(source, options = {}) {
2125
+ const result = analyzeSafety(source, options);
2126
+ if (result.errors.length > 0) {
2127
+ throw new MhsSafetyError(result.errors, result.program.rawLines, options.filename || '<mhs>');
2128
+ }
2129
+ return result;
2130
+ }
2131
+
2132
+ module.exports = {
2133
+ MhsSafetyError,
2134
+ formatDiagnostic,
2135
+ analyzeSafety,
2136
+ assertSafe,
2137
+ UNSAFE_HOST_MODULES,
2138
+ SANDBOX_FORBIDDEN_MODULES,
2139
+ };