Tiny Programming Langauge in 25 Lines of Code
There are certain kinds of programs that fascinate certain kinds of software hackers. Maybe you are into number crunching, chess programs, operating systems, or artificial intelligence. However, on any significant machine, most of the time those activities will require some sort of language. Sure, we all have some processor we can write hex code for in our head, but you really want at least an assembler if not something sturdier. Writing languages can be addictive, but jumping right into a big system like gcc and trying to make changes is daunting for anyone. If you want a gentle introduction, check out [mgechev’s] language that resides in 25 lines of Javascript.
The GitHub page bills it as a tiny compiler, although that is a bit misleading and even the README says it is a transpiler. Actually, the code reads a simple language, uses recursive descent parsing to build a tree, and then uses a “compiler” to convert the tree to JavaScript (which can then be executed, of course). It can also just interpret the tree and produce a numerical answer.
As you might expect, the 25 line number is if you suck all the comments out of the file. With the comments — and they are welcome — it is more like 140 lines of code. Although there’s not much there, it does follow what you’d expect for a traditional language translation system. That is, there’s a lexer, a parser, a parse tree, and parts of the code that interpret or compile (again, sort of) the code.
This probably isn’t practical as-is, but it would be hard to imagine an example that could be simpler to approach. Once you figure out how it works, you could go on to build your own languages. Sure, you would have to figure out a few things like how to best parse algebraic expressions and how to handle parse conflicts, but you’d have the core ideas under your belt.
If you think you don’t need fancy transpilers for your old vintage computers, you might be surprised. We aren’t sure JavaScript would be our first choice for writing something like this, but it is ubiquitous, so for educational purposes, it might be a good choice. Besides, you could always host it in a browser (although, not the original link in that post has moved).
from Hackaday http://ift.tt/2E2ZqLL
via IFTTT