mhs-lang 0.0.0-stage → 2.1.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 (52) hide show
  1. package/README.md +111 -2
  2. package/assets/logo.png +0 -0
  3. package/bin/mhs.js +177 -0
  4. package/examples/__pycache__/alat_py.cpython-312.pyc +0 -0
  5. package/examples/alat_py.py +7 -0
  6. package/examples/demo_lengkap.mhs +19 -0
  7. package/examples/halo.mhs +20 -0
  8. package/examples/python_native.mhs +16 -0
  9. package/examples/rumus_elektronika.mhs +10 -0
  10. package/examples/tes_semua_modul.mhs +48 -0
  11. package/examples/utama_impor.mhs +11 -0
  12. package/package.json +37 -4
  13. package/src/index.js +186 -0
  14. package/src/language_server.js +283 -0
  15. package/src/modules/berkas.js +19 -0
  16. package/src/modules/data_json.js +9 -0
  17. package/src/modules/index.js +29 -0
  18. package/src/modules/jaringan.js +28 -0
  19. package/src/modules/koleksi.js +43 -0
  20. package/src/modules/kripto.js +9 -0
  21. package/src/modules/matematika.js +55 -0
  22. package/src/modules/modul_acak.js +36 -0
  23. package/src/modules/pola.js +13 -0
  24. package/src/modules/sistem.js +13 -0
  25. package/src/modules/uji.js +52 -0
  26. package/src/modules/waktu.js +49 -0
  27. package/src/py_bridge.js +111 -0
  28. package/src/py_modules/__pycache__/berkas.cpython-312.pyc +0 -0
  29. package/src/py_modules/__pycache__/data_json.cpython-312.pyc +0 -0
  30. package/src/py_modules/__pycache__/jaringan.cpython-312.pyc +0 -0
  31. package/src/py_modules/__pycache__/koleksi.cpython-312.pyc +0 -0
  32. package/src/py_modules/__pycache__/kripto.cpython-312.pyc +0 -0
  33. package/src/py_modules/__pycache__/matematika.cpython-312.pyc +0 -0
  34. package/src/py_modules/__pycache__/modul_acak.cpython-312.pyc +0 -0
  35. package/src/py_modules/__pycache__/pola.cpython-312.pyc +0 -0
  36. package/src/py_modules/__pycache__/sistem.cpython-312.pyc +0 -0
  37. package/src/py_modules/__pycache__/uji.cpython-312.pyc +0 -0
  38. package/src/py_modules/__pycache__/waktu.cpython-312.pyc +0 -0
  39. package/src/py_modules/berkas.py +26 -0
  40. package/src/py_modules/data_json.py +14 -0
  41. package/src/py_modules/jaringan.py +15 -0
  42. package/src/py_modules/koleksi.py +24 -0
  43. package/src/py_modules/kripto.py +18 -0
  44. package/src/py_modules/matematika.py +30 -0
  45. package/src/py_modules/modul_acak.py +14 -0
  46. package/src/py_modules/pola.py +17 -0
  47. package/src/py_modules/sistem.py +11 -0
  48. package/src/py_modules/uji.py +39 -0
  49. package/src/py_modules/waktu.py +19 -0
  50. package/src/py_transpiler.js +231 -0
  51. package/src/stdlib.js +164 -0
  52. package/src/transpiler.js +401 -0
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="./assets/logo.png" alt="Logo mhs-lang" width="180" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # mhs-lang v2.1 (`.mhs`)
6
+
7
+ Bahasa pemrograman **Python dalam Bahasa Indonesia** yang bisa diunduh lewat `npm` dan dijalankan di IDE apa pun. Hadir dengan **Dual-Engine**:
8
+ 1. **Engine Node.js + Python Bridge** (`mhs file.mhs`): langsung jalan tanpa Python, tapi otomatis bisa memanggil modul `.py` / `pip` lewat `impor_py` atau `impor "./alat.py"`.
9
+ 2. **Engine Python 3 Native** (`mhs --py file.mhs`): mengubah `.mhs` ke Python 3 murni 1-on-1 sehingga mendukung **100% fitur & library Python asli** (`numpy`, `cv2`, `slicing`, `class`, `decorator`, `with`, dll.).
10
+
11
+ 📦 **[Unduh mhs-lang dari npm](https://www.npmjs.com/package/mhs-lang)**
12
+
13
+ ## 1. Cara Install & Menjalankan
14
+
15
+ Cara paling cepat tanpa instalasi permanen:
16
+
17
+ ```bash
18
+ npx --yes mhs-lang halo.mhs
19
+ ```
20
+
21
+ Atau pasang sekali agar perintah `mhs` bisa digunakan di mana saja:
22
+
23
+ ```bash
24
+ npm install -g mhs-lang
25
+ ```
26
+
27
+ Setelah itu, mulai proyek contoh dan jalankan:
28
+
29
+ ```bash
30
+ mhs init
31
+ mhs halo.mhs
32
+ ```
33
+
34
+ Untuk memakai Python 3 Native engine, jalankan `mhs --py halo.mhs`.
35
+
36
+ ### Dukungan IDE dan Language Server
37
+
38
+ Instalasi npm menyediakan perintah `mhs --lsp`, yaitu language server berbasis LSP untuk autocomplete, diagnostik sintaks, dan semantic highlighting. IDE yang mendukung LSP dapat menjalankannya melalui konfigurasi klien dengan:
39
+
40
+ ```text
41
+ Command: mhs
42
+ Arguments: --lsp
43
+ Transport: stdio
44
+ ```
45
+
46
+ Perintah `mhs --lsp` dijalankan oleh klien editor (bukan sebagai program interaktif di terminal).
47
+
48
+ Instalasi npm **tidak dapat memasang plugin, grammar, atau ikon secara otomatis ke semua IDE**. Setiap editor tetap memerlukan klien LSP, dan ikon file diatur oleh tema/plugin editor masing-masing.
49
+
50
+ - **VS Code dan Antigravity:** pasang ekstensi MHS Tools untuk grammar, ikon, tombol Run, dan koneksi LSP. Di Antigravity gunakan pemasangan VSIX/ekstensi jika tersedia pada versi yang dipakai.
51
+ - **JetBrains:** pasang plugin klien LSP seperti LSP4IJ, lalu daftarkan command `mhs` dengan argumen `--lsp`.
52
+ - **Sublime Text:** pasang paket LSP, lalu daftarkan command server `mhs --lsp`.
53
+ - **Vim/Neovim:** daftarkan filetype `.mhs` dan jalankan klien LSP dengan command `mhs` dan argumen `--lsp`.
54
+ - **Notepad++:** perlu plugin klien LSP pihak ketiga; dukungan warna dan ikon mengikuti plugin/tema yang dipakai.
55
+
56
+ Pada editor selain VS Code, tandai `*.mhs` sebagai file MHS dan aktifkan semantic tokens jika klien LSP menyediakan pengaturan itu. Tidak semua klien LSP menampilkan semantic tokens; warna sintaks dan ikon tetap bergantung pada grammar serta tema editor.
57
+
58
+ Tema ikon VS Code mempertahankan ikon Material, termasuk ikon `.py`, dan memakai PNG proyek untuk file `.mhs`. Untuk membangun dan memasang ekstensi dari repositori:
59
+
60
+ ```powershell
61
+ cd .\vscode-mhs-icons
62
+ npx --yes @vscode/vsce package
63
+ code --install-extension .\mhs-file-icons-1.3.0.vsix
64
+ ```
65
+
66
+ Ekstensi menghubungkan editor ke LSP saat file `.mhs` dibuka. Tombol ▶ menyimpan file lalu menjalankannya dengan `mhs --py`.
67
+ Untuk menampilkan ikon proyek, pilih tema **MHS + Material File Icons** pada perintah **File: Preferences → File Icon Theme**.
68
+
69
+ ### Cara Publish ke npm:
70
+ ```bash
71
+ npm login
72
+ npm publish --access public
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 2. Daftar 11 Modul Standar Bahasa Indonesia
78
+
79
+ Semua modul berikut dapat langsung diimpor baik di mode Node.js (`mhs`) maupun mode Python 3 Native (`mhs --py`):
80
+
81
+ | Modul `.mhs` | Padanan Python | Fungsi Utama |
82
+ | :--- | :--- | :--- |
83
+ | `matematika` | `math` | `pi`, `e`, `akar`, `pangkat`, `sin`, `cos`, `tan`, `log`, `faktorial`, `fpb`, `kpk`, `derajat`, `radian` |
84
+ | `modul_acak` | `random` | `bulat`, `desimal`, `pilih`, `sampel`, `kocok` |
85
+ | `waktu` | `time` / `datetime` | `sekarang`, `tidur`, `tanggal_sekarang`, `jam_sekarang`, `info_waktu` |
86
+ | `berkas` | `os` / `pathlib` | `baca`, `tulis`, `tambah_isi`, `ada`, `hapus`, `daftar_isi`, `buat_folder`, `gabung_jalur` |
87
+ | `sistem` | `sys` / `platform` | `argumen`, `platform`, `arsitektur`, `lingkungan`, `keluar` |
88
+ | `data_json` | `json` | `urai`, `ubah_ke_teks`, `baca_berkas`, `tulis_berkas` |
89
+ | `pola` | `re` | `cocok`, `cari`, `cari_semua`, `ganti`, `pisah` |
90
+ | `koleksi` | `collections` / `statistics` | `hitung`, `unik`, `rata_rata`, `median`, `pasangkan`, `kelompokkan` |
91
+ | `kripto` | `hashlib` / `base64` | `sha256`, `md5`, `acak_hex`, `encode_base64`, `decode_base64` |
92
+ | `jaringan` | `urllib` | `urai_url`, `ambil` |
93
+ | `uji` | `unittest` | `sama`, `benar`, `salah`, `lempar_galat`, `ringkasan` |
94
+
95
+ ---
96
+
97
+ ## 3. Kamus Sintaks `.mhs` vs Python
98
+
99
+ | Python Asli | Sintaks `.mhs` |
100
+ | :--- | :--- |
101
+ | `print(...)` / `input(...)` | `cetak(...)` / `masukan(...)` |
102
+ | `if` / `elif` / `else` | `jika` / `atau_jika` / `selain_itu` |
103
+ | `for x in col:` / `while cond:` | `untuk x dalam col:` / `selama cond:` |
104
+ | `def fn(a):` / `return` | `fungsi fn(a):` / `kembalikan` |
105
+ | `class Foo:` / `self` | `kelas Foo:` / `diri` |
106
+ | `try:` / `except Exception as e:` / `finally:` | `coba:` / `tangkap e:` / `akhirnya:` |
107
+ | `raise Exception(...)` / `assert` | `lempar ...` / `pastikan` |
108
+ | `import mod as alias` / `from mod import x` | `impor mod sebagai alias` / `dari mod impor x` |
109
+ | `True` / `False` / `None` | `Benar` / `Salah` / `Kosong` |
110
+ | `and` / `or` / `not` / `in` | `dan` / `atau` / `bukan` / `dalam` |
111
+ | `break` / `continue` / `pass` | `berhenti` / `lanjut` / `lewat` |
112
+ | `[x*2 for x in range(5)]` | `[x*2 untuk x dalam rentang(5)]` |
Binary file
package/bin/mhs.js ADDED
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const readline = require('readline');
6
+ const { transpile, transpileToPython, runCode, runFile } = require('../src/index');
7
+ const pkg = require('../package.json');
8
+
9
+ function printHelp() {
10
+ console.log(`
11
+ mhs-lang v${pkg.version} — Bahasa pemrograman Python dalam Bahasa Indonesia (.mhs)
12
+
13
+ Penggunaan:
14
+ mhs <file.mhs> Menjalankan .mhs (Otomatis Native Python 3 jika tersedia, fallback ke Node.js)
15
+ mhs --py <file.mhs> Memaksa eksekusi dengan Engine Python 3 Native
16
+ mhs --node <file.mhs> Memaksa eksekusi dengan Engine Node.js
17
+ mhs run <file.mhs> Menjalankan .mhs
18
+ mhs --emit-py <file.mhs> Menampilkan hasil konversi ke Python 3 (.py)
19
+ mhs --js <file.mhs> Menampilkan hasil konversi ke JavaScript
20
+ mhs --lsp Menjalankan language server untuk editor berklien LSP
21
+ mhs init Membuat contoh halo.mhs & konfigurasi VS Code
22
+ mhs Membuka mode interaktif (REPL)
23
+ mhs --version, -v Menampilkan versi
24
+ mhs --help, -h Menampilkan bantuan ini
25
+ `);
26
+ }
27
+
28
+ function initProject() {
29
+ const samplePath = path.join(process.cwd(), 'halo.mhs');
30
+ if (!fs.existsSync(samplePath)) {
31
+ fs.writeFileSync(
32
+ samplePath,
33
+ `# Program pertama menggunakan bahasa .mhs
34
+ nama = "Mahes"
35
+ cetak(f"Halo, {nama}! Selamat datang di bahasa pemrograman .mhs")
36
+
37
+ fungsi hitung_luas_persegi(sisi):
38
+ kembalikan sisi * sisi
39
+
40
+ untuk i dalam rentang(1, 5):
41
+ cetak(f"Luas persegi sisi {i} = {hitung_luas_persegi(i)}")
42
+ `,
43
+ 'utf8'
44
+ );
45
+ console.log('Berhasil membuat halo.mhs');
46
+ }
47
+
48
+ const vscodeDir = path.join(process.cwd(), '.vscode');
49
+ const tasksPath = path.join(vscodeDir, 'tasks.json');
50
+ if (!fs.existsSync(tasksPath)) {
51
+ fs.mkdirSync(vscodeDir, { recursive: true });
52
+ fs.writeFileSync(
53
+ tasksPath,
54
+ JSON.stringify(
55
+ {
56
+ version: '2.0.0',
57
+ tasks: [
58
+ {
59
+ label: 'Jalankan File .mhs',
60
+ type: 'shell',
61
+ command: 'npx mhs-lang "${file}"',
62
+ group: {
63
+ kind: 'build',
64
+ isDefault: true,
65
+ },
66
+ presentation: {
67
+ reveal: 'always',
68
+ panel: 'shared',
69
+ },
70
+ },
71
+ ],
72
+ },
73
+ null,
74
+ 2
75
+ ),
76
+ 'utf8'
77
+ );
78
+ console.log('Berhasil membuat .vscode/tasks.json (tekan Ctrl+Shift+B di VS Code untuk menjalankan file .mhs)');
79
+ }
80
+ }
81
+
82
+ function startRepl() {
83
+ console.log(`mhs-lang v${pkg.version} (Mode Interaktif). Ketik "keluar" untuk berhenti.`);
84
+ const rl = readline.createInterface({
85
+ input: process.stdin,
86
+ output: process.stdout,
87
+ prompt: 'mhs> ',
88
+ });
89
+ rl.prompt();
90
+ rl.on('line', (line) => {
91
+ const trimmed = line.trim();
92
+ if (trimmed === 'keluar' || trimmed === 'exit') {
93
+ rl.close();
94
+ return;
95
+ }
96
+ if (trimmed) {
97
+ try {
98
+ runCode(trimmed, '<repl>');
99
+ } catch (err) {
100
+ console.error('Kesalahan:', err.message);
101
+ }
102
+ }
103
+ rl.prompt();
104
+ });
105
+ }
106
+
107
+ function main() {
108
+ const args = process.argv.slice(2);
109
+
110
+ if (args.length === 0) {
111
+ startRepl();
112
+ return;
113
+ }
114
+
115
+ const cmd = args[0];
116
+
117
+ if (cmd === '--help' || cmd === '-h') {
118
+ printHelp();
119
+ return;
120
+ }
121
+
122
+ if (cmd === '--version' || cmd === '-v') {
123
+ console.log(pkg.version);
124
+ return;
125
+ }
126
+
127
+ if (cmd === '--lsp') {
128
+ require('../src/language_server').createLanguageServer();
129
+ return;
130
+ }
131
+
132
+ if (cmd === 'init') {
133
+ initProject();
134
+ return;
135
+ }
136
+
137
+ if (cmd === '--js' || cmd === '--emit-py') {
138
+ const target = args[1];
139
+ if (!target) {
140
+ console.error(`Kesalahan: Harap sertakan nama file .mhs. Contoh: mhs ${cmd} halo.mhs`);
141
+ process.exit(1);
142
+ }
143
+ const source = fs.readFileSync(path.resolve(target), 'utf8');
144
+ console.log(cmd === '--emit-py' ? transpileToPython(source) : transpile(source));
145
+ return;
146
+ }
147
+
148
+ if (cmd === '--py' || cmd === '--node') {
149
+ const target = args[1];
150
+ if (!target) {
151
+ console.error(`Kesalahan: Harap sertakan nama file .mhs. Contoh: mhs ${cmd} halo.mhs`);
152
+ process.exit(1);
153
+ }
154
+ try {
155
+ runFile(target, { engine: cmd === '--py' ? 'py' : 'node' });
156
+ } catch (err) {
157
+ console.error(`[MHS Error] ${err.message}`);
158
+ process.exit(1);
159
+ }
160
+ return;
161
+ }
162
+
163
+ const fileTarget = cmd === 'run' ? args[1] : cmd;
164
+ if (!fileTarget) {
165
+ printHelp();
166
+ process.exit(1);
167
+ }
168
+
169
+ try {
170
+ runFile(fileTarget, { engine: 'auto' });
171
+ } catch (err) {
172
+ console.error(`[MHS Error] ${err.message}`);
173
+ process.exit(1);
174
+ }
175
+ }
176
+
177
+ main();
@@ -0,0 +1,7 @@
1
+ # Modul Python asli (.py) yang bisa diimpor oleh .mhs
2
+ def sapa_python(nama):
3
+ return f"Halo {nama}, ini pesan langsung dari Python!"
4
+
5
+ def hitung_frekuensi_rc(r_ohm, c_farad):
6
+ import math
7
+ return round(1 / (2 * math.pi * r_ohm * c_farad), 2)
@@ -0,0 +1,19 @@
1
+ # Demo Lengkap mhs-lang v2.0 (Bisa dijalankan di mode Node.js maupun `mhs --py`)
2
+ impor_py "math" sebagai m_py
3
+ dari "./rumus_elektronika.mhs" impor hitung_arus
4
+ impor "./alat_py.py" sebagai alat
5
+
6
+ # 1. List comprehension ala Python
7
+ kuadrat = [x * x untuk x dalam rentang(1, 6)]
8
+ cetak("Kuadrat 1..5:", kuadrat)
9
+
10
+ # 2. Memanggil fungsi Python asli dari .mhs
11
+ cetak(alat.sapa_python("Mahes"))
12
+ cetak("Akar 144 via Python math:", m_py.sqrt(144))
13
+
14
+ # 3. Memanggil modul .mhs lain
15
+ cetak("Arus 12V / 4 Ohm:", hitung_arus(12, 4), "A")
16
+
17
+ # 4. Penanganan error & pastikan
18
+ pastikan panjang(kuadrat) == 5, "Panjang harus 5"
19
+ cetak("Semua fitur berjalan lancar!")
@@ -0,0 +1,20 @@
1
+ # Contoh Program .mhs (Python Bahasa Indonesia)
2
+ nama = "Maheswara"
3
+ jurusan = "Teknik Mekatronika"
4
+
5
+ cetak(f"Halo! Saya {nama} dari jurusan {jurusan}.")
6
+
7
+ fungsi hitung_hambatan_seri(daftar_resistor):
8
+ total = 0
9
+ untuk r dalam daftar_resistor:
10
+ total = total + r
11
+ kembalikan total
12
+
13
+ resistor = [220, 470, 1000]
14
+ total_r = hitung_hambatan_seri(resistor)
15
+ cetak(f"Total hambatan seri: {total_r} Ohm")
16
+
17
+ jika total_r > 1000:
18
+ cetak("Status: Hambatan di atas 1 kOhm")
19
+ selain_itu:
20
+ cetak("Status: Hambatan di bawah atau sama dengan 1 kOhm")
@@ -0,0 +1,16 @@
1
+ # Contoh penggunaan library Python secara NATIVE langsung di .mhs
2
+ impor math sebagai m
3
+ impor json
4
+ impor statistics sebagai stat
5
+ dari datetime impor datetime
6
+ dari pathlib impor Path
7
+ impor "./alat_py.py" sebagai alat
8
+
9
+ # Library Python standar berjalan langsung secara native
10
+ data = [10, 20, 30, 40, 50]
11
+ cetak("Rata-rata (statistics.mean):", stat.mean(data))
12
+ cetak("Akar 256 (math.sqrt):", m.sqrt(256))
13
+ cetak("JSON:", json.dumps({"bahasa": "mhs", "native_python": Benar}))
14
+ cetak("Tahun sekarang (datetime):", datetime.now().year)
15
+ cetak("Ekstensi file (pathlib.Path):", Path("proyek/utama.mhs").suffix)
16
+ cetak(alat.sapa_python("Mahes"))
@@ -0,0 +1,10 @@
1
+ # Modul rumus elektronika dalam bahasa .mhs
2
+ tegang_baterai = 12
3
+
4
+ fungsi hitung_arus(tegangan, hambatan):
5
+ jika hambatan == 0:
6
+ lempar "Hambatan tidak boleh nol"
7
+ kembalikan tegangan / hambatan
8
+
9
+ fungsi hitung_daya(tegangan, arus):
10
+ kembalikan tegangan * arus
@@ -0,0 +1,48 @@
1
+ # Uji Kelengkapan Semua Modul Bahasa Indonesia di mhs-lang
2
+ impor matematika
3
+ impor modul_acak
4
+ impor waktu
5
+ impor berkas
6
+ impor sistem
7
+ impor data_json
8
+ impor pola
9
+ impor koleksi
10
+ impor kripto
11
+ impor jaringan
12
+ impor uji
13
+
14
+ # 1. Matematika
15
+ uji.sama(matematika.fpb(12, 18), 6)
16
+ uji.sama(matematika.faktorial(5), 120)
17
+
18
+ # 2. Modul Acak
19
+ angka_acak = modul_acak.bulat(1, 10)
20
+ uji.benar(angka_acak >= 1 dan angka_acak <= 10)
21
+
22
+ # 3. Waktu & Sistem
23
+ uji.benar(panjang(waktu.tanggal_sekarang()) == 10)
24
+ uji.benar(panjang(sistem.platform()) > 0)
25
+
26
+ # 4. Data JSON & Pola (Regex)
27
+ teks_json = data_json.ubah_ke_teks({"bahasa": "mhs", "versi": 2})
28
+ obj = data_json.urai(teks_json)
29
+ uji.sama(obj["bahasa"], "mhs")
30
+ uji.sama(pola.cari_semua("[0-9]+", "v2 tahun 2026"), ["2", "2026"])
31
+
32
+ # 5. Koleksi
33
+ uji.sama(koleksi.rata_rata([10, 20, 30]), 20)
34
+ uji.sama(koleksi.unik([1, 2, 2, 3]), [1, 2, 3])
35
+
36
+ # 6. Kripto & Jaringan (URL parser)
37
+ b64 = kripto.encode_base64("mhs")
38
+ uji.sama(kripto.decode_base64(b64), "mhs")
39
+ url_info = jaringan.urai_url("https://contoh.id/belajar?lang=mhs")
40
+ uji.sama(url_info["host"], "contoh.id")
41
+
42
+ # 7. Berkas (tulis, baca, hapus)
43
+ jalur_tmp = berkas.gabung_jalur(berkas.folder_kerja(), "_uji_mhs_tmp.txt")
44
+ berkas.tulis(jalur_tmp, "Halo .mhs!")
45
+ uji.sama(berkas.baca(jalur_tmp), "Halo .mhs!")
46
+ berkas.hapus(jalur_tmp)
47
+
48
+ cetak("Ringkasan uji semua modul:", uji.ringkasan())
@@ -0,0 +1,11 @@
1
+ # Contoh Program Utama yang mengimpor modul .mhs lain dan modul sistem
2
+ dari "./rumus_elektronika.mhs" impor hitung_arus, hitung_daya, tegang_baterai
3
+ impor sistem
4
+
5
+ r = 24
6
+ arus = hitung_arus(tegang_baterai, r)
7
+ daya = hitung_daya(tegang_baterai, arus)
8
+
9
+ cetak(f"Berjalan di sistem: {sistem.platform()}")
10
+ cetak(f"Tegangan: {tegang_baterai}V, Hambatan: {r} Ohm")
11
+ cetak(f"Arus: {arus} A, Daya: {daya} Watt")
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "mhs-lang",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.1.0",
4
+ "description": "Bahasa pemrograman Python dalam Bahasa Indonesia (.mhs) dengan dual-engine Node.js + Python 3 native, dukungan impor .mhs, npm, dan modul Python (.py/pip).",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "mhs": "bin/mhs.js",
8
+ "mhs-lang": "bin/mhs.js"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "assets/",
14
+ "examples/",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "test": "node test/run_tests.js"
19
+ },
20
+ "keywords": [
21
+ "bahasa-pemrograman",
22
+ "indonesia",
23
+ "python-indonesia",
24
+ "mhs",
25
+ "transpiler",
26
+ "cli",
27
+ "python",
28
+ "nodejs"
29
+ ],
30
+ "author": "Maheswara",
31
+ "license": "MIT",
32
+ "engines": {
33
+ "node": ">=16.0.0"
34
+ },
35
+ "dependencies": {
36
+ "vscode-languageserver": "^9.0.1",
37
+ "vscode-languageserver-textdocument": "^1.0.12"
38
+ }
39
+ }
package/src/index.js ADDED
@@ -0,0 +1,186 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const vm = require('vm');
5
+ const Module = require('module');
6
+ const { execFileSync } = require('child_process');
7
+ const { transpile } = require('./transpiler');
8
+ const { transpileToPython } = require('./py_transpiler');
9
+ const { importPythonModule } = require('./py_bridge');
10
+ const { stdlib } = require('./stdlib');
11
+ const { STD_MODULES } = require('./modules/index');
12
+
13
+ let _hasPythonCache = null;
14
+ function getPythonCommand() {
15
+ return process.platform === 'win32' ? 'python' : 'python3';
16
+ }
17
+
18
+ function hasPython3() {
19
+ if (_hasPythonCache !== null) return _hasPythonCache;
20
+ try {
21
+ execFileSync(getPythonCommand(), ['--version'], { stdio: 'ignore' });
22
+ _hasPythonCache = true;
23
+ } catch {
24
+ _hasPythonCache = false;
25
+ }
26
+ return _hasPythonCache;
27
+ }
28
+
29
+ function resolveMhsModule(target, baseDir) {
30
+ const candidates = [];
31
+ if (target.endsWith('.mhs')) {
32
+ candidates.push(path.resolve(baseDir, target));
33
+ } else {
34
+ candidates.push(path.resolve(baseDir, `${target}.mhs`));
35
+ candidates.push(path.resolve(baseDir, target, 'index.mhs'));
36
+ }
37
+ for (const cand of candidates) {
38
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) {
39
+ return cand;
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ function resolvePyFile(target, baseDir) {
46
+ if (target.endsWith('.py')) {
47
+ const cand = path.resolve(baseDir, target);
48
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) return cand;
49
+ }
50
+ const candPy = path.resolve(baseDir, `${target}.py`);
51
+ if (fs.existsSync(candPy) && fs.statSync(candPy).isFile()) return candPy;
52
+ return null;
53
+ }
54
+
55
+ function createImporter(baseDir, moduleCache) {
56
+ const localRequire = Module.createRequire(path.join(baseDir, 'index.js'));
57
+
58
+ return function __mhs_impor(target) {
59
+ const mhsPath = resolveMhsModule(target, baseDir);
60
+ if (mhsPath) {
61
+ if (moduleCache.has(mhsPath)) {
62
+ return moduleCache.get(mhsPath);
63
+ }
64
+ const exportsPlaceholder = {};
65
+ moduleCache.set(mhsPath, exportsPlaceholder);
66
+ const source = fs.readFileSync(mhsPath, 'utf8');
67
+ const { exports } = executeMhs(source, mhsPath, moduleCache);
68
+ Object.assign(exportsPlaceholder, exports);
69
+ return exportsPlaceholder;
70
+ }
71
+
72
+ if (Object.prototype.hasOwnProperty.call(STD_MODULES, target)) {
73
+ return STD_MODULES[target];
74
+ }
75
+
76
+ const pyPath = resolvePyFile(target, baseDir);
77
+ if (pyPath) {
78
+ return importPythonModule(pyPath, baseDir);
79
+ }
80
+
81
+ try {
82
+ return localRequire(target);
83
+ } catch (err) {
84
+ try {
85
+ return importPythonModule(target, baseDir);
86
+ } catch (pyErr) {
87
+ throw new Error(`Modul "${target}" tidak ditemukan sebagai modul standar .mhs, file lokal, paket npm/Node.js, maupun modul Python.`);
88
+ }
89
+ }
90
+ };
91
+ }
92
+
93
+ function executeMhs(source, filename = '<mhs>', moduleCache = new Map()) {
94
+ const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
95
+ const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
96
+
97
+ const jsCode = transpile(source);
98
+ const context = {
99
+ ...stdlib,
100
+ __mhs_impor: createImporter(baseDir, moduleCache),
101
+ __mhs_impor_py: (modName) => importPythonModule(modName, baseDir),
102
+ __mhs_exports__: {},
103
+ console,
104
+ Math,
105
+ JSON,
106
+ Date,
107
+ Array,
108
+ Object,
109
+ String,
110
+ Number,
111
+ Boolean,
112
+ Error,
113
+ __filename: absFilename,
114
+ __dirname: baseDir,
115
+ };
116
+ vm.createContext(context);
117
+ const result = vm.runInContext(jsCode, context, { filename: absFilename });
118
+ return { result, exports: context.__mhs_exports__ };
119
+ }
120
+
121
+ function runCode(source, filename = '<mhs>') {
122
+ return executeMhs(source, filename).result;
123
+ }
124
+
125
+ function runFile(filePath, { engine = 'auto' } = {}) {
126
+ const absPath = path.resolve(filePath);
127
+ if (!fs.existsSync(absPath)) {
128
+ throw new Error(`File tidak ditemukan: ${absPath}`);
129
+ }
130
+ const source = fs.readFileSync(absPath, 'utf8');
131
+
132
+ if (engine === 'py' || (engine === 'auto' && hasPython3())) {
133
+ return runPyCode(source, absPath);
134
+ }
135
+ return runCode(source, absPath);
136
+ }
137
+
138
+ function runPyCode(source, filename = '<mhs>') {
139
+ const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
140
+ const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
141
+ const pyModulesDir = path.resolve(__dirname, 'py_modules');
142
+
143
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mhs-py-'));
144
+ try {
145
+ if (fs.existsSync(baseDir)) {
146
+ for (const entry of fs.readdirSync(baseDir)) {
147
+ if (entry.endsWith('.mhs')) {
148
+ const mhsSrc = fs.readFileSync(path.join(baseDir, entry), 'utf8');
149
+ const pyOut = transpileToPython(mhsSrc);
150
+ const pyName = entry.replace(/\.mhs$/i, '.py');
151
+ fs.writeFileSync(path.join(tmpDir, pyName), pyOut, 'utf8');
152
+ }
153
+ }
154
+ }
155
+
156
+ const pyCode = transpileToPython(source);
157
+ const pythonCmd = getPythonCommand();
158
+ const env = {
159
+ ...process.env,
160
+ PYTHONPATH: [tmpDir, pyModulesDir, baseDir, process.env.PYTHONPATH || ''].filter(Boolean).join(path.delimiter),
161
+ };
162
+ return execFileSync(pythonCmd, ['-c', pyCode], {
163
+ cwd: baseDir,
164
+ env,
165
+ stdio: 'inherit',
166
+ });
167
+ } finally {
168
+ fs.rmSync(tmpDir, { recursive: true, force: true });
169
+ }
170
+ }
171
+
172
+ function runPyFile(filePath) {
173
+ return runFile(filePath, { engine: 'py' });
174
+ }
175
+
176
+ module.exports = {
177
+ transpile,
178
+ transpileToPython,
179
+ runCode,
180
+ runFile,
181
+ runPyCode,
182
+ runPyFile,
183
+ hasPython3,
184
+ stdlib,
185
+ STD_MODULES,
186
+ };