Ingwie Phoenix
Ingwie Phoenix

Reputation: 2983

Implementing if-condition in preprocessor

For a project of mine, I want to implement a customized preprocessor in JavaScript that mimics the GNU C Preprocessor (i.e. gcc -E).

This preprocessor I wrote already has most things working, except conditionals. So, #ifdef, #ifndef, #else and #endif is what I am stuck at.

My code thus far: preprocessor.js (permanent link)

I'd be glad to hear about suggestions on how to implement it! :)

Upvotes: 0

Views: 233

Answers (2)

mym
mym

Reputation: 282

Better approach would be parsing into the AST which will contain clearly defined base blocks and control flow graphs.

For example "if" (conditional) construct can be expressed as

conditional
|
-- test
-- consequent base block
-- [alternate bb]
-- [elseif 1]
    |
    -- test
    -- consequent
   ...

This approach is much more flexible and allows creating full-scale language with functions, loops, contexts, etc.

Good example can be seen in Builder preprocessor: https://github.com/electricimp/Builder

Upvotes: 1

georg
georg

Reputation: 214949

Maintain a stack of conditions and keep skipping lines as long as any condition is false. In pseudocode:

 for each line
    if line == "#if <cond>"
        conditions.push(<cond>)
    else if line == "#else" 
        conditions.push(!conditions.pop())
    else if line == "#endif" 
        conditions.pop()
    else if all conditions are true
        everything fine, handle line
    else
        skip line

Upvotes: 3

Related Questions