Skip to content

Latest commit

 

History

History
11 lines (6 loc) · 2.37 KB

thue-api.md

File metadata and controls

11 lines (6 loc) · 2.37 KB

How this Thue implementation works

Everything relevant to core Thue functionality is in thue.js.

The Thue class is the core manager for a Thue program. The constructor takes the list of rules and the string. You then repeatedly call stepOnce() on your Thue instance until it returns true, which means no rules match and the program has halted. However, the base Thue class doesn't handle input and output - the subclass OutputThue handles that. It takes an element along with the rules and text, and inserts a <code> (the workspace) in which it shows the current state of the string, and a <pre> (the output box), in which the output appears. prompt() is used for input. OutputThue's tick() method wraps stepOnce() to keep the workspace element updated with the state.

The parse function covers the task of converting the raw text file into Rules that can be passed to a Thue. It is passed the raw source code and a list of rule classes, and optionally a terminator to signal the end of the rules and the start of the beginning string (which defaults to a line containing ::= and nothing else). For each of the lines, it passes them to each of the Rule classes passed in which do the work of parsing the rule into left and right, or throw an error if they can't parse it. If it throws, the next rule type is tried, until one matches. If none match, that's a syntax error, and that error is allowed to propagate up the Javascript call stack. A 2-tuple containing the list of the final Rule objects and then the starting string is returned. An error is also thrown if there are no rules.

The Rule class (and subclasses) implement two methods that the Thue class uses to apply them. First, findMatches() is passed the string, and must return a list of artifacts that each represent one match. Thue then picks one artifact at random, and passes it and the string to applyMatch(), which returns the new, modified string. The artifact format doesn't need to be anything standardized across rule types -- no artifact generated by class X will ever be passed to class Y. The artifacts just need to be something that will uniquely determine each match to the rule that matched, so it can be applied correctly.

The code in main.js does the aforementioned work of repeatedly calling tick() on the OutputThue instance to run the program, as well as fetching the examples and parse().