Files
tp2-vsl-pds/src/main/antlr/VSLParser.g
2025-04-01 18:17:52 +02:00

114 lines
2.5 KiB
Plaintext

parser grammar VSLParser;
options {
language = Java;
tokenVocab = VSLLexer;
k = 1;
}
@header {
package TP2;
import TP2.asd.Program.*;
import TP2.asd.*;
import TP2.asd.Interface.*;
}
// On syntax error, raise exception rather than silently recovery
@rulecatch {
catch (RecognitionException ex) {
reportError(ex) ;
throw(ex) ;
}
}
program returns [Program p] :
func=function
EOF
{$p = new Program($func.out);}
;
function returns [List<Function> out]
@init{
SymTable sym_table = new SymTable();
}:
FUNCTION t=type i=ident ParO ParF instrs=list_instr[sym_table]
{
$out.add(new Function($t.return_type, $i.out, $instrs.out));
}
;
prototype returns [Program p]:
;
list_instr [SymTable table] returns [ArrayList<Instruction> out]
@init{
$out = new ArrayList<>();
}:
instruction [table] {
$out.addAll($instruction.out);
}
;
instruction [SymTable table] returns [ArrayList<Instruction> out]:
RETURN e=expression [table]
{$out = new ArrayList<>();
$out.add(new Return_instr($e.out));}
;
expression [SymTable table] returns [Type return_Type, Expression out]:
//Fix LL1 and compare add and sub first
left=td_expression[table] {
$out = $left.out;
$return_Type = $left.return_Type;
}
//maybe it will be binop(s) with add/sub here
//if it is mul or div, they are all gonna be left=td_expression[table] to handle
(op=(PLUS | MINUS) right=td_expression[table] {
$out = new BinopExpression(
switch($op.getType()) {
case PLUS -> Op.PLUS;
case MINUS -> Op.MINUS;
default -> throw new IllegalArgumentException("Unknown operator");
},
$left.out,
$right.out
);
$return_Type = $right.return_Type;
})*
;
td_expression [SymTable table] returns [Type return_Type, Expression out]:
left=lit {
$out = $left.out;
$return_Type = $left.return_Type;
}
(op=(TIMES | DIV) right=lit {
$out = new Program.BinopExpression(
switch($op.getType()) {
case TIMES -> Op.TIMES;
case DIV -> Op.DIV;
default -> throw new IllegalArgumentException("Unknown operator");
},
$left.out,
$right.out
);
$return_Type = $right.return_Type;
})*
;
lit returns [Expression out, Type return_Type]:
NUMBER {
$return_Type = new Type_int();
$out = new Const($NUMBER.int);
}
;
ident returns [String out]:
TEXT { $out = $TEXT.getText(); }
;
type returns [Type return_type]:
TYPE_INT { $return_type = new Type_int(); }
|TYPE_VOID { $return_type = new Type_void(); }
;