A polyglot file is a single file that is simultaneously valid in two or more languages or formats - each parser reads the same bytes and produces correct, meaningful output.
Every language has regions it ignores. Polyglots hide language B inside language A's ignored regions - and vice versa.
Every .html file is a polyglot - three parsers, one file, by design.
<!DOCTYPE html>
<html>
<!-- HTML PARSER reads the structure -->
<style>
/* CSS PARSER handles styles */
body {
background: #0d0d0d;
color: var(--green);
font-family: monospace;
}
</style>
<script>
// JAVASCRIPT ENGINE runs logic
document.addEventListener('DOMContentLoaded', () => {
console.log("three parsers, one file");
});
</script>
<p>Hello, polyglot world!</p>
</html>
Reads tags, builds the DOM tree. Treats <style> and <script> contents as opaque blobs and hands them off.
Only processes what's inside <style> tags. The surrounding HTML is completely invisible to it.
Only runs what's inside <script> tags. Has no awareness of HTML or CSS syntax around it.
"""<!--
<!DOCTYPE html>
<html>
<h1>Hello from the browser!</h1>
</html>
<!--"""
print("Hello from Python!")
# -->
Python: triple-quoted string hides HTML.
Browser: <!-- --> hides Python code.
#!/bin/sh
"exec" "python3" "$0" "$@"
import os, sys, platform
print(f"[python {sys.version_info.major}.{sys.version_info.minor}]")
print(f" OS: {platform.system()}")
print(f" Shell: {os.environ.get('SHELL', 'unknown')}")
From examples/bash_python.sh - "exec"
is a quoted word in bash but adjacent string literals in Python.
1 // (lambda: exec("nums=[1,2,3,4,5]\nprint('Python:',list(map(lambda x:x**2,nums)))", globals()) or 1)()
lambda: eval("const nums=[1,2,3,4,5]; console.log('JS:', nums.map(x=>x**2));")
The polycompiler output format. Exploits //
as floor division (Python) vs line comment (JS), and
lambda: as expression prefix (Python) vs
labeled statement (JS).
#if 0
x = """
#endif
#include <stdio.h>
int main(void) {
printf("[ C ] Fibonacci: ");
/* ... loop ... */
}
#if 0
"""
print("[ Python ] Fibonacci: ", end="")
# ... loop ...
#endif
From examples/demo.c - the main demo.
File format parsers have their own ignored regions. A single file can be a valid JPEG and a valid ZIP archive simultaneously.
FF D9cat image.jpg archive.zip > polyglot.jpgunzip polyglot.jpg
We exploit two features: C's #if 0 … #endif preprocessor directive and Python's """…""" triple-quoted strings.
print() call. Python never executes the printf().
Both are 100% correct in their own language.
examples/demo.c#if 0
# Run as Python: python demo.c
# Compile as C: gcc demo.c -o demo && ./demo
x = """
#endif
#include <stdio.h>
int main(void) {
printf("[ C ] Fibonacci: ");
int a = 0, b = 1;
for (int i = 0; i < 8; i++) {
printf("%d ", a);
int t = a + b; a = b; b = t;
}
printf("\n");
return 0;
}
#if 0
"""
print("[ Python ] Fibonacci: ", end="")
a, b = 0, 1
for _ in range(8):
print(a, end=" ")
a, b = b, a + b
print()
#endif
Uses the difference between quoted words in bash and adjacent string literals in Python.
#!/bin/sh
# Polyglot: valid Bash AND valid Python
# Run as bash: bash bash_python.sh
# Run as Python: python3 bash_python.sh
"exec" "python3" "$0" "$@"
import os, sys, platform
print(f"[python {sys.version_info.major}.{sys.version_info.minor}]")
print(f" OS: {platform.system()} {platform.release()}")
print(f" Shell: {os.environ.get('SHELL', 'unknown')}")
print(f" File: {__file__}")
print()
print("Bash hit 'exec python3' and handed off.")
print("Everything above never ran as bash.")
"exec" → the exec shell builtin
"python3" "$0" "$@" → its arguments
Shell is replaced by Python running this
file. Bash never reaches line 8+.
"exec" "python3" "$0" "$@"
→ four adjacent string literals
→ concatenated: "execpython3$0$@"
→ expression statement, result discarded
No exec happens. Python runs the import + print below.
$0 and $@ are literal
strings - no shell expansion. Bash's quoting preserves the builtin name.
Combine both tricks: the exec trick for Bash and the #if 0 trick for C. Same file - three runtimes, all valid.
#if 0
"exec" "python3" "$0" "$@"
x = """
#endif
#include <stdio.h>
int main(void) {
printf("[ C ] Fibonacci: ");
int a = 0, b = 1;
for (int i = 0; i < 8; i++) {
printf("%d ", a);
int t = a+b; a = b; b = t;
}
printf("\n");
return 0;
}
#if 0
"""
print("[ Python ] Fibonacci: ", end="")
a, b = 0, 1
for _ in range(8):
print(a, end=" ")
a, b = b, a + b
print()
#endif
#if 0 - comment, ignored"exec" "python3" ... - runs exec, bash replaced by Python#if 0 - comment, ignored"exec" "python3" ... - string expression, discardedx = """...""" - C code hidden in a string#if 0 - preprocessor skips exec + x = """#include, main() - compiled normally#if 0 skips the Python codebash triple.c ·
python3 triple.c ·
gcc triple.c -o t && ./t
An experimental npm package (304 ★) by evanzhoudev that merges Python and JS into one file runnable by both runtimes. github.com/evanzhoudev/polycompiler
npm install -g polycompiler
# Merge your files
polycompiler script.py script.js out.py.js
# Run with either runtime
python3 out.py.js
node out.py.js
1 // (lambda: exec("PYTHON CODE", globals()) or 1)()
lambda: eval("JS CODE")
Two lines. That's the whole trick.
// operator duality// is floor division - line 1 evaluates// is a line comment - line 1 is skippedlambda: label dualitylambda: creates an uncalled lambda - discardedlambda: is a labeled statement - eval() runs
Node.js only executes files with .py.js extension -
it refuses other extensions. The output file must be named *.py.js.
1 // (lambda: exec("nums=[1,2,3,4,5]\nprint('Python:',list(map(lambda x:x**2,nums)))", globals()) or 1)()
lambda: eval("const nums=[1,2,3,4,5]; console.log('JS: ', nums.map(x => x**2));")
python3 examples/python_js.py.js ·
node examples/python_js.py.js
# means different things in C vs Python
# C + Python polyglot
python examples/demo.c
gcc examples/demo.c -o demo && ./demo
# Bash + Python polyglot
bash examples/bash_python.sh
python3 examples/bash_python.sh
Add a function that prints your name in both the C and Python sections. Both versions must still compile and run correctly.
Create a JPEG+ZIP polyglot:
cat photo.jpg archive.zip > poly.jpg
Verify: image viewer still shows the photo.
Verify: unzip poly.jpg extracts files.
npm install -g polycompiler
# Write hello.py (print "Hello from Python")
# Write hello.js (console.log("Hello from JS"))
# Compile into one file, run with both
Fill in the blanks - the structure is already there:
#if 0
x = """
#endif
/* ── YOUR C CODE HERE ──────────────────────────── */
#include <stdio.h>
int main(void) {
/* TODO: printf("Hello from C!\n"); */
return 0;
}
/* ─────────────────────────────────────────────── */
#if 0
"""
# ── YOUR PYTHON CODE HERE ──────────────────────
# TODO: print("Hello from Python!")
#endif
my_polyglot.cpython my_polyglot.c
gcc my_polyglot.c -o mine && ./mine
#if 0 - it's just a # comment#if 0 and #endifx = """...""" hides C code as a Python string