I've been trying to make a parser which takes tokens from a lexer (jflex), and ive used Java with bison for the parser. Here is my code so far for the parser:
%define api.prefix {EXAMPLE}
%define api.parser.class {EXAMPLE}
%define api.parser.public
%define parse.error verbose
%code imports{
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.IOException;
}
%code {
public static void main(String args[]) throws IOException {
EXAMPLELexer lexer = new EXAMPLELexer(System.in);
EXAMPLE parser = new EXAMPLE(lexer);
if(parser.parse()){
System.out.println("VALID FROM PARSER");
}
else{
System.out.println("ERROR FROM PARSER");
}
return;
}
}
/* Bison Declarations */
%token <Integer> NUM
%type exp
%%
input: line | input line;
line: '\n'
| exp '\n' { System.out.println($exp); }
| error '\n'
;
exp:
NUM { $$ = $1; }
| exp '=' exp { if ($1.intValue() != $3.intValue()) yyerror("calc: error: " + $1 + " != " + $3); }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = (int) Math.pow($1, $3); }
| '(' exp ')' { $$ = $2; }
| '(' error ')' { $$ = 1111; }
| '!' { $$ = 0; return YYERROR; }
| '-' error { $$ = 0; return YYERROR; }
%%
class EXAMPLELexer implements EXAMPLE.Lexer {
InputStreamReader it;
Yylex yylex;
public EXAMPLELexer(InputStream is){
it = new InputStreamReader(is);
yylex = new Yylex(it);
}
@Override
public void yyerror (String s){
}
@Override
public Object getLVal() {
return null;
}
@Override
public int yylex () throws IOException{
return yylex.yylex();
}
}
When I try to use the jflex and bison commands I get this: $$ of ‘exp’ has no declared type, same with $1, $3
Please help, i've been stuck on this for a while! (p.s i've already tried %union{} and it just gave rise to more errors unfortunately, if you have any sample code that actually works with it, i'd love to learn as there seems to be a lack of documentation with Java and bison working with Jflex.)
There was no declared type for exp. Additionally, token NEG was not declared.
The lexer interface needs to be declared in a %code lexer { }; block, before the %% parser end marker.
Following your file example, here is example.y
And here is the start of an example.jf