SPEAKER NOTES

Polyglot Programming - HacKSU Lesson

print as reference  ·  Ctrl+P

Slide 1

Title - Polyglot Programming

Slide 2

What is a Polyglot File?

Slide 3

How Do Parsers Work?

Slide 4

The Web Is Already Polyglot

Slide 5

More Examples

Slide 6

Binary Polyglots - Images

Live demo option: grab any JPEG, zip a text file, concatenate them, verify both open image and unzip work on the result.
Slide 7

The C + Python Mechanism

Slide 8

Live Demo - demo.c

Commands:
python examples/demo.c
gcc examples/demo.c -o demo && ./demo
Slide 9

Bash + Python

Commands:
bash examples/bash_python.sh
python3 examples/bash_python.sh
Slide 10

polycompiler - Overview

Step-by-step demo - run this live:

1. Install polycompiler (needs Node.js)
npm install -g polycompiler

2. Write a Python file
echo 'print("Hello from Python!")' > hello.py

3. Write a JavaScript file
echo 'console.log("Hello from JavaScript!")' > hello.js

4. Merge into one polyglot file
polycompiler hello.py hello.js out.py.js

5. Run with both runtimes
python3 out.py.js  # prints: Hello from Python!
node out.py.js    # prints: Hello from JavaScript!

6. Inspect the output - this is what polycompiler generated:
cat out.py.js

You should see two lines:
1 // (lambda: exec("print('Hello from Python!')", globals()) or 1)()
lambda: eval("console.log('Hello from JavaScript!')")

That's the whole file. Point this out - it's only 2 lines.
Slide 11

polycompiler - The Live Trace

Run the existing example file:
python3 examples/python_js.py.js
node examples/python_js.py.js

Verify the file hasn't changed between runs:
cat examples/python_js.py.js
Slide 12

Why Does This Matter?

Slide 13

Try It Yourself

Slide 14 - Build It Live

Complete Solution (keep off screen!)

Full working solution:
#if 0
x = """
#endif

#include <stdio.h>

int main(void) {
    printf("Hello from C!\n");
    return 0;
}

#if 0
"""
print("Hello from Python!")
#endif
Stretch solution (with name function):
#if 0
x = """
#endif

#include <stdio.h>

void greet(const char *name) {
    printf("Hello, %s! (from C)\n", name);
}

int main(void) {
    printf("Hello from C!\n");
    greet("HacKSU");
    return 0;
}

#if 0
"""
def greet(name):
    print(f"Hello, {name}! (from Python)")

print("Hello from Python!")
greet("HacKSU")
#endif
Slide 15

Questions