more setup :D

This commit is contained in:
404Simon 2023-12-23 14:01:58 +01:00
parent 636229c06b
commit ed7d4a8b71
7 changed files with 66 additions and 1 deletions

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# parse with antlr
`antlr4 -package parser.grammar -o main/java/parser -no-listener -visitor grammar/Loop.g4`

View File

@ -1 +0,0 @@
grammar Loop;

17
src/grammar/Loop.g4 Normal file
View File

@ -0,0 +1,17 @@
grammar Loop;
start: prog EOF;
INT: [0-9]+ ;
VAR: ('x'|'y'|'z') INT;
expr: var=VAR '+' num=INT #Plus
| var=VAR '-' num=INT #Minus
;
asrt: var=VAR '=' ex=expr ';' #Ex
| var=VAR '=' var=VAR ';' #Va
| var=VAR '=' num=INT ';' #Num
;
prog: asrt #Asert
| 'LOOP' var=VAR 'DO' p=prog #Loop
| p1=prog p2=prog #ProgProg
;
NEWLINE : [\r\n]+ -> skip;
LEER: ' ' -> skip;

View File

@ -0,0 +1,22 @@
package compiler.grammar;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import parser.grammar.LoopLexer;
import parser.grammar.LoopParser;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
ANTLRInputStream input = new ANTLRFileStream("src/main/java/compiler/grammar/test.txt");
LoopLexer lexer = new LoopLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
LoopParser parser = new LoopParser(tokens);
ParseTree tree = parser.start();
new MyVisitor().visit(tree);
}
}

View File

@ -0,0 +1,14 @@
package compiler.grammar;
import parser.grammar.LoopBaseVisitor;
import parser.grammar.LoopParser;
public class MyVisitor extends LoopBaseVisitor<String> {
@Override
public String visitPlus(LoopParser.PlusContext ctx) {
String var = ctx.var.getText();
int varVal = 0; //get real value in future;
int num = Integer.parseInt(ctx.num.getText());
return Integer.valueOf(varVal + num).toString();
}
}

View File

@ -0,0 +1,4 @@
x0 = 5;
y0 = 10;
LOOP y0 DO
x0 = x0 + 1;