Question

I'm working on a compiler project and I need to implement functions in a C-ish language: First off, I'm using the Racket parser tools (http://docs.racket-lang.org/parser-tools/LALR_1__Parsers.html?q=~a)

Anyway, my current rule for function declaration in my grammer is:

(fun-declaration 
     [(type-specifier FNCT \( \) compound-stmt) 
      (begin
        $1
        (printf "~nA function is being declared~n")
        $5
        )])

My problem is that the compound-stmt is being evaluated before the code in the begin block (that's a place holder print, the actual code has assembly that is irrelevant to the question). This means that any assembly I print to the file for the function setup/header is written AFTER the compound-stmt, where compound-stmt is {code code code...}

How can I get the code in the begin block to evaluate BEFORE the compound-stmt?

Was it helpful?

Solution

How can I get the code in the begin block to evaluate BEFORE the compound-stmt?

You can't.

The documentation says:

Each action is Racket code that has the same scope as its parser’s definition, except that the variables $1, ..., $i are bound, where i is the number of grammar-ids in the corresponding production. Each $k is bound to the result of the action for the kth grammar symbol on the right of the production, if that grammar symbol is a non-terminal, or the value stored in the token if the grammar symbol is a terminal.

It sounds as if you are attempting to write a one-pass compiler.

The solution to your problem, is to write a two-pass compiler instead.

The first pass is the parsing. The parser must generate a temporary data structure representing the parsed code (i.e. an abstract syntax tree, AST). In the second pass you use the tree representation to generate code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top