Ingwie Phoenix Ingwie Phoenix - 2 years ago 140
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,
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 Source

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>"
    else if line == "#else" 
    else if line == "#endif" 
    else if all conditions are true
        everything fine, handle line
        skip line
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download