0

I am struggling to understand yacc recursion. So I created a minimal language that I want to simply echo a list of number given to it. I am using JISON. Here is the JISON:

/* description: Parses end executes mathematical expressions. */

/* lexical grammar */
%lex
%%

\s+                   /* skip whitespace */
[0-9]+("."[0-9]+)?\b  return 'NUMBER'
<<EOF>>               return 'EOF'
.                     return 'INVALID'

/lex

%start expressions

%% /* language grammar */

expressions
    : e EOF 
        {}
    ;

 e
    : NUMBER {}
    | NUMBER e
 ;

What actions do I need to echo the list of numbers separated by blanks?

user2302244
  • 843
  • 2
  • 11
  • 27

1 Answers1

0

@JoachimPileborg was correct when he said:

To start with you should set the number you scan so the parser can read it. With Lex/Yacc this is typically done by using yylval. Then just add code to the parser-rules to print the number.

JISON uses the grammar processor of yacc/bison but the actions must be specified in Javascript. As you are wanting an example of actions, I am assuming you can program in Javascript?

/* description: Parses end executes mathematical expressions. */

/* lexical grammar */
%lex
%%

\s+                   /* skip whitespace */
[0-9]+("."[0-9]+)?\b  yylval = ParseInt(yytext); return 'NUMBER'
<<EOF>>               return 'EOF'
.                     return 'INVALID'

/lex

%start expressions

%% /* language grammar */

expressions
    : e EOF 
        {}
    ;

 e
    : NUMBER { print($1); }
    | NUMBER e { print($1); }
 ;

All I've done is convert the lexeme for the number into an integer and stored it in yylval in the lexical part, and printed that value in the parser part whenever a NUMBER token is used.

Hopefully, that will make it clear. (PS - I've not run and tested it, not having JISON)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129