Question

I'm creating a C++ parser with PEG.js, and I need to be able to use cin. With the after-match JS, when I use prompt(), the (alternate) online version throws an error of 'Parse Error: prompt is not defined'. I am trying to use the initializer to create a function to replicate prompt (probably not optimized, I was just trying it as a solution). However, when I do this, it still gives me the error. I have tried using window.prompt as well, but again, it does not work. Here's an example of what I'm doing:

{
    function cin() {
        window.prompt("");
    }

    function changeVar(variable, newValue) {
        if(typeof variable === typeof newValue) {
            variable = newValue;
        } else if(typeof variable === 'undefined') {
            alert("You can't assign a value to a variable if the variable isn't declared yet!");
        } else {
            alert("Bad assignment. In C++, a variable *must* have the same type *all the time*.");
        }
    }
}

stdin =
    whitespace* "std::cin" whitespace* ">>" whitespace* varToBeChanged:[a-zA-Z_]+ ";" whitespace*
        { changeVar(varToBeChanged, cin('')); return varToBeChanged; }

whitespace =
    space:[ \t]
        { return space; }

and then in the parser testing field:

std::cin >> variable;

Thank you for looking. I have tried Googling this and SO-searching this but I haven't found any results.

Also, here is the main piece of code, for all the (current) extra information anyone needs. I am having some problems with this as well, but I'll try to figure them out on my own before I post another question.

Was it helpful?

Solution

If you are using http://peg.arcanis.fr/, then the parser code is executed inside of a Web Worker - which has no access to any UI like the window or the DOM. The error "undefined variable" means literally that there is no window or prompt declared.

If you paste your code into http://pegjs.majda.cz/online, it is executed in the web page environment and works flawlessly.

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