4 ms·
For beginners, I would go for a recursive descent interpreter (just made up that term) that implements a 'little language'. That is something on the complexity
by Someone 11y ago
For beginners, I would go for a recursive descent interpreter (just made up that term) that implements a 'little language'. That is something on the complexity of a shell without looping or variables or of parsing argv:
- read a line
- do a switch on the first word of the line
- inside each switch, make up your own syntax, parse the
remainder of the line, and execute it or issue an error
message and abort.
Feel free to cheat by using scanf to parse integers.
Iteration 2 can add printing the line number in error messages.
Iteration 3 can add if/then and looping: keep the lines in an array, and add 'goto' to the list of commands, and hack the jump into the interpreter loop by adjusting a global variable from inside the 'goto' statement.
Iteration 4 can add the 'let' command and variables. Naming them A through Z for simplicity is an option.
Then, add simple assignments of the form
let a = x <op> y
where x and y are liberals or variables. For now, don't bother with expressions with multiple operators.
Next, add statements of the form
y = f(x)
That gives you a sort-of 70's Basic that can be quite useful and fun to use.
Only then would I start introducing grammars, the word 'parse', etc.
- sklogic 11y agoAnd what's a point in such a complex approach, if a proper interpreter (or, even better, compiler) is much simpler?
- Someone 11y agoComplex? Its building up from almost nothing, and shows how simple an interpreter can be. If you start with a grammar, you lose half your audience within 5 minutes (numbers made up) If you start with a program that reads a text file and plays notes for lines contaning do, re, and mi, part of that lost audience will get drawn in, complete the scale, add 'fart' commands, etc. Also, smart kids may figure out they can easily add single-statement loops on their own, by adding a case 'repeat' that scans for the number of iterations, removes the 'repeat' and that number of iterations from the line, and then calls the 'processALine' code. It's "learn by playing" vs "learn through study".
- sklogic 11y agoYou do not have to do such clumsy things to build from nothing. Split the input by whitespaces, lookup word definitions in a table (linked list is ok), push the addresses of the found words to the output stream as call instructions or execute immediately if marked so. That's it, a minimal direct threaded Forth compiler is done.