add --bundle flag for self-contained IIFE output
elc --target=js --bundle source.el > output.js produces a single file
with no import statement that can drop directly into a <script> tag.
How it works:
- detect_bundle() reads the --bundle flag from argv
- resolve_runtime_path() looks for el_runtime.js next to the source file
- compile_js_with_bundle() reads the runtime, calls codegen_js_bundle()
- codegen_js_inner(bundle_mode=true):
- emits ;(function() { "use strict"; at the top
- inlines the runtime content (stripping ES export statements which
are invalid inside an IIFE via js_strip_es_exports())
- skips the const {...} = globalThis.__el destructure -- the inlined
function declarations are already in scope within the IIFE
- closes with })(); after main()
Usage: elc --target=js --bundle app.el > app.js
Place el_runtime.js in the same directory as app.el.
This commit is contained in:
@@ -896,52 +896,75 @@ fn js_is_top_level_decl(stmt: Map<String, Any>) -> Bool {
|
||||
// ── Entry point ───────────────────────────────────────────────────────────────
|
||||
|
||||
fn codegen_js(stmts: [Map<String, Any>], source: String) -> String {
|
||||
codegen_js_inner(stmts, source, false, "")
|
||||
}
|
||||
|
||||
fn codegen_js_bundle(stmts: [Map<String, Any>], source: String, runtime_content: String) -> String {
|
||||
codegen_js_inner(stmts, source, true, runtime_content)
|
||||
}
|
||||
|
||||
fn codegen_js_inner(stmts: [Map<String, Any>], source: String, bundle_mode: Bool, runtime_content: String) -> String {
|
||||
// Reset per-compile state.
|
||||
state_set("__js_int_names", "")
|
||||
state_set("__js_match_counter", "")
|
||||
state_set("__js_async_fns", "")
|
||||
|
||||
// Preamble: inline the runtime via a single import that side-effects
|
||||
// globalThis. The runtime path is resolved relative to the generated
|
||||
// output; users running `elc --target=js` are responsible for ensuring
|
||||
// el_runtime.js is reachable. For self-contained output, the runtime
|
||||
// could be inlined; that is a follow-up.
|
||||
// Preamble: in bundle mode, inline the runtime and wrap in IIFE.
|
||||
// In module mode, emit a single import that side-effects globalThis.
|
||||
js_emit_line("// Generated by elc --target=js")
|
||||
js_emit_line("// Runtime: foundation/el/el-compiler/runtime/el_runtime.js")
|
||||
js_emit_line("import \"./el_runtime.js\";")
|
||||
js_emit_line("const {")
|
||||
js_emit_line(" println, print, el_str_concat, str_concat, str_eq, str_starts_with, str_ends_with,")
|
||||
js_emit_line(" str_len, int_to_str, str_to_int, str_slice, str_contains, str_replace,")
|
||||
js_emit_line(" str_to_upper, str_to_lower, str_trim, str_index_of, str_split, str_char_at,")
|
||||
js_emit_line(" str_char_code, str_lower, str_upper, el_abs, el_max, el_min,")
|
||||
js_emit_line(" el_list_new, el_list_len, el_list_get, el_list_append, el_list_empty, el_list_clone,")
|
||||
js_emit_line(" list_push, list_join, list_range,")
|
||||
js_emit_line(" el_map_new, el_get_field, el_map_get, el_map_set,")
|
||||
js_emit_line(" http_get, http_post, http_post_json,")
|
||||
js_emit_line(" fs_read, fs_write, fs_list,")
|
||||
js_emit_line(" json_parse, json_stringify, json_get, json_get_string, json_get_int,")
|
||||
js_emit_line(" time_now, time_now_utc, sleep_ms, bool_to_str, exit_program,")
|
||||
js_emit_line(" el_retain, el_release,")
|
||||
js_emit_line(" append, len, get, map_get, map_set,")
|
||||
js_emit_line(" native_list_get, native_list_len, native_list_append, native_list_empty,")
|
||||
js_emit_line(" native_list_clone, native_string_chars, native_int_to_str,")
|
||||
js_emit_line(" args, state_set, state_get, state_del, state_keys, env,")
|
||||
js_emit_line(" dharma_connect, dharma_send, dharma_emit, dharma_field, dharma_activate,")
|
||||
js_emit_line(" engram_node, engram_search, engram_activate,")
|
||||
js_emit_line(" llm_call, llm_call_system,")
|
||||
js_emit_line(" dom_get_element, dom_get_value, dom_set_value, dom_get_text, dom_set_text,")
|
||||
js_emit_line(" dom_set_prop, dom_get_prop, dom_set_style, dom_add_class, dom_remove_class,")
|
||||
js_emit_line(" dom_show, dom_hide, dom_listen, dom_query, dom_query_all, dom_create,")
|
||||
js_emit_line(" dom_append, dom_remove, dom_is_null,")
|
||||
js_emit_line(" dom_set_attr, dom_get_attr, dom_remove_attr, dom_set_html, dom_get_html,")
|
||||
js_emit_line(" dom_get_parent, dom_contains_class, dom_get_checked, dom_set_checked,")
|
||||
js_emit_line(" set_timeout, set_interval, clear_interval,")
|
||||
js_emit_line(" local_storage_get, local_storage_set, local_storage_remove,")
|
||||
js_emit_line(" window_location, window_redirect, window_on_load,")
|
||||
js_emit_line(" console_log,")
|
||||
js_emit_line(" window_set, window_get, native_js, native_js_call,")
|
||||
js_emit_line("} = globalThis.__el;")
|
||||
js_emit_blank()
|
||||
if bundle_mode {
|
||||
js_emit_line("// Bundle mode: runtime inlined, no import statement needed.")
|
||||
js_emit_line("// Drop directly into a <script> tag.")
|
||||
js_emit_line(";(function() {")
|
||||
js_emit_line("\"use strict\";")
|
||||
// Inline the runtime content verbatim (already read from el_runtime.js).
|
||||
// Strip the final ES export lines -- they use `export` syntax which is
|
||||
// not valid inside an IIFE. The globalThis.__el assignment is what matters.
|
||||
js_emit_line(js_strip_es_exports(runtime_content))
|
||||
js_emit_line("")
|
||||
} else {
|
||||
js_emit_line("// Runtime: foundation/el/el-compiler/runtime/el_runtime.js")
|
||||
js_emit_line("import \"./el_runtime.js\";")
|
||||
}
|
||||
// In module mode: destructure all builtins off globalThis.__el so call
|
||||
// sites stay flat (println(x) not el.println(x)).
|
||||
// In bundle mode: function declarations from the inlined runtime are
|
||||
// already in scope within the IIFE -- no destructure needed.
|
||||
if !bundle_mode {
|
||||
js_emit_line("const {")
|
||||
js_emit_line(" println, print, el_str_concat, str_concat, str_eq, str_starts_with, str_ends_with,")
|
||||
js_emit_line(" str_len, int_to_str, str_to_int, str_slice, str_contains, str_replace,")
|
||||
js_emit_line(" str_to_upper, str_to_lower, str_trim, str_index_of, str_split, str_char_at,")
|
||||
js_emit_line(" str_char_code, str_lower, str_upper, el_abs, el_max, el_min,")
|
||||
js_emit_line(" el_list_new, el_list_len, el_list_get, el_list_append, el_list_empty, el_list_clone,")
|
||||
js_emit_line(" list_push, list_join, list_range,")
|
||||
js_emit_line(" el_map_new, el_get_field, el_map_get, el_map_set,")
|
||||
js_emit_line(" http_get, http_post, http_post_json,")
|
||||
js_emit_line(" fs_read, fs_write, fs_list,")
|
||||
js_emit_line(" json_parse, json_stringify, json_get, json_get_string, json_get_int,")
|
||||
js_emit_line(" time_now, time_now_utc, sleep_ms, bool_to_str, exit_program,")
|
||||
js_emit_line(" el_retain, el_release,")
|
||||
js_emit_line(" append, len, get, map_get, map_set,")
|
||||
js_emit_line(" native_list_get, native_list_len, native_list_append, native_list_empty,")
|
||||
js_emit_line(" native_list_clone, native_string_chars, native_int_to_str,")
|
||||
js_emit_line(" args, state_set, state_get, state_del, state_keys, env,")
|
||||
js_emit_line(" dharma_connect, dharma_send, dharma_emit, dharma_field, dharma_activate,")
|
||||
js_emit_line(" engram_node, engram_search, engram_activate,")
|
||||
js_emit_line(" llm_call, llm_call_system,")
|
||||
js_emit_line(" dom_get_element, dom_get_value, dom_set_value, dom_get_text, dom_set_text,")
|
||||
js_emit_line(" dom_set_prop, dom_get_prop, dom_set_style, dom_add_class, dom_remove_class,")
|
||||
js_emit_line(" dom_show, dom_hide, dom_listen, dom_query, dom_query_all, dom_create,")
|
||||
js_emit_line(" dom_append, dom_remove, dom_is_null,")
|
||||
js_emit_line(" dom_set_attr, dom_get_attr, dom_remove_attr, dom_set_html, dom_get_html,")
|
||||
js_emit_line(" dom_get_parent, dom_contains_class, dom_get_checked, dom_set_checked,")
|
||||
js_emit_line(" set_timeout, set_interval, clear_interval,")
|
||||
js_emit_line(" local_storage_get, local_storage_set, local_storage_remove,")
|
||||
js_emit_line(" window_location, window_redirect, window_on_load,")
|
||||
js_emit_line(" console_log,")
|
||||
js_emit_line(" window_set, window_get, native_js, native_js_call,")
|
||||
js_emit_line("} = globalThis.__el;")
|
||||
js_emit_blank()
|
||||
}
|
||||
|
||||
// Pre-registration pass: scan all FnDefs for @async decorators so that
|
||||
// forward calls to @async functions get `await` even if the callee is
|
||||
@@ -1010,6 +1033,41 @@ fn codegen_js(stmts: [Map<String, Any>], source: String) -> String {
|
||||
js_emit_line("main();")
|
||||
}
|
||||
|
||||
// Close IIFE in bundle mode.
|
||||
if bundle_mode {
|
||||
js_emit_line("")
|
||||
js_emit_line("})();")
|
||||
}
|
||||
|
||||
// Return empty string — output was streamed via println
|
||||
""
|
||||
}
|
||||
|
||||
// Strip ES module export statements from runtime content for IIFE embedding.
|
||||
// The runtime ends with `export { ... }` and `export { __el as default }` lines
|
||||
// that are invalid inside an IIFE. We strip everything from the first top-level
|
||||
// `export {` line onward.
|
||||
//
|
||||
// Also strips `import` statements at the top if any (though el_runtime.js has none).
|
||||
fn js_strip_es_exports(content: String) -> String {
|
||||
let lines: [String] = str_split(content, "\n")
|
||||
let n: Int = native_list_len(lines)
|
||||
let out: [String] = native_list_empty()
|
||||
let i = 0
|
||||
while i < n {
|
||||
let line: String = native_list_get(lines, i)
|
||||
let trimmed: String = str_trim(line)
|
||||
// Stop at top-level `export {` or `export default`
|
||||
if str_starts_with(trimmed, "export {") {
|
||||
let i = n
|
||||
} else {
|
||||
if str_starts_with(trimmed, "export default") {
|
||||
let i = n
|
||||
} else {
|
||||
let out = native_list_append(out, line)
|
||||
}
|
||||
}
|
||||
let i = i + 1
|
||||
}
|
||||
str_join(out, "\n")
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ fn compile(source: String) -> String {
|
||||
codegen(stmts, source)
|
||||
}
|
||||
|
||||
// compile_js — full pipeline (JS target): source string -> JS source string
|
||||
// compile_js — full pipeline (JS target, module mode): source string -> JS source string
|
||||
fn compile_js(source: String) -> String {
|
||||
let tokens: [Map<String, Any>] = lex(source)
|
||||
let stmts: [Map<String, Any>] = parse(tokens)
|
||||
@@ -38,6 +38,20 @@ fn compile_js(source: String) -> String {
|
||||
codegen_js(stmts, source)
|
||||
}
|
||||
|
||||
// compile_js_with_bundle — JS target in bundle mode.
|
||||
// Reads el_runtime.js from runtime_path and inlines it inside an IIFE.
|
||||
fn compile_js_with_bundle(source: String, runtime_path: String) -> String {
|
||||
let tokens: [Map<String, Any>] = lex(source)
|
||||
let stmts: [Map<String, Any>] = parse(tokens)
|
||||
el_release(tokens)
|
||||
let runtime_content: String = fs_read(runtime_path)
|
||||
if str_eq(runtime_content, "") {
|
||||
println("el-compiler: warning: --bundle: could not read runtime at " + runtime_path)
|
||||
println("el-compiler: warning: bundle output will be incomplete")
|
||||
}
|
||||
codegen_js_bundle(stmts, source, runtime_content)
|
||||
}
|
||||
|
||||
// compile_dispatch — pick a backend based on the requested target.
|
||||
// tgt = "c" | "js"
|
||||
// (The parameter is named `tgt` because `target` is a reserved keyword
|
||||
@@ -48,6 +62,12 @@ fn compile_dispatch(tgt: String, source: String) -> String {
|
||||
compile(source)
|
||||
}
|
||||
|
||||
// compile_dispatch_bundle — like compile_dispatch but bundle mode for JS.
|
||||
fn compile_dispatch_bundle(tgt: String, source: String, runtime_path: String) -> String {
|
||||
if str_eq(tgt, "js") { return compile_js_with_bundle(source, runtime_path) }
|
||||
compile(source)
|
||||
}
|
||||
|
||||
// Detect a `--target=<lang>` flag in argv and return the target.
|
||||
// Returns "c" if none specified or unrecognized.
|
||||
fn detect_target(argv: [String]) -> String {
|
||||
@@ -91,6 +111,32 @@ fn detect_emit_header(argv: [String]) -> Bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Detect --bundle flag in argv.
|
||||
fn detect_bundle(argv: [String]) -> Bool {
|
||||
let n: Int = native_list_len(argv)
|
||||
let i = 0
|
||||
while i < n {
|
||||
let a: String = native_list_get(argv, i)
|
||||
if str_eq(a, "--bundle") { return true }
|
||||
let i = i + 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Resolve the runtime path for --bundle mode.
|
||||
// Looks for el_runtime.js next to the source file first;
|
||||
// if not found there, looks next to the elc binary itself.
|
||||
// Returns "" if not found anywhere (caller emits a warning).
|
||||
fn resolve_runtime_path(src_path: String) -> String {
|
||||
let src_dir: String = dirname_of(src_path)
|
||||
let candidate: String = src_dir + "/el_runtime.js"
|
||||
let existing: String = fs_read(candidate)
|
||||
if !str_eq(existing, "") {
|
||||
return candidate
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Reconstruct an El type annotation string from a parsed type node.
|
||||
fn type_node_to_el(t: Map<String, Any>) -> String {
|
||||
let k: String = t["kind"]
|
||||
@@ -251,10 +297,12 @@ fn resolve_imports(src_path: String) -> String {
|
||||
|
||||
// main — CLI entry point.
|
||||
//
|
||||
// elc <source.el> # emit C to stdout
|
||||
// elc --target=js <source.el> # emit JS to stdout
|
||||
// elc --target=c <source.el> <out.c> # write C to file
|
||||
// elc --target=js <source.el> <out.js> # write JS to file
|
||||
// elc <source.el> # emit C to stdout
|
||||
// elc --target=js <source.el> # emit JS (module) to stdout
|
||||
// elc --target=js --bundle <source.el> # emit self-contained JS (IIFE) to stdout
|
||||
// elc --target=c <source.el> <out.c> # write C to file
|
||||
// elc --target=js <source.el> <out.js> # write JS to file
|
||||
// elc --target=js --bundle <source.el> <out.js> # write bundled JS to file
|
||||
fn main() -> Void {
|
||||
let argv: [String] = args()
|
||||
// Use `tgt` not `target`: `target` is a reserved keyword in the lexer
|
||||
@@ -262,10 +310,11 @@ fn main() -> Void {
|
||||
// because the function-name position has no token-class restriction.
|
||||
let tgt: String = detect_target(argv)
|
||||
let do_emit_header: Bool = detect_emit_header(argv)
|
||||
let do_bundle: Bool = detect_bundle(argv)
|
||||
let positional: [String] = strip_flags(argv)
|
||||
let argc: Int = native_list_len(positional)
|
||||
if argc < 1 {
|
||||
println("el-compiler: usage: elc [--target=c|js] [--emit-header] <source.el> [<output>]")
|
||||
println("el-compiler: usage: elc [--target=c|js] [--bundle] [--emit-header] <source.el> [<output>]")
|
||||
exit(1)
|
||||
}
|
||||
let src_path: String = native_list_get(positional, 0)
|
||||
@@ -283,7 +332,13 @@ fn main() -> Void {
|
||||
}
|
||||
|
||||
let source: String = resolve_imports(src_path)
|
||||
let out: String = compile_dispatch(tgt, source)
|
||||
let out: String = ""
|
||||
if do_bundle {
|
||||
let runtime_path: String = resolve_runtime_path(src_path)
|
||||
let out = compile_dispatch_bundle(tgt, source, runtime_path)
|
||||
} else {
|
||||
let out = compile_dispatch(tgt, source)
|
||||
}
|
||||
if argc >= 2 {
|
||||
let out_path: String = native_list_get(positional, 1)
|
||||
let ok: Bool = fs_write(out_path, out)
|
||||
|
||||
Reference in New Issue
Block a user