Skip to content

Convert JS strings to use template literals. NFC - #27503

Draft
kleisauke wants to merge 3 commits into
emscripten-core:mainfrom
kleisauke:use-template-literals
Draft

Convert JS strings to use template literals. NFC#27503
kleisauke wants to merge 3 commits into
emscripten-core:mainfrom
kleisauke:use-template-literals

Conversation

@kleisauke

Copy link
Copy Markdown
Collaborator

Marked as draft as this seems to regress code size, so perhaps it should not be done everywhere.

This is an automatic change generated by tools/maint/rebaseline_tests.py.

The following (54) test expectation files were updated by
running the tests with `--rebaseline`:

```
codesize/test_codesize_cxx_ctors1.json: 153927 => 153959 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_ctors2.json: 153333 => 153365 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_except.json: 200099 => 200131 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_except_wasm.json: 169465 => 169497 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_except_wasm_legacy.json: 167325 => 167357 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_lto.json: 119542 => 119574 [+32 bytes / +0.03%]
codesize/test_codesize_cxx_mangle.json: 266429 => 266461 [+32 bytes / +0.01%]
codesize/test_codesize_cxx_noexcept.json: 155837 => 155869 [+32 bytes / +0.02%]
codesize/test_codesize_cxx_wasmfs.json: 180955 => 180963 [+8 bytes / +0.00%]
test/codesize/test_codesize_file_preload.expected.js updated
codesize/test_codesize_file_preload.json: 23853 => 23897 [+44 bytes / +0.18%]
codesize/test_codesize_files_js_fs.json: 18236 => 18270 [+34 bytes / +0.19%]
codesize/test_codesize_files_wasmfs.json: 63232 => 63238 [+6 bytes / +0.01%]
codesize/test_codesize_hello_O0.json: 38609 => 38607 [-2 bytes / -0.01%]
codesize/test_codesize_hello_O1.json: 8060 => 8060 [+0 bytes / +0.00%]
codesize/test_codesize_hello_O2.json: 5767 => 5773 [+6 bytes / +0.10%]
codesize/test_codesize_hello_O3.json: 5463 => 5469 [+6 bytes / +0.11%]
codesize/test_codesize_hello_Os.json: 5451 => 5457 [+6 bytes / +0.11%]
codesize/test_codesize_hello_Oz.json: 4622 => 4628 [+6 bytes / +0.13%]
codesize/test_codesize_hello_dylink.json: 44105 => 44137 [+32 bytes / +0.07%]
codesize/test_codesize_hello_dylink_all.json: 856207 => 856314 [+107 bytes / +0.01%]
codesize/test_codesize_hello_esm_integration.json: 8448 => 8452 [+4 bytes / +0.05%]
codesize/test_codesize_hello_export_nothing.json: 2685 => 2691 [+6 bytes / +0.22%]
codesize/test_codesize_hello_wasmfs.json: 5463 => 5469 [+6 bytes / +0.11%]
codesize/test_codesize_libcxxabi_message_O3.json: 3099 => 3105 [+6 bytes / +0.19%]
codesize/test_codesize_libcxxabi_message_O3_standalone.json: 3315 => 3321 [+6 bytes / +0.18%]
codesize/test_codesize_mem_O3.json: 9135 => 9141 [+6 bytes / +0.07%]
codesize/test_codesize_mem_O3_grow.json: 9470 => 9476 [+6 bytes / +0.06%]
codesize/test_codesize_mem_O3_grow_standalone.json: 9298 => 9304 [+6 bytes / +0.06%]
codesize/test_codesize_mem_O3_standalone.json: 9132 => 9138 [+6 bytes / +0.07%]
codesize/test_codesize_mem_O3_standalone_lib.json: 8325 => 8331 [+6 bytes / +0.07%]
codesize/test_codesize_mem_O3_standalone_narg.json: 8447 => 8453 [+6 bytes / +0.07%]
codesize/test_codesize_mem_O3_standalone_narg_flto.json: 7378 => 7384 [+6 bytes / +0.08%]
codesize/test_codesize_minimal_64.json: 2388 => 2394 [+6 bytes / +0.25%]
test/codesize/test_codesize_minimal_O0.expected.js updated
codesize/test_codesize_minimal_O0.json: 19718 => 19716 [-2 bytes / -0.01%]
codesize/test_codesize_minimal_O2.json: 2332 => 2338 [+6 bytes / +0.26%]
codesize/test_codesize_minimal_O3.json: 2073 => 2079 [+6 bytes / +0.29%]
codesize/test_codesize_minimal_Os.json: 2073 => 2079 [+6 bytes / +0.29%]
codesize/test_codesize_minimal_Oz-ctors.json: 2044 => 2050 [+6 bytes / +0.29%]
codesize/test_codesize_minimal_Oz.json: 2073 => 2079 [+6 bytes / +0.29%]
codesize/test_codesize_minimal_esm.json: 2212 => 2216 [+4 bytes / +0.18%]
codesize/test_codesize_minimal_esm_integration.json: 3721 => 3725 [+4 bytes / +0.11%]
codesize/test_codesize_minimal_pthreads.json: 25964 => 25970 [+6 bytes / +0.02%]
codesize/test_codesize_minimal_pthreads_memgrowth.json: 26416 => 26422 [+6 bytes / +0.02%]
codesize/test_codesize_minimal_wasmfs.json: 2073 => 2079 [+6 bytes / +0.29%]
codesize/test_minimal_runtime_code_size_hello_webgl2_wasm.json: 13186 => 13190 [+4 bytes / +0.03%]
codesize/test_minimal_runtime_code_size_hello_webgl2_wasm2js.json: 18559 => 18563 [+4 bytes / +0.02%]
codesize/test_minimal_runtime_code_size_hello_webgl2_wasm_singlefile.json: 15040 => 15044 [+4 bytes / +0.03%]
codesize/test_minimal_runtime_code_size_hello_webgl_wasm.json: 12724 => 12728 [+4 bytes / +0.03%]
codesize/test_minimal_runtime_code_size_hello_webgl_wasm2js.json: 18085 => 18089 [+4 bytes / +0.02%]
test/codesize/test_small_js_flags.expected.js updated
codesize/test_small_js_flags.json: 3728 => 3732 [+4 bytes / +0.11%]
codesize/test_unoptimized_code_size.json: 172395 => 172391 [-4 bytes / -0.00%]

Average change: +0.09% (-0.01% - +0.29%)
```
@kleisauke

Copy link
Copy Markdown
Collaborator Author

Commit 55a68e8 was automatically done with the Biome linter:

$ find src -type f -name '*.js' -exec sed -i -E -e '/^ *#(if|ifdef|elif|else|endif|include|warning|error|preprocess)/d' -e 's/[\{<]{3} .* [\}>]{3}//g' {} +
$ git add src
$ git commit -m"[Temp] Remove pre-process syntax"
$ npx @biomejs/biome lint --only=lint/style/useTemplate --write --unsafe --skip-parse-errors ./src
$ git add src
$ git commit -m"Convert JS strings to use template literals. NFC"

(see: https://biomejs.dev/linter/rules/use-template/)

Though, that doesn't fix all files due to Emscripten's pre-process syntax, so I also ran:

$ ./emcc test/hello_world.c -sINCLUDE_FULL_LIBRARY
$ npx @biomejs/biome lint --only=lint/style/useTemplate a.out.js

And then manually applied the fixes reported by that (in commit 25c22b5).

FWIW, the lint/complexity/useArrowFunction and lint/nursery/useNullishCoalescing lint rules might also be useful as follow-ups.

@sbc100

sbc100 commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Oh nice. I'd assued the "Remove pre-process syntax" part would generate malformed JS because of things like mismatched braces.

e.g. do we not have some places that do horrible things like:

if (x) { 
#if foo
  xxx
}
#else
  yyy
}
#endif

@kleisauke

kleisauke commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator Author

Indeed, I noticed that too. I think the easiest way to fix this is to do it via:

@@ -3,6 +3,9 @@ if (x) {
   xxx
 }
 #else
+#if 0 // STRIP_PREPROCESS
+else {
+#endif
   yyy
 }
 #endif

i.e. just add another always-false preprocessor directive, so that stripping it produces valid JS.

I started experimenting with this in this changeset:
main...kleisauke:preprocess-compat

With that changeset and this strip-preprocess.py script:

Details
#!/usr/bin/env python3

from pathlib import Path
import sys

directives = (
    "if", "ifdef", "elif", "else", "endif",
    "include", "warning", "error", "preprocess",
)

def preprocess_expression(content):
    content = content.strip()

    if content.startswith("asyncIf(") and content.endswith(")"):
        return "async "
    if content.startswith("awaitIf(") and content.endswith(")"):
        return "await "
    if content.startswith("defineI64Param('") and content.endswith("')"):
        return content[len("defineI64Param('"):content.index("')")]
    if content.startswith("maybeExportHeap(") and content.endswith(")"):
        return ""

    return content

for filename in sys.argv[1:]:
    path = Path(filename)
    text = path.read_text()

    # Remove macro and placeholder expressions
    for begin, end in (("{{{", "}}}"), ("<<<", ">>>")):
        while begin in text:
            i = text.index(begin)
            j = text.find(end, i + len(begin))

            if j == -1:
                break

            content = text[i + len(begin):j]
            replacement = preprocess_expression(content)

            text = text[:i] + replacement + text[j + len(end):]

    # Comment out preprocess directives
    lines = []
    for line in text.splitlines(keepends=True):
        s = line.lstrip()
        if s.startswith("#") and any(s[1:].startswith(d) for d in directives):
            line = f"//{line}"
        lines.append(line)

    path.write_text("".join(lines))

I can then run:

$ find src -type f -exec python3 strip-preprocess.py {} +
$ npx @biomejs/biome lint --only=lint/style/useTemplate --write --unsafe --json-parse-allow-comments=true ./src
Checked 135 files in 58ms. Fixed 59 files.

@kleisauke

Copy link
Copy Markdown
Collaborator Author

I forgot to mention that another nice benefit of doing this is that it also catches invalid JS behind preprocessor directives that aren't always enabled. For example:

dbg(`Shader source after preprocessing: ${source}`;

dbg(`Shader source after removing layout location directives: ${source}`;

dbg(`Shader source after removing layout binding directives: ${source}`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants