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
@@ -1,9 +1,13 @@
1
1
  /**
2
- * Transpiler Bahasa .mhs -> Python 3 Murni (.py)
3
- * Mengubah sintaks Bahasa Indonesia ke Python 3 1-on-1 sehingga
4
- * 100% kompatibel dengan seluruh fitur & library Python asli.
2
+ * Transpiler Bahasa .mhs (Rust-Safe Indonesian Pythonic) -> Python 3 Murni (.py)
3
+ * Mengubah sintaks .mhs + fitur keamanan ala Rust ke Python 3 1-on-1 sehingga
4
+ * tetap 100% kompatibel dengan library Python asli.
5
5
  */
6
6
 
7
+ const { tokenize } = require('./lexer');
8
+ const { parseExpression } = require('./parser');
9
+ const { assertSafe } = require('./safety_analyzer');
10
+
7
11
  const PY_PRELUDE = `
8
12
  import math as _mhs_math
9
13
  import random as _mhs_random
@@ -13,14 +17,398 @@ import sys as _mhs_sys
13
17
  import copy as _mhs_copy
14
18
  import importlib.util as _mhs_importlib_util
15
19
 
16
- if len(_mhs_sys.argv) > 1 and _mhs_sys.argv[0] == '-c':
17
- _mhs_sys.argv = _mhs_sys.argv[1:]
20
+ class _MhsPanikError(Exception):
21
+ pass
22
+
23
+ class _MhsPropagasi(Exception):
24
+ def __init__(self, nilai):
25
+ self.nilai = nilai
26
+
27
+ def panik(pesan="Eksekusi panik"):
28
+ raise _MhsPanikError(f"[PANIK] {pesan}")
29
+
30
+ class _MhsRef:
31
+ def __init__(self, getter, setter=None, mut=False):
32
+ object.__setattr__(self, "_getter", getter)
33
+ object.__setattr__(self, "_setter", setter)
34
+ object.__setattr__(self, "_mut", mut)
35
+
36
+ def _get(self):
37
+ return object.__getattribute__(self, "_getter")()
38
+
39
+ def _set(self, val):
40
+ if not object.__getattribute__(self, "_mut"):
41
+ raise _MhsPanikError("Tidak dapat mengubah nilai melalui pinjaman tetap (&)")
42
+ setter = object.__getattribute__(self, "_setter")
43
+ setter(val)
44
+
45
+ def __getattr__(self, attr):
46
+ if not object.__getattribute__(self, "_mut") and attr in (
47
+ "append", "extend", "insert", "pop", "remove", "clear",
48
+ "sort", "reverse", "update", "setdefault", "add", "discard"
49
+ ):
50
+ raise _MhsPanikError(f"Tidak dapat memanggil method pengubah .{attr}() melalui pinjaman tetap (&)")
51
+ return getattr(self._get(), attr)
52
+
53
+ def __setattr__(self, attr, val):
54
+ if not object.__getattribute__(self, "_mut"):
55
+ raise _MhsPanikError("Tidak dapat mengubah properti melalui pinjaman tetap (&)")
56
+ setattr(self._get(), attr, val)
57
+
58
+ def __getitem__(self, k):
59
+ return _mhs_indeks(self._get(), k)
60
+
61
+ def __setitem__(self, k, val):
62
+ if not object.__getattribute__(self, "_mut"):
63
+ raise _MhsPanikError("Tidak dapat mengubah elemen melalui pinjaman tetap (&)")
64
+ _mhs_atur_indeks(self._get(), k, val)
65
+
66
+ def __len__(self):
67
+ return len(self._get())
68
+
69
+ def __iter__(self):
70
+ return iter(self._get())
71
+
72
+ def __contains__(self, item):
73
+ return item in self._get()
74
+
75
+ def __eq__(self, other):
76
+ return self._get() == _mhs_unwrap(other)
77
+
78
+ def __str__(self):
79
+ return str(self._get())
80
+
81
+ def __repr__(self):
82
+ return repr(self._get())
83
+
84
+ def _mhs_unwrap(val):
85
+ while isinstance(val, _MhsRef):
86
+ val = val._get()
87
+ return val
88
+
89
+ def _mhs_pinjam(getter):
90
+ return _MhsRef(getter, None, False)
91
+
92
+ def _mhs_pinjam_ubah(getter, setter):
93
+ return _MhsRef(getter, setter, True)
94
+
95
+ def _mhs_deref(val):
96
+ if isinstance(val, _MhsRef):
97
+ return val._get()
98
+ return val
99
+
100
+ def _mhs_set_deref(ref, val):
101
+ if not isinstance(ref, _MhsRef):
102
+ raise _MhsPanikError("Operator '*' hanya untuk referensi pinjaman")
103
+ ref._set(val)
104
+ return val
105
+
106
+ class _MhsOpsi:
107
+ __class_getitem__ = classmethod(lambda cls, item: cls)
108
+
109
+ def __init__(self, ada, nilai=None):
110
+ self._ada = bool(ada)
111
+ self._nilai = nilai
112
+
113
+ def apakah_ada(self):
114
+ return self._ada
115
+
116
+ def apakah_tidak_ada(self):
117
+ return not self._ada
118
+
119
+ def buka_atau(self, cadangan):
120
+ return self._nilai if self._ada else cadangan
121
+
122
+ def buka_atau_hitung(self, fn):
123
+ return self._nilai if self._ada else fn()
124
+
125
+ def harapkan(self, pesan="Opsi bernilai TidakAda"):
126
+ if not self._ada:
127
+ panik(pesan)
128
+ return self._nilai
129
+
130
+ def buka_tanpa_cek(self):
131
+ if not self._ada:
132
+ panik("Memanggil buka_tanpa_cek() pada TidakAda")
133
+ return self._nilai
134
+
135
+ def petakan(self, fn):
136
+ return Ada(fn(self._nilai)) if self._ada else TidakAda
137
+
138
+ def lalu(self, fn):
139
+ return fn(self._nilai) if self._ada else TidakAda
140
+
141
+ def ke_hasil(self, galat):
142
+ return Ok(self._nilai) if self._ada else Galat(galat)
143
+
144
+ def __eq__(self, other):
145
+ if not isinstance(other, _MhsOpsi):
146
+ return False
147
+ if not self._ada and not other._ada:
148
+ return True
149
+ return self._ada == other._ada and self._nilai == other._nilai
150
+
151
+ def __str__(self):
152
+ return f"Ada({self._nilai!r})" if self._ada else "TidakAda"
153
+
154
+ def __repr__(self):
155
+ return self.__str__()
156
+
157
+ TidakAda = _MhsOpsi(False, None)
158
+ def Ada(nilai):
159
+ return _MhsOpsi(True, nilai)
160
+ Opsi = _MhsOpsi
161
+
162
+ class _MhsHasil:
163
+ __class_getitem__ = classmethod(lambda cls, item: cls)
164
+
165
+ def __init__(self, ok, nilai):
166
+ self._ok = bool(ok)
167
+ self._nilai = nilai
168
+
169
+ def apakah_ok(self):
170
+ return self._ok
171
+
172
+ def apakah_galat(self):
173
+ return not self._ok
174
+
175
+ def buka_atau(self, cadangan):
176
+ return self._nilai if self._ok else cadangan
177
+
178
+ def buka_atau_hitung(self, fn):
179
+ return self._nilai if self._ok else fn(self._nilai)
180
+
181
+ def harapkan(self, pesan="Hasil Galat"):
182
+ if not self._ok:
183
+ panik(f"{pesan}: {self._nilai}")
184
+ return self._nilai
185
+
186
+ def buka_tanpa_cek(self):
187
+ if not self._ok:
188
+ panik(f"Memanggil buka_tanpa_cek() pada Galat: {self._nilai}")
189
+ return self._nilai
190
+
191
+ def petakan(self, fn):
192
+ return Ok(fn(self._nilai)) if self._ok else self
193
+
194
+ def petakan_galat(self, fn):
195
+ return self if self._ok else Galat(fn(self._nilai))
196
+
197
+ def lalu(self, fn):
198
+ return fn(self._nilai) if self._ok else self
199
+
200
+ def nilai_ok(self):
201
+ return Ada(self._nilai) if self._ok else TidakAda
202
+
203
+ def nilai_galat(self):
204
+ return TidakAda if self._ok else Ada(self._nilai)
205
+
206
+ def __eq__(self, other):
207
+ return isinstance(other, _MhsHasil) and self._ok == other._ok and self._nilai == other._nilai
208
+
209
+ def __str__(self):
210
+ return f"Ok({self._nilai!r})" if self._ok else f"Galat({self._nilai!r})"
211
+
212
+ def __repr__(self):
213
+ return self.__str__()
214
+
215
+ def Ok(nilai=None):
216
+ return _MhsHasil(True, nilai)
217
+
218
+ def Galat(pesan):
219
+ return _MhsHasil(False, pesan)
220
+
221
+ Hasil = _MhsHasil
222
+
223
+ def dari_kosong(nilai):
224
+ return TidakAda if nilai is None else Ada(nilai)
225
+
226
+ def _mhs_tanya(val):
227
+ if isinstance(val, _MhsHasil):
228
+ if val._ok:
229
+ return val._nilai
230
+ raise _MhsPropagasi(val)
231
+ if isinstance(val, _MhsOpsi):
232
+ if val._ada:
233
+ return val._nilai
234
+ raise _MhsPropagasi(TidakAda)
235
+ panik("Operator '?' hanya dapat digunakan pada nilai bertipe Hasil atau Opsi")
236
+
237
+ class _MhsEnumVarian:
238
+ def __init__(self, enum_name, varian, *data):
239
+ self.__mhs_enum = enum_name
240
+ self._varian = varian
241
+ self._data = data
242
+
243
+ def __eq__(self, other):
244
+ return (
245
+ isinstance(other, _MhsEnumVarian)
246
+ and self.__mhs_enum == other.__mhs_enum
247
+ and self._varian == other._varian
248
+ and self._data == other._data
249
+ )
250
+
251
+ def __str__(self):
252
+ if self._data:
253
+ args_txt = ", ".join(repr(x) for x in self._data)
254
+ return f"{self.__mhs_enum}.{self._varian}({args_txt})"
255
+ return f"{self.__mhs_enum}.{self._varian}"
256
+
257
+ def __repr__(self):
258
+ return self.__str__()
259
+
260
+ def _mhs_enum_varian(enum_name, varian, *data):
261
+ return _MhsEnumVarian(enum_name, varian, *data)
262
+
263
+ def _mhs_bagi(a, b):
264
+ x, y = _mhs_unwrap(a), _mhs_unwrap(b)
265
+ if y == 0:
266
+ panik("Pembagian dengan nol")
267
+ return x / y
268
+
269
+ def _mhs_bagi_bulat(a, b):
270
+ x, y = _mhs_unwrap(a), _mhs_unwrap(b)
271
+ if y == 0:
272
+ panik("Pembagian bulat dengan nol")
273
+ return x // y
274
+
275
+ def _mhs_sisa(a, b):
276
+ x, y = _mhs_unwrap(a), _mhs_unwrap(b)
277
+ if y == 0:
278
+ panik("Operasi modulo dengan nol")
279
+ return x % y
280
+
281
+ def _mhs_indeks(obj, idx):
282
+ raw = _mhs_unwrap(obj)
283
+ k = _mhs_unwrap(idx)
284
+ if isinstance(raw, (list, tuple, str, bytes)):
285
+ if not isinstance(k, int) or isinstance(k, bool) or k < 0 or k >= len(raw):
286
+ panik(f"Indeks di luar batas: indeks {k} untuk panjang {len(raw)}")
287
+ return raw[k]
288
+ if isinstance(raw, dict):
289
+ if k not in raw:
290
+ panik(f"Kunci tidak ditemukan di kamus: {k!r}")
291
+ return raw[k]
292
+ return raw[k]
293
+
294
+ def _mhs_atur_indeks(obj, idx, val):
295
+ if isinstance(obj, _MhsRef) and not object.__getattribute__(obj, "_mut"):
296
+ panik("Tidak dapat mengubah elemen melalui pinjaman tetap (&)")
297
+ raw = _mhs_unwrap(obj)
298
+ k = _mhs_unwrap(idx)
299
+ if isinstance(raw, list):
300
+ if not isinstance(k, int) or isinstance(k, bool) or k < 0 or k >= len(raw):
301
+ panik(f"Indeks di luar batas saat menulis: indeks {k} untuk panjang {len(raw)}")
302
+ raw[k] = val
303
+ return val
304
+
305
+ def _mhs_ambil(obj, idx):
306
+ raw = _mhs_unwrap(obj)
307
+ if hasattr(raw, "ambil") and not isinstance(raw, (list, tuple, str)):
308
+ return raw.ambil(idx)
309
+ return ambil_indeks(raw, idx)
310
+
311
+ def _mhs_ambil_opsi(obj, k):
312
+ raw = _mhs_unwrap(obj)
313
+ if hasattr(raw, "ambil_opsi") and not isinstance(raw, dict):
314
+ return raw.ambil_opsi(k)
315
+ return ambil_kunci(raw, k)
316
+
317
+ def ambil_indeks(koleksi, idx):
318
+ raw = _mhs_unwrap(koleksi)
319
+ if isinstance(raw, (list, tuple, str)) and isinstance(idx, int) and 0 <= idx < len(raw):
320
+ return Ada(raw[idx])
321
+ return TidakAda
322
+
323
+ def ambil_kunci(kamus_obj, k):
324
+ raw = _mhs_unwrap(kamus_obj)
325
+ if isinstance(raw, dict) and k in raw:
326
+ return Ada(raw[k])
327
+ return TidakAda
328
+
329
+ def urai_bulat(teks_in):
330
+ s = str(_mhs_unwrap(teks_in)).strip()
331
+ try:
332
+ return Ok(int(s, 10))
333
+ except Exception:
334
+ return Galat(f'Tidak dapat mengurai "{s}" menjadi bilangan bulat')
335
+
336
+ def urai_desimal(teks_in):
337
+ s = str(_mhs_unwrap(teks_in)).strip()
338
+ try:
339
+ val = float(s)
340
+ if not _mhs_math.isfinite(val):
341
+ return Galat(f'Nilai "{s}" tidak terhingga')
342
+ return Ok(val)
343
+ except Exception:
344
+ return Galat(f'Tidak dapat mengurai "{s}" menjadi bilangan desimal')
345
+
346
+ _I64_MIN = -(1 << 63)
347
+ _I64_MAX = (1 << 63) - 1
348
+
349
+ def tambah_aman(a, b):
350
+ res = a + b
351
+ if res < _I64_MIN or res > _I64_MAX:
352
+ return Galat(f"Overflow integer pada {a} + {b}")
353
+ return Ok(res)
354
+
355
+ def kurang_aman(a, b):
356
+ res = a - b
357
+ if res < _I64_MIN or res > _I64_MAX:
358
+ return Galat(f"Overflow integer pada {a} - {b}")
359
+ return Ok(res)
360
+
361
+ def kali_aman(a, b):
362
+ res = a * b
363
+ if res < _I64_MIN or res > _I64_MAX:
364
+ return Galat(f"Overflow integer pada {a} * {b}")
365
+ return Ok(res)
366
+
367
+ def bagi_aman(a, b):
368
+ if b == 0:
369
+ return Galat("Pembagian dengan nol")
370
+ return Ok(a / b)
371
+
372
+ def salin(val):
373
+ return _mhs_copy.deepcopy(_mhs_unwrap(val))
374
+
375
+ def bekukan(val):
376
+ from types import MappingProxyType
377
+ if isinstance(val, list):
378
+ return tuple(bekukan(x) for x in val)
379
+ if isinstance(val, dict):
380
+ return MappingProxyType({k: bekukan(v) for k, v in val.items()})
381
+ return val
382
+
383
+ def _mhs_rentang(start, end, inclusive=False):
384
+ return range(start, end + 1 if inclusive else end)
385
+
386
+ def _mhs_lepas(val):
387
+ if val is not None and hasattr(val, "lepas") and callable(getattr(val, "lepas")):
388
+ val.lepas()
389
+
390
+ def _mhs_aktifkan_kotak_pasir():
391
+ import builtins as _bi
392
+ _terlarang = {"os", "sys", "subprocess", "ctypes", "shutil", "socket", "urllib", "pathlib", "berkas", "jaringan", "sistem", "asyncio"}
393
+ class _BlokirImpor:
394
+ def find_spec(self, fullname, path, target=None):
395
+ root = fullname.split(".")[0]
396
+ if root in _terlarang:
397
+ raise ImportError(f"[Kotak Pasir] Impor modul '{fullname}' dilarang")
398
+ return None
399
+ _mhs_sys.meta_path.insert(0, _BlokirImpor())
400
+ def _blok_open(*args, **kwargs):
401
+ panik("[Kotak Pasir] Akses berkas via buka()/open() dilarang")
402
+ _bi.open = _blok_open
403
+ globals()["buka"] = _blok_open
404
+
405
+ def cetak(*args, **kwargs):
406
+ print(*[_mhs_unwrap(a) for a in args], **kwargs)
18
407
 
19
- cetak = print
20
408
  masukan = input
21
409
  rentang = range
22
- panjang = len
23
- teks = str
410
+ panjang = lambda x: len(_mhs_unwrap(x))
411
+ teks = lambda x: str(_mhs_unwrap(x))
24
412
  angka = lambda x: float(x) if '.' in str(x) else int(x)
25
413
  bulat = int
26
414
  desimal = float
@@ -28,246 +416,935 @@ daftar = list
28
416
  kamus = dict
29
417
  himpunan = set
30
418
  tupel = tuple
419
+ Daftar = list
420
+ Kamus = dict
421
+ Himpunan = set
422
+ Tupel = tuple
423
+ Fungsi = object
424
+ Unit = type(None)
425
+ ApaSaja = object
31
426
  mutlak = abs
32
427
  bulatkan = round
33
428
  akar = _mhs_math.sqrt
34
429
  pangkat = pow
35
430
  bawah = _mhs_math.floor
36
431
  atas = _mhs_math.ceil
37
- min_nilai = min
38
- maks_nilai = max
39
- jumlah = sum
40
- urutkan = lambda x, menurun=False: sorted(x, reverse=menurun)
41
- balik = lambda x: list(reversed(x))
42
- tambah = lambda d, item: d.append(item) or d
43
- hapus = lambda d, idx=None: d.pop() if idx is None else d.pop(idx)
44
- gabung = lambda d, pemisah="": pemisah.join(str(i) for i in d)
45
- pisah = lambda s, pemisah=" ": str(s).split(pemisah)
46
- huruf_besar = lambda s: str(s).upper()
47
- huruf_kecil = lambda s: str(s).lower()
48
- potong = lambda s: str(s).strip()
49
- ganti = lambda s, lama, baru: str(s).replace(lama, baru)
50
- mengandung = lambda k, item: item in k
432
+ min_nilai = lambda *a: min(_mhs_unwrap(a[0])) if len(a) == 1 else min(*[_mhs_unwrap(x) for x in a])
433
+ maks_nilai = lambda *a: max(_mhs_unwrap(a[0])) if len(a) == 1 else max(*[_mhs_unwrap(x) for x in a])
434
+ jumlah = lambda d: sum(_mhs_unwrap(d))
435
+ urutkan = lambda x, menurun=False: sorted(_mhs_unwrap(x), reverse=menurun)
436
+ balik = lambda x: list(reversed(_mhs_unwrap(x)))
437
+ def tambah(d, item):
438
+ if isinstance(d, _MhsRef) and not object.__getattribute__(d, "_mut"):
439
+ panik("Tidak dapat memanggil tambah() melalui pinjaman tetap (&)")
440
+ raw = _mhs_unwrap(d)
441
+ raw.append(item)
442
+ return raw
443
+ def hapus(d, idx=None):
444
+ if isinstance(d, _MhsRef) and not object.__getattribute__(d, "_mut"):
445
+ panik("Tidak dapat memanggil hapus() melalui pinjaman tetap (&)")
446
+ raw = _mhs_unwrap(d)
447
+ return raw.pop() if idx is None else raw.pop(idx)
448
+ gabung = lambda d, pemisah="": pemisah.join(str(i) for i in _mhs_unwrap(d))
449
+ pisah = lambda s, pemisah=" ": str(_mhs_unwrap(s)).split(pemisah)
450
+ huruf_besar = lambda s: str(_mhs_unwrap(s)).upper()
451
+ huruf_kecil = lambda s: str(_mhs_unwrap(s)).lower()
452
+ potong = lambda s: str(_mhs_unwrap(s)).strip()
453
+ ganti = lambda s, lama, baru: str(_mhs_unwrap(s)).replace(lama, baru)
454
+ mengandung = lambda k, item: item in _mhs_unwrap(k)
51
455
  acak = lambda a=0, b=100: _mhs_random.randint(a, b)
52
456
  waktu_sekarang = lambda: int(_mhs_time.time() * 1000)
53
457
  tunggu = lambda ms: _mhs_time.sleep(ms / 1000.0)
54
- kunci = lambda d: list(d.keys())
55
- nilai = lambda d: list(d.values())
458
+ kunci = lambda d: list(_mhs_unwrap(d).keys())
459
+ nilai = lambda d: list(_mhs_unwrap(d).values())
56
460
  buka = open
57
461
 
58
- # Fitur & fungsi bawaan Python dalam Bahasa Indonesia
59
- semua = all
60
- ada_yang = any
61
- cacah = enumerate
62
- pasangkan = zip
63
- saring = lambda fn, kol: list(filter(fn, kol))
64
- petakan = lambda fn, kol: list(map(fn, kol))
65
- bisa_dipanggil = callable
66
- punya_atribut = hasattr
67
- ambil_atribut = getattr
68
- atur_atribut = setattr
69
- hapus_atribut = delattr
70
- adalah_turunan = isinstance
71
- turunan_dari = isinstance
72
- nilai_karakter = ord
73
- karakter = chr
74
- format_teks = format
75
- teks_biner = bin
76
- teks_heksa = hex
77
- teks_oktal = oct
78
- evaluasi = eval
79
- eksekusi = exec
80
- daftar_anggota = dir
81
- penghitung = iter
82
- berikutnya = next
83
- keluar = _mhs_sys.exit
84
- salin = lambda x: _mhs_copy.copy(x)
85
- salin_dalam = lambda x: _mhs_copy.deepcopy(x)
86
- bekukan = frozenset
87
-
88
462
  def tipe(x):
463
+ x = _mhs_unwrap(x)
89
464
  if x is None: return "kosong"
465
+ if isinstance(x, _MhsOpsi): return "Opsi"
466
+ if isinstance(x, _MhsHasil): return "Hasil"
467
+ if isinstance(x, _MhsEnumVarian): return x._MhsEnumVarian__mhs_enum
90
468
  if isinstance(x, bool): return "boolean"
91
- if isinstance(x, (int, float)): return "angka"
469
+ if isinstance(x, int): return "bulat"
470
+ if isinstance(x, float): return "desimal"
92
471
  if isinstance(x, str): return "teks"
93
472
  if isinstance(x, list): return "daftar"
94
473
  if isinstance(x, dict): return "kamus"
95
474
  if callable(x): return "fungsi"
96
475
  return type(x).__name__
476
+
477
+ import types as _mhs_types
478
+ if "_mhs_shared_rt" in _mhs_sys.modules:
479
+ _rt = _mhs_sys.modules["_mhs_shared_rt"]
480
+ _MhsPanikError = _rt._MhsPanikError
481
+ _MhsPropagasi = _rt._MhsPropagasi
482
+ _MhsRef = _rt._MhsRef
483
+ _MhsOpsi = _rt._MhsOpsi
484
+ Opsi = _rt.Opsi
485
+ Ada = _rt.Ada
486
+ TidakAda = _rt.TidakAda
487
+ _MhsHasil = _rt._MhsHasil
488
+ Hasil = _rt.Hasil
489
+ Ok = _rt.Ok
490
+ Galat = _rt.Galat
491
+ _MhsEnumVarian = _rt._MhsEnumVarian
492
+ _mhs_enum_varian = _rt._mhs_enum_varian
493
+ _mhs_tanya = _rt._mhs_tanya
494
+ _mhs_pinjam = _rt._mhs_pinjam
495
+ _mhs_pinjam_ubah = _rt._mhs_pinjam_ubah
496
+ _mhs_deref = _rt._mhs_deref
497
+ _mhs_set_deref = _rt._mhs_set_deref
498
+ _mhs_unwrap = _rt._mhs_unwrap
499
+ dari_kosong = _rt.dari_kosong
500
+ panik = _rt.panik
501
+ else:
502
+ _rt = _mhs_types.ModuleType("_mhs_shared_rt")
503
+ _rt._MhsPanikError = _MhsPanikError
504
+ _rt._MhsPropagasi = _MhsPropagasi
505
+ _rt._MhsRef = _MhsRef
506
+ _rt._MhsOpsi = _MhsOpsi
507
+ _rt.Opsi = Opsi
508
+ _rt.Ada = Ada
509
+ _rt.TidakAda = TidakAda
510
+ _rt._MhsHasil = _MhsHasil
511
+ _rt.Hasil = Hasil
512
+ _rt.Ok = Ok
513
+ _rt.Galat = Galat
514
+ _rt._MhsEnumVarian = _MhsEnumVarian
515
+ _rt._mhs_enum_varian = _mhs_enum_varian
516
+ _rt._mhs_tanya = _mhs_tanya
517
+ _rt._mhs_pinjam = _mhs_pinjam
518
+ _rt._mhs_pinjam_ubah = _mhs_pinjam_ubah
519
+ _rt._mhs_deref = _mhs_deref
520
+ _rt._mhs_set_deref = _mhs_set_deref
521
+ _rt._mhs_unwrap = _mhs_unwrap
522
+ _rt.dari_kosong = dari_kosong
523
+ _rt.panik = panik
524
+ _mhs_sys.modules["_mhs_shared_rt"] = _rt
97
525
  `.trim();
98
526
 
99
- function protectStringsAndComments(line) {
100
- const tokens = [];
101
- let out = '';
102
- let i = 0;
103
-
104
- while (i < line.length) {
105
- const ch = line[i];
106
-
107
- if ((ch === 'f' || ch === 'F') && (line[i + 1] === '"' || line[i + 1] === "'")) {
108
- const quote = line[i + 1];
109
- let j = i + 2;
110
- let raw = ch + quote;
111
- while (j < line.length) {
112
- if (line[j] === '\\' && j + 1 < line.length) {
113
- raw += line[j] + line[j + 1];
114
- j += 2;
527
+ function cleanModuleName(mod) {
528
+ return mod
529
+ .replace(/^\.\//, '')
530
+ .replace(/\.(mhs|py)$/i, '')
531
+ .replace(/\//g, '.');
532
+ }
533
+
534
+ function pyTypeStr(t) {
535
+ if (!t) return 'Any';
536
+ if (t.kind === 'Pinjam' || t.kind === 'PinjamUbah') return pyTypeStr(t.inner);
537
+ if (t.kind === 'Named') {
538
+ const map = {
539
+ bulat: 'int',
540
+ desimal: 'float',
541
+ angka: 'float',
542
+ teks: 'str',
543
+ bool: 'bool',
544
+ bytes: 'bytes',
545
+ Unit: 'None',
546
+ Daftar: 'list',
547
+ Kamus: 'dict',
548
+ Himpunan: 'set',
549
+ Tupel: 'tuple',
550
+ Opsi: 'Opsi',
551
+ Hasil: 'Hasil',
552
+ Fungsi: 'object',
553
+ ApaSaja: 'object',
554
+ };
555
+ const base = map[t.name] || t.rawName || t.name;
556
+ if (t.args && t.args.length > 0 && base !== 'object') {
557
+ return `${base}[${t.args.map(pyTypeStr).join(', ')}]`;
558
+ }
559
+ return base;
560
+ }
561
+ return 'object';
562
+ }
563
+
564
+ function transpileToPython(source, options = {}) {
565
+ const { includePrelude = true } = options;
566
+ const analysis = assertSafe(source, options);
567
+ const { program, metadata } = analysis;
568
+ const { usesTanyaInFn, enums, structs, variantToEnum, sandbox } = metadata;
569
+
570
+ let tmpCounter = 0;
571
+ function nextTmp(prefix = '_mhs_tmp') {
572
+ return `${prefix}_${tmpCounter++}`;
573
+ }
574
+
575
+ class PyScope {
576
+ constructor(parent = null, isModule = false) {
577
+ this.parent = parent;
578
+ this.isModule = isModule;
579
+ this.vars = new Map(); // origName -> { pyName, isModule, isRef }
580
+ this.shadowCounts = new Map();
581
+ }
582
+ resolveInfo(name) {
583
+ if (this.vars.has(name)) return this.vars.get(name);
584
+ return this.parent ? this.parent.resolveInfo(name) : null;
585
+ }
586
+ resolve(name) {
587
+ const info = this.resolveInfo(name);
588
+ return info ? info.pyName : name;
589
+ }
590
+ declare(name, isRef = false, allowReuse = false) {
591
+ if (!allowReuse && this.vars.has(name)) {
592
+ const count = (this.shadowCounts.get(name) || 0) + 1;
593
+ this.shadowCounts.set(name, count);
594
+ const pyName = `${name}__s${count}`;
595
+ this.vars.set(name, { pyName, isModule: this.isModule, isRef });
596
+ return pyName;
597
+ }
598
+ this.vars.set(name, { pyName: name, isModule: this.isModule, isRef });
599
+ return name;
600
+ }
601
+ }
602
+
603
+ const rootScope = new PyScope(null, true);
604
+ const lines = [];
605
+ const dropSlotMap = new Map();
606
+
607
+ function emitFStringPy(inner, quote, scope, preStmts) {
608
+ let out = '';
609
+ let i = 0;
610
+ while (i < inner.length) {
611
+ if (inner[i] === '\\' && i + 1 < inner.length) {
612
+ out += inner[i] + inner[i + 1];
613
+ i += 2;
614
+ continue;
615
+ }
616
+ if (inner[i] === '{') {
617
+ if (inner[i + 1] === '{') {
618
+ out += '{{';
619
+ i += 2;
115
620
  continue;
116
621
  }
117
- raw += line[j];
118
- if (line[j] === quote) {
622
+ let depth = 1;
623
+ let j = i + 1;
624
+ let inStr = null;
625
+ while (j < inner.length && depth > 0) {
626
+ const ch = inner[j];
627
+ if (inStr) {
628
+ if (ch === '\\') { j += 2; continue; }
629
+ if (ch === inStr) inStr = null;
630
+ } else if (ch === '"' || ch === "'") {
631
+ inStr = ch;
632
+ } else if (ch === '{') depth++;
633
+ else if (ch === '}') { depth--; if (depth === 0) break; }
119
634
  j++;
120
- break;
121
635
  }
122
- j++;
636
+ const raw = inner.slice(i + 1, j);
637
+ let splitColon = -1;
638
+ let pDepth = 0;
639
+ let qStr = null;
640
+ for (let k = 0; k < raw.length; k++) {
641
+ const c = raw[k];
642
+ if (qStr) {
643
+ if (c === '\\') { k++; continue; }
644
+ if (c === qStr) qStr = null;
645
+ } else if (c === '"' || c === "'") qStr = c;
646
+ else if (c === '(' || c === '[' || c === '{') pDepth++;
647
+ else if (c === ')' || c === ']' || c === '}') pDepth--;
648
+ else if (c === ':' && pDepth === 0) { splitColon = k; break; }
649
+ }
650
+ const exprText = splitColon === -1 ? raw.trim() : raw.slice(0, splitColon).trim();
651
+ const spec = splitColon === -1 ? '' : raw.slice(splitColon + 1).trim();
652
+ const toks = tokenize(exprText).tokens.filter((t) => !['LINE_START', 'NEWLINE', 'EOF'].includes(t.type));
653
+ const exprAst = parseExpression(toks);
654
+ const pyExpr = emitExpr(exprAst, scope, preStmts);
655
+ out += spec ? `{${pyExpr}:${spec}}` : `{${pyExpr}}`;
656
+ i = j + 1;
657
+ continue;
658
+ }
659
+ if (inner[i] === '}' && inner[i + 1] === '}') {
660
+ out += '}}';
661
+ i += 2;
662
+ continue;
663
+ }
664
+ out += inner[i];
665
+ i++;
666
+ }
667
+ return `f${quote}${out}${quote}`;
668
+ }
669
+
670
+ function emitCompPy(expr, scope, preStmts, kind) {
671
+ const compScope = new PyScope(scope, false);
672
+ const clauses = expr.clauses || [];
673
+ const clauseStrs = [];
674
+ for (let idx = 0; idx < clauses.length; idx++) {
675
+ const cl = clauses[idx];
676
+ const iterPy = emitExpr(cl.iter, idx === 0 ? scope : compScope, preStmts);
677
+ const tgts = cl.targets.map((t) => compScope.declare(t, false, true)).join(', ');
678
+ let part = `for ${tgts} in ${iterPy}`;
679
+ if (cl.cond) {
680
+ part += ` if ${emitExpr(cl.cond, compScope, preStmts)}`;
123
681
  }
124
- const id = `__MHS_PY_STR_${tokens.length}__`;
125
- const inner = raw.slice(2, -1).replace(/\{([^}]+)\}/g, (_, expr) => '{' + transformPyExpr(expr) + '}');
126
- tokens.push(`f${quote}${inner}${quote}`);
127
- out += id;
128
- i = j;
129
- continue;
682
+ clauseStrs.push(part);
683
+ }
684
+ if (kind === 'DictComp') {
685
+ return `{${emitExpr(expr.key, compScope, preStmts)}: ${emitExpr(expr.value, compScope, preStmts)} ${clauseStrs.join(' ')}}`;
130
686
  }
687
+ if (kind === 'GeneratorComp') {
688
+ return `(${emitExpr(expr.body, compScope, preStmts)} ${clauseStrs.join(' ')})`;
689
+ }
690
+ return `[${emitExpr(expr.body, compScope, preStmts)} ${clauseStrs.join(' ')}]`;
691
+ }
131
692
 
132
- if (ch === '"' || ch === "'") {
133
- const quote = ch;
134
- let j = i + 1;
135
- let raw = quote;
136
- while (j < line.length) {
137
- if (line[j] === '\\' && j + 1 < line.length) {
138
- raw += line[j] + line[j + 1];
139
- j += 2;
140
- continue;
693
+ function emitExpr(expr, scope, preStmts, { inCallArgs = false } = {}) {
694
+ if (!expr) return 'None';
695
+
696
+ switch (expr.kind) {
697
+ case 'Literal':
698
+ if (expr.litType === 'teks') return `${expr.quote || '"'}${expr.value}${expr.quote || '"'}`;
699
+ if (expr.litType === 'bytes') return `b${expr.quote || '"'}${expr.value}${expr.quote || '"'}`;
700
+ if (expr.litType === 'bool') return expr.value ? 'True' : 'False';
701
+ return String(expr.raw ?? expr.value);
702
+
703
+ case 'NullLiteral':
704
+ return 'None';
705
+
706
+ case 'OptionNone':
707
+ return 'TidakAda';
708
+
709
+ case 'FString':
710
+ return emitFStringPy(expr.value, expr.quote || '"', scope, preStmts);
711
+
712
+ case 'Ident':
713
+ if (expr.name === 'diri') return 'self';
714
+ return scope.resolve(expr.name);
715
+
716
+ case 'Borrow': {
717
+ if (expr.target?.kind === 'Ident') {
718
+ const info = scope.resolveInfo(expr.target.name);
719
+ const pyVar = info ? info.pyName : expr.target.name;
720
+ if (expr.mutable) {
721
+ const setFn = nextTmp(`_mhs_set_${pyVar}`);
722
+ const declScope = info?.isModule ? `global ${pyVar}` : `nonlocal ${pyVar}`;
723
+ preStmts.push(`def ${setFn}(_v):`);
724
+ preStmts.push(` ${declScope}`);
725
+ preStmts.push(` ${pyVar} = _v`);
726
+ return `_mhs_pinjam_ubah(lambda: ${pyVar}, ${setFn})`;
727
+ }
728
+ return `_mhs_pinjam(lambda: ${pyVar})`;
141
729
  }
142
- raw += line[j];
143
- if (line[j] === quote) {
144
- j++;
145
- break;
730
+ const tPy = emitExpr(expr.target, scope, preStmts);
731
+ return `_mhs_pinjam(lambda: ${tPy})`;
732
+ }
733
+
734
+ case 'Move': {
735
+ if (expr.target?.kind === 'Ident' && dropSlotMap.has(expr.target.name)) {
736
+ const slot = dropSlotMap.get(expr.target.name);
737
+ const pyVar = scope.resolve(expr.target.name);
738
+ const mv = nextTmp('_mv');
739
+ preStmts.push(`${mv} = ${pyVar}`);
740
+ preStmts.push(`${slot} = None`);
741
+ return mv;
742
+ }
743
+ return emitExpr(expr.target, scope, preStmts);
744
+ }
745
+
746
+ case 'DerefOrSpread': {
747
+ if (inCallArgs && expr.target?.kind === 'Ident') {
748
+ const info = scope.resolveInfo(expr.target.name);
749
+ if (!info || !info.isRef) {
750
+ return `*${info ? info.pyName : expr.target.name}`;
751
+ }
752
+ }
753
+ return `_mhs_deref(${emitExpr(expr.target, scope, preStmts)})`;
754
+ }
755
+
756
+ case 'KwSpread':
757
+ return `**${emitExpr(expr.target, scope, preStmts)}`;
758
+
759
+ case 'Await':
760
+ return `await ${emitExpr(expr.target, scope, preStmts)}`;
761
+
762
+ case 'TryPropagate':
763
+ return `_mhs_tanya(${emitExpr(expr.expr, scope, preStmts)})`;
764
+
765
+ case 'Unary': {
766
+ const op = expr.op === 'bukan' ? 'not ' : expr.op;
767
+ return `(${op}${emitExpr(expr.operand, scope, preStmts)})`;
768
+ }
769
+
770
+ case 'Range':
771
+ return `_mhs_rentang(${emitExpr(expr.start, scope, preStmts)}, ${emitExpr(expr.end, scope, preStmts)}, ${expr.inclusive ? 'True' : 'False'})`;
772
+
773
+ case 'Binary': {
774
+ const l = emitExpr(expr.left, scope, preStmts);
775
+ const r = emitExpr(expr.right, scope, preStmts);
776
+ switch (expr.op) {
777
+ case 'dan': return `(${l} and ${r})`;
778
+ case 'atau': return `(${l} or ${r})`;
779
+ case 'adalah': return `(${l} is ${r})`;
780
+ case 'bukan_adalah': return `(${l} is not ${r})`;
781
+ case 'dalam':
782
+ case 'in': return `(${l} in ${r})`;
783
+ case 'bukan_dalam': return `(${l} not in ${r})`;
784
+ case '/': return `_mhs_bagi(${l}, ${r})`;
785
+ case '//': return `_mhs_bagi_bulat(${l}, ${r})`;
786
+ case '%': return `_mhs_sisa(${l}, ${r})`;
787
+ default: return `(${l} ${expr.op} ${r})`;
146
788
  }
147
- j++;
148
789
  }
149
- const id = `__MHS_PY_STR_${tokens.length}__`;
150
- tokens.push(raw);
151
- out += id;
152
- i = j;
153
- continue;
790
+
791
+ case 'Ternary':
792
+ return `(${emitExpr(expr.consequent, scope, preStmts)} if ${emitExpr(expr.cond, scope, preStmts)} else ${emitExpr(expr.alternate, scope, preStmts)})`;
793
+
794
+ case 'List':
795
+ return `[${expr.items.map((it) => emitExpr(it, scope, preStmts)).join(', ')}]`;
796
+
797
+ case 'Tuple':
798
+ if (expr.items.length === 1) return `(${emitExpr(expr.items[0], scope, preStmts)},)`;
799
+ return `(${expr.items.map((it) => emitExpr(it, scope, preStmts)).join(', ')})`;
800
+
801
+ case 'Set':
802
+ return `{${expr.items.map((it) => emitExpr(it, scope, preStmts)).join(', ')}}`;
803
+
804
+ case 'Dict':
805
+ return `{${expr.entries.map((e) => `${emitExpr(e.key, scope, preStmts)}: ${emitExpr(e.value, scope, preStmts)}`).join(', ')}}`;
806
+
807
+ case 'ListComp':
808
+ case 'GeneratorComp':
809
+ case 'DictComp':
810
+ return emitCompPy(expr, scope, preStmts, expr.kind);
811
+
812
+ case 'Lambda': {
813
+ const lScope = new PyScope(scope, false);
814
+ const ps = expr.params.map((p) => lScope.declare(p, false, true)).join(', ');
815
+ return `(lambda ${ps}: ${emitExpr(expr.body, lScope, preStmts)})`;
816
+ }
817
+
818
+ case 'Member':
819
+ return `${emitExpr(expr.object, scope, preStmts)}.${expr.property}`;
820
+
821
+ case 'Index':
822
+ return `_mhs_indeks(${emitExpr(expr.object, scope, preStmts)}, ${emitExpr(expr.index, scope, preStmts)})`;
823
+
824
+ case 'Slice': {
825
+ const s = expr.start ? emitExpr(expr.start, scope, preStmts) : '';
826
+ const e = expr.end ? emitExpr(expr.end, scope, preStmts) : '';
827
+ const stp = expr.step ? `:${emitExpr(expr.step, scope, preStmts)}` : '';
828
+ return `${emitExpr(expr.object, scope, preStmts)}[${s}:${e}${stp}]`;
829
+ }
830
+
831
+ case 'Call': {
832
+ if (expr.callee?.kind === 'Member') {
833
+ if (expr.callee.property === 'ambil' && expr.args.length === 1) {
834
+ return `_mhs_ambil(${emitExpr(expr.callee.object, scope, preStmts)}, ${emitExpr(expr.args[0], scope, preStmts)})`;
835
+ }
836
+ if (expr.callee.property === 'ambil_opsi' && expr.args.length === 1) {
837
+ return `_mhs_ambil_opsi(${emitExpr(expr.callee.object, scope, preStmts)}, ${emitExpr(expr.args[0], scope, preStmts)})`;
838
+ }
839
+ }
840
+ const calleePy = emitExpr(expr.callee, scope, preStmts);
841
+ const parts = expr.args.map((a) => emitExpr(a, scope, preStmts, { inCallArgs: true }));
842
+ for (const kw of expr.kwargs) {
843
+ parts.push(`${kw.kwargName}=${emitExpr(kw.value, scope, preStmts)}`);
844
+ }
845
+ return `${calleePy}(${parts.join(', ')})`;
846
+ }
154
847
  }
848
+ return 'None';
849
+ }
155
850
 
156
- if (ch === '#') {
157
- const id = `__MHS_PY_STR_${tokens.length}__`;
158
- tokens.push(line.slice(i));
159
- out += id;
160
- break;
851
+ function emitPatternCheckPy(pat, targetVar, scope, preStmts) {
852
+ switch (pat.kind) {
853
+ case 'Wildcard':
854
+ return { cond: 'True', binds: [] };
855
+
856
+ case 'Literal': {
857
+ const v = pat.litType === 'teks' ? JSON.stringify(pat.value) : pat.litType === 'bool' ? (pat.value ? 'True' : 'False') : String(pat.value);
858
+ return { cond: `(_mhs_unwrap(${targetVar}) == ${v})`, binds: [] };
859
+ }
860
+
861
+ case 'Range':
862
+ return {
863
+ cond: pat.inclusive
864
+ ? `(${emitExpr(pat.start, scope, preStmts)} <= ${targetVar} <= ${emitExpr(pat.end, scope, preStmts)})`
865
+ : `(${emitExpr(pat.start, scope, preStmts)} <= ${targetVar} < ${emitExpr(pat.end, scope, preStmts)})`,
866
+ binds: [],
867
+ };
868
+
869
+ case 'IdentOrUnitVariant':
870
+ if (pat.name === 'TidakAda') {
871
+ return { cond: `(isinstance(${targetVar}, _MhsOpsi) and not ${targetVar}._ada)`, binds: [] };
872
+ }
873
+ if (variantToEnum.has(pat.name)) {
874
+ const eName = variantToEnum.get(pat.name);
875
+ return {
876
+ cond: `(isinstance(${targetVar}, _MhsEnumVarian) and ${targetVar}._MhsEnumVarian__mhs_enum == ${JSON.stringify(eName)} and ${targetVar}._varian == ${JSON.stringify(pat.name)})`,
877
+ binds: [],
878
+ };
879
+ }
880
+ return { cond: 'True', binds: [{ name: pat.name, expr: targetVar }] };
881
+
882
+ case 'QualifiedVariant':
883
+ return {
884
+ cond: `(isinstance(${targetVar}, _MhsEnumVarian) and ${targetVar}._MhsEnumVarian__mhs_enum == ${JSON.stringify(pat.enumName)} and ${targetVar}._varian == ${JSON.stringify(pat.variantName)})`,
885
+ binds: (pat.args || []).flatMap((a, idx) => {
886
+ if (a.kind === 'IdentOrUnitVariant' && a.name !== '_') return [{ name: a.name, expr: `${targetVar}._data[${idx}]` }];
887
+ return [];
888
+ }),
889
+ };
890
+
891
+ case 'Variant':
892
+ if (pat.name === 'Ada') {
893
+ const binds = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
894
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai` }] : [];
895
+ return { cond: `(isinstance(${targetVar}, _MhsOpsi) and ${targetVar}._ada)`, binds };
896
+ }
897
+ if (pat.name === 'TidakAda') {
898
+ return { cond: `(isinstance(${targetVar}, _MhsOpsi) and not ${targetVar}._ada)`, binds: [] };
899
+ }
900
+ if (pat.name === 'Ok') {
901
+ const binds = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
902
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai` }] : [];
903
+ return { cond: `(isinstance(${targetVar}, _MhsHasil) and ${targetVar}._ok)`, binds };
904
+ }
905
+ if (pat.name === 'Galat') {
906
+ const binds = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
907
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai` }] : [];
908
+ return { cond: `(isinstance(${targetVar}, _MhsHasil) and not ${targetVar}._ok)`, binds };
909
+ }
910
+ if (variantToEnum.has(pat.name)) {
911
+ const eName = variantToEnum.get(pat.name);
912
+ const binds = [];
913
+ (pat.args || []).forEach((a, idx) => {
914
+ if (a.kind === 'IdentOrUnitVariant' && a.name !== '_') {
915
+ binds.push({ name: a.name, expr: `${targetVar}._data[${idx}]` });
916
+ }
917
+ });
918
+ return {
919
+ cond: `(isinstance(${targetVar}, _MhsEnumVarian) and ${targetVar}._MhsEnumVarian__mhs_enum == ${JSON.stringify(eName)} and ${targetVar}._varian == ${JSON.stringify(pat.name)})`,
920
+ binds,
921
+ };
922
+ }
923
+ return { cond: 'False', binds: [] };
924
+
925
+ case 'ExprPattern':
926
+ return { cond: `(_mhs_unwrap(${targetVar}) == ${emitExpr(pat.expr, scope, preStmts)})`, binds: [] };
927
+ }
928
+ return { cond: 'False', binds: [] };
929
+ }
930
+
931
+ function emitBlock(stmts, scope, indentLevel, { blockKey = null, inClass = false } = {}) {
932
+ const pad = ' '.repeat(indentLevel);
933
+ const blockDrops = blockKey && metadata.droppableVars.has(blockKey)
934
+ ? Array.from(metadata.droppableVars.get(blockKey))
935
+ : [];
936
+
937
+ const prevSlots = [];
938
+ if (blockDrops.length > 0) {
939
+ for (const dv of blockDrops) {
940
+ const slot = nextTmp(`_drop_${dv}`);
941
+ prevSlots.push({ orig: dv, prev: dropSlotMap.get(dv), slot });
942
+ dropSlotMap.set(dv, slot);
943
+ lines.push(`${pad}${slot} = None`);
944
+ }
945
+ lines.push(`${pad}try:`);
161
946
  }
162
947
 
163
- out += ch;
164
- i++;
948
+ const innerIndent = blockDrops.length > 0 ? indentLevel + 1 : indentLevel;
949
+ const innerPad = ' '.repeat(innerIndent);
950
+ if (stmts.length === 0) {
951
+ lines.push(`${innerPad}pass`);
952
+ } else {
953
+ for (const st of stmts) {
954
+ emitStmt(st, scope, innerIndent, { inClass, pad: innerPad });
955
+ }
956
+ }
957
+
958
+ if (blockDrops.length > 0) {
959
+ lines.push(`${pad}finally:`);
960
+ for (let i = prevSlots.length - 1; i >= 0; i--) {
961
+ const { orig, prev, slot } = prevSlots[i];
962
+ lines.push(`${pad} _mhs_lepas(${slot})`);
963
+ if (prev) dropSlotMap.set(orig, prev);
964
+ else dropSlotMap.delete(orig);
965
+ }
966
+ }
165
967
  }
166
968
 
167
- return { code: out, tokens };
168
- }
969
+ function emitStmt(st, scope, indentLevel, { inClass = false, pad } = {}) {
970
+ const preStmts = [];
971
+ const flushPre = () => {
972
+ for (const ps of preStmts) lines.push(`${pad}${ps}`);
973
+ preStmts.length = 0;
974
+ };
169
975
 
170
- function restoreTokens(str, tokens) {
171
- return str.replace(/__MHS_PY_STR_(\d+)__/g, (_, idx) => tokens[Number(idx)]);
172
- }
976
+ switch (st.kind) {
977
+ case 'ImportStmt': {
978
+ const mod = cleanModuleName(st.target);
979
+ scope.declare(st.alias, false, true);
980
+ lines.push(`${pad}import ${mod}${st.alias !== mod ? ` as ${st.alias}` : ''}`);
981
+ break;
982
+ }
173
983
 
174
- function cleanModuleName(modToken, tokens) {
175
- return modToken.replace(/__MHS_PY_STR_(\d+)__/g, (_, idx) => {
176
- return tokens[Number(idx)]
177
- .slice(1, -1)
178
- .replace(/^\.\//, '')
179
- .replace(/\.(mhs|py)$/i, '')
180
- .replace(/\//g, '.');
181
- });
182
- }
984
+ case 'FromImportStmt': {
985
+ const mod = cleanModuleName(st.target);
986
+ const itemsStr = st.items.map((it) => {
987
+ scope.declare(it.alias, false, true);
988
+ return it.name === it.alias ? it.name : `${it.name} as ${it.alias}`;
989
+ }).join(', ');
990
+ lines.push(`${pad}from ${mod} import ${itemsStr}`);
991
+ break;
992
+ }
183
993
 
184
- function transformPyExpr(expr) {
185
- let res = expr;
186
- res = res.replace(/(?<!\.)\b(Benar|benar)\b(?!\s*\()/g, 'True');
187
- res = res.replace(/(?<!\.)\b(Salah|salah)\b(?!\s*\()/g, 'False');
188
- res = res.replace(/(?<!\.)\b(Kosong|kosong)\b(?!\s*\()/g, 'None');
189
- res = res.replace(/\bdiri\b/g, 'self');
190
- res = res.replace(/\bbukan_adalah\b/g, 'is not');
191
- res = res.replace(/\badalah\b/g, 'is');
192
- res = res.replace(/\bbukan_dalam\b/g, 'not in');
193
- res = res.replace(/\bdan\b/g, 'and');
194
- res = res.replace(/\batau\b/g, 'or');
195
- res = res.replace(/\bbukan\b/g, 'not');
196
- res = res.replace(/\bdalam\b/g, 'in');
197
- res = res.replace(/\buntuk\b/g, 'for');
198
- res = res.replace(/\bjika\b/g, 'if');
199
- res = res.replace(/\bselain_itu\b/g, 'else');
200
- res = res.replace(/\banonim\b/g, 'lambda');
201
- res = res.replace(/\btunggu_eksekusi\b/g, 'await');
202
- return res;
203
- }
994
+ case 'VarDecl': {
995
+ const valPy = st.value ? emitExpr(st.value, scope, preStmts) : 'None';
996
+ flushPre();
997
+ const isRef = st.value?.kind === 'Borrow' || st.type?.kind === 'Pinjam' || st.type?.kind === 'PinjamUbah';
998
+ if (st.names.length === 1) {
999
+ const n = st.names[0].name;
1000
+ const pyName = scope.declare(n, isRef);
1001
+ const rhs = st.qualifier === 'konst' ? `bekukan(${valPy})` : valPy;
1002
+ lines.push(`${pad}${pyName} = ${rhs}`);
1003
+ if (dropSlotMap.has(n)) {
1004
+ lines.push(`${pad}${dropSlotMap.get(n)} = ${pyName}`);
1005
+ }
1006
+ } else {
1007
+ const pyNames = st.names.map((n) => scope.declare(n.name, isRef));
1008
+ lines.push(`${pad}${pyNames.join(', ')} = ${valPy}`);
1009
+ }
1010
+ break;
1011
+ }
1012
+
1013
+ case 'FieldDecl':
1014
+ lines.push(`${pad}${st.name}: ${pyTypeStr(st.type)}`);
1015
+ break;
1016
+
1017
+ case 'AssignStmt': {
1018
+ if (st.target?.kind === 'DerefOrSpread') {
1019
+ const rPy = emitExpr(st.target.target, scope, preStmts);
1020
+ const vPy = emitExpr(st.value, scope, preStmts);
1021
+ flushPre();
1022
+ if (st.op === '=') {
1023
+ lines.push(`${pad}_mhs_set_deref(${rPy}, ${vPy})`);
1024
+ } else {
1025
+ const rawOp = st.op.slice(0, -1);
1026
+ lines.push(`${pad}_mhs_set_deref(${rPy}, _mhs_deref(${rPy}) ${rawOp} ${vPy})`);
1027
+ }
1028
+ break;
1029
+ }
1030
+ if (st.target?.kind === 'Index') {
1031
+ const objPy = emitExpr(st.target.object, scope, preStmts);
1032
+ const idxPy = emitExpr(st.target.index, scope, preStmts);
1033
+ const vPy = emitExpr(st.value, scope, preStmts);
1034
+ flushPre();
1035
+ if (st.op === '=') {
1036
+ lines.push(`${pad}_mhs_atur_indeks(${objPy}, ${idxPy}, ${vPy})`);
1037
+ } else {
1038
+ const rawOp = st.op.slice(0, -1);
1039
+ lines.push(`${pad}_mhs_atur_indeks(${objPy}, ${idxPy}, _mhs_indeks(${objPy}, ${idxPy}) ${rawOp} ${vPy})`);
1040
+ }
1041
+ break;
1042
+ }
1043
+ if (st.target?.kind === 'Member') {
1044
+ const lhs = emitExpr(st.target, scope, preStmts);
1045
+ const rhs = emitExpr(st.value, scope, preStmts);
1046
+ flushPre();
1047
+ lines.push(`${pad}${lhs} ${st.op} ${rhs}`);
1048
+ break;
1049
+ }
1050
+ if (st.target?.kind === 'Ident') {
1051
+ const name = st.target.name;
1052
+ const isRef = st.value?.kind === 'Borrow' || st.type?.kind === 'Pinjam' || st.type?.kind === 'PinjamUbah';
1053
+ const rhs = emitExpr(st.value, scope, preStmts);
1054
+ flushPre();
1055
+ let pyName;
1056
+ if (!scope.resolveInfo(name) && st.op === '=') {
1057
+ pyName = scope.declare(name, isRef, true);
1058
+ } else {
1059
+ pyName = scope.resolve(name);
1060
+ }
1061
+ lines.push(`${pad}${pyName} ${st.op} ${rhs}`);
1062
+ if (dropSlotMap.has(name)) {
1063
+ lines.push(`${pad}${dropSlotMap.get(name)} = ${pyName}`);
1064
+ }
1065
+ break;
1066
+ }
1067
+ if (st.target?.kind === 'Tuple') {
1068
+ const rhs = emitExpr(st.value, scope, preStmts);
1069
+ flushPre();
1070
+ const lhs = st.target.items.map((it) => {
1071
+ if (!scope.resolveInfo(it.name)) return scope.declare(it.name, false, true);
1072
+ return scope.resolve(it.name);
1073
+ }).join(', ');
1074
+ lines.push(`${pad}${lhs} = ${rhs}`);
1075
+ break;
1076
+ }
1077
+ break;
1078
+ }
204
1079
 
205
- function transformPyLine(rawLine) {
206
- const indentMatch = rawLine.match(/^(\s*)/);
207
- const indent = indentMatch ? indentMatch[1] : '';
208
- const { code, tokens } = protectStringsAndComments(rawLine.slice(indent.length));
209
- const trimmed = code.trim();
1080
+ case 'ExprStmt':
1081
+ if (st.expr) {
1082
+ const exprPy = emitExpr(st.expr, scope, preStmts);
1083
+ flushPre();
1084
+ lines.push(`${pad}${exprPy}`);
1085
+ }
1086
+ break;
210
1087
 
211
- if (!trimmed) {
212
- return indent + restoreTokens(code, tokens);
1088
+ case 'ReturnStmt': {
1089
+ const valPy = st.expr ? emitExpr(st.expr, scope, preStmts) : '';
1090
+ flushPre();
1091
+ lines.push(st.expr ? `${pad}return ${valPy}` : `${pad}return`);
1092
+ break;
1093
+ }
1094
+
1095
+ case 'YieldStmt': {
1096
+ const valPy = st.expr ? emitExpr(st.expr, scope, preStmts) : '';
1097
+ flushPre();
1098
+ lines.push(st.expr ? `${pad}yield ${valPy}` : `${pad}yield`);
1099
+ break;
1100
+ }
1101
+
1102
+ case 'BreakStmt':
1103
+ lines.push(`${pad}break`);
1104
+ break;
1105
+
1106
+ case 'ContinueStmt':
1107
+ lines.push(`${pad}continue`);
1108
+ break;
1109
+
1110
+ case 'PassStmt':
1111
+ lines.push(`${pad}pass`);
1112
+ break;
1113
+
1114
+ case 'RaiseStmt': {
1115
+ const msgPy = emitExpr(st.expr, scope, preStmts);
1116
+ flushPre();
1117
+ lines.push(`${pad}raise Exception(${msgPy})`);
1118
+ break;
1119
+ }
1120
+
1121
+ case 'AssertStmt': {
1122
+ const cPy = emitExpr(st.cond, scope, preStmts);
1123
+ const mPy = st.msg ? `, ${emitExpr(st.msg, scope, preStmts)}` : '';
1124
+ flushPre();
1125
+ lines.push(`${pad}assert ${cPy}${mPy}`);
1126
+ break;
1127
+ }
1128
+
1129
+ case 'GlobalStmt':
1130
+ lines.push(`${pad}global ${st.names.join(', ')}`);
1131
+ break;
1132
+
1133
+ case 'IfStmt': {
1134
+ st.branches.forEach((br, idx) => {
1135
+ if (br.isIfLet) {
1136
+ const tmp = nextTmp('_jc');
1137
+ const ePy = emitExpr(br.expr, scope, preStmts);
1138
+ flushPre();
1139
+ lines.push(`${pad}${tmp} = ${ePy}`);
1140
+ const { cond, binds } = emitPatternCheckPy(br.pattern, tmp, scope, preStmts);
1141
+ const brScope = new PyScope(scope, false);
1142
+ lines.push(`${pad}${idx === 0 ? 'if' : 'elif'} ${cond}:`);
1143
+ for (const b of binds) {
1144
+ const pyN = brScope.declare(b.name, false, true);
1145
+ lines.push(`${pad} ${pyN} = ${b.expr}`);
1146
+ }
1147
+ emitBlock(br.body, brScope, indentLevel + 1, { blockKey: `if_${br.line}` });
1148
+ } else if (br.isElse) {
1149
+ lines.push(`${pad}else:`);
1150
+ emitBlock(br.body, new PyScope(scope, false), indentLevel + 1, { blockKey: `if_${br.line}` });
1151
+ } else {
1152
+ const cPy = emitExpr(br.cond, scope, preStmts);
1153
+ flushPre();
1154
+ lines.push(`${pad}${idx === 0 ? 'if' : 'elif'} ${cPy}:`);
1155
+ emitBlock(br.body, new PyScope(scope, false), indentLevel + 1, { blockKey: `if_${br.line}` });
1156
+ }
1157
+ });
1158
+ break;
1159
+ }
1160
+
1161
+ case 'WhileStmt': {
1162
+ const cPy = emitExpr(st.cond, scope, preStmts);
1163
+ flushPre();
1164
+ lines.push(`${pad}while ${cPy}:`);
1165
+ emitBlock(st.body, new PyScope(scope, false), indentLevel + 1, { blockKey: `while_${st.line}` });
1166
+ break;
1167
+ }
1168
+
1169
+ case 'ForStmt': {
1170
+ const iterPy = emitExpr(st.iter, scope, preStmts);
1171
+ flushPre();
1172
+ const loopScope = new PyScope(scope, false);
1173
+ const tgts = st.targets.map((t) => loopScope.declare(t.name, false, true)).join(', ');
1174
+ lines.push(`${pad}for ${tgts} in ${iterPy}:`);
1175
+ emitBlock(st.body, loopScope, indentLevel + 1, { blockKey: `for_${st.line}` });
1176
+ break;
1177
+ }
1178
+
1179
+ case 'MatchStmt': {
1180
+ const targetTmp = nextTmp('_cocok');
1181
+ const matchedFlag = nextTmp('_cocok_ok');
1182
+ const tPy = emitExpr(st.target, scope, preStmts);
1183
+ flushPre();
1184
+ lines.push(`${pad}${targetTmp} = ${tPy}`);
1185
+ lines.push(`${pad}${matchedFlag} = False`);
1186
+ for (const arm of st.arms) {
1187
+ const { cond, binds } = emitPatternCheckPy(arm.pattern, targetTmp, scope, preStmts);
1188
+ lines.push(`${pad}if not ${matchedFlag} and (${cond}):`);
1189
+ const armScope = new PyScope(scope, false);
1190
+ for (const b of binds) {
1191
+ const pyN = armScope.declare(b.name, false, true);
1192
+ lines.push(`${pad} ${pyN} = ${b.expr}`);
1193
+ }
1194
+ if (arm.guard) {
1195
+ const gPre = [];
1196
+ const gPy = emitExpr(arm.guard, armScope, gPre);
1197
+ for (const gp of gPre) lines.push(`${pad} ${gp}`);
1198
+ lines.push(`${pad} if ${gPy}:`);
1199
+ lines.push(`${pad} ${matchedFlag} = True`);
1200
+ emitBlock(arm.body, armScope, indentLevel + 2, { blockKey: `match_${arm.line}` });
1201
+ } else {
1202
+ lines.push(`${pad} ${matchedFlag} = True`);
1203
+ emitBlock(arm.body, armScope, indentLevel + 1, { blockKey: `match_${arm.line}` });
1204
+ }
1205
+ }
1206
+ break;
1207
+ }
1208
+
1209
+ case 'UnsafeBlock':
1210
+ lines.push(`${pad}if True: # tidak_aman`);
1211
+ emitBlock(st.body, new PyScope(scope, false), indentLevel + 1, { blockKey: `unsafe_${st.line}` });
1212
+ break;
1213
+
1214
+ case 'TryStmt':
1215
+ lines.push(`${pad}try:`);
1216
+ emitBlock(st.tryBody, new PyScope(scope, false), indentLevel + 1, { blockKey: `try_${st.line}` });
1217
+ if (st.catches.length > 0) {
1218
+ lines.push(`${pad}except _MhsPropagasi:`);
1219
+ lines.push(`${pad} raise`);
1220
+ for (const c of st.catches) {
1221
+ const cScope = new PyScope(scope, false);
1222
+ const ev = c.errVar ? cScope.declare(c.errVar, false, true) : null;
1223
+ lines.push(`${pad}except Exception${ev ? ` as ${ev}` : ''}:`);
1224
+ emitBlock(c.body, cScope, indentLevel + 1, { blockKey: `catch_${c.line}` });
1225
+ }
1226
+ }
1227
+ if (st.finallyBody) {
1228
+ lines.push(`${pad}finally:`);
1229
+ emitBlock(st.finallyBody, new PyScope(scope, false), indentLevel + 1, { blockKey: `finally_${st.line}` });
1230
+ }
1231
+ break;
1232
+
1233
+ case 'WithStmt': {
1234
+ const cPy = emitExpr(st.ctxExpr, scope, preStmts);
1235
+ flushPre();
1236
+ const wScope = new PyScope(scope, false);
1237
+ const asPart = st.asVar ? ` as ${wScope.declare(st.asVar, false, true)}` : '';
1238
+ lines.push(`${pad}with ${cPy}${asPart}:`);
1239
+ emitBlock(st.body, wScope, indentLevel + 1, { blockKey: `with_${st.line}` });
1240
+ break;
1241
+ }
1242
+
1243
+ case 'FunctionDecl': {
1244
+ for (const dec of st.decorators || []) {
1245
+ const decTxt = dec.tokens.map((t) => (t.type === 'STRING' ? `${t.quote}${t.value}${t.quote}` : t.value)).join('');
1246
+ lines.push(`${pad}@${decTxt}`);
1247
+ }
1248
+ const fnScope = new PyScope(scope, false);
1249
+ const pyFnName = inClass ? st.name : scope.declare(st.name, false, true);
1250
+ const pyParams = st.params.map((p, idx) => {
1251
+ if (idx === 0 && inClass && (p.name === 'diri' || p.name === 'self')) {
1252
+ fnScope.declare('diri', false, true);
1253
+ return 'self';
1254
+ }
1255
+ const isRef = p.isBorrow || p.type?.kind === 'Pinjam' || p.type?.kind === 'PinjamUbah';
1256
+ const pName = fnScope.declare(p.name, isRef, true);
1257
+ let prefix = p.isDoubleStar ? '**' : p.isStar ? '*' : '';
1258
+ let ann = p.type ? `: ${pyTypeStr(p.type)}` : '';
1259
+ let defVal = p.defaultExpr ? ` = ${emitExpr(p.defaultExpr, scope, preStmts)}` : '';
1260
+ return `${prefix}${pName}${ann}${defVal}`;
1261
+ }).join(', ');
1262
+ flushPre();
1263
+ const asyncKw = st.isAsync ? 'async ' : '';
1264
+ const retAnn = st.returnType ? ` -> ${pyTypeStr(st.returnType)}` : '';
1265
+ lines.push(`${pad}${asyncKw}def ${pyFnName}(${pyParams})${retAnn}:`);
1266
+
1267
+ const fnKey = `${st.line}:${st.name}`;
1268
+ if (usesTanyaInFn.has(fnKey)) {
1269
+ lines.push(`${pad} try:`);
1270
+ emitBlock(st.body, fnScope, indentLevel + 2, { blockKey: `fn_${st.line}_${st.name}` });
1271
+ lines.push(`${pad} except _MhsPropagasi as _mhs_p:`);
1272
+ lines.push(`${pad} return _mhs_p.nilai`);
1273
+ } else {
1274
+ emitBlock(st.body, fnScope, indentLevel + 1, { blockKey: `fn_${st.line}_${st.name}` });
1275
+ }
1276
+ break;
1277
+ }
1278
+
1279
+ case 'StructDecl':
1280
+ case 'ClassDecl': {
1281
+ for (const dec of st.decorators || []) {
1282
+ const decTxt = dec.tokens.map((t) => (t.type === 'STRING' ? `${t.quote}${t.value}${t.quote}` : t.value)).join('');
1283
+ lines.push(`${pad}@${decTxt}`);
1284
+ }
1285
+ if (st.kind === 'StructDecl' && (!st.decorators || st.decorators.length === 0)) {
1286
+ lines.push(`${pad}from dataclasses import dataclass as _mhs_dataclass`);
1287
+ lines.push(`${pad}@_mhs_dataclass`);
1288
+ }
1289
+ scope.declare(st.name, false, true);
1290
+ const base = st.baseClass ? `(${st.baseClass})` : '';
1291
+ lines.push(`${pad}class ${st.name}${base}:`);
1292
+ if (st.body.length === 0) {
1293
+ lines.push(`${pad} pass`);
1294
+ } else {
1295
+ const cScope = new PyScope(scope, false);
1296
+ for (const item of st.body) {
1297
+ emitStmt(item, cScope, indentLevel + 1, { inClass: true, pad: `${pad} ` });
1298
+ }
1299
+ }
1300
+ break;
1301
+ }
1302
+
1303
+ case 'EnumDecl': {
1304
+ scope.declare(st.name, false, true);
1305
+ lines.push(`${pad}class ${st.name}:`);
1306
+ if (st.variants.length === 0) {
1307
+ lines.push(`${pad} pass`);
1308
+ } else {
1309
+ for (const v of st.variants) {
1310
+ if (v.fields.length === 0) {
1311
+ lines.push(`${pad} ${v.name} = _mhs_enum_varian(${JSON.stringify(st.name)}, ${JSON.stringify(v.name)})`);
1312
+ } else {
1313
+ const ps = v.fields.map((f) => f.name).join(', ');
1314
+ lines.push(`${pad} @staticmethod`);
1315
+ lines.push(`${pad} def ${v.name}(${ps}):`);
1316
+ lines.push(`${pad} return _mhs_enum_varian(${JSON.stringify(st.name)}, ${JSON.stringify(v.name)}, ${ps})`);
1317
+ }
1318
+ }
1319
+ }
1320
+ for (const v of st.variants) {
1321
+ scope.declare(v.name, false, true);
1322
+ lines.push(`${pad}${v.name} = ${st.name}.${v.name}`);
1323
+ }
1324
+ break;
1325
+ }
1326
+
1327
+ case 'ImplDecl': {
1328
+ for (const item of st.body) {
1329
+ if (item.kind === 'FunctionDecl') {
1330
+ const origName = item.name;
1331
+ const tempName = `_mhs_impl_${st.targetName}_${origName}`;
1332
+ const patched = { ...item, name: tempName };
1333
+ emitStmt(patched, scope, indentLevel, { inClass: true, pad });
1334
+ lines.push(`${pad}${st.targetName}.${origName} = ${tempName}`);
1335
+ }
1336
+ }
1337
+ break;
1338
+ }
1339
+ }
213
1340
  }
214
1341
 
215
- let res = code;
216
-
217
- // impor_py "mod" sebagai alias | impor "./file.py" sebagai alias | impor mod
218
- res = res.replace(/^(\s*)(?:impor_py|impor)\s+([^\s]+)(.*)$/, (_, sp, mod, rest) => {
219
- const cleanMod = cleanModuleName(mod, tokens);
220
- const cleanRest = rest.replace(/\bsebagai\b/g, 'as');
221
- return `${sp}import ${cleanMod}${cleanRest}`;
222
- });
223
-
224
- // dari ... impor ...
225
- res = res.replace(/^(\s*)(?:dari_py|dari)\s+([^\s]+)\s+impor\s+(.+)$/, (_, sp, mod, items) => {
226
- const cleanMod = cleanModuleName(mod, tokens);
227
- const cleanItems = items.replace(/\bsebagai\b/g, 'as');
228
- return `${sp}from ${cleanMod} import ${cleanItems}`;
229
- });
230
-
231
- // Kata kunci blok & pernyataan Python dalam Bahasa Indonesia
232
- res = res.replace(/^fungsi\s+/, 'def ');
233
- res = res.replace(/^asinkron\s+fungsi\s+/, 'async def ');
234
- res = res.replace(/^kelas\s+/, 'class ');
235
- res = res.replace(/^atau_jika\b/, 'elif');
236
- res = res.replace(/^jika_tidak\b/, 'elif');
237
- res = res.replace(/^jika\b/, 'if');
238
- res = res.replace(/^(?:selain_itu|lainnya)\b/, 'else');
239
- res = res.replace(/^selama\b/, 'while');
240
- res = res.replace(/^untuk\b/, 'for');
241
- res = res.replace(/^coba\b/, 'try');
242
- res = res.replace(/^(?:tangkap|kecuali)(?:\s+([A-Za-z_]\w*))?\s*:/, (_, v) => (v ? `except Exception as ${v}:` : 'except Exception:'));
243
- res = res.replace(/^akhirnya\b/, 'finally');
244
- res = res.replace(/^dengan\b/, 'with');
245
- res = res.replace(/^kembalikan\b/, 'return');
246
- res = res.replace(/^hasilkan\b/, 'yield');
247
- res = res.replace(/^berhenti\b/, 'break');
248
- res = res.replace(/^lanjut\b/, 'continue');
249
- res = res.replace(/^lewat\b/, 'pass');
250
- res = res.replace(/^lempar\s+(.+)$/, (_, msg) => `raise Exception(${transformPyExpr(msg)})`);
251
- res = res.replace(/^pastikan\b/, 'assert');
252
- res = res.replace(/^umum\b/, 'global');
253
- res = res.replace(/^bukan_lokal\b/, 'nonlocal');
254
- res = res.replace(/^hapus_var\b/, 'del');
255
- res = res.replace(/^@properti\b/, '@property');
256
- res = res.replace(/^@metode_statis\b/, '@staticmethod');
257
- res = res.replace(/^@metode_kelas\b/, '@classmethod');
258
-
259
- res = res.replace(/\bsebagai\b/g, 'as');
260
- res = transformPyExpr(res);
261
-
262
- return indent + restoreTokens(res, tokens);
263
- }
1342
+ emitBlock(program.body, rootScope, 0, { blockKey: 'root' });
264
1343
 
265
- function transpileToPython(source, { includePrelude = true } = {}) {
266
- const cleanSource = source.replace(/\uFEFF/g, '');
267
- const lines = cleanSource.replace(/\r\n/g, '\n').split('\n');
268
- const body = lines.map(transformPyLine).join('\n');
1344
+ const body = lines.join('\n');
1345
+ const sandboxInit = sandbox ? '\n_mhs_aktifkan_kotak_pasir()\n' : '\n';
269
1346
  if (!includePrelude) return body;
270
- return `${PY_PRELUDE}\n\n${body}\n`;
1347
+ return `${PY_PRELUDE}\n${sandboxInit}${body}\n`;
271
1348
  }
272
1349
 
273
1350
  module.exports = { transpileToPython, PY_PRELUDE };