News for hackers. Stuff that matters.
Re:Self hosted C – breakdown by userbinator on Friday December 04, 2015 @04:59AM (#10675480)
It's always great to see more people writing their own compilers - a "proof by example" that compilers do not have to be magical and mysterious special software that only few experts can write. The theory may be deep, but in practice getting a basic working compiler doesn't require all that much.

I notice you're using a recursive-descent parser, which I think is a good idea because it can actually reduce complexity over one made with parser-generators; in fact it's simple enough that even beginners who have just grasped recursion should be able to understand and write one. Once you have a basic parser that can evaluate arithmetic expressions, extending that to generating AST nodes and parse a (mostly) simple language like C is not so difficult. If I remember correctly, at least one college has an expression evaluator as a first-year CS assignment related to recursion. It's interesting that one of the sections of K&R, on reading and writing C declarations, even contains a simple parser for them --- I'm not aware of any introductory books for other languages which contain small pieces of their implementation.

That said, you can use the "precedence climbing" technique[1] to collapse many of the recursive functions for most of the expression operators into one function with a succinct loop and a table, making your parser even simpler and faster. C4[2] is an example of this technique but with a series of if-else in the body of the function instead of a table, and I think is worth some careful study just for its mindblowingly awesome ridiculous simplicity.

[1] https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm#climbing

[2] https://news.ycombinator.com/item?id=8558822

Re:Self hosted C – breakdown by david-given on Friday December 04, 2015 @06:59AM (#10675812)
C is notoriously painful to parse with a parser generator because it's not context free --- consider this statement:

    foo * bar;
It can't be parsed until you know whether foo is a type or a variable --- indeed, depending on the implementation, it can't even be tokenised correctly. So you need hooks from the symbol table back into the tokeniser/parser. I'm not at all surprised that the author's using a hand-written parser, as it reduces the problem space considerably.

(There's a really good article which I've been trying to find which goes into details about all the weird parsing edge cases due to the rules about exactly when a word goes into the symbol table which I've been completely unable to find...)

Re:Self hosted C – breakdown by kazinator on Friday December 04, 2015 @01:17PM (#10677993)
C is completely easy to parse, because it reduces to a LALR(1) parseable context-free language after the semantic mapping of input symbols into abstract lexical categories. In fact, it can be parsed by recursive descent with a suitable factoring, so that it is almost certainly LL(k), possibly with k = 1. Pardon me, k == 1. :)

That mapping requires semantic information (type declarations), but that information is something the compiler must maintain anyway so that it can type check the language.

Yes, if we simply treat "foo" as an IDENTIFIER token and feed that to the parser, thing swill be difficult. But we don't; what we return to the parser is a TYPESPEC token, based on peering into the current parse-time lexical environment where we resolve "foo" to a typedef name. The parser then quite easily goes through the state transitions corresponding to its declaration rule.

Sure, a parser which maintains parse-time lexical environments which are also visible to the lexer is slightly harder to write than one which doesn't have such stuff (and just returns an unadorned AST which you can walk again to build that info).

But if the year is 1973, you would likely do that anyway even if the language doesn't require it. Why? Because building the compile-time environment tree reduces the number of passes: from a single pass through the raw code, you already have the syntax tree with type info (and possibly type info that has even been checked).

Re:Self hosted C – breakdown by yepguy on Friday December 04, 2015 @11:19AM (#10677161)
As far as I know C is context-free. If C's grammar is ambiguous, that just makes it an ambiguous context-free grammar [1].

[1]: https://en.wikipedia.org/wiki/Ambiguous_grammar

Re:Self hosted C – breakdown by kazinator on Friday December 04, 2015 @01:12PM (#10677955)
The context-free terminology doesn't apply to C because the ambiguity rests in not knowing what is the lexical category of foo in "foo * bar". That information comes from semantics.

A language whose semantics you have to understand to understand its syntax is outside of the entire formal language realm inside which we formally recognize a "context-free" category. That formal language realm is purely syntactic: the terminal symbols are just "dumb" and stand for themselves. They are subject to rules which indicate how those symbols are combined.

C is "quasi context free" in that if we resolve what the raw tokens mean (which one is a type and which one isn't), then the resulting language is context-free. In fact stronger than context free: amenable not only to LALR(1) parsing approaches but to recursive descent, with a suitable refactoring of the left-recursive rules given in the standard.

Re:Self hosted C – breakdown by yepguy on Friday December 04, 2015 @10:15PM (#10680640)
Your post doesn't really agree with what I was taught.

> the ambiguity rests in not knowing what is the lexical category of foo in "foo * bar".

Right, so there are 2 possible parse trees. Being able to disambiguate them with more information doesn't mean it's not context-free. Given just a CFG, you were still able to determine that you have a syntactically valid C program.

> A language whose semantics you have to understand to understand its syntax is outside of the entire formal language realm inside which we formally recognize a "context-free" category.

A formal language is just the set of strings that belong to it. That's it. An absurd example might be "the set of strings corresponding to valid C programs that do not terminate". To recognize such a language, you would not only have to understand the semantics of C, you would even need to solve the halting problem, but that doesn't make it "outside of the entire formal language realm".

Re:Self hosted C – breakdown by kazinator on Saturday December 05, 2015 @12:58AM (#10681049)
> Right, so there are 2 possible parse trees.

Not with the same symbols, though.

> A formal language is just the set of strings that belong to it. That's it.

That is correct, and in that framework, we cannot reason about the meaning of "foo"; that if it's a type apply this rule otherwise that rule.

If we do that reasoning, what we're really doing is replacing "foo" with one of two other symbols, and then parsing those; then we have different strings (so of course the parse trees cannot be the same, no matter what).

Re:Self hosted C – breakdown by yepguy on Saturday December 05, 2015 @02:02AM (#10681166)
We don't need to decide to apply this rule sometimes but other times that rule. When we come to an ambiguous string, we apply both rules nondeterministically. Here's a pseudo-grammar that I think describes both possibilities.

  Statement -> Type Op Var ";"
  Statement -> Var Op Var ";" 
  Op -> "*"
I think the disconnect here is that most lexers would insist on feeding a different token to the parser depending on whether "foo" is a Type or a Var, and choosing one or the other means the lexer might feed it bad information. The pragmatic way to implement this in a real compiler is to add some logic to the lexer so that it's working with more information than just the syntax. Theoretically though, all that really matters is that both possibilities are syntactically valid. So another way to implement it would be to pass on both possibilities, letting the parser eliminate the one that doesn't compile.
Re:Self hosted C – breakdown by kazinator on Sunday December 06, 2015 @01:00PM (#10685926)
Indeed. There is a rule that Type generates Identifier, which can generate an example like foo. Likewise, Var generates Identifier, which generates foo. But these generations are not purely grammar rules; Type can only generate foo if there exists a declaration in the semantic space. If we regard it as purely a grammar rule, then we have a straightforward ambiguity in a context-free language. It is context-free simply because the rules are all of the form one_sym -> zero_or_more_syms.

If C were parsed this way, nondeterministically, ultimately the ambiguity would be resolved by looking up the type info anyway. (The interesting possibility exists, though, that in some cases the type info could be inferred, based on how the declared identifier is used.)

Re:Self hosted C – breakdown by dbpokorny on Friday December 04, 2015 @02:28PM (#10678486)
> you need hooks from the symbol table back into the tokeniser/parser

not necessary. you can add a bit of information to each identifier token: is this the name of a type or not?

you have to split up one of the parser passes, so if you had a two pass "tokenizer" and "LR parser" compiler now you have a tokenizer pass followed by two LR parser passes. The first LR pass is "last mile tokenization". I guess another word would be a (very short) cascade tokenizer/parser.

The intermediate pass adds a piece of metadata to each token marking it as the name of a type or not (this makes the language actually context free instead of just nearly context free). If you do this, then the second pass doesn't see this as two identifiers at all because it knows which identifiers refer to types and which do not.

It's a different application (computing scope data instead of type data) but I've implemented the basic concept of annotating token data with the result of an intermediate parsing stage here...check out line 318 here:

https://github.com/dbpokorny/autoclave/blob/master/tree.js

Re:Self hosted C – breakdown by JoeAltmaier on Friday December 04, 2015 @11:49AM (#10677361)
But that hook is trivial. Scanner returns Identifier or Type as appropriate. Not really painful at all.
Re:Self hosted C – breakdown by andrewchambers on Friday December 04, 2015 @07:07AM (#10675838)
Re:Self hosted C – breakdown by emptybits on Friday December 04, 2015 @05:06AM (#10675503)
introductory books for other languages which contain small pieces of their implementation

I feel like two of the very few contenders for this might be books on Forth or Lisp, though still maybe not an "introductory" book.

Re:Self hosted C – breakdown by junke on Friday December 04, 2015 @05:15AM (#10675521)
Such as Queinnec's Lisp in Small Pieces (https://en.wikipedia.org/wiki/Lisp_in_Small_Pieces)
Re:Self hosted C – breakdown by andrewchambers on Friday December 04, 2015 @05:51AM (#10675607)
I actually plan to do exactly that that for the preprocessor's expression parser. Thanks for the info!
Re:Self hosted C – breakdown by w23j on Friday December 04, 2015 @06:45AM (#10675766)
You probably already know this stuff and don't need the info. But maybe somebody else reading this can find the link useful.

This is a great tutorial on expression parsing using Pratt Parsers by Bob Nystrom:

http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-e...