Generic C / Python Polyglot

A polyglot — coming from the Greek words πολύς (many) and γλώττα (tongue) — is a piece of source code which can run in multiple languages, often performing language-dependent tasks.
Even though such a source code’s feature may not seem particularily useful or possible with certain language combinations, trying to bend not one but multiple language’s syntactic rules and overall behavior is still interesting.

An example of a rather simple polyglot would be a Python 2 / Python 3 polyglot — if one counts those as two separate languages. Because of their enormous similarities, one can pick out differences and use those to determine which language runs the source code.

if 1/2>0:print("Python 3")
else:print("Python 2")

Utilizing Python’s version difference regarding integer division and real division is one of the most common ways to tell them apart, as it can also be used to only control a specific part of a program instead of having to write two nearly identical programs (increases the program’s style and cuts on bytes — an important consideration if one golfs a polyglot).

However, polyglots combining languages that are not as similar as Python 2 and Python 3 require more effort. The following is a general Python 2 / C polyglot, meaning that nearly all C and Python 2 programs can be mixed using this template (there are a few rules both languages need to abide which will come apparent later).

#define _\
"""
main(){printf("C");}
#define _"""
#define/*
print"Python 2"
#*/_f

In the above code, main(){printf("C");} can be nearly any C code and print"Python 2" can be nearly any Python 2 code.
Language determination is exclusively done via syntax. A C compiler sees a #define statement and a line continuation \, another two #define statements with a block comment in between and actual compilable C source code (view first emphasis).
Python, on the other hand, treats all octothorps, #, as comments, ignoring the line continuation, and triple-quoted strings, """...""", as strings rather than statements and thus only sees the Python code (view second emphasis).

My first ever polyglot used this exact syntactical language differentiation and solved a task titled Life and Death of Trees (link to my answer).

Advertisements

Brainfuck X

While browsing StackExchange PCG questions and answers, I came across a challenge regarding drawing the swiss flag. In particular, I was interested in benzene’s answer, in which they showcased a Brainfuck dialect capable of creating two-dimensional 24-bit color images. In this post I present this dialect with slight changes of my own, as well as an interpreter I wrote in Python 2.7 (source code is listed below and can also be downloaded).

Brainfuck X generated Swiss flagUrban Müller’s original Brainfuck (my vanilla Brainfuck post can be found here) works similar to a Turing machine, in that the memory consists of a theoretically infinitely large tape with individual cells which can be modified. What allows Brainfuck X (or Braindraw, as benzene called their dialect) to create color images is, that instead of a one-dimensional tape, a three-dimensional tape is used. This tape extends infinitely in two spacial dimensions and has three color planes. Each cell’s value is limited to a byte (an integer value from 0 to 255) which results in a 24-bit color depth.

Adding to Brainfucks eight commands (+-<>[].,), there are two characters to move up and down the tape (^v) and one character to move forwards in the color dimension (*). Starting on the red color plane, continuing with the green and ending in the blue. After the blue color plane, the color planes cycle and the red color plane is selected. benzene’s original language design which I altered slightly had three characters (rgb) to directly select a color plane. Whilst this version is supported by my interpreter (the flag --colorletters is necessary for that functionality), I find my color star more Brainfucky — directly calling color planes by their name seems nearly readable.
Brainfuck’s vanilla eight characters still work in the same way, Brainfuck X can thereby execute any vanilla Brainfuck program. Also, there still is a plaintext output — the tape’s image is a program’s secondary output.

Having executed the final Brainfuck instruction, the interpreter prints out the tape to the terminal — using ANSI escape codes. Because of this, the color depth is truncated in the terminal view, as there are only 216 colors supported.
For the full 24-bit color depth output, I use the highly inefficient Portable Pixmap Format (.ppm) as an output image file format. To open .ppm files, I recommend using the GNU Image Manipulation Program; specifying the output file name is done via the --output flag.

The Swiss flag image above was generated by benzene’s Braindraw code (see their StackExchange answer linked to above); the resulting .ppm file was then scaled and converted using GIMP.
Interpreter command: python brainfuckx.py swiss.bfx -l -o swiss.ppm

Usage

  • Being written in pure Python, the interpreter is completely controlled via the command line. The basic usage is python brainfuckx.py <source code file>; by using certain flags the functionality can be altered.
  • --input <input string>-i <input string> specifies Brainfuck’s input and is given as a byte stream (string).
  • --simplify, -s outputs the source code’s simplified version; the source code with all unnecessary characters removed.
  • --colorstar selects the color star color plane change model which is the default.
  • --colorletters, -l selects the color letter color plane change model.
  • --silent stops the interpreter from outputting warnings, infos and the final tape.
  • --maxcycles <cycles>, -m <cycles> defines the maximum number of cycles the Brainfuck program can run; the default is one million.
  • --watch, -w allows the user to watch the program’s execution.
  • --watchdelay <delay> defines the time in seconds the interpreter sleeps between each watch frame.
  • --watchskip <N> tells the interpreter to only show every Nth cycle of the execution.
  • --output <output file name>, -o <output file name> saves the final tape as a .ppm image file.

# Python 2.7 Code; Jonathan Frech, 24th, 25th of August 2017

Continue reading

Cyclic Quine

A classic quine is a program which outputs its own source code.
At first, such a program’s existence seems weird if not impossible, as it has to be so self-referential that it knows about itself everything, including how to know about itself. However, writing quines is possible, if not trivial.

A cyclic quine therefore is a program which outputs source code which differs from its own source code, yet outputs the original source code when run (the cycle length could be greater than one). So when running source codes \Psi and \Phi, they output source codes \Phi and \Psi.

Therefore, when one saves the first program as q0.py and the second as q1.py, one can create both source codes from one another (the following bash commands will not change the files’ contents).

$ python q0.py > q1.py
$ python q1.py > q0.py
$ python q0.py | python > q0.py
$ python q0.py | python | python | python | python > q1.py

j=0;Q,q="j=1;Q,q={}{}{}.replace(str(j),str(int(not(int(j)))),1),chr(34);print Q.format(q,Q,q)".replace(str(j),str(int(not(int(j)))),1),chr(34);print Q.format(q,Q,q)
j=1;Q,q="j=1;Q,q={}{}{}.replace(str(j),str(int(not(int(j)))),1),chr(34);print Q.format(q,Q,q)".replace(str(j),str(int(not(int(j)))),1),chr(34);print Q.format(q,Q,q)