Ingwie Phoenix Ingwie Phoenix - 7 months ago 24
Javascript Question

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! :)

Answer

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
Comments