Use other words for the same functionality of a reserved keyword in JavaScript

Viewed 41

I'm exploring language interpreters and compilers to build a small international compiler that compiles JavaScript with little modifications (to the English reserved words), to vanilla JS.

Modified JS Example:

notfor(notlet i=0; i<5; i++) {
    ...
}

*obviously "notfor" and "notlet" will not be the real keywords

Vanilla JS Compilation:

for(let i=0; i<5; i++) {
    ...
}

I've tried the RegEx approach, but I keep finding edge cases where the RegExes fail.

Ex. /notfor(.*)/, this fails when notfor(..){..} is put inside of a string or there is a closing parentheses in any part of the initialization, condition or final-expression of the for statement.

What is another simple approach to this problem?

1 Answers

As CertainPerformance suggested I separated strings from the other code so that the parser can simply just replace stuff outside of strings and not worry about changing user-made strings. This is just my late night approach, I'm sure there's a better way to do it, but this will do just fine.

let code = fs.readFileSync('./code.js', {encoding:'utf8', flag:'r'}).split('\n')
let compiled = ''
code.forEach(line => {
    line.split(/(?=["'`])/).forEach(analLine => {
        if (!analLine.match(/^["'`].*/)) {
            compiled += analLine.replace('notlet', 'let')
                                .replace('notfor', 'for')
        } else {
            compiled += analLine
        }
    })
    compiled += '\n'
})
console.log(compiled)
eval(compiled)
Related