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/index.js CHANGED
@@ -9,6 +9,7 @@ const { transpileToPython } = require('./py_transpiler');
9
9
  const { importPythonModule } = require('./py_bridge');
10
10
  const { stdlib } = require('./stdlib');
11
11
  const { STD_MODULES } = require('./modules/index');
12
+ const { analyzeSafety, assertSafe, MhsSafetyError, SANDBOX_FORBIDDEN_MODULES } = require('./safety_analyzer');
12
13
 
13
14
  let _hasPythonCache = null;
14
15
  function getPythonCommand() {
@@ -52,10 +53,15 @@ function resolvePyFile(target, baseDir) {
52
53
  return null;
53
54
  }
54
55
 
55
- function createImporter(baseDir, moduleCache) {
56
+ function createImporter(baseDir, moduleCache, { sandbox = false } = {}) {
56
57
  const localRequire = Module.createRequire(path.join(baseDir, 'index.js'));
57
58
 
58
59
  return function __mhs_impor(target) {
60
+ const baseMod = target.replace(/\.(mhs|py)$/i, '').split('.')[0];
61
+ if (sandbox && (SANDBOX_FORBIDDEN_MODULES.has(baseMod) || target.endsWith('.py'))) {
62
+ throw new Error(`[Kotak Pasir] Impor modul "${target}" dilarang dalam mode --sandbox.`);
63
+ }
64
+
59
65
  const mhsPath = resolveMhsModule(target, baseDir);
60
66
  if (mhsPath) {
61
67
  if (moduleCache.has(mhsPath)) {
@@ -64,7 +70,7 @@ function createImporter(baseDir, moduleCache) {
64
70
  const exportsPlaceholder = {};
65
71
  moduleCache.set(mhsPath, exportsPlaceholder);
66
72
  const source = fs.readFileSync(mhsPath, 'utf8');
67
- const { exports } = executeMhs(source, mhsPath, moduleCache);
73
+ const { exports } = executeMhs(source, mhsPath, moduleCache, { sandbox });
68
74
  Object.assign(exportsPlaceholder, exports);
69
75
  return exportsPlaceholder;
70
76
  }
@@ -73,6 +79,10 @@ function createImporter(baseDir, moduleCache) {
73
79
  return STD_MODULES[target];
74
80
  }
75
81
 
82
+ if (sandbox) {
83
+ throw new Error(`[Kotak Pasir] Impor eksternal "${target}" dilarang dalam mode --sandbox.`);
84
+ }
85
+
76
86
  const pyPath = resolvePyFile(target, baseDir);
77
87
  if (pyPath) {
78
88
  return importPythonModule(pyPath, baseDir);
@@ -90,16 +100,32 @@ function createImporter(baseDir, moduleCache) {
90
100
  };
91
101
  }
92
102
 
93
- function executeMhs(source, filename = '<mhs>', moduleCache = new Map()) {
103
+ function executeMhs(source, filename = '<mhs>', moduleCache = new Map(), options = {}) {
94
104
  source = source.replace(/^\uFEFF/, '');
105
+ const { sandbox = false, isRepl = false } = options;
95
106
  const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
96
107
  const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
97
108
 
98
- const jsCode = transpile(source);
109
+ const jsCode = transpile(source, { filename: absFilename, sandbox, isRepl });
110
+
111
+ const safeStdlib = sandbox
112
+ ? {
113
+ ...stdlib,
114
+ masukan: () => {
115
+ throw new Error('[Kotak Pasir] masukan() stdin dilarang dalam mode --sandbox');
116
+ },
117
+ }
118
+ : stdlib;
119
+
99
120
  const context = {
100
- ...stdlib,
101
- __mhs_impor: createImporter(baseDir, moduleCache),
102
- __mhs_impor_py: (modName) => importPythonModule(modName, baseDir),
121
+ ...safeStdlib,
122
+ __mhs_impor: createImporter(baseDir, moduleCache, { sandbox }),
123
+ __mhs_impor_py: (modName) => {
124
+ if (sandbox) {
125
+ throw new Error(`[Kotak Pasir] impor_py("${modName}") dilarang dalam mode --sandbox`);
126
+ }
127
+ return importPythonModule(modName, baseDir);
128
+ },
103
129
  __mhs_exports__: {},
104
130
  console,
105
131
  Math,
@@ -119,11 +145,11 @@ function executeMhs(source, filename = '<mhs>', moduleCache = new Map()) {
119
145
  return { result, exports: context.__mhs_exports__ };
120
146
  }
121
147
 
122
- function runCode(source, filename = '<mhs>') {
123
- return executeMhs(source, filename).result;
148
+ function runCode(source, filename = '<mhs>', options = {}) {
149
+ return executeMhs(source, filename, new Map(), options).result;
124
150
  }
125
151
 
126
- function runFile(filePath, { engine = 'auto' } = {}) {
152
+ function runFile(filePath, { engine = 'auto', sandbox = false, args = [] } = {}) {
127
153
  const absPath = path.resolve(filePath);
128
154
  if (!fs.existsSync(absPath)) {
129
155
  throw new Error(`File tidak ditemukan: ${absPath}`);
@@ -131,37 +157,61 @@ function runFile(filePath, { engine = 'auto' } = {}) {
131
157
  const source = fs.readFileSync(absPath, 'utf8').replace(/^\uFEFF/, '');
132
158
 
133
159
  if (engine === 'py' || (engine === 'auto' && hasPython3())) {
134
- return runPyCode(source, absPath);
160
+ return runPyCode(source, absPath, { sandbox, args });
135
161
  }
136
- return runCode(source, absPath);
162
+ return runCode(source, absPath, { sandbox, args });
137
163
  }
138
164
 
139
- function runPyCode(source, filename = '<mhs>') {
165
+ function collectImportedMhsFiles(source, baseDir, visited = new Set(), options = {}) {
166
+ const { program } = analyzeSafety(source, options);
167
+ const files = [];
168
+ for (const st of program.body) {
169
+ if (st.kind === 'ImportStmt' || st.kind === 'FromImportStmt') {
170
+ const mhsPath = resolveMhsModule(st.target, baseDir);
171
+ if (mhsPath && !visited.has(mhsPath)) {
172
+ visited.add(mhsPath);
173
+ const subSrc = fs.readFileSync(mhsPath, 'utf8').replace(/^\uFEFF/, '');
174
+ files.push({ mhsPath, source: subSrc });
175
+ files.push(...collectImportedMhsFiles(subSrc, path.dirname(mhsPath), visited, { ...options, filename: mhsPath }));
176
+ }
177
+ }
178
+ }
179
+ return files;
180
+ }
181
+
182
+ function runPyCode(source, filename = '<mhs>', options = {}) {
140
183
  source = source.replace(/^\uFEFF/, '');
184
+ const { sandbox = false, args = [] } = options;
141
185
  const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
142
186
  const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
143
187
  const pyModulesDir = path.resolve(__dirname, 'py_modules');
144
188
 
145
189
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mhs-py-'));
146
190
  try {
191
+ const pyCode = transpileToPython(source, { filename: absFilename, sandbox });
192
+
147
193
  if (fs.existsSync(baseDir)) {
148
- for (const entry of fs.readdirSync(baseDir)) {
149
- if (entry.endsWith('.mhs')) {
150
- const mhsSrc = fs.readFileSync(path.join(baseDir, entry), 'utf8');
151
- const pyOut = transpileToPython(mhsSrc);
152
- const pyName = entry.replace(/\.mhs$/i, '.py');
153
- fs.writeFileSync(path.join(tmpDir, pyName), pyOut, 'utf8');
154
- }
194
+ const visited = new Set([absFilename]);
195
+ const importedMods = collectImportedMhsFiles(source, baseDir, visited, { filename: absFilename, sandbox });
196
+ for (const mod of importedMods) {
197
+ const pyOut = transpileToPython(mod.source, { filename: mod.mhsPath, sandbox });
198
+ const relName = path.basename(mod.mhsPath).replace(/\.mhs$/i, '.py');
199
+ fs.writeFileSync(path.join(tmpDir, relName), pyOut, 'utf8');
155
200
  }
156
201
  }
157
202
 
158
- const pyCode = transpileToPython(source);
159
203
  const pythonCmd = getPythonCommand();
160
204
  const env = {
161
205
  ...process.env,
162
206
  PYTHONPATH: [tmpDir, pyModulesDir, baseDir, process.env.PYTHONPATH || ''].filter(Boolean).join(path.delimiter),
163
207
  };
164
- return execFileSync(pythonCmd, ['-c', pyCode], {
208
+
209
+ // Eksekusi via berkas temporer agar bebas dari batas panjang baris perintah (-c) di Windows
210
+ const entryPyPath = path.join(tmpDir, '__mhs_entry__.py');
211
+ const entryCode = `import sys as _mhs_sys\n_mhs_sys.argv[0] = ${JSON.stringify(absFilename)}\n` + pyCode;
212
+ fs.writeFileSync(entryPyPath, entryCode, 'utf8');
213
+
214
+ return execFileSync(pythonCmd, [entryPyPath, ...args], {
165
215
  cwd: baseDir,
166
216
  env,
167
217
  stdio: 'inherit',
@@ -171,8 +221,17 @@ function runPyCode(source, filename = '<mhs>') {
171
221
  }
172
222
  }
173
223
 
174
- function runPyFile(filePath) {
175
- return runFile(filePath, { engine: 'py' });
224
+ function runPyFile(filePath, options = {}) {
225
+ return runFile(filePath, { engine: 'py', ...options });
226
+ }
227
+
228
+ function checkFile(filePath, { sandbox = false } = {}) {
229
+ const absPath = path.resolve(filePath);
230
+ if (!fs.existsSync(absPath)) {
231
+ throw new Error(`File tidak ditemukan: ${absPath}`);
232
+ }
233
+ const source = fs.readFileSync(absPath, 'utf8').replace(/^\uFEFF/, '');
234
+ return assertSafe(source, { filename: absPath, sandbox });
176
235
  }
177
236
 
178
237
  module.exports = {
@@ -182,6 +241,10 @@ module.exports = {
182
241
  runFile,
183
242
  runPyCode,
184
243
  runPyFile,
244
+ checkFile,
245
+ analyzeSafety,
246
+ assertSafe,
247
+ MhsSafetyError,
185
248
  hasPython3,
186
249
  stdlib,
187
250
  STD_MODULES,
@@ -8,13 +8,15 @@ const {
8
8
  createConnection,
9
9
  } = require('vscode-languageserver/node');
10
10
  const { TextDocument } = require('vscode-languageserver-textdocument');
11
- const { transpile } = require('./transpiler');
11
+ const { analyzeSafety } = require('./safety_analyzer');
12
12
 
13
13
  const KEYWORDS = new Set([
14
+ 'tetap', 'ubah', 'konst', 'pindah', 'pinjam', 'pinjam_ubah', 'tidak_aman',
15
+ 'cocok', 'struktur', 'pilihan_tipe', 'implementasi',
14
16
  'asinkron', 'fungsi', 'kelas', 'jika', 'atau_jika', 'jika_tidak', 'selain_itu',
15
17
  'lainnya', 'selama', 'untuk', 'dalam', 'coba', 'tangkap', 'akhirnya', 'dengan',
16
18
  'kembalikan', 'hasilkan', 'berhenti', 'lanjut', 'lewat', 'lempar', 'pastikan',
17
- 'umum', 'impor', 'dari', 'sebagai', 'impor_py', 'dari_py',
19
+ 'umum', 'impor', 'dari', 'sebagai', 'impor_py', 'dari_py', 'anonim',
18
20
  'if', 'elif', 'else', 'while', 'for', 'in', 'def', 'class', 'return', 'yield',
19
21
  'break', 'continue', 'pass', 'raise', 'assert', 'try', 'except', 'finally',
20
22
  'with', 'import', 'from', 'as', 'async', 'await', 'global', 'nonlocal',
@@ -22,12 +24,20 @@ const KEYWORDS = new Set([
22
24
  'adalah', 'bukan_adalah',
23
25
  ]);
24
26
 
27
+ const TYPES = new Set([
28
+ 'bulat', 'desimal', 'angka', 'teks', 'bool', 'logika', 'bytes',
29
+ 'Daftar', 'Kamus', 'Himpunan', 'Tupel', 'Opsi', 'Hasil', 'Fungsi', 'Unit', 'ApaSaja',
30
+ 'int', 'float', 'str', 'list', 'dict', 'set', 'tuple', 'List', 'Dict', 'Optional',
31
+ ]);
32
+
25
33
  const BUILTINS = new Set([
26
34
  'cetak', 'masukan', 'rentang', 'panjang', 'tipe', 'teks', 'angka', 'bulat',
27
35
  'desimal', 'tambah', 'hapus', 'urutkan', 'balik', 'gabung', 'pisah',
28
36
  'huruf_besar', 'huruf_kecil', 'potong', 'ganti', 'mengandung', 'acak',
29
37
  'akar', 'pangkat', 'mutlak', 'bulatkan', 'bawah', 'atas', 'min_nilai',
30
38
  'maks_nilai', 'jumlah', 'waktu_sekarang', 'tunggu', 'daftar', 'kamus',
39
+ 'panik', 'salin', 'bekukan', 'dari_kosong', 'ambil_indeks', 'ambil_kunci',
40
+ 'urai_bulat', 'urai_desimal', 'tambah_aman', 'kurang_aman', 'kali_aman', 'bagi_aman',
31
41
  'print', 'input', 'range', 'len', 'str', 'int', 'float', 'list', 'dict',
32
42
  'set', 'tuple', 'enumerate', 'zip', 'sum', 'min', 'max', 'abs', 'round',
33
43
  ]);
@@ -37,13 +47,17 @@ const MODULES = [
37
47
  'pola', 'koleksi', 'kripto', 'jaringan', 'uji',
38
48
  ];
39
49
 
40
- const CONSTANTS = ['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'];
50
+ const CONSTANTS = ['Benar', 'Salah', 'Kosong', 'Ada', 'TidakAda', 'Ok', 'Galat', 'True', 'False', 'None'];
41
51
 
42
52
  const COMPLETIONS = [
43
53
  ...Array.from(KEYWORDS, (label) => ({
44
54
  label,
45
55
  kind: CompletionItemKind.Keyword,
46
56
  })),
57
+ ...Array.from(TYPES, (label) => ({
58
+ label,
59
+ kind: CompletionItemKind.TypeParameter,
60
+ })),
47
61
  ...CONSTANTS.map((label) => ({
48
62
  label,
49
63
  kind: CompletionItemKind.Constant,
@@ -88,7 +102,7 @@ function collectSemanticTokens(text) {
88
102
  break;
89
103
  }
90
104
 
91
- const stringStart = /[fF]/.test(character) && /["']/.test(line[offset + 1])
105
+ const stringStart = /[fFrRbB]/.test(character) && /["']/.test(line[offset + 1])
92
106
  ? offset + 1
93
107
  : offset;
94
108
  if (line[stringStart] === '"' || line[stringStart] === "'") {
@@ -124,15 +138,17 @@ function collectSemanticTokens(text) {
124
138
  type = 'keyword';
125
139
  if (label === 'fungsi' || label === 'def') {
126
140
  pendingDeclaration = 'function';
127
- } else if (label === 'kelas' || label === 'class') {
141
+ } else if (label === 'kelas' || label === 'class' || label === 'struktur' || label === 'pilihan_tipe' || label === 'implementasi') {
128
142
  pendingDeclaration = 'type';
129
143
  }
130
144
  } else if (pendingDeclaration) {
131
145
  type = pendingDeclaration;
132
146
  pendingDeclaration = null;
147
+ } else if (TYPES.has(label)) {
148
+ type = 'type';
133
149
  } else if (BUILTINS.has(label)) {
134
150
  type = 'function';
135
- } else if (['Benar', 'Salah', 'Kosong', 'True', 'False', 'None'].includes(label)) {
151
+ } else if (CONSTANTS.includes(label)) {
136
152
  type = 'keyword';
137
153
  }
138
154
 
@@ -148,7 +164,7 @@ function collectSemanticTokens(text) {
148
164
  continue;
149
165
  }
150
166
 
151
- const number = line.slice(offset).match(/^\d+(?:\.\d+)?/);
167
+ const number = line.slice(offset).match(/^\d+(?:_\d+)*(?:\.\d+)?/);
152
168
  if (number) {
153
169
  tokens.push({
154
170
  line: lineNumber,
@@ -161,9 +177,9 @@ function collectSemanticTokens(text) {
161
177
  continue;
162
178
  }
163
179
 
164
- if (/[+\-*/%=<>!&|^~]/.test(character)) {
180
+ if (/[+\-*/%=<>!&|^~?.]/.test(character)) {
165
181
  let end = offset + 1;
166
- while (end < line.length && /[+\-*/%=<>!&|^~]/.test(line[end])) {
182
+ while (end < line.length && /[+\-*/%=<>!&|^~?.]/.test(line[end])) {
167
183
  end += 1;
168
184
  }
169
185
  tokens.push({
@@ -185,11 +201,35 @@ function collectSemanticTokens(text) {
185
201
  return tokens;
186
202
  }
187
203
 
188
- function getDiagnostics(text) {
189
- text = text.replace(/^\uFEFF/, '');
204
+ function getDiagnostics(text, filename = '<mhs>') {
190
205
  try {
191
- transpile(text);
192
- return [];
206
+ const result = analyzeSafety(text, { filename });
207
+ const lines = result.program.rawLines || text.split(/\r\n|\r|\n/);
208
+
209
+ return result.diagnostics.map((diag) => {
210
+ const lineIdx = Math.max(0, (diag.line || 1) - 1);
211
+ const lineText = lines[lineIdx] || '';
212
+ const startChar = Math.max(0, (diag.col || 1) - 1);
213
+ const endChar = Math.max(
214
+ startChar + 1,
215
+ Math.min(lineText.length || startChar + 1, (diag.endCol ? diag.endCol - 1 : startChar + 1))
216
+ );
217
+
218
+ let fullMessage = `[${diag.code}] ${diag.message}`;
219
+ if (diag.note) fullMessage += `\nCatatan: ${diag.note}`;
220
+ if (diag.hint) fullMessage += `\nBantuan: ${diag.hint}`;
221
+
222
+ return {
223
+ range: {
224
+ start: { line: lineIdx, character: startChar },
225
+ end: { line: lineIdx, character: endChar },
226
+ },
227
+ severity: diag.severity === 'warning' ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error,
228
+ code: diag.code,
229
+ source: 'mhs-rust-safety',
230
+ message: fullMessage,
231
+ };
232
+ });
193
233
  } catch (error) {
194
234
  if (!(error instanceof SyntaxError)) {
195
235
  throw error;
@@ -225,7 +265,7 @@ function createLanguageServer(
225
265
  capabilities: {
226
266
  textDocumentSync: TextDocumentSyncKind.Incremental,
227
267
  completionProvider: {
228
- triggerCharacters: ['.'],
268
+ triggerCharacters: ['.', '&'],
229
269
  },
230
270
  semanticTokensProvider: {
231
271
  legend,
@@ -237,14 +277,14 @@ function createLanguageServer(
237
277
  documents.onDidOpen(({ document }) => {
238
278
  connection.sendDiagnostics({
239
279
  uri: document.uri,
240
- diagnostics: getDiagnostics(document.getText()),
280
+ diagnostics: getDiagnostics(document.getText(), document.uri),
241
281
  });
242
282
  });
243
283
 
244
284
  documents.onDidChangeContent(({ document }) => {
245
285
  connection.sendDiagnostics({
246
286
  uri: document.uri,
247
- diagnostics: getDiagnostics(document.getText()),
287
+ diagnostics: getDiagnostics(document.getText(), document.uri),
248
288
  });
249
289
  });
250
290