Get locality with graphics and dictionary stack

When you add or change a value to the dictionary, all changes are global. This can become a problem when you use variables in operators you define.

Javascript Editor

As you see in this example, foo is first 1, then becomes 2 when you use bar which has defined foo as 2. When your code becomes more complex, it may become complicated to keep track of the variables.

There is a similar problem for transformation. An operator might change user space. How do you want to get back to the original user space.

Javascript Editor

It is possible to get back to the original user space, if you make the inverse operations in the reverse order. However, this is difficult to track. You might also have to deal with rounding errors.

There must be a way to create locality. Actually, there is. PostScript provides a stack of dictionaries and also a stack of graphics state. You can add a new dictionary to the stack with n dict begin, remove it with end. You can add a new graphics state width grestore and remove it with gsave.

We adapt the context to host a stack of dictionaries and a stack of graphics and create a datatype dict, because dict can also be on the stack. The mechanism PostScript uses is to go down all the dictionary stack to find the value.

Javascript Editor

We define the operators for dictionaries. n dict creates a new dictionary and puts it on the stack. n is the original size of the dictionary. That played a role in PostScript version 1 when memory was limited. You can give any size. begin puts the dictionary from the stack to the top of the dictionary stack. end removes it.

Javascript Editor

No this works.

Javascript Editor

For the graphics stack, the code is similar, with the difference that the set of graphics parameters is fixed, so that we just copy the entire graphics. Note that the stack never gets empty.

Javascript

We can no rewrite the above code more savely

Javascript Editor

The codebase is now 1633 lines ps20240802.js

My Journey to PostScript