NewsCrawler.org

Let's Write a PostScript Interpreter

The author argues that the most trustworthy languages are human-scale ones, which a single user could reasonably write from scratch. The article shows how to implement a simplified subset of PostScript, a language designed mainly for describing printed documents, which is treated here as a general-purpose language. Many features are simplified and most error handling is left out, but the examples in the toy subset behave the same as in a standard interpreter such as Ghostscript.

PostScript programs are sequences of tokens separated by whitespace, and special characters such as % / ( ) < > [ ] { } end the preceding token. Procedures in braces are collected without being executed and run later, as in the example that defines double. Execution relies on an operand stack[1] for arguments and a dictionary stack[2] that links names to values. The [ operator pushes a mark, and ] builds an array from the values above the mark.

The interpreter is written in a concise JavaScript style influenced by Forth, an influential ancestor of PostScript. Data types map to JavaScript values, and a RegExp splits the program into tokens. The stacks are global arrays, and each operator is a JavaScript function that pops its arguments from the operand stack.

Read the original beyondloom.comDiscussion

Discussion

Commenters mostly welcome the human-scale idea and the compact JavaScript style, and several share their own PostScript projects, including a Deflate decompressor, a C interpreter and a Python interpreter with PyCairo graphics. One commenter calls the tutorial a yawner, arguing that the language itself is simple and that the hard part of a real implementation is graphics and font rendering.

Sources

Published: First seen: Читать по-русски

Open as a page