mhs-lang 2.2.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lexer.js ADDED
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Lexer untuk Bahasa .mhs (dengan pelacakan indentasi, bracket, string, dan posisi baris/kolom).
3
+ */
4
+
5
+ const TWO_CHAR_OPS = new Set([
6
+ '=>', '->', '+=', '-=', '*=', '/=', '%=', '==', '!=', '<=', '>=',
7
+ '**', '//', '&&', '||', '..', '<<', '>>',
8
+ ]);
9
+
10
+ const THREE_CHAR_OPS = new Set(['**=', '//=', '..=', '<<=', '>>=']);
11
+
12
+ const KEYWORDS = new Set([
13
+ 'tetap', 'ubah', 'konst', 'pindah', 'pinjam', 'pinjam_ubah',
14
+ 'tidak_aman', 'cocok', 'struktur', 'pilihan_tipe', 'implementasi',
15
+ 'fungsi', 'asinkron', 'await', 'kelas', 'jika', 'atau_jika', 'jika_tidak',
16
+ 'selain_itu', 'lainnya', 'selama', 'untuk', 'dalam', 'coba', 'tangkap',
17
+ 'akhirnya', 'dengan', 'kembalikan', 'hasilkan', 'berhenti', 'lanjut',
18
+ 'lewat', 'lempar', 'pastikan', 'umum', 'impor', 'dari', 'sebagai',
19
+ 'impor_py', 'dari_py', 'dan', 'atau', 'bukan', 'adalah', 'bukan_adalah',
20
+ 'anonim', 'Benar', 'Salah', 'Kosong', 'benar', 'salah', 'kosong',
21
+ 'Ada', 'TidakAda', 'Ok', 'Galat', 'panik',
22
+ // Python compat keywords still recognized by parser/analyzer
23
+ 'def', 'class', 'if', 'elif', 'else', 'while', 'for', 'in', 'try',
24
+ 'except', 'finally', 'with', 'return', 'yield', 'break', 'continue',
25
+ 'pass', 'raise', 'assert', 'global', 'import', 'from', 'as', 'async',
26
+ 'lambda', 'and', 'or', 'not', 'is', 'True', 'False', 'None',
27
+ ]);
28
+
29
+ function extractFStringExpressions(inner) {
30
+ const exprs = [];
31
+ let i = 0;
32
+ while (i < inner.length) {
33
+ if (inner[i] === '{') {
34
+ if (inner[i + 1] === '{') {
35
+ i += 2;
36
+ continue;
37
+ }
38
+ let depth = 1;
39
+ let j = i + 1;
40
+ let inStr = null;
41
+ let exprEnd = -1;
42
+ while (j < inner.length && depth > 0) {
43
+ const ch = inner[j];
44
+ if (inStr) {
45
+ if (ch === '\\') {
46
+ j += 2;
47
+ continue;
48
+ }
49
+ if (ch === inStr) inStr = null;
50
+ j++;
51
+ continue;
52
+ }
53
+ if (ch === '"' || ch === "'") {
54
+ inStr = ch;
55
+ j++;
56
+ continue;
57
+ }
58
+ if (ch === '{') depth++;
59
+ else if (ch === '}') {
60
+ depth--;
61
+ if (depth === 0) {
62
+ exprEnd = j;
63
+ break;
64
+ }
65
+ }
66
+ j++;
67
+ }
68
+ if (exprEnd !== -1) {
69
+ let rawExpr = inner.slice(i + 1, exprEnd);
70
+ // Pisahkan format specifier seperti {val:.2f} atau {val:,.2f} tanpa memotong dict/ternary
71
+ let splitColon = -1;
72
+ let pDepth = 0;
73
+ let qStr = null;
74
+ for (let k = 0; k < rawExpr.length; k++) {
75
+ const c = rawExpr[k];
76
+ if (qStr) {
77
+ if (c === '\\') { k++; continue; }
78
+ if (c === qStr) qStr = null;
79
+ continue;
80
+ }
81
+ if (c === '"' || c === "'") { qStr = c; continue; }
82
+ if (c === '(' || c === '[' || c === '{') pDepth++;
83
+ else if (c === ')' || c === ']' || c === '}') pDepth--;
84
+ else if (c === ':' && pDepth === 0) {
85
+ splitColon = k;
86
+ break;
87
+ }
88
+ }
89
+ if (splitColon !== -1) {
90
+ rawExpr = rawExpr.slice(0, splitColon);
91
+ }
92
+ if (rawExpr.trim()) {
93
+ exprs.push(rawExpr.trim());
94
+ }
95
+ i = exprEnd + 1;
96
+ continue;
97
+ }
98
+ } else if (inner[i] === '}' && inner[i + 1] === '}') {
99
+ i += 2;
100
+ continue;
101
+ }
102
+ i++;
103
+ }
104
+ return exprs;
105
+ }
106
+
107
+ /**
108
+ * Memecah sumber kode menjadi token logis dan baris-baris logis (menghormati indentasi & multiline bracket).
109
+ */
110
+ function tokenize(source) {
111
+ const normalized = source.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
112
+ const rawLines = normalized.split('\n');
113
+ const tokens = [];
114
+
115
+ let i = 0;
116
+ let line = 1;
117
+ let col = 1;
118
+ let bracketDepth = 0;
119
+ let atLineStart = true;
120
+
121
+ function advance(n = 1) {
122
+ for (let k = 0; k < n; k++) {
123
+ if (normalized[i] === '\n') {
124
+ line++;
125
+ col = 1;
126
+ } else {
127
+ col++;
128
+ }
129
+ i++;
130
+ }
131
+ }
132
+
133
+ while (i < normalized.length) {
134
+ const ch = normalized[i];
135
+
136
+ // Awal baris fisik (di luar bracket) -> catat indentasi
137
+ if (atLineStart && bracketDepth === 0) {
138
+ let indentCount = 0;
139
+ const startCol = col;
140
+ while (i < normalized.length && (normalized[i] === ' ' || normalized[i] === '\t')) {
141
+ indentCount += normalized[i] === '\t' ? 4 : 1;
142
+ advance(1);
143
+ }
144
+ if (i >= normalized.length) break;
145
+ const nextCh = normalized[i];
146
+ if (nextCh === '\n') {
147
+ advance(1);
148
+ continue;
149
+ }
150
+ if (nextCh === '#') {
151
+ // Baris komentar penuh: lewati sampai akhir baris
152
+ while (i < normalized.length && normalized[i] !== '\n') advance(1);
153
+ if (i < normalized.length && normalized[i] === '\n') advance(1);
154
+ continue;
155
+ }
156
+ tokens.push({
157
+ type: 'LINE_START',
158
+ indent: indentCount,
159
+ line,
160
+ col: startCol,
161
+ });
162
+ atLineStart = false;
163
+ continue;
164
+ }
165
+
166
+ if (ch === ' ' || ch === '\t') {
167
+ advance(1);
168
+ continue;
169
+ }
170
+
171
+ if (ch === '\n') {
172
+ if (bracketDepth === 0) {
173
+ tokens.push({ type: 'NEWLINE', value: '\n', line, col, endCol: col + 1 });
174
+ atLineStart = true;
175
+ }
176
+ advance(1);
177
+ continue;
178
+ }
179
+
180
+ // Line continuation backslash
181
+ if (ch === '\\' && normalized[i + 1] === '\n') {
182
+ advance(2);
183
+ continue;
184
+ }
185
+
186
+ // Komentar
187
+ if (ch === '#') {
188
+ while (i < normalized.length && normalized[i] !== '\n') {
189
+ advance(1);
190
+ }
191
+ continue;
192
+ }
193
+
194
+ // String prefix (f, F, r, R, b, B, fr, rf) + quote
195
+ let prefix = '';
196
+ const next1 = normalized[i + 1] || '';
197
+ const next2 = normalized[i + 2] || '';
198
+ if (/[fFrRbB]/.test(ch) && (next1 === '"' || next1 === "'")) {
199
+ prefix = ch.toLowerCase();
200
+ } else if (
201
+ next1 && /[fFrR]/.test(ch) && /[fFrR]/.test(next1) && ch.toLowerCase() !== next1.toLowerCase() &&
202
+ (next2 === '"' || next2 === "'")
203
+ ) {
204
+ prefix = (ch + next1).toLowerCase();
205
+ }
206
+
207
+ if (prefix || ch === '"' || ch === "'") {
208
+ const startLine = line;
209
+ const startCol = col;
210
+ if (prefix) advance(prefix.length);
211
+ const quote = normalized[i];
212
+ const isTriple = normalized.slice(i, i + 3) === quote.repeat(3);
213
+ const delim = isTriple ? quote.repeat(3) : quote;
214
+ advance(delim.length);
215
+
216
+ let inner = '';
217
+ let closed = false;
218
+ while (i < normalized.length) {
219
+ if (!prefix.includes('r') && normalized[i] === '\\' && i + 1 < normalized.length) {
220
+ inner += normalized[i] + normalized[i + 1];
221
+ advance(2);
222
+ continue;
223
+ }
224
+ if (isTriple) {
225
+ if (normalized.slice(i, i + 3) === delim) {
226
+ advance(3);
227
+ closed = true;
228
+ break;
229
+ }
230
+ } else {
231
+ if (normalized[i] === quote) {
232
+ advance(1);
233
+ closed = true;
234
+ break;
235
+ }
236
+ if (normalized[i] === '\n') {
237
+ break;
238
+ }
239
+ }
240
+ inner += normalized[i];
241
+ advance(1);
242
+ }
243
+
244
+ if (!closed) {
245
+ throw new SyntaxError(`String tidak ditutup pada baris ${startLine} kolom ${startCol}`);
246
+ }
247
+
248
+ if (prefix.includes('f')) {
249
+ tokens.push({
250
+ type: 'FSTRING',
251
+ value: inner,
252
+ quote: delim,
253
+ prefix,
254
+ exprs: extractFStringExpressions(inner),
255
+ line: startLine,
256
+ col: startCol,
257
+ endCol: col,
258
+ });
259
+ } else {
260
+ tokens.push({
261
+ type: 'STRING',
262
+ value: inner,
263
+ quote: delim,
264
+ prefix,
265
+ line: startLine,
266
+ col: startCol,
267
+ endCol: col,
268
+ });
269
+ }
270
+ continue;
271
+ }
272
+
273
+ // Angka (termasuk underscore 500_000, desimal, hex/bin)
274
+ if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(next1))) {
275
+ const startLine = line;
276
+ const startCol = col;
277
+ let numStr = '';
278
+ if (ch === '0' && (next1 === 'x' || next1 === 'X' || next1 === 'b' || next1 === 'B' || next1 === 'o' || next1 === 'O')) {
279
+ numStr += ch + next1;
280
+ advance(2);
281
+ while (i < normalized.length && /[0-9a-fA-F_]/.test(normalized[i])) {
282
+ numStr += normalized[i];
283
+ advance(1);
284
+ }
285
+ } else {
286
+ let seenDot = false;
287
+ while (i < normalized.length) {
288
+ const c = normalized[i];
289
+ if (/[0-9_]/.test(c)) {
290
+ numStr += c;
291
+ advance(1);
292
+ } else if (c === '.' && !seenDot && normalized[i + 1] !== '.' && /[0-9]/.test(normalized[i + 1])) {
293
+ seenDot = true;
294
+ numStr += c;
295
+ advance(1);
296
+ } else if ((c === 'e' || c === 'E') && /[0-9+\-]/.test(normalized[i + 1])) {
297
+ numStr += c;
298
+ advance(1);
299
+ if (normalized[i] === '+' || normalized[i] === '-') {
300
+ numStr += normalized[i];
301
+ advance(1);
302
+ }
303
+ } else {
304
+ break;
305
+ }
306
+ }
307
+ }
308
+ const cleanNum = numStr.replace(/_/g, '');
309
+ const isFloat = cleanNum.includes('.') || cleanNum.includes('e') || cleanNum.includes('E');
310
+ tokens.push({
311
+ type: 'NUMBER',
312
+ value: cleanNum,
313
+ raw: numStr,
314
+ isFloat,
315
+ line: startLine,
316
+ col: startCol,
317
+ endCol: col,
318
+ });
319
+ continue;
320
+ }
321
+
322
+ // Identifier / Keyword
323
+ if (/[A-Za-z_]/.test(ch)) {
324
+ const startLine = line;
325
+ const startCol = col;
326
+ let id = '';
327
+ while (i < normalized.length && /[A-Za-z0-9_]/.test(normalized[i])) {
328
+ id += normalized[i];
329
+ advance(1);
330
+ }
331
+ tokens.push({
332
+ type: KEYWORDS.has(id) ? 'KEYWORD' : 'IDENT',
333
+ value: id,
334
+ line: startLine,
335
+ col: startCol,
336
+ endCol: col,
337
+ });
338
+ continue;
339
+ }
340
+
341
+ // Bracket
342
+ if (ch === '(' || ch === '[' || ch === '{') {
343
+ bracketDepth++;
344
+ tokens.push({ type: 'PUNCT', value: ch, line, col, endCol: col + 1 });
345
+ advance(1);
346
+ continue;
347
+ }
348
+ if (ch === ')' || ch === ']' || ch === '}') {
349
+ bracketDepth = Math.max(0, bracketDepth - 1);
350
+ tokens.push({ type: 'PUNCT', value: ch, line, col, endCol: col + 1 });
351
+ advance(1);
352
+ continue;
353
+ }
354
+
355
+ // Operator 3 karakter
356
+ const three = normalized.slice(i, i + 3);
357
+ if (THREE_CHAR_OPS.has(three)) {
358
+ tokens.push({ type: 'OP', value: three, line, col, endCol: col + 3 });
359
+ advance(3);
360
+ continue;
361
+ }
362
+
363
+ // Operator 2 karakter
364
+ const two = normalized.slice(i, i + 2);
365
+ if (TWO_CHAR_OPS.has(two)) {
366
+ tokens.push({ type: 'OP', value: two, line, col, endCol: col + 2 });
367
+ advance(2);
368
+ continue;
369
+ }
370
+
371
+ // Punctuation & single-char operators
372
+ if (',:;.@?'.includes(ch)) {
373
+ tokens.push({ type: 'PUNCT', value: ch, line, col, endCol: col + 1 });
374
+ advance(1);
375
+ continue;
376
+ }
377
+
378
+ if ('+-*/%=<>!&|^~'.includes(ch)) {
379
+ tokens.push({ type: 'OP', value: ch, line, col, endCol: col + 1 });
380
+ advance(1);
381
+ continue;
382
+ }
383
+
384
+ throw new SyntaxError(`Karakter tidak dikenal "${ch}" pada baris ${line} kolom ${col}`);
385
+ }
386
+
387
+ tokens.push({ type: 'EOF', value: '', line, col, endCol: col });
388
+ return { tokens, rawLines };
389
+ }
390
+
391
+ /**
392
+ * Mengelompokkan token menjadi baris-baris logis beserta level indentasi.
393
+ */
394
+ function groupLogicalLines(source) {
395
+ const { tokens, rawLines } = tokenize(source);
396
+ const lines = [];
397
+ let idx = 0;
398
+
399
+ while (idx < tokens.length) {
400
+ const tok = tokens[idx];
401
+ if (tok.type === 'EOF') break;
402
+ if (tok.type === 'NEWLINE') {
403
+ idx++;
404
+ continue;
405
+ }
406
+
407
+ let indent = 0;
408
+ let startLine = tok.line;
409
+ if (tok.type === 'LINE_START') {
410
+ indent = tok.indent;
411
+ startLine = tok.line;
412
+ idx++;
413
+ }
414
+
415
+ const lineTokens = [];
416
+ while (idx < tokens.length && tokens[idx].type !== 'NEWLINE' && tokens[idx].type !== 'EOF') {
417
+ if (tokens[idx].type !== 'LINE_START') {
418
+ lineTokens.push(tokens[idx]);
419
+ }
420
+ idx++;
421
+ }
422
+ if (idx < tokens.length && tokens[idx].type === 'NEWLINE') idx++;
423
+
424
+ if (lineTokens.length > 0) {
425
+ const last = lineTokens[lineTokens.length - 1];
426
+ lines.push({
427
+ indent,
428
+ line: startLine,
429
+ endLine: last.line,
430
+ tokens: lineTokens,
431
+ rawText: rawLines[startLine - 1] || '',
432
+ });
433
+ }
434
+ }
435
+
436
+ return { lines, rawLines };
437
+ }
438
+
439
+ module.exports = {
440
+ KEYWORDS,
441
+ tokenize,
442
+ groupLogicalLines,
443
+ extractFStringExpressions,
444
+ };
@@ -1,9 +1,21 @@
1
1
  const fs = require('fs');
2
+ const { __mhs_unwrap_ref } = require('../rust_runtime');
3
+
4
+ function unwrapDeep(val) {
5
+ const raw = __mhs_unwrap_ref(val);
6
+ if (Array.isArray(raw)) return raw.map(unwrapDeep);
7
+ if (raw && typeof raw === 'object') {
8
+ const out = {};
9
+ for (const [k, v] of Object.entries(raw)) out[k] = unwrapDeep(v);
10
+ return out;
11
+ }
12
+ return raw;
13
+ }
2
14
 
3
15
  module.exports = {
4
- urai: (teks) => JSON.parse(teks),
5
- ubah_ke_teks: (objek, rapi = false) => JSON.stringify(objek, null, rapi ? 2 : 0),
6
- baca_berkas: (jalur) => JSON.parse(fs.readFileSync(jalur, 'utf8')),
16
+ urai: (teks) => JSON.parse(String(__mhs_unwrap_ref(teks))),
17
+ ubah_ke_teks: (objek, rapi = false) => JSON.stringify(unwrapDeep(objek), null, rapi ? 2 : 0),
18
+ baca_berkas: (jalur) => JSON.parse(fs.readFileSync(String(__mhs_unwrap_ref(jalur)), 'utf8')),
7
19
  tulis_berkas: (jalur, objek, rapi = true) =>
8
- fs.writeFileSync(jalur, JSON.stringify(objek, null, rapi ? 2 : 0), 'utf8'),
20
+ fs.writeFileSync(String(__mhs_unwrap_ref(jalur)), JSON.stringify(unwrapDeep(objek), null, rapi ? 2 : 0), 'utf8'),
9
21
  };