Scope of variables

80 views
Skip to first unread message

Gleki Arxokuna

unread,
Apr 8, 2015, 4:25:34 AM4/8/15
to pe...@googlegroups.com
I don't think I understand well how javascript variables work in PEG.js. Consider the following:

string_1 = &(string_2 {var foo=1;return;}) string_4 {return foo;}
string_4 = string_2 string_3

The output will be "foo is not defined", isn't it?

Two questions: 
1. How to put the declaration of foo and returning of its value under one scope?
2. Can we have shadowing of javascript values in inner rules?

David Majda

unread,
Apr 11, 2015, 1:44:23 AM4/11/15
to Gleki Arxokuna, pegjs
2015-04-08 10:25 GMT+02:00 Gleki Arxokuna <gleki.is...@gmail.com>:
I don't think I understand well how javascript variables work in PEG.js. Consider the following:

string_1 = &(string_2 {var foo=1;return;}) string_4 {return foo;}
string_4 = string_2 string_3

The output will be "foo is not defined", isn't it?

Yes. As described in the documentation, both action and predicate code is executed as if it was inside a function. This means local variable scope is limited to the action or predicate they were defined in.

Two questions: 
1. How to put the declaration of foo and returning of its value under one scope?

The only way is to define the variable as parser-global in the initializer. It is then accessible in all actions and predicates.
 
2. Can we have shadowing of javascript values in inner rules?

No.

My overall feel from your example is that you abuse variables for something you should use the match result for. Variables should generally be used only for cases where match results can't.

--
David Majda
Entropy fighter
http://majda.cz/

David Majda

unread,
Apr 17, 2015, 3:55:13 AM4/17/15
to Gleki Arxokuna, pegjs
2015-04-11 10:25 GMT+02:00 Gleki Arxokuna <gleki.is...@gmail.com>:
2. Can we have shadowing of javascript values in inner rules?

No.

My overall feel from your example is that you abuse variables for something you should use the match result for. Variables should generally be used only for cases where match results can't.

Generally, I just want to output "1" for the first match, "2" for the second match etc. I don't want to hardcode these numbers because I don't know how many of them to hardcode.
Global variables won't help me here due to recursion, i.e. when during a recursion the rule with these local variables is met then I can again increment from "1", something like:

["1","2","3",["1","2","3","4","5","6"],"4"]

I see. One approach to consider is to build a traversable data structure in the PEG.js parser and then traverse it using normal recursion later (outside of PEG.js parser).
Reply all
Reply to author
Forward
0 new messages