275 points · by keyvank · 1y ago · 128 comments
I took a 2-second peek at the code, and just wanted to offer a small piece of advice that I think makes it better. Or two, really. Counting is hard.
Instead of (this is from parser.c):
apply_result *ret = (apply_result*)malloc(sizeof(apply_result));
apply the two common principles of DRY [1] and "don't cast the return value of malloc()" [2] and you get: apply_result *ret = malloc(sizeof *ret);
I think the latter is way better.yes that makes sense. unfortunately 30cc is not able to compile that syntax, and will probably give type-checker errors when passing a void* to pointer of another type. but will implement it sometime soon!
But while the cast is a matter of style (or C++ compatibility), sizeof(*ret) is definitely superior to sizeof(thing_t). The reason is that people sometimes change the type of ret but forget the change the size of the allocation, especially if ret is assigned to on a different line it's declared.
C++ shot itself in the foot by removing automatic conversion from void* to T*, because it forces programmers to add casts that weaken type safety.
Not sure why I was down-voted, I think that is ... not nice. :(
Also... it felt kind of... unnecessary? to tell someone who is making a compiler how to write basic code in the language they're writing a compiler for. It almost felt like telling an overweight medical student/doctor that he should avoid eating fatty foods.
auto p = (thing_t *)malloc(sizeof(thing_t));
and you get both DRY and avoid (void *) casting.While that line of code is DRY, it doesn't avoid casting "void *" to "thing_t *".
If you really feel the need to give unsolicited coding style feedback maybe at least spend more than a few seconds looking at the code before you do so. Otherwise it's just rude.
I simply don't agree that redundant casts are something to be ignored, since they can be harmful and hide actual errors (the cast is a bit like `sudo make me a sandwich`, it makes the compiler do what you say which is not always a good idea).
I guess I believe that publicly posting code, and even writing a compiler for the language in question, kind of automatically marks you as interested in the language and open for ideas of usage and so on.
My apologies to the OP if you were offended. Thanks for the feedback, @gizmo.
If someone’s technical article is submitted and they are themselves participating in a discussion out feeling insulted, then accusations of unsolicited advice are unfounded.
Mh, at the same time, people who know their craft can give solid feedback within a very short timeframe. It's very impressive how good sound engineers can just pickup your mixed recording, listen to some 5 second batches, 15 - 20 seconds in total and already give very solid advice for improvement. Or when I was playing foosball more actively with league players. I could hold myself, but after 2-3 exchanges they could usually point out some technique issues.
I found GPs feedback (and the resulting discussion, heh) useful and the resulting code cleaner (in case I ever have to touch C-Code again, brr), and then learned that the compiler can't do that yet.
(And few people know that sizeof is a unary operator so the parentheses are rarely necessary. Dropping them reduces the visual noise => improves readability.)
I thought parentheses where still required for types, and are optional for variables. Even if that's not so, I still use them for types and avoid them for variables just to add one more cue about what's being sized.
as someone who works largely in C and C++ codebases, these kinds of comments are gems, especially when i learn something.
what about it seems condescending? we are on a public forum, literally designed for discussion -- unsolicited perspectives, factual or otherwise -- are the norm, not some off-beaten, micro-transgression.
to reciprocate using a similar tone to the one you used with OP: i just do not understand how people find this offenses -- what are you so sensitive about?
Why isn't that also done by the Makefile? The only catch I could see is that you'd need to have it build to different output names, but that seems fine for what it is?
---
Also, I'm curious - did you find yourself having to constrain your use of C in order to make sure that the compiler could compile itself? Or does it implement everything you would use naturally anyways?
(And of course, congrats/bravo; super impressive:])
That would be the "bootstrapping" process. Nearly a half-century ago I took a compiler lab class where we were given a working, but slightly lame, compiler, and were tasked with adding new, less lame, language features by bootstrapping. That is: 1) implement new feature without using the new feature, 2) using the compiler that results from step 1, re-implement the feature using the new feature, and compile again. 3) Repeat with more features until end of semester for best grade.
Oh, and to the OP, well done!
In all seriousness, the bootstrap process is fascinating to me. At some point, it did all start with switches and manually loading commands directly into memory. And over time, we’ve slowly kept this thing going and growing. Also… I’m old enough to have seen a Altair with toggle switches, but I’m not old enough to have had to toggle in a boot loader on one. :)
- Breadboarding some CPU components
- Breadboarding a very, very minimal CPU. More like a simple Adding + Multiplication machine with 4 registers or so, with a few premade components.
- Eventually moving up to microcoding a simulated CPU
- Eventually writing binary code to control the microcoded CPU
- At that point I kinda cheated and wrote my own assembler because I got sick of checking so many bits.
- This project then stopped at an assembly level.
- But then we implemented our own ML-variant interpreter and later on ML-variant compiler in OCaml
- And later on we had that ML-Compiler compile itself and extended it from there.
Pick your poison where to start. Just be aware that breadboarding stuff becomes very... messy very quickly[1]. And I do include Hardware in this, because you needed simpler CPUs to design more complex CPUs.
In practice, you want to pick the best combination of a familiar language that is as high level as it can be. But back in the day, that would've been assembly, binary. In the case of C, it went from BCPL, in which a compiler for B was written, in which a compiler for New B (NB) was written, which then turned into C.
Taking this process to the extreme, no one could ever bootstrap anything because eventually you're bootstrapping mineral extraction.
My guess is that some people would rather write Python code than dig into Make’s documentation. That said, ChatGPT is excellent at creating valid make files.
The thing about Makefiles is that simples ones at least are really easy to write, and read. Much simpler and quicker than a cumbersome python script, that will most likely do less with much more boilerplate code (e.g. dependencies), and be much harder to read.
Of course, you may hit a point where you stretch your Makefile so much beyond its common capabilities that that no longer becomes true, but in my experience that point is pretty far away.
Whether this is true or not depends a lot on from which programming culture/background you come.
https://bootstrappable.org/ https://lwn.net/Articles/983340/
if you want more of a challenge try a compiler compiler that can compile itself... :)
i got pretty far with this myself, although it doesn't work for weirdo languages like Python that need an exceptional lexer. i keep meaning to revisit this problem, since the tools in this space are pretty much non-existent or trash quality.
Is that not what OP did?
Modify source, compile self, repeat.
This repo claims to have the code: https://github.com/DosWorld/smallc
https://www.cs.cmu.edu/~rdriley/487/papers/Thompson_1984_Ref...
But why 3 steps of compilation?
The first step merely shows that you wrote valid C code that gcc can compile. It doesn't prove that the program actually does what promised. For example, if you missed to implement 'for' loops, this step would still produce a compiler, which could still work for a subset of C.
Here comes the second step: it proves that it implements enough features to at least recompile itself. Now, this is still not a guarantee that all C constructs and features work, but we can reason that even if it only implements a subset of C, it's a large enough subset to build such a substantial app as a compiler. How likely is it that a compiler doesn't use a 'for' loop, not even once?
But what is the reason for the third step? It doesn't add anything, it doesn't trigger any code path that was excluded in the first one. After all, if you did miss 'for' loops, and the 2nd step hasn't detected it, it must be because there are no 'for' loops in the source, so you will never detect it this way, no matter how many steps of recompilation you run.
The 1st step uses gcc, so it's not going to find any bugs in this compiler.
The 2nd step uses the compiler as compiled by gcc. That will find some bugs, such as crash bugs or missing features (like your for loop example). However, it does not find bugs that lead to generating incorrect code.
The 3rd step uses the compiler compiled by itself. If there is a bug in code generation that led to the stage-2 compiler being compiled incorrectly, that is likely to lead to some error during stage-3 compilation, such as a crash. And if it doesn't crash outright, it is very likely to cause the resulting executable to differ between steps 2 and 3. The incorrectly compiled compiler is surely even worse at compiling correctly than the compiler that was presumably compiled correctly (using gcc)!
So, this 3-step process is a pretty good way of finding bugs, especially if you compare the stage-2 result against the stage-3 result.
I think that could be done with a single-pass C compiler. In a very trivial (and terrible) case, you could keep a running "line_counter" variable that every statement in the loop is predicated with, which either gets incremented at the end of the loop, or set to an arbitrary value for representing branches.
It would of course be a horrible (but very amusing) mess, and rather enforces your actual point.
PS: Why all the downvotes? Just another perspective.