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
package/src/transpiler.js CHANGED
@@ -1,402 +1,878 @@
1
1
  /**
2
- * Transpiler Bahasa .mhs (Python dalam Bahasa Indonesia) -> JavaScript
2
+ * Transpiler Bahasa .mhs (Rust-Safe Indonesian Pythonic) -> JavaScript
3
3
  */
4
4
 
5
- const BUILTIN_NAMES = new Set([
6
- 'cetak', 'masukan', 'rentang', 'panjang', 'tipe', 'teks', 'angka',
7
- 'bulat', 'desimal', 'tambah', 'hapus', 'urutkan', 'balik', 'gabung',
8
- 'pisah', 'huruf_besar', 'huruf_kecil', 'potong', 'ganti', 'mengandung',
9
- 'acak', 'akar', 'pangkat', 'mutlak', 'bulatkan', 'bawah', 'atas',
10
- 'min_nilai', 'maks_nilai', 'jumlah', 'waktu_sekarang', 'tunggu',
11
- 'kunci', 'nilai', '__mhs_impor', '__mhs_impor_py', '__mhs_exports__',
12
- 'console', 'Math', 'JSON', 'Date', 'Array', 'Object',
13
- 'String', 'Number', 'Boolean', 'Error'
14
- ]);
15
-
16
- function stripCommentAndProtectStrings(line) {
17
- const strings = [];
18
- let out = '';
19
- let i = 0;
20
-
21
- while (i < line.length) {
22
- const ch = line[i];
23
-
24
- // f-string: f"..." atau f'...'
25
- if ((ch === 'f' || ch === 'F') && (line[i + 1] === '"' || line[i + 1] === "'")) {
26
- const quote = line[i + 1];
27
- let j = i + 2;
28
- let content = '';
29
- while (j < line.length) {
30
- if (line[j] === '\\' && j + 1 < line.length) {
31
- content += line[j] + line[j + 1];
32
- j += 2;
33
- continue;
34
- }
35
- if (line[j] === quote) {
36
- j++;
37
- break;
38
- }
39
- if (line[j] === '`') {
40
- content += '\\`';
41
- } else if (line[j] === '$' && line[j + 1] === '{') {
42
- content += '\\${';
43
- j += 2;
44
- continue;
45
- } else {
46
- content += line[j];
47
- }
48
- j++;
5
+ const { tokenize } = require('./lexer');
6
+ const { parseExpression } = require('./parser');
7
+ const { assertSafe } = require('./safety_analyzer');
8
+
9
+ function transpile(source, options = {}) {
10
+ const analysis = assertSafe(source, options);
11
+ const { program, metadata } = analysis;
12
+ const { usesTanyaInFn, enums, structs, variantToEnum } = metadata;
13
+
14
+ let tmpCounter = 0;
15
+ function nextTmp(prefix = '_mhs_tmp') {
16
+ return `${prefix}_${tmpCounter++}`;
17
+ }
18
+
19
+ // Pelacakan cakupan & shadowing agar `tetap x = x + 1` aman di JS
20
+ class EmitScope {
21
+ constructor(parent = null) {
22
+ this.parent = parent;
23
+ this.vars = new Map(); // origName -> jsName
24
+ this.shadowCounts = new Map();
25
+ }
26
+ resolve(name) {
27
+ if (this.vars.has(name)) return this.vars.get(name);
28
+ return this.parent ? this.parent.resolve(name) : name;
29
+ }
30
+ declare(name) {
31
+ if (this.vars.has(name)) {
32
+ const count = (this.shadowCounts.get(name) || 0) + 1;
33
+ this.shadowCounts.set(name, count);
34
+ const shadowed = `${name}__s${count}`;
35
+ this.vars.set(name, shadowed);
36
+ return shadowed;
37
+ }
38
+ this.vars.set(name, name);
39
+ return name;
40
+ }
41
+ }
42
+
43
+ const rootScope = new EmitScope(null);
44
+ const topLevelExports = new Map(); // exportedName -> jsVarName
45
+ const lines = [];
46
+ const dropSlotMap = new Map(); // origName -> slotVar
47
+
48
+ function escapeToJsString(rawInner) {
49
+ let out = '';
50
+ for (let i = 0; i < rawInner.length; i++) {
51
+ const ch = rawInner[i];
52
+ if (ch === '\\' && i + 1 < rawInner.length) {
53
+ out += ch + rawInner[i + 1];
54
+ i++;
55
+ } else if (ch === '"') {
56
+ out += '\\"';
57
+ } else if (ch === '\n') {
58
+ out += '\\n';
59
+ } else if (ch === '\r') {
60
+ out += '\\r';
61
+ } else {
62
+ out += ch;
49
63
  }
50
- const jsTemplate = '`' + content.replace(/\{([^}]+)\}/g, (_, expr) => '${' + transformExpression(expr) + '}') + '`';
51
- const token = `__MHS_STR_${strings.length}__`;
52
- strings.push(jsTemplate);
53
- out += token;
54
- i = j;
55
- continue;
56
64
  }
65
+ return `"${out}"`;
66
+ }
67
+
68
+ function isDroppableVar(name) {
69
+ for (const s of metadata.droppableVars.values()) {
70
+ if (s.has(name)) return true;
71
+ }
72
+ return false;
73
+ }
57
74
 
58
- // String biasa "..." atau '...'
59
- if (ch === '"' || ch === "'") {
60
- const quote = ch;
61
- let j = i + 1;
62
- let raw = quote;
63
- while (j < line.length) {
64
- if (line[j] === '\\' && j + 1 < line.length) {
65
- raw += line[j] + line[j + 1];
66
- j += 2;
75
+ function emitFStringJs(inner, scope) {
76
+ let out = '`';
77
+ let i = 0;
78
+ while (i < inner.length) {
79
+ if (inner[i] === '\\' && i + 1 < inner.length) {
80
+ out += inner[i] + inner[i + 1];
81
+ i += 2;
82
+ continue;
83
+ }
84
+ if (inner[i] === '`') {
85
+ out += '\\`';
86
+ i++;
87
+ continue;
88
+ }
89
+ if (inner[i] === '$' && inner[i + 1] === '{') {
90
+ out += '\\${';
91
+ i += 2;
92
+ continue;
93
+ }
94
+ if (inner[i] === '{') {
95
+ if (inner[i + 1] === '{') {
96
+ out += '{';
97
+ i += 2;
67
98
  continue;
68
99
  }
69
- raw += line[j];
70
- if (line[j] === quote) {
100
+ let depth = 1;
101
+ let j = i + 1;
102
+ let inStr = null;
103
+ while (j < inner.length && depth > 0) {
104
+ const ch = inner[j];
105
+ if (inStr) {
106
+ if (ch === '\\') { j += 2; continue; }
107
+ if (ch === inStr) inStr = null;
108
+ } else if (ch === '"' || ch === "'") {
109
+ inStr = ch;
110
+ } else if (ch === '{') depth++;
111
+ else if (ch === '}') { depth--; if (depth === 0) break; }
71
112
  j++;
72
- break;
73
113
  }
74
- j++;
114
+ const raw = inner.slice(i + 1, j);
115
+ let splitColon = -1;
116
+ let pDepth = 0;
117
+ let qStr = null;
118
+ for (let k = 0; k < raw.length; k++) {
119
+ const c = raw[k];
120
+ if (qStr) {
121
+ if (c === '\\') { k++; continue; }
122
+ if (c === qStr) qStr = null;
123
+ } else if (c === '"' || c === "'") qStr = c;
124
+ else if (c === '(' || c === '[' || c === '{') pDepth++;
125
+ else if (c === ')' || c === ']' || c === '}') pDepth--;
126
+ else if (c === ':' && pDepth === 0) { splitColon = k; break; }
127
+ }
128
+ const exprText = splitColon === -1 ? raw.trim() : raw.slice(0, splitColon).trim();
129
+ const spec = splitColon === -1 ? '' : raw.slice(splitColon + 1).trim();
130
+ const toks = tokenize(exprText).tokens.filter((t) => !['LINE_START', 'NEWLINE', 'EOF'].includes(t.type));
131
+ const exprAst = parseExpression(toks);
132
+ let jsExpr = emitExpr(exprAst, scope);
133
+ if (spec) {
134
+ const m = spec.match(/^\.(\d+)f$/);
135
+ if (m) {
136
+ jsExpr = `Number(${jsExpr}).toFixed(${m[1]})`;
137
+ }
138
+ }
139
+ out += `\${formatRuntimeVal(${jsExpr})}`;
140
+ i = j + 1;
141
+ continue;
75
142
  }
76
- const token = `__MHS_STR_${strings.length}__`;
77
- strings.push(raw);
78
- out += token;
79
- i = j;
80
- continue;
143
+ if (inner[i] === '}' && inner[i + 1] === '}') {
144
+ out += '}';
145
+ i += 2;
146
+ continue;
147
+ }
148
+ out += inner[i];
149
+ i++;
81
150
  }
151
+ return out + '`';
152
+ }
82
153
 
83
- if (ch === '#') {
84
- break;
154
+ function emitComp(expr, scope, isDict = false) {
155
+ const compScope = new EmitScope(scope);
156
+ const clauses = expr.clauses || [];
157
+ if (clauses.length === 0) return '[]';
158
+
159
+ function buildLoop(idx) {
160
+ const cl = clauses[idx];
161
+ const iterJs = emitExpr(cl.iter, idx === 0 ? scope : compScope);
162
+ const tgt = cl.targets.length === 1
163
+ ? compScope.declare(cl.targets[0])
164
+ : `[${cl.targets.map((t) => compScope.declare(t)).join(', ')}]`;
165
+ const condJs = cl.cond ? emitExpr(cl.cond, compScope) : null;
166
+
167
+ if (idx === clauses.length - 1) {
168
+ if (isDict) {
169
+ const kJs = emitExpr(expr.key, compScope);
170
+ const vJs = emitExpr(expr.value, compScope);
171
+ const pushStmt = `_res[${kJs}] = ${vJs};`;
172
+ return `for (const ${tgt} of __mhs_unwrap_ref(${iterJs})) { ${condJs ? `if (${condJs}) { ${pushStmt} }` : pushStmt} }`;
173
+ }
174
+ const bJs = emitExpr(expr.body, compScope);
175
+ const pushStmt = `_res.push(${bJs});`;
176
+ return `for (const ${tgt} of __mhs_unwrap_ref(${iterJs})) { ${condJs ? `if (${condJs}) { ${pushStmt} }` : pushStmt} }`;
177
+ }
178
+ const inner = buildLoop(idx + 1);
179
+ return `for (const ${tgt} of __mhs_unwrap_ref(${iterJs})) { ${condJs ? `if (${condJs}) { ${inner} }` : inner} }`;
85
180
  }
86
181
 
87
- out += ch;
88
- i++;
182
+ const initVal = isDict ? '{}' : '[]';
183
+ return `(() => { const _res = ${initVal}; ${buildLoop(0)} return _res; })()`;
89
184
  }
90
185
 
91
- return { code: out.trimEnd(), strings };
92
- }
186
+ function emitExpr(expr, scope, { inCallArgs = false, classNew = false } = {}) {
187
+ if (!expr) return 'undefined';
93
188
 
94
- function restoreStrings(code, strings) {
95
- return code.replace(/__MHS_STR_(\d+)__/g, (_, idx) => strings[Number(idx)]);
96
- }
189
+ switch (expr.kind) {
190
+ case 'Literal':
191
+ if (expr.litType === 'teks' || expr.litType === 'bytes') {
192
+ return escapeToJsString(expr.value);
193
+ }
194
+ if (expr.litType === 'bool') return expr.value ? 'true' : 'false';
195
+ return String(expr.raw ?? expr.value);
97
196
 
98
- function unquoteToken(rawOrToken, strings) {
99
- const restored = restoreStrings(rawOrToken.trim(), strings);
100
- if (
101
- (restored.startsWith('"') && restored.endsWith('"')) ||
102
- (restored.startsWith("'") && restored.endsWith("'"))
103
- ) {
104
- return restored.slice(1, -1);
105
- }
106
- return restored;
107
- }
197
+ case 'NullLiteral':
198
+ return 'null';
199
+
200
+ case 'OptionNone':
201
+ return 'TidakAda';
108
202
 
109
- function transformExpression(expr) {
110
- let res = expr;
203
+ case 'FString':
204
+ return emitFStringJs(expr.value, scope);
111
205
 
112
- // List comprehension: [expr untuk var dalam iterable (jika cond)]
113
- res = res.replace(
114
- /\[\s*([^[\]]+?)\s+untuk\s+([A-Za-z_]\w*)\s+dalam\s+([^[\]]+?)(?:\s+jika\s+([^[\]]+?))?\s*\]/g,
115
- (_, body, v, iter, cond) => {
116
- const tIter = transformExpression(iter);
117
- const tBody = transformExpression(body);
118
- if (cond) {
119
- const tCond = transformExpression(cond);
120
- return `Array.from(${tIter}).filter((${v}) => ${tCond}).map((${v}) => ${tBody})`;
206
+ case 'Ident': {
207
+ if (expr.name === 'diri' || expr.name === 'self') return 'this';
208
+ if (expr.name === '__name__') return '"__main__"';
209
+ return scope.resolve(expr.name);
121
210
  }
122
- return `Array.from(${tIter}).map((${v}) => ${tBody})`;
123
- }
124
- );
125
211
 
126
- res = res.replace(/(?<!\.)\b(Benar|benar)\b(?!\s*\()/g, 'true');
127
- res = res.replace(/(?<!\.)\b(Salah|salah)\b(?!\s*\()/g, 'false');
128
- res = res.replace(/(?<!\.)\b(Kosong|kosong)\b(?!\s*\()/g, 'null');
129
- res = res.replace(/\bdiri\b/g, 'this');
212
+ case 'Borrow': {
213
+ if (expr.target?.kind === 'Ident') {
214
+ const jsVar = scope.resolve(expr.target.name);
215
+ if (expr.mutable) {
216
+ return `__mhs_pinjam_ubah(() => ${jsVar}, (_v) => { ${jsVar} = _v; })`;
217
+ }
218
+ return `__mhs_pinjam(() => ${jsVar})`;
219
+ }
220
+ const targetJs = emitExpr(expr.target, scope);
221
+ return `__mhs_pinjam(() => ${targetJs})`;
222
+ }
130
223
 
131
- res = res.replace(/\bbukan_adalah\b/g, '!==');
132
- res = res.replace(/\badalah\b/g, '===');
133
- res = res.replace(/\bdan\b/g, '&&');
134
- res = res.replace(/\batau\b/g, '||');
135
- res = res.replace(/\bbukan\b/g, '!');
224
+ case 'Move': {
225
+ if (expr.target?.kind === 'Ident') {
226
+ const slot = dropSlotMap.get(expr.target.name);
227
+ const jsVar = scope.resolve(expr.target.name);
228
+ if (slot) {
229
+ return `((_mv) => { ${slot} = null; return _mv; })(${jsVar})`;
230
+ }
231
+ return jsVar;
232
+ }
233
+ return emitExpr(expr.target, scope);
234
+ }
136
235
 
137
- res = res.replace(
138
- /([A-Za-z_]\w*(?:\.[A-Za-z_]\w*|\[[^\]]+\])*|__MHS_STR_\d+__|\d+(?:\.\d+)?)\s+dalam\s+([A-Za-z_]\w*(?:\.[A-Za-z_]\w*|\[[^\]]+\])*|\[[^\]]*\]|__MHS_STR_\d+__)/g,
139
- 'mengandung($2, $1)'
140
- );
236
+ case 'DerefOrSpread': {
237
+ if (inCallArgs && expr.target?.kind === 'Ident') {
238
+ // Cek apakah ini pinjaman atau iterable spread
239
+ const resolved = scope.resolve(expr.target.name);
240
+ return `...(Array.isArray(__mhs_unwrap_ref(${resolved})) ? __mhs_unwrap_ref(${resolved}) : [__mhs_deref(${resolved})])`;
241
+ }
242
+ return `__mhs_deref(${emitExpr(expr.target, scope)})`;
243
+ }
141
244
 
142
- res = res.replace(/([^=!<>])={2}([^=])/g, '$1===$2');
143
- res = res.replace(/!={1}([^=])/g, '!==$1');
245
+ case 'KwSpread':
246
+ return `...${emitExpr(expr.target, scope)}`;
144
247
 
145
- return res;
146
- }
248
+ case 'Await':
249
+ return `(await ${emitExpr(expr.target, scope)})`;
147
250
 
148
- function getIndent(line) {
149
- let count = 0;
150
- for (const ch of line) {
151
- if (ch === ' ') count += 1;
152
- else if (ch === '\t') count += 4;
153
- else break;
154
- }
155
- return count;
156
- }
251
+ case 'TryPropagate':
252
+ return `__mhs_tanya(${emitExpr(expr.expr, scope)})`;
157
253
 
158
- function transpile(source) {
159
- const cleanSource = source.replace(/\uFEFF/g, '');
160
- const rawLines = cleanSource.replace(/\r\n/g, '\n').split('\n');
161
- const indentStack = [0];
162
- const scopeStack = [new Set(BUILTIN_NAMES)];
163
- const blockTypeStack = ['root'];
164
- const topLevelExports = new Set();
165
- const outputLines = [];
166
-
167
- function currentScope() {
168
- return scopeStack[scopeStack.length - 1];
169
- }
254
+ case 'Unary': {
255
+ const op = expr.op === 'bukan' ? '!' : expr.op;
256
+ return `(${op}${emitExpr(expr.operand, scope)})`;
257
+ }
170
258
 
171
- function isTopLevel() {
172
- return scopeStack.length === 1;
173
- }
259
+ case 'Range':
260
+ return `__mhs_rentang(${emitExpr(expr.start, scope)}, ${emitExpr(expr.end, scope)}, ${expr.inclusive ? 'true' : 'false'})`;
261
+
262
+ case 'Binary': {
263
+ const l = emitExpr(expr.left, scope);
264
+ const r = emitExpr(expr.right, scope);
265
+ switch (expr.op) {
266
+ case 'dan': return `(${l} && ${r})`;
267
+ case 'atau': return `(${l} || ${r})`;
268
+ case '==':
269
+ case 'adalah': return `(${l} === ${r})`;
270
+ case '!=':
271
+ case 'bukan_adalah': return `(${l} !== ${r})`;
272
+ case 'dalam':
273
+ case 'in': return `mengandung(${r}, ${l})`;
274
+ case 'bukan_dalam': return `(!mengandung(${r}, ${l}))`;
275
+ case '/': return `__mhs_bagi(${l}, ${r})`;
276
+ case '//': return `__mhs_bagi_bulat(${l}, ${r})`;
277
+ case '%': return `__mhs_sisa(${l}, ${r})`;
278
+ case '**': return `Math.pow(${l}, ${r})`;
279
+ default: return `(${l} ${expr.op} ${r})`;
280
+ }
281
+ }
174
282
 
175
- function insideClass() {
176
- return blockTypeStack[blockTypeStack.length - 1] === 'class';
177
- }
283
+ case 'Ternary':
284
+ return `(${emitExpr(expr.cond, scope)} ? ${emitExpr(expr.consequent, scope)} : ${emitExpr(expr.alternate, scope)})`;
178
285
 
179
- function declareInCurrentScope(name) {
180
- currentScope().add(name);
181
- if (isTopLevel()) {
182
- topLevelExports.add(name);
183
- }
184
- }
286
+ case 'List':
287
+ return `[${expr.items.map((it) => emitExpr(it, scope)).join(', ')}]`;
185
288
 
186
- function isDeclared(name) {
187
- for (let i = scopeStack.length - 1; i >= 0; i--) {
188
- if (scopeStack[i].has(name)) return true;
189
- }
190
- return false;
191
- }
289
+ case 'Tuple':
290
+ return `Object.freeze([${expr.items.map((it) => emitExpr(it, scope)).join(', ')}])`;
192
291
 
193
- for (let lineIdx = 0; lineIdx < rawLines.length; lineIdx++) {
194
- const rawLine = rawLines[lineIdx];
195
- const lineNum = lineIdx + 1;
292
+ case 'Set':
293
+ return `Array.from(new Set([${expr.items.map((it) => emitExpr(it, scope)).join(', ')}]))`;
196
294
 
197
- const { code: stripped, strings } = stripCommentAndProtectStrings(rawLine);
198
- const trimmed = stripped.trim();
295
+ case 'Dict':
296
+ return `{ ${expr.entries.map((e) => `[${emitExpr(e.key, scope)}]: ${emitExpr(e.value, scope)}`).join(', ')} }`;
199
297
 
200
- if (!trimmed) {
201
- continue;
202
- }
298
+ case 'ListComp':
299
+ case 'GeneratorComp':
300
+ return emitComp(expr, scope, false);
203
301
 
204
- const indent = getIndent(rawLine);
302
+ case 'DictComp':
303
+ return emitComp(expr, scope, true);
205
304
 
206
- while (indent < indentStack[indentStack.length - 1]) {
207
- indentStack.pop();
208
- scopeStack.pop();
209
- blockTypeStack.pop();
210
- const pad = ' '.repeat(indentStack.length - 1);
211
- outputLines.push(`${pad}}`);
212
- }
305
+ case 'Lambda': {
306
+ const lScope = new EmitScope(scope);
307
+ const ps = expr.params.map((p) => lScope.declare(p)).join(', ');
308
+ return `((${ps}) => ${emitExpr(expr.body, lScope)})`;
309
+ }
213
310
 
214
- if (indent !== indentStack[indentStack.length - 1]) {
215
- throw new SyntaxError(`Kesalahan indentasi pada baris ${lineNum}: "${rawLine.trim()}"`);
216
- }
311
+ case 'Member': {
312
+ const objJs = emitExpr(expr.object, scope);
313
+ if (expr.property === 'strip') return `${objJs}.trim`;
314
+ if (expr.property === 'upper') return `${objJs}.toUpperCase`;
315
+ if (expr.property === 'lower') return `${objJs}.toLowerCase`;
316
+ return `${objJs}.${expr.property}`;
317
+ }
217
318
 
218
- const pad = ' '.repeat(indentStack.length - 1);
219
- let jsLine = '';
220
- let opensBlock = false;
221
- let nextBlockType = 'block';
222
- let newScopeVars = [];
223
-
224
- // 0a. impor / impor_py
225
- const imporMatch = trimmed.match(/^(impor_py|impor)\s+(__MHS_STR_\d+__|[A-Za-z_][\w./-]*)(?:\s+sebagai\s+([A-Za-z_]\w*))?$/);
226
- if (imporMatch) {
227
- const imporFn = imporMatch[1] === 'impor_py' ? '__mhs_impor_py' : '__mhs_impor';
228
- const targetStr = unquoteToken(imporMatch[2], strings);
229
- let alias = imporMatch[3];
230
- if (!alias) {
231
- const base = targetStr.replace(/\.(mhs|py)$/i, '').split(/[\\/]/).pop();
232
- alias = base.replace(/[^A-Za-z0-9_]/g, '_');
233
- }
234
- declareInCurrentScope(alias);
235
- jsLine = `const ${alias} = ${imporFn}(${JSON.stringify(targetStr)});`;
236
- }
237
- // 0b. dari / dari_py ... impor ...
238
- else if (/^(dari_py|dari)\s+(__MHS_STR_\d+__|[A-Za-z_][\w./-]*)\s+impor\s+(.+)$/.test(trimmed)) {
239
- const m = trimmed.match(/^(dari_py|dari)\s+(__MHS_STR_\d+__|[A-Za-z_][\w./-]*)\s+impor\s+(.+)$/);
240
- const imporFn = m[1] === 'dari_py' ? '__mhs_impor_py' : '__mhs_impor';
241
- const targetStr = unquoteToken(m[2], strings);
242
- const items = m[3].split(',').map((part) => {
243
- const seg = part.trim();
244
- const aliasMatch = seg.match(/^([A-Za-z_]\w*)\s+sebagai\s+([A-Za-z_]\w*)$/);
245
- if (aliasMatch) {
246
- declareInCurrentScope(aliasMatch[2]);
247
- return `${aliasMatch[1]}: ${aliasMatch[2]}`;
248
- }
249
- declareInCurrentScope(seg);
250
- return seg;
251
- });
252
- jsLine = `const { ${items.join(', ')} } = ${imporFn}(${JSON.stringify(targetStr)});`;
253
- }
254
- // 1. Fungsi / Method kelas
255
- else if (/^fungsi\s+([A-Za-z_]\w*)\s*\(([^)]*)\)\s*:$/.test(trimmed)) {
256
- const fnMatch = trimmed.match(/^fungsi\s+([A-Za-z_]\w*)\s*\(([^)]*)\)\s*:$/);
257
- const fnName = fnMatch[1];
258
- const paramsRaw = fnMatch[2].trim();
259
- let paramsList = paramsRaw ? paramsRaw.split(',').map((p) => p.trim()) : [];
260
-
261
- if (insideClass()) {
262
- // Hapus parameter `diri` / `self` untuk method JS
263
- if (paramsList[0] === 'diri' || paramsList[0] === 'self') {
264
- paramsList = paramsList.slice(1);
319
+ case 'Index':
320
+ return `__mhs_indeks(${emitExpr(expr.object, scope)}, ${emitExpr(expr.index, scope)})`;
321
+
322
+ case 'Slice':
323
+ return `__mhs_slice(${emitExpr(expr.object, scope)}, ${expr.start ? emitExpr(expr.start, scope) : 'null'}, ${expr.end ? emitExpr(expr.end, scope) : 'null'}, ${expr.step ? emitExpr(expr.step, scope) : 'null'})`;
324
+
325
+ case 'Call': {
326
+ // Handle `.ambil(i)` and `.ambil_opsi(k)` safely without prototype pollution
327
+ if (expr.callee?.kind === 'Member') {
328
+ if (expr.callee.property === 'ambil' && expr.args.length === 1) {
329
+ return `__mhs_ambil(${emitExpr(expr.callee.object, scope)}, ${emitExpr(expr.args[0], scope)})`;
330
+ }
331
+ if (expr.callee.property === 'ambil_opsi' && expr.args.length === 1) {
332
+ return `__mhs_ambil_opsi(${emitExpr(expr.callee.object, scope)}, ${emitExpr(expr.args[0], scope)})`;
333
+ }
334
+ if (expr.callee.property === 'isdigit' && expr.args.length === 0) {
335
+ return `/^\\d+$/.test(${emitExpr(expr.callee.object, scope)})`;
336
+ }
265
337
  }
266
- const jsMethodName = fnName === '__init__' || fnName === '__inisialisasi__' ? 'constructor' : fnName;
267
- newScopeVars = paramsList.map((p) => p.split('=')[0].trim());
268
- const jsParams = paramsList.map((p) => transformExpression(p)).join(', ');
269
- jsLine = `${jsMethodName}(${jsParams}) {`;
270
- } else {
271
- declareInCurrentScope(fnName);
272
- newScopeVars = paramsList.map((p) => p.split('=')[0].trim());
273
- const jsParams = paramsRaw ? transformExpression(paramsRaw) : '';
274
- jsLine = `function ${fnName}(${jsParams}) {`;
338
+
339
+ // Constructor struct/kelas
340
+ if (expr.callee?.kind === 'Ident' && structs.has(expr.callee.name)) {
341
+ const sName = expr.callee.name;
342
+ const sInfo = structs.get(sName);
343
+ const argsList = [];
344
+ for (const a of expr.args) argsList.push(emitExpr(a, scope));
345
+ if (expr.kwargs.length > 0) {
346
+ const fieldOrder = Array.from(sInfo.fields.keys());
347
+ if (fieldOrder.length > 0 && argsList.length === 0) {
348
+ for (const fName of fieldOrder) {
349
+ const kw = expr.kwargs.find((k) => k.kwargName === fName);
350
+ argsList.push(kw ? emitExpr(kw.value, scope) : 'undefined');
351
+ }
352
+ } else {
353
+ for (const kw of expr.kwargs) argsList.push(emitExpr(kw.value, scope));
354
+ }
355
+ }
356
+ return `new ${scope.resolve(sName)}(${argsList.join(', ')})`;
357
+ }
358
+
359
+ const calleeJs = emitExpr(expr.callee, scope);
360
+ const argParts = expr.args.map((a) => {
361
+ if (a?.kind === 'DerefOrSpread') {
362
+ return emitExpr(a, scope, { inCallArgs: true });
363
+ }
364
+ return emitExpr(a, scope);
365
+ });
366
+ for (const kw of expr.kwargs) {
367
+ argParts.push(emitExpr(kw.value, scope));
368
+ }
369
+ return `${calleeJs}(${argParts.join(', ')})`;
275
370
  }
276
- opensBlock = true;
277
- }
278
- // 2. Kelas
279
- else if (/^kelas\s+([A-Za-z_]\w*)(?:\s*\(([A-Za-z_]\w*)\))?\s*:$/.test(trimmed)) {
280
- const m = trimmed.match(/^kelas\s+([A-Za-z_]\w*)(?:\s*\(([A-Za-z_]\w*)\))?\s*:$/);
281
- const className = m[1];
282
- const baseClass = m[2];
283
- declareInCurrentScope(className);
284
- jsLine = baseClass ? `class ${className} extends ${baseClass} {` : `class ${className} {`;
285
- opensBlock = true;
286
- nextBlockType = 'class';
287
371
  }
288
- // 3. Jika / atau_jika / selain_itu
289
- else if (/^jika\s+(.+):$/.test(trimmed)) {
290
- const cond = trimmed.match(/^jika\s+(.+):$/)[1];
291
- jsLine = `if (${transformExpression(cond)}) {`;
292
- opensBlock = true;
293
- } else if (/^(?:atau_jika|jika_tidak)\s+(.+):$/.test(trimmed)) {
294
- const cond = trimmed.match(/^(?:atau_jika|jika_tidak)\s+(.+):$/)[1];
295
- jsLine = `else if (${transformExpression(cond)}) {`;
296
- opensBlock = true;
297
- } else if (/^(?:selain_itu|lainnya)\s*:$/.test(trimmed)) {
298
- jsLine = `else {`;
299
- opensBlock = true;
300
- }
301
- // 4. Loop: selama
302
- else if (/^selama\s+(.+):$/.test(trimmed)) {
303
- const cond = trimmed.match(/^selama\s+(.+):$/)[1];
304
- jsLine = `while (${transformExpression(cond)}) {`;
305
- opensBlock = true;
306
- }
307
- // 5. Loop: untuk var dalam koleksi
308
- else if (/^untuk\s+([A-Za-z_]\w*)\s+dalam\s+(.+):$/.test(trimmed)) {
309
- const m = trimmed.match(/^untuk\s+([A-Za-z_]\w*)\s+dalam\s+(.+):$/);
310
- const varName = m[1];
311
- const iterable = transformExpression(m[2]);
312
- newScopeVars = [varName];
313
- jsLine = `for (const ${varName} of ${iterable}) {`;
314
- opensBlock = true;
372
+ return 'undefined';
373
+ }
374
+
375
+ function emitPatternCheck(pat, targetVar, scope) {
376
+ switch (pat.kind) {
377
+ case 'Wildcard':
378
+ return { cond: 'true', binds: [] };
379
+
380
+ case 'Literal': {
381
+ const valJs = pat.litType === 'teks' ? `"${pat.value}"` : pat.litType === 'bool' ? (pat.value ? 'true' : 'false') : String(pat.value);
382
+ return { cond: `(__mhs_unwrap_ref(${targetVar}) === ${valJs})`, binds: [] };
383
+ }
384
+
385
+ case 'Range':
386
+ return {
387
+ cond: pat.inclusive
388
+ ? `(${targetVar} >= ${emitExpr(pat.start, scope)} && ${targetVar} <= ${emitExpr(pat.end, scope)})`
389
+ : `(${targetVar} >= ${emitExpr(pat.start, scope)} && ${targetVar} < ${emitExpr(pat.end, scope)})`,
390
+ binds: [],
391
+ };
392
+
393
+ case 'IdentOrUnitVariant':
394
+ if (pat.name === 'TidakAda') {
395
+ return { cond: `(${targetVar} instanceof MhsOpsi && !${targetVar}._ada)`, binds: [] };
396
+ }
397
+ if (variantToEnum.has(pat.name)) {
398
+ const eName = variantToEnum.get(pat.name);
399
+ return { cond: `(${targetVar} && ${targetVar}.__mhsEnum === "${eName}" && ${targetVar}._varian === "${pat.name}")`, binds: [] };
400
+ }
401
+ return { cond: 'true', binds: [{ name: pat.name, expr: targetVar, isMut: !!pat.isMut }] };
402
+
403
+ case 'QualifiedVariant':
404
+ return {
405
+ cond: `(${targetVar} && ${targetVar}.__mhsEnum === "${pat.enumName}" && ${targetVar}._varian === "${pat.variantName}")`,
406
+ binds: (pat.args || []).flatMap((a, idx) => {
407
+ if (a.kind === 'IdentOrUnitVariant') return [{ name: a.name, expr: `${targetVar}._data[${idx}]`, isMut: !!a.isMut }];
408
+ return [];
409
+ }),
410
+ };
411
+
412
+ case 'Variant': {
413
+ if (pat.name === 'Ada') {
414
+ const innerBind = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
415
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai`, isMut: !!pat.args[0].isMut }] : [];
416
+ return { cond: `(${targetVar} instanceof MhsOpsi && ${targetVar}._ada)`, binds: innerBind };
417
+ }
418
+ if (pat.name === 'TidakAda') {
419
+ return { cond: `(${targetVar} instanceof MhsOpsi && !${targetVar}._ada)`, binds: [] };
420
+ }
421
+ if (pat.name === 'Ok') {
422
+ const innerBind = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
423
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai`, isMut: !!pat.args[0].isMut }] : [];
424
+ return { cond: `(${targetVar} instanceof MhsHasil && ${targetVar}._ok)`, binds: innerBind };
425
+ }
426
+ if (pat.name === 'Galat') {
427
+ const innerBind = pat.args[0]?.kind === 'IdentOrUnitVariant' && pat.args[0].name !== '_'
428
+ ? [{ name: pat.args[0].name, expr: `${targetVar}._nilai`, isMut: !!pat.args[0].isMut }] : [];
429
+ return { cond: `(${targetVar} instanceof MhsHasil && !${targetVar}._ok)`, binds: innerBind };
430
+ }
431
+ if (variantToEnum.has(pat.name)) {
432
+ const eName = variantToEnum.get(pat.name);
433
+ const binds = [];
434
+ (pat.args || []).forEach((a, idx) => {
435
+ if (a.kind === 'IdentOrUnitVariant' && a.name !== '_') {
436
+ binds.push({ name: a.name, expr: `${targetVar}._data[${idx}]`, isMut: !!a.isMut });
437
+ }
438
+ });
439
+ return { cond: `(${targetVar} && ${targetVar}.__mhsEnum === "${eName}" && ${targetVar}._varian === "${pat.name}")`, binds };
440
+ }
441
+ return { cond: 'false', binds: [] };
442
+ }
443
+
444
+ case 'ExprPattern':
445
+ return { cond: `(__mhs_unwrap_ref(${targetVar}) === ${emitExpr(pat.expr, scope)})`, binds: [] };
315
446
  }
316
- // 6. Coba / tangkap / akhirnya
317
- else if (/^coba\s*:$/.test(trimmed)) {
318
- jsLine = `try {`;
319
- opensBlock = true;
320
- } else if (/^tangkap(?:\s+([A-Za-z_]\w*))?\s*:$/.test(trimmed)) {
321
- const errVar = trimmed.match(/^tangkap(?:\s+([A-Za-z_]\w*))?\s*:$/)[1] || '_err';
322
- newScopeVars = [errVar];
323
- jsLine = `catch (${errVar}) {`;
324
- opensBlock = true;
325
- } else if (/^akhirnya\s*:$/.test(trimmed)) {
326
- jsLine = `finally {`;
327
- opensBlock = true;
447
+ return { cond: 'false', binds: [] };
448
+ }
449
+
450
+ function emitBlock(stmts, scope, indentLevel, { isTop = false, blockKey = null, inClass = false } = {}) {
451
+ const pad = ' '.repeat(indentLevel);
452
+ const blockDrops = blockKey && metadata.droppableVars.has(blockKey)
453
+ ? Array.from(metadata.droppableVars.get(blockKey))
454
+ : [];
455
+
456
+ const prevSlots = [];
457
+ if (blockDrops.length > 0) {
458
+ for (const dv of blockDrops) {
459
+ const slot = nextTmp(`_drop_${dv}`);
460
+ prevSlots.push({ orig: dv, prev: dropSlotMap.get(dv), slot });
461
+ dropSlotMap.set(dv, slot);
462
+ lines.push(`${pad}let ${slot} = null;`);
463
+ }
464
+ lines.push(`${pad}try {`);
328
465
  }
329
- // 7. Pernyataan tunggal
330
- else if (/^kembalikan(?:\s+(.*))?$/.test(trimmed)) {
331
- const val = trimmed.match(/^kembalikan(?:\s+(.*))?$/)[1];
332
- jsLine = val ? `return ${transformExpression(val)};` : `return;`;
333
- } else if (trimmed === 'berhenti') {
334
- jsLine = 'break;';
335
- } else if (trimmed === 'lanjut') {
336
- jsLine = 'continue;';
337
- } else if (trimmed === 'lewat') {
338
- jsLine = '/* lewat */';
339
- } else if (/^lempar\s+(.+)$/.test(trimmed)) {
340
- const msg = trimmed.match(/^lempar\s+(.+)$/)[1];
341
- jsLine = `throw new Error(${transformExpression(msg)});`;
342
- } else if (/^pastikan\s+(.+)$/.test(trimmed)) {
343
- const rest = trimmed.match(/^pastikan\s+(.+)$/)[1];
344
- const parts = rest.split(',');
345
- const cond = transformExpression(parts[0].trim());
346
- const msg = parts[1] ? transformExpression(parts.slice(1).join(',').trim()) : '"Pernyataan pastikan() gagal"';
347
- jsLine = `if (!(${cond})) { throw new Error(${msg}); }`;
466
+
467
+ const innerPad = blockDrops.length > 0 ? ' '.repeat(indentLevel + 1) : pad;
468
+ const innerIndent = blockDrops.length > 0 ? indentLevel + 1 : indentLevel;
469
+
470
+ for (const st of stmts) {
471
+ emitStmt(st, scope, innerIndent, { isTop, inClass, pad: innerPad });
348
472
  }
349
- // 8. Assignment: nama = ekspresi (tidak berlaku untuk diri.properti = ...)
350
- else if (/^([A-Za-z_]\w*)\s*=\s*(?!=)(.+)$/.test(trimmed)) {
351
- const m = trimmed.match(/^([A-Za-z_]\w*)\s*=\s*(?!=)(.+)$/);
352
- const varName = m[1];
353
- const rhs = transformExpression(m[2]);
354
- if (!isDeclared(varName)) {
355
- declareInCurrentScope(varName);
356
- jsLine = `let ${varName} = ${rhs};`;
357
- } else {
358
- jsLine = `${varName} = ${rhs};`;
473
+
474
+ if (blockDrops.length > 0) {
475
+ lines.push(`${pad}} finally {`);
476
+ for (let i = prevSlots.length - 1; i >= 0; i--) {
477
+ const { orig, prev, slot } = prevSlots[i];
478
+ lines.push(`${pad} __mhs_lepas(${slot});`);
479
+ if (prev) dropSlotMap.set(orig, prev);
480
+ else dropSlotMap.delete(orig);
359
481
  }
482
+ lines.push(`${pad}}`);
360
483
  }
361
- // 9. Ekspresi umum (termasuk diri.x = ... atau pemanggilan fungsi)
362
- else {
363
- jsLine = `${transformExpression(trimmed)};`;
364
- }
484
+ }
485
+
486
+ function emitStmt(st, scope, indentLevel, { isTop = false, inClass = false, pad } = {}) {
487
+ switch (st.kind) {
488
+ case 'ImportStmt': {
489
+ const fn = st.isPyImport ? '__mhs_impor_py' : '__mhs_impor';
490
+ const jsAlias = scope.declare(st.alias);
491
+ if (isTop) topLevelExports.set(st.alias, jsAlias);
492
+ lines.push(`${pad}const ${jsAlias} = ${fn}(${JSON.stringify(st.target)});`);
493
+ break;
494
+ }
495
+
496
+ case 'FromImportStmt': {
497
+ const fn = st.isPyImport ? '__mhs_impor_py' : '__mhs_impor';
498
+ const parts = st.items.map((it) => {
499
+ const jsAlias = scope.declare(it.alias);
500
+ if (isTop) topLevelExports.set(it.alias, jsAlias);
501
+ return it.name === jsAlias ? it.name : `${it.name}: ${jsAlias}`;
502
+ });
503
+ lines.push(`${pad}const { ${parts.join(', ')} } = ${fn}(${JSON.stringify(st.target)});`);
504
+ break;
505
+ }
365
506
 
366
- outputLines.push(pad + restoreStrings(jsLine, strings));
507
+ case 'VarDecl': {
508
+ const valJs = st.value ? emitExpr(st.value, scope) : 'undefined';
509
+ if (st.names.length === 1) {
510
+ const n = st.names[0].name;
511
+ const jsName = scope.declare(n);
512
+ if (isTop) topLevelExports.set(n, jsName);
513
+ const declKw = st.qualifier === 'ubah' ? 'let' : 'const';
514
+ const rhs = st.qualifier === 'konst' ? `bekukan(${valJs})` : valJs;
515
+ lines.push(`${pad}${declKw} ${jsName} = ${rhs};`);
516
+ if (dropSlotMap.has(n)) {
517
+ lines.push(`${pad}${dropSlotMap.get(n)} = ${jsName};`);
518
+ }
519
+ } else {
520
+ const jsNames = st.names.map((n) => {
521
+ const jn = scope.declare(n.name);
522
+ if (isTop) topLevelExports.set(n.name, jn);
523
+ return jn;
524
+ });
525
+ const declKw = st.qualifier === 'ubah' ? 'let' : 'const';
526
+ lines.push(`${pad}${declKw} [${jsNames.join(', ')}] = ${valJs};`);
527
+ }
528
+ break;
529
+ }
367
530
 
368
- if (opensBlock) {
369
- let nextIndent = null;
370
- for (let k = lineIdx + 1; k < rawLines.length; k++) {
371
- const nextStripped = stripCommentAndProtectStrings(rawLines[k]).code.trim();
372
- if (nextStripped) {
373
- nextIndent = getIndent(rawLines[k]);
531
+ case 'AssignStmt': {
532
+ if (st.target?.kind === 'DerefOrSpread') {
533
+ const rJs = emitExpr(st.target.target, scope);
534
+ const vJs = emitExpr(st.value, scope);
535
+ if (st.op === '=') {
536
+ lines.push(`${pad}__mhs_set_deref(${rJs}, ${vJs});`);
537
+ } else {
538
+ const rawOp = st.op.slice(0, -1);
539
+ lines.push(`${pad}__mhs_set_deref(${rJs}, __mhs_deref(${rJs}) ${rawOp} ${vJs});`);
540
+ }
541
+ break;
542
+ }
543
+ if (st.target?.kind === 'Index') {
544
+ const objJs = emitExpr(st.target.object, scope);
545
+ const idxJs = emitExpr(st.target.index, scope);
546
+ const vJs = emitExpr(st.value, scope);
547
+ if (st.op === '=') {
548
+ lines.push(`${pad}__mhs_atur_indeks(${objJs}, ${idxJs}, ${vJs});`);
549
+ } else {
550
+ const rawOp = st.op.slice(0, -1);
551
+ lines.push(`${pad}__mhs_atur_indeks(${objJs}, ${idxJs}, __mhs_indeks(${objJs}, ${idxJs}) ${rawOp} ${vJs});`);
552
+ }
374
553
  break;
375
554
  }
555
+ if (st.target?.kind === 'Member') {
556
+ const lhs = emitExpr(st.target, scope);
557
+ const rhs = emitExpr(st.value, scope);
558
+ lines.push(`${pad}${lhs} ${st.op} ${rhs};`);
559
+ break;
560
+ }
561
+ if (st.target?.kind === 'Ident') {
562
+ const name = st.target.name;
563
+ const alreadyExists = scope.vars.has(name) || (scope.parent && scope.parent.resolve(name) !== name) || inClass;
564
+ const isExplicitNew = !scope.vars.has(name) && (!scope.parent || !hasInChain(scope, name));
565
+ if (isExplicitNew && st.op === '=') {
566
+ const rhs = emitExpr(st.value, scope);
567
+ const jsName = scope.declare(name);
568
+ if (isTop) topLevelExports.set(name, jsName);
569
+ lines.push(`${pad}const ${jsName} = ${rhs};`);
570
+ if (dropSlotMap.has(name)) {
571
+ lines.push(`${pad}${dropSlotMap.get(name)} = ${jsName};`);
572
+ }
573
+ } else {
574
+ const lhs = scope.resolve(name);
575
+ const rhs = emitExpr(st.value, scope);
576
+ if (st.op === '//=' || st.op === '**=') {
577
+ const fn = st.op === '//=' ? '__mhs_bagi_bulat' : 'Math.pow';
578
+ lines.push(`${pad}${lhs} = ${fn}(${lhs}, ${rhs});`);
579
+ } else {
580
+ lines.push(`${pad}${lhs} ${st.op} ${rhs};`);
581
+ }
582
+ }
583
+ break;
584
+ }
585
+ if (st.target?.kind === 'Tuple') {
586
+ const rhs = emitExpr(st.value, scope);
587
+ const names = st.target.items.map((it) => {
588
+ if (!hasInChain(scope, it.name)) {
589
+ const jn = scope.declare(it.name);
590
+ if (isTop) topLevelExports.set(it.name, jn);
591
+ return jn;
592
+ }
593
+ return scope.resolve(it.name);
594
+ });
595
+ lines.push(`${pad}let [${names.join(', ')}] = ${rhs};`);
596
+ break;
597
+ }
598
+ break;
599
+ }
600
+
601
+ case 'WithStmt': {
602
+ const wScope = new EmitScope(scope);
603
+ const ctxJs = emitExpr(st.ctxExpr, scope);
604
+ const varJs = st.asVar ? wScope.declare(st.asVar) : nextTmp('_with');
605
+ lines.push(`${pad}{`);
606
+ lines.push(`${pad} const ${varJs} = ${ctxJs};`);
607
+ lines.push(`${pad} try {`);
608
+ emitBlock(st.body, wScope, indentLevel + 2, { blockKey: `with_${st.line}` });
609
+ lines.push(`${pad} } finally {`);
610
+ lines.push(`${pad} __mhs_lepas(${varJs});`);
611
+ lines.push(`${pad} }`);
612
+ lines.push(`${pad}}`);
613
+ break;
614
+ }
615
+
616
+ case 'FieldDecl':
617
+ // Field tipe kelas/struktur di JS diinisialisasi di constructor
618
+ break;
619
+
620
+ case 'ExprStmt':
621
+ if (st.expr) {
622
+ lines.push(`${pad}${emitExpr(st.expr, scope)};`);
623
+ }
624
+ break;
625
+
626
+ case 'ReturnStmt':
627
+ lines.push(st.expr ? `${pad}return ${emitExpr(st.expr, scope)};` : `${pad}return;`);
628
+ break;
629
+
630
+ case 'BreakStmt':
631
+ lines.push(`${pad}break;`);
632
+ break;
633
+
634
+ case 'ContinueStmt':
635
+ lines.push(`${pad}continue;`);
636
+ break;
637
+
638
+ case 'PassStmt':
639
+ lines.push(`${pad}/* lewat */`);
640
+ break;
641
+
642
+ case 'RaiseStmt':
643
+ lines.push(`${pad}throw new Error(${emitExpr(st.expr, scope)});`);
644
+ break;
645
+
646
+ case 'AssertStmt': {
647
+ const condJs = emitExpr(st.cond, scope);
648
+ const msgJs = st.msg ? emitExpr(st.msg, scope) : '"Pernyataan pastikan() gagal"';
649
+ lines.push(`${pad}if (!(${condJs})) { panik(${msgJs}); }`);
650
+ break;
651
+ }
652
+
653
+ case 'GlobalStmt':
654
+ break;
655
+
656
+ case 'IfStmt': {
657
+ st.branches.forEach((br, idx) => {
658
+ if (br.isIfLet) {
659
+ const tmp = nextTmp('_jc');
660
+ lines.push(`${pad}const ${tmp} = ${emitExpr(br.expr, scope)};`);
661
+ const { cond, binds } = emitPatternCheck(br.pattern, tmp, scope);
662
+ const brScope = new EmitScope(scope);
663
+ lines.push(`${pad}${idx === 0 ? 'if' : 'else if'} (${cond}) {`);
664
+ for (const b of binds) {
665
+ const jn = brScope.declare(b.name);
666
+ lines.push(`${pad} ${b.isMut ? 'let' : 'const'} ${jn} = ${b.expr};`);
667
+ }
668
+ emitBlock(br.body, brScope, indentLevel + 1, { blockKey: `if_${br.line}` });
669
+ lines.push(`${pad}}`);
670
+ } else if (br.isElse) {
671
+ lines.push(`${pad}else {`);
672
+ emitBlock(br.body, new EmitScope(scope), indentLevel + 1, { blockKey: `if_${br.line}` });
673
+ lines.push(`${pad}}`);
674
+ } else {
675
+ const kw = idx === 0 ? 'if' : 'else if';
676
+ lines.push(`${pad}${kw} (${emitExpr(br.cond, scope)}) {`);
677
+ emitBlock(br.body, new EmitScope(scope), indentLevel + 1, { blockKey: `if_${br.line}` });
678
+ lines.push(`${pad}}`);
679
+ }
680
+ });
681
+ break;
682
+ }
683
+
684
+ case 'WhileStmt':
685
+ lines.push(`${pad}while (${emitExpr(st.cond, scope)}) {`);
686
+ emitBlock(st.body, new EmitScope(scope), indentLevel + 1, { blockKey: `while_${st.line}` });
687
+ lines.push(`${pad}}`);
688
+ break;
689
+
690
+ case 'ForStmt': {
691
+ const iterJs = emitExpr(st.iter, scope);
692
+ const loopScope = new EmitScope(scope);
693
+ const lhs = st.targets.length === 1
694
+ ? loopScope.declare(st.targets[0].name)
695
+ : `[${st.targets.map((t) => loopScope.declare(t.name)).join(', ')}]`;
696
+ lines.push(`${pad}for (const ${lhs} of __mhs_unwrap_ref(${iterJs})) {`);
697
+ emitBlock(st.body, loopScope, indentLevel + 1, { blockKey: `for_${st.line}` });
698
+ lines.push(`${pad}}`);
699
+ break;
376
700
  }
377
- if (nextIndent === null || nextIndent <= indent) {
378
- throw new SyntaxError(`Blok setelah baris ${lineNum} ("${trimmed}") harus memiliki indentasi lebih dalam.`);
701
+
702
+ case 'MatchStmt': {
703
+ const targetTmp = nextTmp('_cocok');
704
+ const matchedFlag = nextTmp('_cocok_ok');
705
+ lines.push(`${pad}const ${targetTmp} = ${emitExpr(st.target, scope)};`);
706
+ lines.push(`${pad}let ${matchedFlag} = false;`);
707
+ for (const arm of st.arms) {
708
+ const { cond, binds } = emitPatternCheck(arm.pattern, targetTmp, scope);
709
+ lines.push(`${pad}if (!${matchedFlag} && (${cond})) {`);
710
+ const armScope = new EmitScope(scope);
711
+ for (const b of binds) {
712
+ const jn = armScope.declare(b.name);
713
+ lines.push(`${pad} ${b.isMut ? 'let' : 'const'} ${jn} = ${b.expr};`);
714
+ }
715
+ if (arm.guard) {
716
+ lines.push(`${pad} if (${emitExpr(arm.guard, armScope)}) {`);
717
+ lines.push(`${pad} ${matchedFlag} = true;`);
718
+ emitBlock(arm.body, armScope, indentLevel + 2, { blockKey: `match_${arm.line}` });
719
+ lines.push(`${pad} }`);
720
+ } else {
721
+ lines.push(`${pad} ${matchedFlag} = true;`);
722
+ emitBlock(arm.body, armScope, indentLevel + 1, { blockKey: `match_${arm.line}` });
723
+ }
724
+ lines.push(`${pad}}`);
725
+ }
726
+ break;
727
+ }
728
+
729
+ case 'UnsafeBlock':
730
+ lines.push(`${pad}/* tidak_aman */ {`);
731
+ emitBlock(st.body, new EmitScope(scope), indentLevel + 1, { blockKey: `unsafe_${st.line}` });
732
+ lines.push(`${pad}}`);
733
+ break;
734
+
735
+ case 'TryStmt':
736
+ lines.push(`${pad}try {`);
737
+ emitBlock(st.tryBody, new EmitScope(scope), indentLevel + 1, { blockKey: `try_${st.line}` });
738
+ lines.push(`${pad}}`);
739
+ if (st.catches.length > 0) {
740
+ const c = st.catches[0];
741
+ const cScope = new EmitScope(scope);
742
+ const errVar = cScope.declare(c.errVar || '_err');
743
+ lines.push(`${pad}catch (${errVar}) {`);
744
+ lines.push(`${pad} if (${errVar} instanceof MhsPropagasi) throw ${errVar};`);
745
+ emitBlock(c.body, cScope, indentLevel + 1, { blockKey: `catch_${c.line}` });
746
+ lines.push(`${pad}}`);
747
+ }
748
+ if (st.finallyBody) {
749
+ lines.push(`${pad}finally {`);
750
+ emitBlock(st.finallyBody, new EmitScope(scope), indentLevel + 1, { blockKey: `finally_${st.line}` });
751
+ lines.push(`${pad}}`);
752
+ }
753
+ break;
754
+
755
+ case 'FunctionDecl': {
756
+ const fnScope = new EmitScope(scope);
757
+ let paramsList = st.params;
758
+ if (inClass && paramsList[0] && (paramsList[0].name === 'diri' || paramsList[0].name === 'self')) {
759
+ paramsList = paramsList.slice(1);
760
+ }
761
+ const jsParams = paramsList.map((p) => {
762
+ const pName = fnScope.declare(p.name);
763
+ if (p.isStar) return `...${pName}`;
764
+ if (p.defaultExpr) return `${pName} = ${emitExpr(p.defaultExpr, scope)}`;
765
+ return pName;
766
+ }).join(', ');
767
+
768
+ const asyncPrefix = st.isAsync ? 'async ' : '';
769
+ let header;
770
+ if (inClass) {
771
+ const methodName = (st.name === '__init__' || st.name === '__inisialisasi__') ? 'constructor' : st.name;
772
+ header = `${pad}${asyncPrefix}${methodName}(${jsParams}) {`;
773
+ } else {
774
+ const jsFnName = scope.declare(st.name);
775
+ if (isTop) topLevelExports.set(st.name, jsFnName);
776
+ header = `${pad}${asyncPrefix}function ${jsFnName}(${jsParams}) {`;
777
+ }
778
+ lines.push(header);
779
+
780
+ const fnKey = `${st.line}:${st.name}`;
781
+ const usesTanya = usesTanyaInFn.has(fnKey);
782
+ if (usesTanya) {
783
+ lines.push(`${pad} try {`);
784
+ emitBlock(st.body, fnScope, indentLevel + 2, { blockKey: `fn_${st.line}_${st.name}` });
785
+ lines.push(`${pad} } catch (_mhs_p) {`);
786
+ lines.push(`${pad} if (_mhs_p instanceof MhsPropagasi) return _mhs_p.nilai;`);
787
+ lines.push(`${pad} throw _mhs_p;`);
788
+ lines.push(`${pad} }`);
789
+ } else {
790
+ emitBlock(st.body, fnScope, indentLevel + 1, { blockKey: `fn_${st.line}_${st.name}` });
791
+ }
792
+ lines.push(`${pad}}`);
793
+ break;
794
+ }
795
+
796
+ case 'StructDecl':
797
+ case 'ClassDecl': {
798
+ const jsCls = scope.declare(st.name);
799
+ if (isTop) topLevelExports.set(st.name, jsCls);
800
+ const ext = st.baseClass ? ` extends ${scope.resolve(st.baseClass)}` : '';
801
+ lines.push(`${pad}class ${jsCls}${ext} {`);
802
+ const fields = st.body.filter((b) => b.kind === 'FieldDecl' || (b.kind === 'AssignStmt' && b.target?.kind === 'Ident'));
803
+ const methods = st.body.filter((b) => b.kind === 'FunctionDecl');
804
+ const hasInit = methods.some((m) => m.name === '__init__' || m.name === '__inisialisasi__');
805
+ if (!hasInit && fields.length > 0) {
806
+ const fNames = fields.map((f) => f.name || f.target.name);
807
+ lines.push(`${pad} constructor(${fNames.join(', ')}) {`);
808
+ for (const fn of fNames) {
809
+ lines.push(`${pad} this.${fn} = ${fn};`);
810
+ }
811
+ lines.push(`${pad} }`);
812
+ }
813
+ for (const m of methods) {
814
+ emitStmt(m, new EmitScope(scope), indentLevel + 1, { inClass: true, pad: `${pad} ` });
815
+ }
816
+ lines.push(`${pad}}`);
817
+ break;
818
+ }
819
+
820
+ case 'EnumDecl': {
821
+ const jsEnum = scope.declare(st.name);
822
+ if (isTop) topLevelExports.set(st.name, jsEnum);
823
+ const entries = st.variants.map((v) => {
824
+ if (v.fields.length === 0) {
825
+ return `${v.name}: __mhs_enum_varian(${JSON.stringify(st.name)}, ${JSON.stringify(v.name)})`;
826
+ }
827
+ const ps = v.fields.map((f) => f.name).join(', ');
828
+ return `${v.name}: (${ps}) => __mhs_enum_varian(${JSON.stringify(st.name)}, ${JSON.stringify(v.name)}, ${ps})`;
829
+ });
830
+ lines.push(`${pad}const ${jsEnum} = { ${entries.join(', ')} };`);
831
+ for (const v of st.variants) {
832
+ const jv = scope.declare(v.name);
833
+ if (isTop) topLevelExports.set(v.name, jv);
834
+ lines.push(`${pad}const ${jv} = ${jsEnum}.${v.name};`);
835
+ }
836
+ break;
837
+ }
838
+
839
+ case 'ImplDecl': {
840
+ const tgt = scope.resolve(st.targetName);
841
+ for (const item of st.body) {
842
+ if (item.kind === 'FunctionDecl') {
843
+ const fnScope = new EmitScope(scope);
844
+ let paramsList = item.params;
845
+ if (paramsList[0] && (paramsList[0].name === 'diri' || paramsList[0].name === 'self')) {
846
+ paramsList = paramsList.slice(1);
847
+ }
848
+ const jsParams = paramsList.map((p) => fnScope.declare(p.name)).join(', ');
849
+ lines.push(`${pad}${tgt}.prototype.${item.name} = function(${jsParams}) {`);
850
+ emitBlock(item.body, fnScope, indentLevel + 1, { blockKey: `fn_${item.line}_${item.name}` });
851
+ lines.push(`${pad}};`);
852
+ }
853
+ }
854
+ break;
379
855
  }
380
- indentStack.push(nextIndent);
381
- blockTypeStack.push(nextBlockType);
382
- const childScope = new Set(newScopeVars);
383
- scopeStack.push(childScope);
384
856
  }
385
857
  }
386
858
 
387
- while (indentStack.length > 1) {
388
- indentStack.pop();
389
- scopeStack.pop();
390
- blockTypeStack.pop();
391
- const pad = ' '.repeat(indentStack.length - 1);
392
- outputLines.push(`${pad}}`);
859
+ function hasInChain(sc, name) {
860
+ let cur = sc;
861
+ while (cur) {
862
+ if (cur.vars.has(name)) return true;
863
+ cur = cur.parent;
864
+ }
865
+ return false;
393
866
  }
394
867
 
868
+ emitBlock(program.body, rootScope, 0, { isTop: true, blockKey: 'root' });
869
+
395
870
  if (topLevelExports.size > 0) {
396
- outputLines.push(`__mhs_exports__ = { ${Array.from(topLevelExports).join(', ')} };`);
871
+ const expParts = Array.from(topLevelExports.entries()).map(([k, v]) => (k === v ? k : `${k}: ${v}`));
872
+ lines.push(`__mhs_exports__ = { ${expParts.join(', ')} };`);
397
873
  }
398
874
 
399
- return outputLines.join('\n');
875
+ return lines.join('\n');
400
876
  }
401
877
 
402
878
  module.exports = { transpile };