One file, two interpretations

A polyglot script is written so that more than one programming language can read the same file as valid code. The trick is not that the computer switches languages halfway through. Instead, each language’s parser—the part that reads code and decides what it means—interprets the file according to its own rules.

Comment syntax can create room for both interpretations. A comment marker tells one language to ignore text, while another language may treat that same text as executable syntax. By carefully arranging the markers and code, a script can hide one language’s instructions inside a region the other language overlooks.

Making both versions work

The hard part is that the file must remain valid from each language’s point of view. A sequence that begins a comment in one language might be an error in the other, or might keep the rest of the file from being read as intended. Authors therefore have to account for where comments begin and end, which characters each parser recognizes, and what each language expects at the start of a program.

This is a form of syntax engineering: the same characters are arranged to satisfy two sets of grammatical rules at once. The result can be useful when one file needs to serve different runtimes, but it can also make code harder to inspect. A reader looking at the file through only one language’s rules may miss what the other interpreter will execute.

The consequence of shared text

Because each runtime sees a different meaning in the same source, understanding a polyglot script requires checking it in every language that may run it. The surprising part is that no special file format is required: the ambiguity comes from ordinary text, interpreted by two different rulebooks.