1use regex::Regex;
2use std::collections::HashSet;
3
4#[cfg(feature = "wasm")]
5use wasm_bindgen::prelude::*;
6
7pub struct IsEngine;
10
11impl IsEngine {
12 pub fn compile(source: &str) -> String {
13 compile_is(source)
14 }
15}
16
17#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = compile))]
19pub fn compile_is(source: &str) -> String {
20 let mut js = String::new();
21 let mut reactive_vars = HashSet::new();
22
23 js.push_str("/* === Indonesian Script (.is) Compiled Output === */\n");
25 js.push_str("(function() {\n");
26
27 js.push_str(r#"
29 // Core Runtime Indonesian Script (.is)
30 if (!window.__IS_RUNTIME__) {
31 window.__IS_RUNTIME__ = true;
32 window.__IS_STATE__ = window.__IS_STATE__ || {};
33 window.__IS_LISTENERS__ = window.__IS_LISTENERS__ || {};
34
35 window.__IS_PROXY__ = new Proxy(window.__IS_STATE__, {
36 set(target, prop, value) {
37 target[prop] = value;
38 // Auto update DOM elements bound to this state
39 document.querySelectorAll(`[is-bind="${prop}"], [is-text="${prop}"], [is-model="${prop}"]`).forEach(el => {
40 if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT') {
41 if (el.value != value) el.value = value;
42 } else {
43 el.textContent = value;
44 }
45 });
46 document.querySelectorAll(`[is-show="${prop}"]`).forEach(el => {
47 el.style.display = value ? '' : 'none';
48 });
49 if (window.__IS_LISTENERS__[prop]) {
50 window.__IS_LISTENERS__[prop].forEach(fn => fn(value));
51 }
52 return true;
53 },
54 get(target, prop) {
55 return target[prop];
56 }
57 });
58
59 // Auto setup DOM listeners for input bindings (is-model / is-bind)
60 document.addEventListener('input', function(e) {
61 const modelAttr = e.target.getAttribute('is-model') || e.target.getAttribute('is-bind');
62 if (modelAttr) {
63 window.__IS_PROXY__[modelAttr] = e.target.value;
64 }
65 });
66
67 // Auto setup AJAX / Action attributes (is-jupuk, is-kirim, is-click)
68 document.addEventListener('click', async function(e) {
69 const btn = e.target.closest('[is-jupuk], [is-ambil], [is-kirim], [is-click]');
70 if (!btn) return;
71
72 const jupukUrl = btn.getAttribute('is-jupuk') || btn.getAttribute('is-ambil');
73 const kirimUrl = btn.getAttribute('is-kirim');
74 const targetSel = btn.getAttribute('is-target');
75
76 if (jupukUrl) {
77 e.preventDefault();
78 try {
79 const res = await fetch(jupukUrl);
80 const text = await res.text();
81 if (targetSel) {
82 const targetEl = document.querySelector(targetSel);
83 if (targetEl) targetEl.innerHTML = text;
84 }
85 } catch (err) {
86 console.error('[IndonesianScript] Error fetching:', err);
87 }
88 } else if (kirimUrl) {
89 e.preventDefault();
90 const form = btn.closest('form');
91 const data = form ? Object.fromEntries(new FormData(form)) : {};
92 try {
93 const res = await fetch(kirimUrl, {
94 method: 'POST',
95 headers: { 'Content-Type': 'application/json' },
96 body: JSON.stringify(data)
97 });
98 const text = await res.text();
99 if (targetSel) {
100 const targetEl = document.querySelector(targetSel);
101 if (targetEl) targetEl.innerHTML = text;
102 }
103 } catch (err) {
104 console.error('[IndonesianScript] Error posting:', err);
105 }
106 }
107 });
108 }
109 const $state = window.__IS_PROXY__;
110"#);
111
112 let re_reaktif = Regex::new(r#"(?m)^\s*(reaktif|state)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(.*?);"#).unwrap();
113 let mut processed_source = source.to_string();
114 let mut decl_replacements = Vec::new();
115
116 for caps in re_reaktif.captures_iter(source) {
118 let var_name = caps[2].to_string();
119 let initial_val = caps[3].to_string();
120 reactive_vars.insert(var_name.clone());
121
122 let placeholder = format!("__IS_STATE_DECL_{}__;", var_name);
123 let final_decl = format!(
124 "/* [Indonesian Script] State Reaktif: {} */\n $state.{} = {};\n let {} = $state.{};",
125 var_name, var_name, initial_val, var_name, var_name
126 );
127 decl_replacements.push((placeholder.clone(), final_decl));
128
129 processed_source = processed_source.replace(&caps[0], &placeholder);
130 }
131
132 let re_else_if = Regex::new(r"\b(selain_itu\s+jika|utawa\s+yen)\b").unwrap();
136 processed_source = re_else_if.replace_all(&processed_source, "else if").to_string();
137
138 let re_else = Regex::new(r"\b(selain_itu|liyane)\b").unwrap();
140 processed_source = re_else.replace_all(&processed_source, "else").to_string();
141
142 let re_if = Regex::new(r"\b(jika|kalau|yen)\b").unwrap();
144 processed_source = re_if.replace_all(&processed_source, "if").to_string();
145
146 let re_fungsi = Regex::new(r"\b(fungsi|pranata|tugas)\b").unwrap();
148 processed_source = re_fungsi.replace_all(&processed_source, "function").to_string();
149
150 let re_kembalikan = Regex::new(r"\b(kembalikan|balekno)\b").unwrap();
152 processed_source = re_kembalikan.replace_all(&processed_source, "return").to_string();
153
154 let re_selama = Regex::new(r"\b(selama|suwene)\b").unwrap();
156 processed_source = re_selama.replace_all(&processed_source, "while").to_string();
157
158 let re_untuk = Regex::new(r"\b(untuk|kanggo)\b").unwrap();
160 processed_source = re_untuk.replace_all(&processed_source, "for").to_string();
161
162 let re_berhenti = Regex::new(r"\b(berhenti|mandek)\b").unwrap();
164 processed_source = re_berhenti.replace_all(&processed_source, "break").to_string();
165
166 let re_lanjut = Regex::new(r"\b(lanjut|terusno)\b").unwrap();
168 processed_source = re_lanjut.replace_all(&processed_source, "continue").to_string();
169
170 let re_benar = Regex::new(r"\b(benar|bener)\b").unwrap();
172 processed_source = re_benar.replace_all(&processed_source, "true").to_string();
173
174 let re_salah = Regex::new(r"\b(salah|kliru)\b").unwrap();
176 processed_source = re_salah.replace_all(&processed_source, "false").to_string();
177
178 let re_kosong = Regex::new(r"\b(kosong|suwung)\b").unwrap();
180 processed_source = re_kosong.replace_all(&processed_source, "null").to_string();
181
182 let re_cetak = Regex::new(r"\b(dudohno|cetak|tulis)\s*\(").unwrap();
187 processed_source = re_cetak.replace_all(&processed_source, "console.log(/* [Indonesian Script: cetak/dudohno] */ ").to_string();
188
189 let re_jupuk = Regex::new(r"\b(jupuk|ambil)\s*\(\s*([^)]+)\s*\)").unwrap();
191 processed_source = re_jupuk.replace_all(&processed_source, "(await fetch($2).then(r => r.json()))").to_string();
192
193 let re_kirim = Regex::new(r"\b(kirim|kirimkan)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
195 processed_source = re_kirim.replace_all(&processed_source, "(await fetch($2, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify($3) }).then(r => r.json()))").to_string();
196
197 for var_name in &reactive_vars {
199 let re_assign = Regex::new(&format!(r"\b{}\s*=\s*([^;]+);", regex::escape(var_name))).unwrap();
200 let replacement = format!("$state.{} = $1;", var_name);
201 processed_source = re_assign.replace_all(&processed_source, &replacement).to_string();
202 }
203
204 for (placeholder, final_decl) in decl_replacements {
206 processed_source = processed_source.replace(&placeholder, &final_decl);
207 }
208
209 let re_pilih = Regex::new(r"\b(siji|pilih)\s*\(\s*([^)]+)\s*\)").unwrap();
211 processed_source = re_pilih.replace_all(&processed_source, "document.querySelector($2)").to_string();
212
213 let re_pilih_semua = Regex::new(r"\b(kabeh|pilihSemua)\s*\(\s*([^)]+)\s*\)").unwrap();
215 processed_source = re_pilih_semua.replace_all(&processed_source, "document.querySelectorAll($2)").to_string();
216
217 let re_saat = Regex::new(r"\b(saat|ketika)\s*\(\s*([^,]+)\s*,\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
219 processed_source = re_saat.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2)?.addEventListener($3, $4)").to_string();
220
221 let re_ganti_html = Regex::new(r"\b(gantiHtml|tumpuk)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
223 processed_source = re_ganti_html.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).innerHTML = $3").to_string();
224
225 let re_umpet = Regex::new(r"\b(sembunyikan|umpetno)\s*\(\s*([^)]+)\s*\)").unwrap();
227 processed_source = re_umpet.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).style.display = 'none'").to_string();
228
229 let re_tampil = Regex::new(r"\b(tampilkan|tuduhno)\s*\(\s*([^)]+)\s*\)").unwrap();
231 processed_source = re_tampil.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).style.display = ''").to_string();
232
233 let re_peringatan = Regex::new(r"\b(peringatan|elingno)\s*\(").unwrap();
235 processed_source = re_peringatan.replace_all(&processed_source, "alert(").to_string();
236
237 let re_konfirmasi = Regex::new(r"\b(konfirmasi|takon)\s*\(").unwrap();
238 processed_source = re_konfirmasi.replace_all(&processed_source, "confirm(").to_string();
239
240 let re_masukan = Regex::new(r"\b(masukan|jaluk)\s*\(").unwrap();
241 processed_source = re_masukan.replace_all(&processed_source, "prompt(").to_string();
242
243 let re_tunggu = Regex::new(r"\btunggu\s*\(\s*([^)]+)\s*\)").unwrap();
245 processed_source = re_tunggu.replace_all(&processed_source, "(await new Promise(r => setTimeout(r, $1)))").to_string();
246
247 let re_setiap = Regex::new(r"\b(setiap|saben)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
248 processed_source = re_setiap.replace_all(&processed_source, "setInterval($3, $2)").to_string();
249
250 let re_nanti = Regex::new(r"\b(nanti|mengko)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
251 processed_source = re_nanti.replace_all(&processed_source, "setTimeout($3, $2)").to_string();
252
253 let re_salin = Regex::new(r"\b(salin|salinTeks)\s*\(\s*([^)]+)\s*\)").unwrap();
255 processed_source = re_salin.replace_all(&processed_source, "navigator.clipboard?.writeText($2)").to_string();
256
257 let re_simpan = Regex::new(r"\b(simpan|simpen)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
258 processed_source = re_simpan.replace_all(&processed_source, "localStorage.setItem($2, JSON.stringify($3))").to_string();
259
260 let re_ambil_penyimpanan = Regex::new(r"\b(ambilPenyimpanan|jupukSimpenan)\s*\(\s*([^)]+)\s*\)").unwrap();
261 processed_source = re_ambil_penyimpanan.replace_all(&processed_source, "JSON.parse(localStorage.getItem($2) || 'null')").to_string();
262
263 let re_hapus_penyimpanan = Regex::new(r"\b(hapusPenyimpanan|busakSimpenan)\s*\(\s*([^)]+)\s*\)").unwrap();
264 processed_source = re_hapus_penyimpanan.replace_all(&processed_source, "localStorage.removeItem($2)").to_string();
265
266 let re_rupiah = Regex::new(r"\b(formatRupiah|rupiah)\s*\(\s*([^)]+)\s*\)").unwrap();
268 processed_source = re_rupiah.replace_all(&processed_source, "(new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format($2))").to_string();
269
270 let re_format_angka = Regex::new(r"\bformatAngka\s*\(\s*([^)]+)\s*\)").unwrap();
271 processed_source = re_format_angka.replace_all(&processed_source, "(new Intl.NumberFormat('id-ID').format($2))").to_string();
272
273 let re_format_tanggal = Regex::new(r"\bformatTanggal\s*\(\s*([^)]+)\s*\)").unwrap();
274 processed_source = re_format_tanggal.replace_all(&processed_source, "(new Intl.DateTimeFormat('id-ID', { dateStyle: 'full' }).format(new Date($2)))").to_string();
275
276 let re_tambah_kelas = Regex::new(r"\btambahKelas\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
278 processed_source = re_tambah_kelas.replace_all(&processed_source, "((typeof $1 === 'string' ? document.querySelector($1) : $1)?.classList?.add($2))").to_string();
279
280 let re_hapus_kelas = Regex::new(r"\bhapusKelas\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
281 processed_source = re_hapus_kelas.replace_all(&processed_source, "((typeof $1 === 'string' ? document.querySelector($1) : $1)?.classList?.remove($2))").to_string();
282
283 let re_ganti_kelas = Regex::new(r"\b(gantiKelas|putarKelas)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
284 processed_source = re_ganti_kelas.replace_all(&processed_source, "((typeof $1 === 'string' ? document.querySelector($1) : $1)?.classList?.toggle($2))").to_string();
285
286 let re_ada_kelas = Regex::new(r"\badaKelas\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
287 processed_source = re_ada_kelas.replace_all(&processed_source, "((typeof $1 === 'string' ? document.querySelector($1) : $1)?.classList?.contains($2))").to_string();
288
289 js.push_str(" ");
290 js.push_str(&processed_source);
291 js.push_str("\n})();\n");
292
293 js
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[test]
301 fn test_is_engine_compiler_basic() {
302 let code = r#"
303reaktif jumlah = 0;
304fungsi tambah() {
305 jumlah = jumlah + 1;
306 dudohno('Jumlah saiki:', jumlah);
307}
308"#;
309 let compiled = compile_is(code);
310 assert!(compiled.contains("State Reaktif: jumlah"));
311 assert!(compiled.contains("$state.jumlah = 0;"));
312 assert!(compiled.contains("console.log"));
313 assert!(compiled.contains("function tambah()"));
314 }
315
316 #[test]
317 fn test_is_engine_control_flow_and_helpers() {
318 let code = r#"
319fungsi cek_status(skor) {
320 jika skor >= 80 {
321 kembalikan benar;
322 } selain_itu jika skor >= 60 {
323 cetak("Cukup");
324 kembalikan benar;
325 } selain_itu {
326 kembalikan salah;
327 }
328}
329
330fungsi bayar(nominal) {
331 let harga_rp = rupiah(nominal);
332 salin(harga_rp);
333 peringatan("Disalin: " + harga_rp);
334}
335"#;
336 let compiled = compile_is(code);
337 assert!(compiled.contains("function cek_status(skor)"));
338 assert!(compiled.contains("if skor >= 80"));
339 assert!(compiled.contains("return true;"));
340 assert!(compiled.contains("else if skor >= 60"));
341 assert!(compiled.contains("else"));
342 assert!(compiled.contains("return false;"));
343 assert!(compiled.contains("Intl.NumberFormat('id-ID'"));
344 assert!(compiled.contains("navigator.clipboard?.writeText"));
345 assert!(compiled.contains("alert("));
346 }
347
348 #[test]
349 fn test_is_engine_dom_and_storage_helpers() {
350 let code = r##"
351fungsi init_ui() {
352 tambahKelas("#card", "aktif");
353 simpan("pengaturan", { tema: "gelap" });
354 let p = ambilPenyimpanan("pengaturan");
355}
356"##;
357 let compiled = compile_is(code);
358 assert!(compiled.contains("classList?.add"));
359 assert!(compiled.contains("localStorage.setItem"));
360 assert!(compiled.contains("localStorage.getItem"));
361 }
362}
363
364