esolang
Learn · Ideas9 languages show it

Polyglot

One file, several languages. Each interpreter reads the same characters and sees a different program.

●●○ moderate · where to see it

The idea

A polyglot is a text that is a valid program in two or more languages. Sometimes all versions do the same thing; sometimes each language does something different, which is harder.

Read the story

The trick is always the same. Find a character or construct that one language treats as code and the other ignores, usually a comment. Then hide each language's program in the other's blind spot.

Some languages make this easy.

  • Brainfuck ignores every character except +-<>.,[]. Any program in another language that avoids those eight characters is already a Brainfuck program that does nothing.
  • Whitespace ignores everything except spaces, tabs and newlines, so it can live in the indentation of almost any file.
  • Befunge reads a 2D grid and only goes where the pointer goes, so code for another language can sit in cells it never visits.

Famous examples include polyglot entries in the International Obfuscated C Code Contest, and polyglot quines, programs that print their own source in each of their languages. A cousin is the "quine relay" (an ouroboros quine). Yusuke Endoh's version is a Ruby program that prints a program in the next language, which prints the next, through over a hundred languages and back to the start.

How it works

A Python and Brainfuck polyglot.

A Python and Brainfuck polyglot.

print("hi")
# ++++++++[>+++++++++++++<-]>.+.

How each reader sees it.

Line 1Line 2
Pythonprints hia comment, ignored
Brainfuckno command characters, ignored8 × 13 = 104 (h), print, add 1 (i), print

Both print hi.

The Python line had to avoid all eight Brainfuck characters. print("hi") happens to; print(1+1) would not, because Brainfuck would execute the +. That is the whole difficulty of polyglots in one example; every character is read by every interpreter, and each must find what it needs and survive the rest.

Seen in

  • Brainfuck. The easiest partner; it ignores almost everything.
  • Whitespace. Hides in any language's indentation.
  • Befunge. 2D layout leaves room for a second program.

Try this

  1. Run the polyglot above in both languages.
  2. Make the Brainfuck half print hi! while the Python half still prints hi. Watch out for the characters Python needs.
  3. Hard: write a text that is a quine in one language and a Brainfuck program that prints H.

Further

Where to see it