436 points · by azhenley · 6y ago · 131 comments
The trick to reading it:
* next() is the lexer
* expr() is a precedence-climbing expression parser
* stmt() parses statements and generates code
* main() has the virtual machine loop.
* It never bothers to produce a machine code. The use of stack-based VM simplifies the single-pass compilation, and it never makes use of unknown library functions so no machine-specific knowledge is required (like dlsym in Bellard's OTCC [1]).
* It chose its primitives wisely. It never implements structs and returning with values, for example, but the code is carefully structured that the lack of them doesn't make it harder to read.
* And yet it has tons of little tricks. Switching from r-value to l-value (triggered when infix `=` or postfix `++`/`--` are read) is a single opcode fix. Reserved words are initialized from an imaginary source code. The type is represented by a single number 2n+k where n is the number of indirections.
What does it mean? Could you point to a place in the source?
p = "char else enum if int return sizeof while "
"open read close printf malloc free memset memcmp exit void main";
i = Char; while (i <= While) { next(); id[Tk] = i++; } // add keywords to symbol table
i = OPEN; while (i <= EXIT) { next(); id[Class] = Sys; id[Type] = INT; id[Val] = i++; } // add library to symbol table
next(); id[Tk] = Char; // handle void type
next(); idmain = id; // keep track of main
Throughout the entire source code p is a source code pointer, but at the very beginning of the program it is a string containing all reserved words and library functions, and they are read with the same lexing function `next` to the symbol table before the memory for the actual source code is allocated.For a just-as-interesting "sequel", look at C4x86: https://github.com/EarlGray/c4
The real size of this code, after putting each statement on its own line, would be on the order of 300%.
Imagine this:
if (tk == Mul) { next(); *++e = PSH; expr(Inc); *++e = MUL; ty = INT; }
Turning into this: if (tk == Mul) {
next();
*++e = PSH;
expr(Inc);
*++e = MUL;
ty = INT;
} else if (tk == Mul) { next(); *++e = PSH; expr(Inc); *++e = MUL; ty = INT; }
else if (tk == Div) { next(); *++e = PSH; expr(Inc); *++e = DIV; ty = INT; }
else if (tk == Mod) { next(); *++e = PSH; expr(Inc); *++e = MOD; ty = INT; }What's more impressive is that it's self-hosted and implements just the subset of C required to compile itself, which makes it harder to keep the code short, but it manages anyways.
$ cc float.c && ./a.out && ./c4 -s float.c && ./c4 float.c && echo 'struct { int a; } s;' >struct.c && cc -c struct.c && ./c4 -s struct.c
hello, world 1.250000
1: #include <stdio.h>
2:
3: int main()
4: {
5: printf("hello, world %f\n", 1.25);
ENT 0
IMM 83656704
PSH
IMM 1
PSH
IMM 25
PSH
PRTF
ADJ 3
6: return 0;
IMM 0
LEV
7: }
LEV
hello, world 0.000000
exit(0) cycle = 13
1: bad global declaration
$Most variables names are what I expected them to mean despite their shortness: pc, sp, bp are registers, a is the accumulator, fd is a file descriptor (of the input file, what else?), tk is for the token, t is temporary, etc... For the less obvious ones, it is usually not that hard to infer their meaning from either the code or comments.
Because yes, they are comments, not many, but they are helpful. For example, the VM has unusual instructions (for me) like LEV and ADJ, and they are commented. The "obvious" ones like MUL and SHR are not.
The variable names are not "needlessly cryptic". I've seen (and written, not proud of it) a lot of needlessly cryptic variable names, and believe me, these are crystal clear by comparison. Here, there is a clear influence from assembly mnemonics that really helps understanding.
Now on the why. This is minimalism, and minimizing the number of comments and variable name length is part of it. It is actually a very interesting exercise. The golden rule in making understandable code is making it as short as possible. There is a limited amount of space on your screen and in your mind, and the shorter your code is, the more you can see/understand at once. Of course, too much is too much, you don't want to do things IOCCC style, and striking a balance is difficult. So once in a while, reading or writing very compact code can help you understand where shaving off characters is fine and where it really hurts understanding.
Absolutely not true, in any way.
And I fail to see a single reasonable argument for why writing "tk" should be better than writing "token". Just name things using real words. Cryptic abbreviation does not help anyone.
The same way you "grep", "ls" or "cd" --- it easily becomes as natural as any other language, unless you consciously try to stop yourself from learning.
The source of my favorite C compiler, on the other hand:
Compare with this, which is probably more in the style you're thinking of:
https://github.com/dotnet/roslyn/blob/master/src/Compilers/C...
There's so much "noise" that it's hard to see the "big picture", and the repetition of VeryLongIdentifiers causes https://en.wikipedia.org/wiki/Semantic_satiation to occur quickly.
So long lines need to be split. Which is difficult to do properly and results in more lines, and more lines mean less of the code is visible at once and that makes it harder to see the big picture.
But to each his own I guess. Anyway, you can try it out yourself. Just take the code, do the replacements and see for yourself.
If that were the case people wouldn't even bother with assembler mnemonics, comments and white spacing. People would write their Javascript / CSS minified from the outset and code golfing would be a best practice rather than a niche activity that some developers do for fun.
I do actually get the point you're trying to make in your post and you do raise some valid points but that sentence is massively overreaching and thus works against you.
Including: p -> position, pointer ? lp -> location pointer ? bss ??? e -> expression ? emitted code? le -> location of emitted code?
Num number? -> why 128, I guess it's related to ASCII ending at 127 Fun function? Sys ??? Glo ??? Loc location? Id identifier?
[reserved keyword are mostly complete word] Char (charset, sign) Else Enum (enumeration, roll) If Int Return Sizeof (size of, heft) While
Assign (assignation, peg) Cond (condition, ply) Lor (logical? or, ere) Lan (logical? and, also) Or Xor (exclusive or, otherwise) And Eq (equals, dows) Ne (not equals, jars) Lt (lower than, Gt (greater than, Le (lower equal Ge (greater equal Shl (shift left, haw) Shr (shift right, gee) Add Sub (subtract, take) Mul (multiply, time) Div (divide, rive) Mod (modulo, lap) Inc (increment, amp/eke/pip) Dec (decrement, ebb/dip) Brak (break, blow)
between parentheses I provided a guess, and a real English word that could carry the same meaning, generally in less than four letters.
I didn't go further in the code so far.
Maybe you have the right background to channel the author's particular form of abbreviation, but I have no idea what bp is supposed to stand for, despite having read and understood how it's being used in the program. If that name was supposed to communicate something, I am really not sure sure what it was. Yes, I understand it's probably a reference to some register in some architecture, but that's only effective communication to an audience with a background in that architecture. Even if you know pc = program counter, what exactly does that communicate to someone who doesn't know assembly language?
Of course, using "pc" allows a person with a background in assembly to quickly grok what that variable is, so there are upsides. A best-of-both-worlds approach might be to name it pc and teach people who aren't familiar with assembly language what that means with a comment, like:
int *pc; // program counter, points to the current instruction
Ask yourself, even if the person knows a = accumulator, what is the accumulator accumulating? When you realize that that isn't even a really sensible question in the context because "accumulating" isn't even really what that variable does, then I have to wonder why you think that's a good name for that variable.> Because yes, they are comments, not many, but they are helpful. For example, the VM has unusual instructions (for me) like LEV and ADJ, and they are commented. The "obvious" ones like MUL and SHR are not.
> The variable names are not "needlessly cryptic". I've seen (and written, not proud of it) a lot of needlessly cryptic variable names, and believe me, these are crystal clear by comparison. Here, there is a clear influence from assembly mnemonics that really helps understanding.
That's helpful if you know the specific assembly language the author is referencing. But if you don't know assembly language, or if you know a different assembly language, it's not helpful. That SHR instruction you said is obvious doesn't exist in MIPS[1], which is what a lot of assembly beginners will get introduced to. Oh and by the way, which assembly is being imitated isn't documented, so you can't even look that up easily.
The "unusual instructions (for me)" aside is telling: not everyone is you. If your variable names only communicate to you, they don't communicate (an activity that famously involves just one person[2]).
> The golden rule in making understandable code is making it as short as possible.
That's total nonsense. Code becomes understandable when you see it as communication, which starts with understanding who your audience is, and catering your communication to their vocabulary. If your audience has a strong background in x86 assembly, they probably have the vocabulary they need to understand this program. But that is actually a quite narrow audience.
Just to be clear, I don't think this is a bad program. There's a lot to be said for choosing a goal and following through with it, and some of this code is downright brilliant. But effective communication, it is not.
[1] http://inst.eecs.berkeley.edu/~cs61c/resources/MIPS_Green_Sh...
I get it to compile on macOS if I remove the int define but then it segfaults when you run it. I wonder if there is some magic flag to make "main does not return int" a non-fatal error on Clang?
It's fun to read this code but running it is even more fun, you can see the VM code it generates, with source line annotations and all.
#include <stdint.h>
...and then replace the two "int" in main() with int32_t.
https://news.ycombinator.com/item?id=8560127
You can compile it on 64 bit OS X with clang's -m32 option and it should work.
BTW, the code looks relatively short because many semicolon-separated statements are crammed on a single line, and short variable names make that somewhat manageable and even visually symmetric. If you were to unfold it with each statement on its own line, I guess it would be at least 3 times the size.
This should be added to the README.
But yes, many people rely on parsers and VMs without really knowing how it works and assume some black magic, whereas it can be really simple and elegant.
int main(int argc, char **argv) {
}
Sadly, it doesn't support that much…Well maybe that's not the right word. But the minimalism of it is soothing.
So I sketched my refactorings without bothering to check them or to publish it.
https://michaelfeathers.silvrback.com/characterization-testi...
Can't the author use pre-processor string concatenation to write once and then leverage that to map enum to string and back?
At least I'm doing that in a little scripting language parser and it looks portable.
Edit: I'm actually using pre-processor string concatenation for something unrelated. You don't even need that to do the mapping.
(I have mixed feelings about this code: it has both good ideas and pointless obscurity. I guess the newer version would've taken me 'only' three evenings.)
The code quality is terrible. Few explaining comments (actually mos of those are only 1 or 2 words, so not explaining anything at all) and almost all variable names consist of 1 or 2 characters, which do not say what the thing actually is. Then to achieve this arbitrary goal of doing it "in 4 functions" (actually procedures) loads of stuff was apparently stuffed into 4 those 4 functions, so much so, that they are longer than a whole page of code. Most of it looks like gigantic switch statements. It's horribly written code. It looks like what I think of as a C nightmare.
I will admit, I could not write such a thing myself. I lack the knowledge for writing such a low level stuff, do not use C, and if I had that knowledge to do it, my inner drive to do a cleaner job than anything remotely looking like that code, would prevent me from ever sharing such a thing with anyone in public. At least group cases into procedures as it makes sense. Even people writing this low level type of code should be aware of how unreadable that code is, right?
And yet you have a strong opinion about how terrible it is.
It is very minimal and it is very readable. It is actually a joy to read. You have no idea what a C-nightmare really is.
Wait, you are telling me, that people write even less readable code in C? Perhaps you are right. Perhaps people can really be that much without care.
It still does not make this code "very readable". If it was very readable, I would have a vague idea about what each of the "functions" does from reading its name or its docstring. Oh wait, there is no docstring at the beginning of each of the "functions" and the name consists of one word, sometimes abbreviated word. And the variable names don't give me hints either. I think our definitions of readable code simply differ quite a lot. When I write code myself, I am unwilling to accept code on that readability level, but we probably have different standards.
Perhaps for entertainment purposes only, you could show me a real C nightmare. I do honestly believe you, that there is worse ;)
I don't understand mathematics, therefore math is undreadable.
I don't understand music, therefore sheet is unreadable.
That is your problem in a nutshell.
Meanwhile, people here take a glance at the code and immediately get it, because it is written in a language they understand. These people tend to find it quite readable -- not necessarily an example of most pretty code, but nevertheless readable.
I'm a person who has written a lot of c, readable and unreadable. It's not that folks don't care; I find that notion slightly offensive. It's that a lot of c programmers care about different things. And, especially those of an older school have a different mindset.
When you read c source, especially that labelled "exercise in minimalism", you should approach it as hallowed. Enter the file with a sense of reverence; lose the ego; ask not why the file wasn't written in service to you. As you have here, tsk tsk. Expect a challenge, a puzzle. Ignore the variable names; they may be misleading -- learn for yourself what role each variable takes on each line -- some of us will reuse a variable for multiple purposes throughout its lifetime. Humble yourself with the understanding that the code was not written for you. It was written for a machine infinitely more patient and methodical than you. Use that machine to execute and debug, watch and analyze, to discover the true meaning.
Perhaps people would be less reluctant to show their code in public if it were not so often criticised for falling short of some criteria that the author was never intending to meet?
Ah, let me quote: "Programs must be written for people to read, and only incidentally for machines to execute." – Hal Abelson
And I believe he is right. If you don't write your programs for other people to read, then they not worth being written in that way. Always consider that next person, who needs to read and understand your code. If you don't, then you are not much of a great team player at all. It's great you can do some brain acrobatics, but not much use, if the only one on team being able to understand your code is yourself. I don't know how many 1 person software developer jobs there are still out there, but I guess the number is vanishingly small, compared to team jobs. I would not want someone in my team, who does not pay attention to keeping things very readable.
> Perhaps people would be less reluctant to show their code in public if it were not so often criticised for falling short of some criteria that the author was never intending to meet?
True, you got a point here. But do we want this display of code? However, personally, I'd probably not miss reading such code and maybe it would even be good for the entire profession of software development, if such code was not displayed as something to be achieved but rather something to be shunned.
I write both terse notes to myself, and longer more well-thought out sets of notes to distribute to undergraduates in classes I teach. I wouldn’t give the undergraduates my personal notes - they are simply too unpolished and terse - but my colleagues find them very helpful on occasion. Is it wrong to have two different ways of writing?
I would say this C implementation leans somewhere between “note to self” and “arty exploration”. Is it worth being written? I don’t think you or I could be the judge of that, but the author obviously thought so. Live and let live.
If you think this is unreadable, then you are not qualified to read it --- yet. I implore you to try; maybe it will actually be enlightening.