1c1d34ed7852ec94bdb416c2ac543c864dcebeae — Noam Preil 8 months ago 957353f master
design: add parser document
1 files changed, 50 insertions(+), 0 deletions(-)

A design/parser.roff
A design/parser.roff => design/parser.roff +50 -0
@@ 0,0 1,50 @@
.so ../c3lib/design/shared.roff
Zig Parser


The zyg parser directly translates Zig source code into Carbon IR. There are a few difficulties to such direct translation.

Control flow

When translating many constructs, the control flow target is not known. For instance, take the following sample input:

const foo = fn()void{

When parsing the while's block, we generate a conditional branch for the if statement. Every conditional branch terminates its block, and has two targets: the truthy block, and the falsy block. The truthy block for the if statement is, of course, the empty block defined on the line with the if. The falsy block is more tricky.

Since the conditional branch is terminal, the block containing the if is terminated at that point. We could simply assume that there is logic after the conditional, and begin construction of the following block - but, IR constructs cannot be produced until all of their children is known. As such, we cannot target the conditional branch until \fIafter constructing the target\fR. As such, tracking where control flow goes is \fImandatory\fR.

As such, there is no reason to construct a shim block to redirect control flow, anyways. After evaluating the conditional, we leave the falsy target blank, and track it in the parser's state. We then resume processing instructions in the block containing the conditional - in this case, the while(false) block. At this point, there \fIis no active block\fR. We see there are no instructions in the block, and we're in the middle of control flow, so we target the falsy branch of the if to where control is flowing, up to the beginning of the loop.

In other words:

Evaluate function block
	While found - generate conditional branch.
		Since this is the beginning of the block, mark this block as the loop start.
		Fully parse truthy target
			Parsing if statement, generating conditional branch.
				Fully parse truthy target
					Empty block produced
				Leave dangling control flow edge
			Control needs to flow to beginning of loop. Control flow is dangling.
				Target falsy branch of if at beginning of loop.
		Leave control flow dangling
	Function end, control flow is dangling.
		Generate a block which returns, set as control flow target.