Compare commits

47 Commits
test ... main

Author SHA1 Message Date
Rochas
058ea815a1 clean 2025-04-30 19:41:42 +02:00
Rochas
c8bbfc991d clean toLLVM 2025-04-30 19:31:59 +02:00
Rochas
114d2c22aa clean PrettyPrinterVisitor 2025-04-30 19:15:35 +02:00
Rochas
c82d6a237d clean PrettyPrinterLLVM 2025-04-30 19:12:28 +02:00
Rochas
18beb717b2 petit readme 2025-04-30 18:52:33 +02:00
Rochas
d6301bad2d correction bug pour SemanticError 2025-04-30 18:07:59 +02:00
Vu Tuan Minh
5a86f474bc Merge branch 'main' of https://gitlab2.istic.univ-rennes1.fr/tuvu/tp2-vsl-pds 2025-04-30 16:34:31 +02:00
Vu Tuan Minh
a918ae8736 decl_array 2025-04-30 16:34:24 +02:00
Rochas
a1f597c67e getelementptr 2025-04-30 16:11:55 +02:00
Rochas
15ad215e6f clean 2025-04-30 15:24:47 +02:00
Rochas
ed78ab828d clean 2025-04-30 15:23:46 +02:00
Vu Tuan Minh
c58d524dd1 have to cahnge alloca 2025-04-30 15:22:38 +02:00
Rochas
43eccbd4c9 correction bug dans Declaration 2025-04-30 14:15:51 +02:00
Vu Tuan Minh
19c637e323 tableau update 2025-04-30 14:07:05 +02:00
Rochas
43ef0b93d3 génération du fichier .ll sans passer par la sorti Print, pour controller le type d'encodage 2025-04-30 14:02:19 +02:00
Rochas
e27dcdb0a0 génération du fichier .ll sans passer par la sorti Print, pour controller le type d'encodage 2025-04-30 13:59:25 +02:00
Vu Tuan Minh
88c5047e5f tableau 2025-04-30 13:44:12 +02:00
Vu Tuan Minh
854b2387c4 Merge branch 'main' of https://gitlab2.istic.univ-rennes1.fr/tuvu/tp2-vsl-pds 2025-04-30 12:54:53 +02:00
Vu Tuan Minh
23059a87b8 readme 2025-04-30 12:54:49 +02:00
Rochas
ad30cd3c64 correction param 2025-04-30 12:53:55 +02:00
Rochas
e27e112f6c correction nom variable 2025-04-30 12:16:21 +02:00
Rochas
6070ab0f3c correction nom variable 2025-04-30 12:14:53 +02:00
Rochas
9273eb7021 correction nom variable 2025-04-30 12:10:48 +02:00
Vu Tuan Minh
44a1d9918f add brLLVM labelWhile 2025-04-30 12:09:32 +02:00
Rochas
adb1858c2f Correction SymTable, param, et Type en TypeLLVM 2025-04-30 11:17:20 +02:00
Rochas
35561e5023 correction erreur + clean 2025-04-30 10:41:45 +02:00
Rochas
2853688baa correction Call et CallVoid avec print et read + clean 2025-04-30 10:32:07 +02:00
Vu Tuan Minh
2537f6d300 fix \OA 2025-04-30 10:30:10 +02:00
Vu Tuan Minh
d4a9b1f71d scanf bon 2025-04-30 09:59:44 +02:00
Vu Tuan Minh
20f6170168 add ret void pour func void 2025-04-30 09:38:30 +02:00
Vu Tuan Minh
0e82527b4b change fmt to .fmt 2025-04-30 08:40:17 +02:00
Rochas
d238ac0887 return 0 à la fin, suppression du typeFunction dans la symTable, Appeal renomé en Call 2025-04-29 23:25:07 +02:00
Vu Tuan Minh
7e9b49b08a Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/TP2/asd/toLLVM_Visitor.java
2025-04-29 14:06:55 +02:00
Vu Tuan Minh
7fc7eb773f tesst bugged 2025-04-29 14:05:51 +02:00
Rochas
ec643ffc6a correction de certain nom de label qui tonenait un ':' 2025-04-29 13:25:48 +02:00
Rochas
0929ce1b71 correction bug INDENT dans Lexer, TODO réparé NUMBER négatif ! 2025-04-29 01:23:15 +02:00
Rochas
bd56995d63 print et read fini ! 2025-04-29 00:50:56 +02:00
trochas
291bc96079 print et read presque fini ! 2025-04-28 18:14:31 +02:00
trochas
79920ed4d4 maj SymTable (id global) + DeclGlobal 2025-04-28 17:20:15 +02:00
trochas
1b5dd97226 correction 2025-04-28 14:55:34 +02:00
trochas
d9a2c0a4dd Merge branch 'main' of https://gitlab2.istic.univ-rennes1.fr/tuvu/tp2-vsl-pds 2025-04-28 14:41:03 +02:00
trochas
f2c2dfedfc call réparé 2025-04-28 14:40:59 +02:00
Vu Tuan Minh
6778440827 call 2025-04-28 14:37:25 +02:00
Vu Tuan Minh
a421811002 test call void 2025-04-28 13:48:52 +02:00
Vu Tuan Minh
4a48ee286b change name to LLVM 2025-04-28 06:43:58 +02:00
Vu Tuan Minh
3b36c75dae Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/TP2/asd/toLLVM_Visitor.java
#	tests/aLaMain.vsl
2025-04-28 06:34:25 +02:00
Rochas
d8d24e618d Appeal, todo : corriger callLLVM 2025-04-27 23:59:34 +02:00
57 changed files with 964 additions and 428 deletions

4
NULL Normal file
View File

@@ -0,0 +1,4 @@
tests\testsAdvanced\hanoi.ll:62:1: error: expected instruction opcode
62 | fi3:
| ^
1 error generated.

View File

@@ -1,17 +1,58 @@
# TP2 PDS - VSL+
Ce projet VSCode contient tout le nécessaire pour commencer à programmer le compilateur.
Vous pouvez forker ce dépôt, mais devez impérativement garder votre dépôt privé.
Ce fichier `README.md` doit être complété au fur et à mesure de votre avancement.
func::=Func(String,)
Réalisé par Thibaut ROCHAS et Tuan Minh VU
#### Program
```
Program ::= Program(Function+)
```
#### Function
```
Function ::= Function(Type, String, Var*, Instruction)
| Prototype(Type, String, Var*)
```
#### Var
```
Var ::= Var(String)
```
#### Declaration
```
Declaration ::= Declaration(Type, String+)
```
#### Instruction
```
Instruction ::= Assign(String, Expression)
| Return(Expression)
| Bloc(Instruction+)
| BlocWithDecl(Declaration+, Instruction+)
| VoidFunctionCall(String, Expression*)
| IfThen(Expression, Instruction)
| IfThenElse(Expression, Instruction, Instruction)
| While(Expression, Instruction)
| Read(Var+)
| Print(ExpressionOuText+)
```
#### Expression
```
ExpressionOuText ::= Expression
| Text(String)
Expression ::= Binop(Op, Expression, Expression)
| Const(Int)
| Var(String)
| Call(String, Expression*)
| Paren(Expression)
```
#### Autres
```
Op ::= PLUS | MINUS | TIMES | DIV | MOD
Type ::= INT | VOID
```
## Etat
Nous sommes arrivés jusqu'au segment 2, nous avons commencé le segment 3 mais celui-ci ne marche pas encore complètement
Au niveau de la détection de type, nous l'avons directement intégré à l'intérieur du visitor toLLVM au lieu de le faire dans un bloc séparé, par manque de temps.
## Compatibilité

BIN
a.exe Normal file

Binary file not shown.

BIN
a.out Executable file

Binary file not shown.

169
runAllTests2.py Normal file
View File

@@ -0,0 +1,169 @@
#!/usr/bin/env python3
import os
import subprocess
from colorama import init as colorama_init
from colorama import Fore
from colorama import Style
stats = {}
# Détermine quel est l'exécutable clang utilisable.
# Note : à l'istic c'est clang-19
def clangName():
for name in ["clang-" + str(v) for v in range(20,16,-1)]:
p = subprocess.run(f"command -v {name} 2>&1 >/dev/null", shell=True)
if p.returncode == 0 :
return name
return "clang"
clang = clangName()
def runNormalTestSuit(testSuit):
print(f"Running test suit : {testSuit}")
stats[testSuit] = (0,0,0,0)
for dirname, dirnames, filenames in os.walk(testSuit):
for filename in filenames:
runNormalTest(testSuit, dirname, filename)
def runNormalTest(testSuit, dirname,filename):
vslToLLVM = False
llvmToBin = False
executionCorrect = False
path = os.path.join(dirname, filename)
basename, ext = os.path.splitext(path)
# Ignore not .vsl files
if ext != ".vsl":
return
print(f'\tRunning test {filename}')
# VSL -> LLVM
p = subprocess.run(f"java -jar build/libs/TP2.jar {path}", shell=True)
print(f"java -jar build/libs/TP2.jar {path}")
if p.returncode == 0 :
vslToLLVM = True
# LLVM -> Bin
if vslToLLVM :
p = subprocess.run(f"{clang} {basename}.ll -o {basename} 2>NULL", shell=True)
print(f"{clang} {basename}.ll -o {basename} 2>NULL")
if p.returncode == 0:
llvmToBin = True
executionCorrect = True
# Exe
if llvmToBin :
executionCorrect = True
try:
input = ""
if os.path.isfile(f"{basename}.test_in"):
input = f"< {basename}.test_in"
p = subprocess.run(f".\{basename} " + input, shell=True, stdout=subprocess.PIPE, timeout=5)
print(f".\{basename} ")
except subprocess.TimeoutExpired:
executionCorrect = "diverge" in basename
# Check return code
if os.path.isfile(f"{basename}.test_ret"):
with open(f"{basename}.test_ret", "r") as expected:
executionCorrect = executionCorrect and int(expected.read()) == p.returncode
# Check stdout
if os.path.isfile(f"{basename}.test_out"):
with open(f"{basename}.test_out", "rb") as expected:
executionCorrect = executionCorrect and expected.read() == p.stdout
print(f"{colorFromBool(vslToLLVM)}\t\tVSL to LLVM : {'OK' if vslToLLVM else 'Fail'}{Style.RESET_ALL}")
print(f"{colorFromBool(llvmToBin)}\t\tLLVM to Bin : {'OK' if llvmToBin else 'Fail'}{Style.RESET_ALL}")
print(f"{colorFromBool(executionCorrect)}\t\tCorrect Execution : {'OK' if executionCorrect else 'Fail'}{Style.RESET_ALL}")
x,y,z,t = stats[testSuit]
if vslToLLVM :
x += 1
if llvmToBin :
y += 1
if executionCorrect :
z += 1
t += 1
stats[testSuit] = (x,y,z,t)
def colorFromBool(b):
if b:
return Fore.GREEN
else:
return Fore.RED
def afficheStats(stat):
x,y,z,t = stat
print(f'\t Nombre de tests : {t}')
print(f'{colorFromBool(x==t)}\t vsl to llvm : {x} / {t}{Style.RESET_ALL}')
print(f'{colorFromBool(y==t)}\t llvm to bin : {y} / {t}{Style.RESET_ALL}')
print(f'{colorFromBool(z==t)}\t resultat correct: {z} / {t}{Style.RESET_ALL}')
nbError = 0
nbErrorTests = 0
def runErrorTest(testSuit, dirname,filename):
path = os.path.join(dirname, filename)
basename, ext = os.path.splitext(path)
if ext != ".vsl":
return
print(f'\tRunning test {filename}')
hasError = False
p = subprocess.run(f"java -jar build/libs/TP2.jar < {path} 1>{basename}.ll", shell=True, stderr=subprocess.PIPE)
if p.returncode != 0 and p.stderr != b'':
print(f"\t\t{Fore.GREEN}Error : Yes{Style.RESET_ALL}")
hasError = True
else:
print(f"\t\t{Fore.RED}Error : No{Style.RESET_ALL}")
hasError = False
x,t = stats[testSuit]
if hasError :
x += 1
t += 1
stats[testSuit] = (x,t)
def runErrorLevelTests(testSuit):
print(f"Running test suit : {testSuit}")
stats[testSuit] = (0,0)
for dirname, dirnames, filenames in os.walk(testSuit):
for filename in filenames:
runErrorTest(testSuit, dirname, filename)
def runTests(testDirName):
folderContent = [os.path.join(testDirName, d) for d in os.listdir(testDirName)]
testSuits = [d for d in folderContent if os.path.isdir(d)]
testSuits.sort()
for suit in testSuits:
if "error" in suit or "Error" in suit:
runErrorLevelTests(suit)
else:
runNormalTestSuit(suit)
for suit in testSuits:
print(f'Résumé du test {suit}')
if "error" in suit or "Error" in suit:
nbError, nbErrorTests = stats[suit]
print(f'{colorFromBool(nbError==nbErrorTests)}\t Nombre d\'erreurs : {nbError} / {nbErrorTests}{Style.RESET_ALL}')
else:
afficheStats(stats[suit])
if __name__ == "__main__" :
colorama_init()
runTests("tests")

View File

@@ -50,6 +50,10 @@ BacO: '{'
;
BacF: '}'
;
CroO: '['
;
CroF:']'
;
PLUS: '+'
;
MINUS: '-'
@@ -62,7 +66,7 @@ MOD: '%'
;
VIRGULE: ','
;
IDENT: ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'-')*
IDENT: ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
WS : (' '|'\n'|'\t'| '\r') { skip(); }
;

View File

@@ -87,17 +87,32 @@ list_decls returns [ArrayList<Declaration> out]
})+
;
declaration returns [Declaration out]:
t=type i=ident
declaration returns [Declaration out]
@init{
ArrayList<VarDeclImp> vars = new ArrayList<>();
}:
t=type v1=var_decl
{
vars.add($v1.out);
}
(VIRGULE v2=var_decl
{
vars.add($v2.out);
}
)*
{
ArrayList<String> declare= new ArrayList<String>();
declare.add($i.out);
}(VIRGULE i2=ident
{
declare.add($i2.out);
})*
{$out = new DeclarationImp($t.return_type, declare);}
;
$out= new DeclarationImp($t.return_type, vars);
}
;
var_decl returns [VarDeclImp out]:
id=ident
(CroO e=expression CroF
{$out= new VarDeclImp($id.out,$e.out);}
|
{$out= new VarDeclImp($id.out, null);}
)
;
list_instr returns [ArrayList<Instruction> out]
@init{
@@ -124,10 +139,16 @@ instruction returns [Instruction out]:
}
) BacF
| //ASSIGN
i=ident ASSIGN e=expression
{
i=ident
(ASSIGN e=expression
{
$out = new AssignImp($i.out, $e.out);
}
}
|ParO (para=list_expression)? ParF
{
$out = new VoidFunctionImp($i.out,($para.out != null) ? $para.out : new ArrayList<>());
}
)
| // PRINT
PRINT
{ArrayList<Object> printer= new ArrayList<Object>();}
@@ -212,6 +233,10 @@ td_expression returns [Expression out]:
;
lit returns [Expression out]:
MINUS n=lit {
$out = new BinopExpressionImp(Op.MINUS, new ConstImp(0), $n.out);
}
|
NUMBER {
$out = new ConstImp($NUMBER.int);
}
@@ -220,7 +245,7 @@ lit returns [Expression out]:
}
| t=ident
(
ParO (para=list_expression)? ParF {$out = new AppealImp($t.out,($para.out !=null) ?$para.out : new ArrayList<>());}
ParO (para=list_expression)? ParF {$out = new CallImp($t.out,($para.out !=null) ?$para.out : new ArrayList<>());}
| {$out=new VarImp($t.out);}
)
;

View File

@@ -1,4 +1,5 @@
package TP2.Error;
//TypeChecking implémenté à l'intèrieur de toLLVM...
/*package TP2.Error;
import TP2.asd.SymTable;
import TP2.asd.Program.*;
@@ -158,9 +159,9 @@ public class TypeChecking {
}
@Override
public TypeCheckExprDiag visitAppeal(AppealImp instr, SymTable h) {
public TypeCheckExprDiag visitCall(CallImp instr, SymTable h) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'visitAppeal'");
throw new UnsupportedOperationException("Unimplemented method 'visitCall'");
}
}
}
}*/

View File

@@ -1,6 +1,12 @@
package TP2;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.ANTLRInputStream;
@@ -17,11 +23,22 @@ import java.util.*;
/*
./gradlew build
java -jar build/libs/TP2.jar tests/fragment0/priority2.vsl
java -jar build/libs/TP2.jar tests/aLaMain.vsl
(pas besoin, pour les test à la main) java -jar build/libs/TP2.jar tests/fragment1/while2.vsl > tests/fragment1/while2.ll
clang tests/aLaMain.ll -o tests/aLaMain
*/
public class Main {
static Boolean TESTAUTOMOD = true; //pour les tests python mettre à true
static Boolean AFFICHAGE = true;
public static void main(String[] args) {
try {
// Set input
@@ -45,21 +62,43 @@ public class Main {
ProgramImp ast = parser.program();
// Pretty-print the program (to debug parsing)
//System.err.println("todo " + ast);
//System.out.println("\n\n PRETTYPRINTER VSL : \n--------------\n");
System.out.println(ast.prettyprinter());
//System.out.println("\n\n PRETTYPRINTER VSL : \n--------------\n");
if(!TESTAUTOMOD && AFFICHAGE) System.out.println("\nVSL:\n");
if(!TESTAUTOMOD && AFFICHAGE) System.out.println(ast.prettyprinter());
// Verify the program semantic
//Par manque de temps la vérification sémantique se fait uniquement dans toLLVM
// Generate the intermediate representation
//System.out.println("todo");
if(!TESTAUTOMOD && AFFICHAGE) System.out.println("\nLLVM:\n");
ProgramLLVMImp astLLVM = ast.toLLVM();
//System.out.println("\n\n PRETTYPRINTER LLVM : \n--------------\n");
System.out.println(astLLVM.prettyprinter());
//System.out.println("\n\n PRETTYPRINTER LLVM : \n--------------\n");
String llvmStr = astLLVM.prettyprinter();
if(TESTAUTOMOD || AFFICHAGE){
System.out.println(llvmStr);
}
/*
utiliser la commande :
java -jar build/libs/TP2.jar file.vsl > file.ll
provoque peut provoquer de mauvais encodage (UTF16(LE) au lieu d'UTF8)
et empêche l'utilisation de print pour autre chose
*/
if(!TESTAUTOMOD){
String sortieLLVM = args[0].replace(".vsl", ".ll");
Files.write(
Paths.get(sortieLLVM),
llvmStr.getBytes(StandardCharsets.UTF_8)
);
if(AFFICHAGE){
System.out.println("\n[VSL compile succes] : " + args[0] + " -> " + sortieLLVM);
System.out.println("Pour compiler en bin utilisez :");
System.out.println("clang " + sortieLLVM + " -o " + sortieLLVM.replace(".ll", "") + "\n");
}
}
} catch (IOException | RecognitionException e) {
e.printStackTrace();

View File

@@ -4,7 +4,9 @@ import TP2.asd.Program.*;
import TP2.llvm.ProgramLLVM.*;
public interface Interface{
//PROGRAM
public interface ProgramI {
public <H,S> S accept(ProgramVisitor<H,S> v, H h);
public String prettyprinter();
@@ -15,8 +17,8 @@ public interface Interface{
public S visitProgram(ProgramImp prog, H h);
}
//FUNCTION
public interface Function {
public <H,S> S accept(FunctionVisitor<H,S> v, H h);
}
@@ -34,6 +36,7 @@ public interface Interface{
public interface DeclVisitor<H,S>{
public S visitDeclaration(DeclarationImp instr,H h);
public S visitVarDecl(VarDeclImp instr, H h);
}
//INSTRUCTION
@@ -42,7 +45,6 @@ public interface Interface{
public <H,S> S accept(InstrVisitor<H,S> v, H h);
}
public interface InstrVisitor<H,S>{
public S visitReturn(Return_instrImp instr, H h);
public S visitBloc(BlocImp instr, H h);
@@ -53,6 +55,7 @@ public interface Interface{
public S visitIfThen(IfThenImp instr, H h);
public S visitIfThenElse(IfThenElseImp instr, H h);
public S visitWhile(WhileImp instr, H h);
public S visitVoidFunction(VoidFunctionImp instr, H h);
}
//EXPRESSION
@@ -64,9 +67,9 @@ public interface Interface{
public interface ExprVisitor<H,S> {
public S visitConst(ConstImp e,H h);
public S visitBinOp(BinopExpressionImp e, H h);
public S visitVar(VarImp e,H h);
public S visitAppeal(AppealImp instr, H h);
public S visitBinOp(BinopExpressionImp e, H h);
public S visitCall(CallImp instr, H h);
}
public interface Type{
@@ -78,8 +81,5 @@ public interface Interface{
public S visitVoid(Type_voidImp t, H h);
}
public enum Op {PLUS, MINUS, TIMES, DIV, MOD}
}

View File

@@ -13,7 +13,7 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
static String INDENT = " ";
//PROGRAM
//PROGRAM -----------------------------------
@Override
public String visitProgram(ProgramImp prog, String indent) {
@@ -25,7 +25,9 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
//PROTOTYPE
//FUNCTION -----------------------------------
@Override
public String visitPrototype(PrototypeImp proto, String indent){
String str= indent + "PROTO "+proto.type().accept(this, "")+ " "+ proto.nom() + "(";
@@ -38,7 +40,7 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str+")";
}
//FUNCTION
@Override
public String visitFunction(FunctionImp fun, String indent) {
String str = indent+"FUNC " + fun.type().accept(this,"")+ " " + fun.nom() +"(";
@@ -53,23 +55,39 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
//DELCARATION
//DELCARATION -----------------------------------
@Override
public String visitDeclaration(DeclarationImp instr, String indent) {
String str = indent +instr.t().accept(this,"") + " ";
for(int i = 0; i<instr.s().size();i++){
str += instr.s().get(i);
str += instr.s().get(i).accept(this, indent);
if(i<instr.s().size()-1) str += ",";
}
return str;
}
//INSTRUCTION
@Override
public String visitVarDecl(VarDeclImp instr, String indent){
String str = "";
if(instr.size()==null){
str+= instr.nom();
}else{
str+= instr.nom()+ "["+instr.size().accept(this, indent)+"]";
}
return str;
}
//INSTRUCTION -----------------------------------
@Override
public String visitReturn(Return_instrImp instr, String indent) {
return indent+"RETURN " + instr.e().accept(this,"");
}
@Override
public String visitBloc(BlocImp instr, String indent) {
String str = "{\n";
@@ -80,6 +98,7 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
@Override
public String visitBlocDec(BlocDecImp instr, String indent) {
String str = "{\n";
@@ -94,11 +113,13 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
@Override
public String visitAssign(AssignImp instr, String indent) {
return indent + instr.t()+ " := " + instr.e().accept(this,"");
}
@Override
public String visitPrint(PrintImp instr, String indent) {
String str = indent + "PRINT ";
@@ -115,6 +136,18 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
@Override
public String visitRead(ReadImp instr, String indent) {
String str = indent+"READ ";
for(int i = 0; i<instr.t().size(); i++){
str += instr.t().get(i).accept(this,indent);
if(i<instr.t().size()-1) str += ", ";
}
return str;
}
@Override
public String visitIfThen(IfThenImp instr, String indent) {
String str = indent + "IF ";
@@ -135,15 +168,6 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return str;
}
@Override
public String visitRead(ReadImp instr, String indent) {
String str = indent+"READ ";
for(int i = 0; i<instr.t().size(); i++){
str += instr.t().get(i).accept(this,indent);
if(i<instr.t().size()-1) str += ", ";
}
return str;
}
@Override
public String visitWhile(WhileImp instr, String indent) {
@@ -156,21 +180,20 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
}
@Override
public String visitAppeal(AppealImp instr,String indent){
String str = indent + instr.fName() + "(";
for(int i=0; i<instr.params().size();i++){
str += instr.params().get(i).accept(this, "");
if(i<instr.params().size()-1) str += ",";
public String visitVoidFunction(VoidFunctionImp instr, String h) {
String str = h+instr.nom()+ "(";
for(int i=0;i<instr.expr().size();i++){
str+= instr.expr().get(i).accept(this,h);
if(i<instr.expr().size()-1){
str+=", ";
}
}
return str+")";
str+=")";
return str;
}
//EXPRESSION
@Override
public String visitConst(ConstImp e, String indent) {
return e.c()+"";
}
//EXPRESSION -----------------------------------
@Override
public String visitBinOp(BinopExpressionImp e, String indent) {
@@ -186,7 +209,30 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return "(" + e.e1().accept(this,"") +" "+ opStr +" " + e.e2().accept(this,"") + ")";
}
//TYPE
@Override
public String visitConst(ConstImp e, String indent) {
return e.c()+"";
}
@Override
public String visitVar(VarImp e, String h) {
return e.name();
}
@Override
public String visitCall(CallImp instr,String indent){
String str = indent + instr.fName() + "(";
for(int i=0; i<instr.params().size();i++){
str += instr.params().get(i).accept(this, "");
if(i<instr.params().size()-1) str += ",";
}
return str+")";
}
//TYPE -----------------------------------
@Override
public String visitInt(Type_intImp t, String h) {
@@ -198,9 +244,5 @@ public class PrettyprinterVisitor implements ProgramVisitor<String,String>,
return "VOID";
}
@Override
public String visitVar(VarImp e, String h) {
return e.name();
}
}

View File

@@ -1,6 +1,7 @@
package TP2.asd;
import java.util.ArrayList;
import TP2.asd.Interface.*;
import TP2.llvm.ProgramLLVM.*;
@@ -17,7 +18,11 @@ public class Program{
return this.accept(ppVisitor, "");
}
@Override
//public TypeCheckExprDiag typeChecking(){
// TypeChecking tcVisitor = new TypeChecking();
// return this.accept(tcVisitor, new SymTable());
//}
public ProgramLLVMImp toLLVM() {
toLLVM_Visitor llvmVisitor = new toLLVM_Visitor();
return this.accept(llvmVisitor,new SymTable());
@@ -27,9 +32,6 @@ public class Program{
//Fonction
public static record FunctionImp(Type type, String nom, ArrayList<VarImp> params,Instruction instruction) implements Function {
//public FunctionImp(Type type, String name, Instruction instruction) {
// this(type, name, new ArrayList<>() {{ add(instruction); }}); C KOI ?
//}
public <H, S> S accept(FunctionVisitor<H, S> v, H h) {
return v.visitFunction(this, h);
@@ -62,21 +64,28 @@ public class Program{
}
}
public static record AppealImp(String fName, ArrayList<Expression> params) implements Expression{
public static record CallImp(String fName, ArrayList<Expression> params) implements Expression{
@Override
public <H, S> S accept(ExprVisitor<H, S> v, H h) {
return v.visitAppeal(this, h);
return v.visitCall(this, h);
}
}
//Declaration
public static record DeclarationImp(Type t, ArrayList<String> s) implements Declaration{
public static record DeclarationImp(Type t, ArrayList<VarDeclImp> s) implements Declaration{
@Override
public <H, S> S accept(DeclVisitor<H, S> v, H h) {
return v.visitDeclaration(this, h);
}
}
public static record VarDeclImp(String nom, Expression size) implements Declaration{
@Override
public <H, S> S accept(DeclVisitor<H, S> v, H h) {
return v.visitVarDecl(this, h);
}
}
//Instructions
public static record Return_instrImp(Expression e) implements Instruction{
public <H, S> S accept(InstrVisitor<H, S> v, H h) {
@@ -101,7 +110,8 @@ public class Program{
return v.visitAssign(this, h);
}
}
//t : String et Expression
public static record PrintImp(ArrayList<Object> t) implements Instruction{
@Override
public <H, S> S accept(InstrVisitor<H, S> v, H h) {
@@ -137,6 +147,13 @@ public class Program{
}
}
public static record VoidFunctionImp(String nom, ArrayList<Expression> expr) implements Instruction{
@Override
public <H, S> S accept(InstrVisitor<H, S> v, H h) {
return v.visitVoidFunction(this, h);
}
}
//Type
public static record Type_voidImp() implements Type{
@Override

View File

@@ -1,28 +1,39 @@
package TP2.asd;
import java.util.ArrayList;
import org.pcollections.*;
import TP2.asd.Interface.Type;
import TP2.asd.Program.Type_intImp;
import TP2.llvm.Interface.TypeLLVM;
import TP2.llvm.ProgramLLVM.DeclarGlobalLLVMImp;
import TP2.llvm.ProgramLLVM.DefineLLVMImp;
import TP2.llvm.ProgramLLVM.IntLLVMImp;
public class SymTable {
private PStack<PMap<String,ValueVarMap>> varMap;
private PMap<String,ValueFunMap> functionsMap;
private int id=1;
private int idLabel = 1;
public SymTable(){
private int[] id ; //id partagé entre toute les symTable, [0] : idVar, [1] : idLabel, [2] : idGlobalVar
private ArrayList<DeclarGlobalLLVMImp> declarationsGlobal; //aussi partagé entre toute les symTable (.fmt pour les print et scan)
public SymTable(){
this.id = new int[3];
this.varMap= ConsPStack.singleton(HashTreePMap.empty());
this.functionsMap = HashTreePMap.empty();
this.declarationsGlobal = new ArrayList<>();
this.id[0] = 1; //idVar
this.id[1] = 1; //idLaber
this.id[2] = 1; //idGlobalVar
}
public SymTable(PStack<PMap<String,ValueVarMap>> varMap, PMap<String,ValueFunMap> functionsMap, int id, int idLabel){
public SymTable(PStack<PMap<String,ValueVarMap>> varMap, PMap<String,ValueFunMap> functionsMap,
int[] id,ArrayList<DeclarGlobalLLVMImp> declarationsGlobal){
this.varMap= varMap;
this.id = id;
this.functionsMap = functionsMap;
this.idLabel = idLabel;
this.declarationsGlobal = declarationsGlobal;
}
public static class ValueFunMap{
public DefineLLVMImp define;
public Boolean isProto;
@@ -33,34 +44,16 @@ public class SymTable {
}
}
public SymTable newBlock() {
return new SymTable(varMap.plus(HashTreePMap.empty()), functionsMap, id, idLabel);
}
public SymTable outBlock() {
if (varMap.size() > 1) {
return new SymTable(varMap.minus(0), functionsMap, id, idLabel);
} else {
System.err.println("Vide");
return this;
}
}
public static class ValueVarMap{
public Type type;
public TypeLLVM type;
public int id;
public Boolean isParam;
public ValueVarMap(Type type,int id, Boolean isParam){
public ValueVarMap(TypeLLVM type,int id, Boolean isParam){
this.type = type;
this.id = id;
this.isParam = isParam;
}
}
public void updateId(SymTable symTable2){
this.id = symTable2.getId();
this.idLabel = symTable2.getIdLabel();
}
public static class Result{
public SymTable symTable;
@@ -72,64 +65,106 @@ public class SymTable {
}
//Fonction SymTable :
public SymTable newBlock() {
return new SymTable(varMap.plus(HashTreePMap.empty()), functionsMap, id,declarationsGlobal);
}
public SymTable outBlock() {
if (varMap.size() > 1) {
return new SymTable(varMap.minus(0), functionsMap, id,declarationsGlobal);
} else {
return this;
}
}
public ArrayList<DeclarGlobalLLVMImp> getDeclarationGlobal(){
return this.declarationsGlobal;
}
public SymTable addFunction(DefineLLVMImp function, Boolean isProto){
ValueFunMap value = this.functionsMap.get(function.name());
if(value == null || (value!=null && value.isProto && !isProto)){
return new SymTable(this.varMap, this.functionsMap.plus(function.name(),new ValueFunMap(function,isProto)), this.id, this.idLabel);
if(value!=null && value.isProto && (value.define.type().getClass() != function.type().getClass() || value.define.params().size() != function.params().size())){
System.err.println("[VSL compile error] : La fonction '"+function.name()+"()' est incompatible avec le Proto déjà déclaré");
System.exit(1);
}
return new SymTable(this.varMap, this.functionsMap.plus(function.name(),new ValueFunMap(function,isProto)), this.id,this.declarationsGlobal);
}
else{
if(value.isProto) System.err.println("[VSL compile error] : Le prototype "+function.name()+" existe déjà");
else if(isProto) System.err.println("[VSL compile error] : Le prototype "+function.name()+" doit être déclaré avant son implémentation");
else System.err.println("[VSL compile error] : La fonction "+function.name()+" existe déjà");
if(value.isProto) System.err.println("[VSL compile error] : Le prototype '"+function.name()+"()' existe déjà");
else if(isProto) System.err.println("[VSL compile error] : Le prototype '"+function.name()+"()' doit être déclaré avant son implémentation");
else System.err.println("[VSL compile error] : La fonction '"+function.name()+"()' existe déjà");
System.exit(1);
return null;
}
}
public ValueFunMap getFunction(String name){
return this.functionsMap.get(name);
ValueFunMap f = this.functionsMap.get(name);
if (f==null){
System.err.println("[VSL compile error] : la fonction '" + name + "()' n'existe pas, veuillez vous assurer de l'avoir déclarée avant l'appel");
System.exit(1);
}
return f;
}
public int getId(){
return this.id;
return this.id[0];
}
public int getIdLabel(){
return this.idLabel;
return this.id[1];
}
public int getNewId(){
int a = this.id;
this.id++;
int a = this.id[0];
this.id[0]++;
return a;
}
public int getNewIdLabel(){
int a = this.idLabel;
this.idLabel++;
int a = this.id[1];
this.id[1]++;
return a;
}
public Result addNewTempVar(){
String newVar = "temp"+id;
SymTable newSymTab = this.addVar(newVar,new Type_intImp(),false);
String newVar = "temp"+id[0];
SymTable newSymTab = this.addVarInTab(newVar,new IntLLVMImp(),false);
return new Result(newSymTab,newVar);
}
public Result addParam(String nomParam){
String newParam = "param_"+nomParam+id;
SymTable newSymTab = this.addVar(nomParam,new Type_intImp(),true);
String newParam = "param_"+nomParam;
SymTable newSymTab = this.addVarInTab(nomParam,new IntLLVMImp(),true);
return new Result(newSymTab,newParam);
}
public Result addVar(String nomVar) {
public String getGlobalDeclName(){;
return ".fmt"+id[2];
}
public void addGlobalDecl(DeclarGlobalLLVMImp decl){
id[2]++;
this.declarationsGlobal.add(decl);
}
public Result addVar(String nomVar, TypeLLVM type) {
PMap<String, ValueVarMap> top = varMap.get(0);
if (top.containsKey(nomVar)) {
System.err.println("Erreur");
return new Result(this, null);
if(!top.get(nomVar).isParam){ //si non on écrase, on a plus besoin du param après
System.err.println("[VSL compile error] : '" + nomVar+ "' a déjà été déclaré");
System.exit(1);
return new Result(this, null);
}
}
String realName = nomVar + id;
top = top.plus(nomVar, new ValueVarMap(new Type_intImp(), id, false));
SymTable newSym = new SymTable(varMap.minus(0).plus(0, top), functionsMap, id+1, idLabel);
String realName = nomVar + "_" + id[0];
top = top.plus(nomVar, new ValueVarMap(type, id[0], false));
id[0]++;
SymTable newSym = new SymTable(varMap.minus(0).plus(0, top), functionsMap, id,this.declarationsGlobal);
return new Result(newSym, realName);
}
@@ -139,13 +174,16 @@ public class SymTable {
if (scope.containsKey(nomVar)) {
ValueVarMap value = scope.get(nomVar);
String prefix = "";
String id = "_"+value.id;
if(value.isParam){
prefix = "param_";
id ="";
}
return prefix + nomVar + value.id;
return prefix + nomVar + id;
}
}
System.err.println(nomVar+" n'est pas trovué");
System.err.println("[VSL compile error] : '" + nomVar + "' n'a pas été déclaré");
System.exit(1);
return null;
}
@@ -155,21 +193,14 @@ public class SymTable {
return true;
}
}
System.err.println(nomVar+" n'est pas trouvé");
System.err.println("[VSL compile error] : '" + nomVar+"' n'est pas trouvé");
System.exit(1);
return false;
}
public Type getvar_Type(String s){
for (PMap<String,ValueVarMap> scope : varMap) {
if (scope.containsKey(s)) {
return scope.get(s).type;
}
}
return null;
}
//retourne le type de la var
public Type getType(String nomVar){
public TypeLLVM getType(String nomVar){
for (PMap<String,ValueVarMap> scope : varMap) {
if (scope.containsKey(nomVar)) {
return scope.get(nomVar).type;
@@ -179,40 +210,41 @@ public class SymTable {
}
public SymTable addVar(String nomVar, Interface.Type type, boolean isParam) {
public SymTable addVarInTab(String nomVar, TypeLLVM type, boolean isParam) {
PMap<String,ValueVarMap> top = varMap.get(0);
if (top.containsKey(nomVar)) {
System.err.println(nomVar+ " déjà déclaré.");
System.err.println("[VSL compile error] : " + nomVar+ " déjà déclaré.");
return this;
}
top = top.plus(nomVar, new ValueVarMap(type, id, isParam));
return new SymTable(varMap.minus(0).plus(0, top), functionsMap, id+1, idLabel);
top = top.plus(nomVar, new ValueVarMap(type, id[0], isParam));
if(!isParam) this.id[0]++;
return new SymTable(varMap.minus(0).plus(0, top), functionsMap, id, this.declarationsGlobal);
}
public String print_all(){
StringBuilder str = new StringBuilder();
str.append("Id = ").append(id).append("\n");
str.append("VARIABLES:\n");
str.append("Id = ").append(id[0]).append("\n");
str.append("VARIABLES:\n");
int scopeLevel = varMap.size();
for (PMap<String, ValueVarMap> scope : varMap) {
str.append("Block Level ").append(scopeLevel--).append(":\n");
for (String varName : scope.keySet()) {
ValueVarMap value = scope.get(varName);
str.append("Name: ").append(varName)
.append(", Id: ").append(value.id)
.append(", Type: ").append(value.type)
.append(", IsParam: ").append(value.isParam)
.append("\n");
int scopeLevel = varMap.size();
for (PMap<String, ValueVarMap> scope : varMap) {
str.append("Block Level ").append(scopeLevel--).append(":\n");
for (String varName : scope.keySet()) {
ValueVarMap value = scope.get(varName);
str.append("Name: ").append(varName)
.append(", Id: ").append(value.id)
.append(", Type: ").append(value.type)
.append(", IsParam: ").append(value.isParam)
.append("\n");
}
}
}
str.append("FUNCTIONS:\n");
for (String funcName : functionsMap.keySet()) {
str.append(" Name: ").append(funcName).append("\n");
}
str.append("FUNCTIONS:\n");
for (String funcName : functionsMap.keySet()) {
str.append(" Name: ").append(funcName).append("\n");
}
return str.toString();
return str.toString();
}
}

View File

@@ -49,64 +49,125 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
for(int i = 0; i<prog.fonctions().size(); i++){
DefineLLVMImp function = prog.fonctions().get(i).accept(this, h);
Boolean isProto = (prog.fonctions().get(i) instanceof PrototypeImp);
TypeLLVM type = function.type();
h = h.addFunction(function,isProto);
if(!isProto){ //les prototypes n'existent pas dans LLVM
fonctionLLVM.add(function);
}
}
System.out.println(h.print_all());
return new ProgramLLVMImp(new ArrayList<>(),fonctionLLVM);
return new ProgramLLVMImp(h.getDeclarationGlobal(),fonctionLLVM);
}
//FUNCTION
//FUNCTION -----------------------------------
@Override
public DefineLLVMImp visitFunction(FunctionImp fun, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> instrLLVM = new ArrayList<>();
ArrayList<VarLLVMImp> paramsLLVM = new ArrayList<>();
ArrayList<InstructionLLVM> setParam = new ArrayList<>();
for(VarImp param: fun.params()){
TypeLLVM type = new IntLLVMImp();
Result r = h.addParam(param.name());
String name = r.var;
VarLLVMImp var = new VarLLVMImp(new IntLLVMImp(), name);
String nameParam = r.var;
h = r.symTable;
Result r2 = h.addVar(param.name(),type);
String nameVar = r2.var;
h = r2.symTable;
VarLLVMImp var = new VarLLVMImp(type, nameParam,false);
paramsLLVM.add(var);
VarLLVMImp newVar =new VarLLVMImp(type, nameVar,false);
setParam.add(new AssignLLVMImp(newVar,new allocaLLVMImp(type)));
setParam.add(new StoreLLVMImp(type,var,newVar));
}
instrLLVM.addAll(setParam);
instrLLVM.addAll(fun.instruction().accept(this, h));
DefineLLVMImp define = new DefineLLVMImp(fun.nom(), fun.type().accept(this, h), paramsLLVM, instrLLVM);
prevSymTable.updateId(h);
TypeLLVM type = fun.type().accept(this, h);
if(!(type instanceof VoidLLVMImp)){ //on ajoute un return 0 si la fonction n'est pas un void, et ne finit ni par un return ni pas un goto (sans condition)
if(!(instrLLVM.getLast() instanceof ReturnLLVMImp || instrLLVM.getLast() instanceof BrLLVMImp)){
instrLLVM.add(new ReturnLLVMImp(type, new ValLLVMImp(type,0)));
}
}else if(type instanceof VoidLLVMImp){
instrLLVM.add(new ReturnLLVMImp(type,null));
}
DefineLLVMImp define = new DefineLLVMImp(fun.nom(), type, paramsLLVM, instrLLVM);
return define;
}
@Override
public DefineLLVMImp visitPrototype(PrototypeImp fun, SymTable h) {
return new DefineLLVMImp(fun.nom(), fun.type().accept(this, h), null,null);
ArrayList<VarLLVMImp> params = new ArrayList<>();
for(VarImp param: fun.params()){
params.add(new VarLLVMImp(new IntLLVMImp(),param.name(),false));
}
return new DefineLLVMImp(fun.nom(), fun.type().accept(this, h), params,null);
}
//DECLARATION
//DECLARATION -----------------------------------
@Override
public InstrAndSymTable visitDeclaration(DeclarationImp instr, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> list = new ArrayList<>();
for(int i = 0; i<instr.s().size();i++){
TypeLLVM t2 = instr.t().accept(this,h);
//String name = instr.s().get(i);//h.addVarLLVM(instr.s().get(i));
Result r = h.addVar(instr.s().get(i));
String name = r.var;
h = r.symTable;
list.add(new AssignLVMImp(new VarLLVMImp(t2, name),new allocaLLVMImp(t2)));
Result r;
String nom= instr.s().get(i).nom();
Expression size=instr.s().get(i).size();
if(size==null){
r= h.addVar(nom,t2);
h = r.symTable;
list.add(new AssignLLVMImp(new VarLLVMImp(t2, r.var,false),new allocaLLVMImp(t2)));
}else {
TypeLLVM arrayType = new PointerLLVMImp(t2);
//Alloca
Result r_size= h.addNewTempVar();
VarLLVMImp tmpVar = new VarLLVMImp(new IntLLVMImp(), r_size.var, false);
list.add(new AssignLLVMImp(tmpVar, new allocaLLVMImp(t2)));
//Alloca table
r = h.addVar(nom, arrayType);
h = r.symTable;
list.add(new AssignLLVMImp(new VarLLVMImp(t2, r.var,false),new allocaLLVMImp(new PointerLLVMImp(t2))));
//Store
}
}
prevSymTable.updateId(h);
return new InstrAndSymTable(list,h);
}
//INSTRUCTION
@Override
public InstrAndSymTable visitVarDecl(VarDeclImp instr, SymTable h) {
ArrayList<InstructionLLVM> list = new ArrayList<>();
return new InstrAndSymTable(list,h);
}
//INSTRUCTION -----------------------------------
@Override
public ArrayList<InstructionLLVM> visitReturn(Return_instrImp instr, SymTable h) {
ArrayList<InstructionLLVM> result = new ArrayList<>();
//ret void
if (instr.e() == null) {
result.add(new ReturnLLVMImp(new VoidLLVMImp(), null));
}else{
InstrAndVal res = instr.e().accept(this,h);
ValLLVM var = res.val;
InstructionLLVM r = new ReturnLLVMImp(var.getType(),var);
result.addAll(res.instrs);
result.add(r);
}
return result;
}
@Override
public ArrayList<InstructionLLVM> visitBloc(BlocImp instr, SymTable h) {
SymTable prev = h;
h= h.newBlock();
ArrayList<InstructionLLVM> instrLLVM = new ArrayList<>();
for(int i = 0; i<instr.instrs().size(); i++){
@@ -114,13 +175,12 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
}
h= h.outBlock();
prev.updateId(h);
return instrLLVM;
}
@Override
public ArrayList<InstructionLLVM> visitBlocDec(BlocDecImp instr, SymTable h) {
SymTable prev = h;
ArrayList<InstructionLLVM> instrLLVM = new ArrayList<>();
for(int i = 0; i<instr.decls().size(); i++){
@@ -132,23 +192,9 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
instrLLVM.addAll(instr.instrs().get(i).accept(this, h));
}
prev.updateId(h);
return instrLLVM;
}
@Override
public ArrayList<InstructionLLVM> visitReturn(Return_instrImp instr, SymTable h) {
InstrAndVal res = instr.e().accept(this,h);
ValLLVM var = res.val;
InstructionLLVM r = new ReturnLLVMImp(var.getType(),var);
ArrayList<InstructionLLVM> result = new ArrayList<>();
result.addAll(res.instrs);
result.add(r);
return result;
}
@Override
public ArrayList<InstructionLLVM> visitAssign(AssignImp instr, SymTable h) {
@@ -156,8 +202,12 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
ValLLVM var = res.val;
ArrayList<InstructionLLVM> result = new ArrayList<>();
result.addAll(res.instrs);
//InstructionLLVM r = new AssignLVMImp(new VarLLVMImpl(var.getType(),instr.t()),var);
InstructionLLVM r = new StoreLLVMImp(var.getType(),var,var.getType(),new VarLLVMImp(var.getType(),h.getVar(instr.t())));
//InstructionLLVM r = new AssignLLVMImp(new VarLLVMImpl(var.getType(),instr.t()),var);
if(var.getType().getClass() != h.getType(instr.t()).getClass()){
System.err.println("[VSL compile error] : Erreur de typage");
System.exit(1);
}
InstructionLLVM r = new StoreLLVMImp(var.getType(),var,new VarLLVMImp(var.getType(),h.getVar(instr.t()),false));
result.add(r);
return result;
}
@@ -167,32 +217,93 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
public ArrayList<InstructionLLVM> visitPrint(PrintImp instr, SymTable h) {
ArrayList<InstructionLLVM> l = new ArrayList<>();
ArrayList<ValLLVM> params = new ArrayList<>();
l.add(new PrintLLVMImp(params)); //TODO
String name = h.getGlobalDeclName();
VarLLVMImp varGlobal = new VarLLVMImp(new PointerLLVMImp(new CharLLVMImp()),name,true);
params.add(varGlobal);
String strGlobal = "";
int size = 1; //le \00 est focément à la fin et compte comme un seul char
for(int i = 0; i<instr.t().size(); i++){
Object obj = instr.t().get(i);
if(obj instanceof String){
String str = (String)obj;
str = str.replace("\\n", "\\0A");
//count OA
int countOA = 0;
int index = 0;
//using array
while ((index = str.indexOf("\\0A", index)) != -1) {
countOA++;
index += 3;
}
size += str.length() - countOA * 2;
strGlobal += str;
}
else if(obj instanceof Expression){
Expression exp = (Expression)obj;
InstrAndVal r = exp.accept(this, h);
l.addAll(r.instrs);
params.add(r.val);
strGlobal+="%d";
size+=2;
}
}
strGlobal+="\\00";
DeclarGlobalLLVMImp globalDecl = new DeclarGlobalLLVMImp(varGlobal,new CharLLVMImp(),strGlobal,size); //TODO
h.addGlobalDecl(globalDecl);
l.add(new PrintLLVMImp(globalDecl,params));
return l;
}
@Override
public ArrayList<InstructionLLVM> visitRead(ReadImp instr, SymTable h) {
ArrayList<InstructionLLVM> l = new ArrayList<>();
ArrayList<ValLLVM> params = new ArrayList<>();
String name = h.getGlobalDeclName();
VarLLVMImp varGlobal = new VarLLVMImp(new PointerLLVMImp(new CharLLVMImp()),name,true);
params.add(varGlobal);
String strGlobal = "";
int size = 1; //le \00 est focément à la fin et compte comme un seul char
for(int i = 0; i<instr.t().size(); i++){
String nomVar = h.getVar(instr.t().get(i).name());
Type typeVar = h.getType(instr.t().get(i).name());
VarLLVMImp newVar = new VarLLVMImp(typeVar.accept(this,h), nomVar);
ArrayList<ValLLVM> params = new ArrayList<>();
TypeLLVM typeVar = h.getType(instr.t().get(i).name());
//Ajout * par passant PointerType
TypeLLVM ptrType = new PointerLLVMImp(typeVar);
VarLLVMImp newVar = new VarLLVMImp(ptrType, nomVar,false);
strGlobal+="%d"; //2 char de long
size+=2;
params.add(newVar);
l.add(new ReadLLVMImp(params));
}
}
strGlobal+="\\00";
DeclarGlobalLLVMImp globalDecl = new DeclarGlobalLLVMImp(varGlobal,new CharLLVMImp(),strGlobal,size);//TODO
h.addGlobalDecl(globalDecl);
l.add(new ScanLLVMImp(globalDecl,params));
return l;
}
@Override
public ArrayList<InstructionLLVM> visitIfThen(IfThenImp instr, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> l = new ArrayList<>();
String labelIf= "if"+h.getNewIdLabel()+":";
String labelThen= "then"+h.getNewIdLabel()+":";
String labelFin= "fin"+h.getNewIdLabel();
String labelIf= "if"+h.getNewIdLabel();
String labelThen= "then"+h.getNewIdLabel();
String labelFin= "fi"+h.getNewIdLabel();
l.add(new BrLLVMImp(labelIf));
l.add(new LabelLLVMImp(labelIf));
InstrAndVal temp = instr.e().accept(this,h);
l.addAll(temp.instrs);
@@ -200,8 +311,8 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
ExpressionLLVM exTemp = new IcmpLLVMImp(val,new ValLLVMImp(new IntLLVMImp(), 0));
Result r = h.addNewTempVar();
h = r.symTable;
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var);
l.add(new AssignLVMImp(varCond,exTemp));
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var,false);
l.add(new AssignLLVMImp(varCond,exTemp));
l.add(new BrCondLLVMImp(varCond,labelThen,labelFin));
l.add(new LabelLLVMImp(labelThen));
@@ -211,19 +322,19 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
h=h.outBlock();
l.add(new LabelLLVMImp(labelFin));
prevSymTable.updateId(h);
return l;
}
@Override
public ArrayList<InstructionLLVM> visitIfThenElse(IfThenElseImp instr, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> l = new ArrayList<>();
String labelIf= "if"+h.getNewIdLabel()+":";
String labelThen= "then"+h.getNewIdLabel()+":";
String labelElse= "else"+h.getNewIdLabel()+":";
String labelFin= "fin"+h.getNewIdLabel();
String labelIf= "if"+h.getNewIdLabel();
String labelThen= "then"+h.getNewIdLabel();
String labelElse= "else"+h.getNewIdLabel();
String labelFin= "fi"+h.getNewIdLabel();
l.add(new BrLLVMImp(labelIf));
l.add(new LabelLLVMImp(labelIf));
InstrAndVal temp = instr.e().accept(this,h);
l.addAll(temp.instrs);
@@ -231,8 +342,8 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
ExpressionLLVM exTemp = new IcmpLLVMImp(val,new ValLLVMImp(new IntLLVMImp(), 0));
Result r = h.addNewTempVar();
h = r.symTable;
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var);
l.add(new AssignLVMImp(varCond,exTemp));
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var,false);
l.add(new AssignLLVMImp(varCond,exTemp));
l.add(new BrCondLLVMImp(varCond,labelThen,labelElse));
l.add(new LabelLLVMImp(labelThen));
@@ -249,14 +360,16 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
return l;
}
@Override
public ArrayList<InstructionLLVM> visitWhile(WhileImp instr, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> l = new ArrayList<>();
String labelWhile = "while"+h.getNewIdLabel()+":";
String labelDo = "do"+h.getNewIdLabel()+":";
String labelWhile = "while"+h.getNewIdLabel();
String labelDo = "do"+h.getNewIdLabel();
String labelDone = "done"+h.getNewIdLabel();
l.add(new BrLLVMImp(labelWhile));
l.add(new LabelLLVMImp(labelWhile));
InstrAndVal temp = instr.e().accept(this,h); //retourne les instructionz pour obtenir le résultat de l'expression ainsi que la variable contenant le résultat final
@@ -265,8 +378,8 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
ExpressionLLVM exTemp = new IcmpLLVMImp(val,new ValLLVMImp(new IntLLVMImp(), 0));
Result r = h.addNewTempVar();
h = r.symTable;
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var);
l.add(new AssignLVMImp(varCond,exTemp));
VarLLVMImp varCond = new VarLLVMImp(exTemp.getType(), r.var,false);
l.add(new AssignLLVMImp(varCond,exTemp));
l.add(new BrCondLLVMImp(varCond,labelDo,labelDone));
l.add(new LabelLLVMImp(labelDo));
@@ -278,12 +391,37 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
l.add(new BrLLVMImp(labelWhile));
l.add(new LabelLLVMImp(labelDone));
prevSymTable.updateId(h);
return l;
}
@Override
public ArrayList<InstructionLLVM> visitVoidFunction(VoidFunctionImp instr, SymTable h) {
ArrayList<InstructionLLVM> l = new ArrayList<>();
ArrayList<ValLLVM> paramsLLVM = new ArrayList<>();
for(Expression param: instr.expr()){
InstrAndVal result = param.accept(this, h);
l.addAll(result.instrs);
paramsLLVM.add(result.val);
}
ValueFunMap fun= h.getFunction(instr.nom());
if(fun == null){
System.err.println("Function n'est pas trouvé");
return l;
}
if (!(fun.define.type() instanceof VoidLLVMImp)){
System.err.println("Fonction n'est pas un void");
return l;
}
l.add(new CallVoidLLVMImp(fun.define,paramsLLVM,""));
return l;
}
//EXPRESSION
//EXPRESSION -----------------------------------
@Override
public InstrAndVal visitConst(ConstImp e, SymTable h) {
@@ -293,20 +431,17 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
@Override
public InstrAndVal visitVar(VarImp e, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> l =new ArrayList<>();
ValLLVM val = new VarLLVMImp(h.getvar_Type(e.name()).accept(this,h),h.getVar(e.name()));
ValLLVM val = new VarLLVMImp(h.getType(e.name()),h.getVar(e.name()),false);
Result r = h.addNewTempVar();
h = r.symTable;
VarLLVMImp varTemp = new VarLLVMImp(h.getvar_Type(e.name()).accept(this,h),r.var);
l.add(new AssignLVMImp(varTemp,((ExpressionLLVM)(new LoadLLVMImp(val)))));
prevSymTable.updateId(h);
VarLLVMImp varTemp = new VarLLVMImp(h.getType(e.name()),r.var,false);
l.add(new AssignLLVMImp(varTemp,((ExpressionLLVM)(new LoadLLVMImp(val)))));
return new InstrAndVal(l, varTemp);
}
@Override
public InstrAndVal visitBinOp(BinopExpressionImp e, SymTable h) {
SymTable prevSymTable = h;
ArrayList<InstructionLLVM> list = new ArrayList<>();
InstrAndVal res1 = e.e1().accept(this, h);
InstrAndVal res2 = e.e2().accept(this, h);
@@ -325,13 +460,12 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
Result r = h.addNewTempVar();
String temp = r.var;
h = r.symTable;
VarLLVMImp var = new VarLLVMImp(type,temp);
list.add(new AssignLVMImp(var, new BinOpLLVMImp(type,e.op(),val1,val2)));
prevSymTable.updateId(h);
VarLLVMImp var = new VarLLVMImp(type,temp,false);
list.add(new AssignLLVMImp(var, new BinOpLLVMImp(type,e.op(),val1,val2)));
return new InstrAndVal(list, var);
}
public InstrAndVal visitAppeal(AppealImp instr,SymTable h){
public InstrAndVal visitCall(CallImp instr,SymTable h){
ArrayList<InstructionLLVM> l = new ArrayList<>();
ArrayList<ValLLVM> paramsLLVM = new ArrayList<>();
for(Expression param : instr.params()){
@@ -339,21 +473,24 @@ public class toLLVM_Visitor implements ProgramVisitor<SymTable,ProgramLLVMImp>,
l.addAll( result.instrs);
paramsLLVM.add(result.val);
}
ValueFunMap fLLVM = h.getFunction(instr.fName()); //on récupère la fonction LLVM dans la table des Symboles
if(fLLVM == null){
System.err.println("[VSL compile error] : la fonction n'existe pas, veuillez vous assurer de l'avoir déclarée avant l'appel");
return new InstrAndVal(l, null);
}
//Pour c=func(x,y)
Result res = h.addNewTempVar();
h = res.symTable;
VarLLVMImp var = new VarLLVMImp(fLLVM.define.type(), res.var);
ValueFunMap fLLVM = h.getFunction(instr.fName());
l.add(new CallLLVMImp(fLLVM.define,paramsLLVM,""));
return new InstrAndVal(l, var);
//Pour c=func(x,y)
if (fLLVM.define.type() instanceof VoidLLVMImp) {
l.add(new CallVoidLLVMImp(fLLVM.define, paramsLLVM, ""));
return new InstrAndVal(l, null);
} else {
Result res = h.addNewTempVar();
h = res.symTable;
VarLLVMImp var = new VarLLVMImp(fLLVM.define.type(), res.var, false);
l.add(new AssignLLVMImp(var, new CallLLVMImp(fLLVM.define, paramsLLVM, "")));
return new InstrAndVal(l, var);
}
}
//TYPE -----------------------------------
@Override
public TypeLLVM visitInt(Type_intImp t, SymTable h) {
return new IntLLVMImp();

View File

@@ -27,14 +27,15 @@ public interface Interface {
public interface InstructionLLVMVisitor<H,S> {
public S visitReturnLLVM(ReturnLLVMImp instr, H h);
public S visitAssignLLVM(AssignLVMImp instr, H h);
public S visitAssignLLVM(AssignLLVMImp instr, H h);
public S visitStoreLLVM(StoreLLVMImp instr, H h);
public S visitPrintLLVM(PrintLLVMImp instr, H h);
public S visitReadLLVM(ReadLLVMImp instr, H h);
public S visitScanLLVM(ScanLLVMImp instr, H h);
public S visitLabelLLVM(LabelLLVMImp instr, H h);
public S visitBrLLVM(BrLLVMImp instr, H h);
public S visitBrCondLLVM(BrCondLLVMImp instr, H h);
public S visitCallLLVM(CallLLVMImp instr, H h);
public S visitCallVoidLLVM(CallVoidLLVMImp instr, H h);
public S visitDeclarGlobalLLVM(DeclarGlobalLLVMImp instr, H h);
}
//////////ExpressionLLVM (expression)
@@ -53,6 +54,8 @@ public interface Interface {
public S visitValLLVM(ValLLVMImp e,H h);
public S visitVarLLVM(VarLLVMImp e,H h);
public S visitIcmpLLVM(IcmpLLVMImp e, H h);
public S visitCallLLVM(CallLLVMImp e, H h);
public S visitGetElementPtrLLVM(GetElementPtr getElementPtr, H h);
}
/*public interface IdentifierLLVM{ //globaux @ et local %
@@ -70,7 +73,9 @@ public interface Interface {
public S visitIntLLVM(IntLLVMImp e,H h);
public S visitVoidLLVM(VoidLLVMImp e, H h);
public S visitBooleanLLVM(BooleanLLVMImp e, H h);
public S visitStringLLVM(StringLLVMImp e, H h);
public S visitCharLLVM(CharLLVMImp e, H h);
public S visitPointerLLVM(PointerLLVMImp e,H h);
public S visitArrayLLVM(ArrayLLVMImp e, H h);
}
}

View File

@@ -14,6 +14,8 @@ TypeLLVMVisitor<String,String>
{
static String INDENT = " ";
//PROGRAMME ---------------------------------------------
@Override
public String visitProgramLLVM(ProgramLLVMImp prog, String indent) {
StringBuilder str = new StringBuilder();
@@ -25,10 +27,11 @@ TypeLLVMVisitor<String,String>
str.append("\n");
str.append("; Actual code begins\n");
// Déclaration pour les string
//for(int i = 0; i<declration.size(); i++){
//str.append(declration.get(i) + "\n");
//}
for(int i = 0; i<prog.declarGlobal().size(); i++){
str.append(prog.declarGlobal().get(i).accept(this, indent));
}
str.append("\n");
//PROTO et FUNC
@@ -39,6 +42,8 @@ TypeLLVMVisitor<String,String>
return str.toString();
}
//DEFINE ---------------------------------------------
@Override
public String visitDefineLLVM(DefineLLVMImp define, String indent) {
StringBuilder str = new StringBuilder("define ");
@@ -59,16 +64,86 @@ TypeLLVMVisitor<String,String>
return str.toString();
}
//INSTRUCTION ---------------------------------------------
@Override
public String visitReturnLLVM(ReturnLLVMImp instr, String h) {
return INDENT+"ret " + instr.type().accept(this, h) + " " + instr.e().accept(this, h);
if (instr.e() == null) {
return INDENT + "ret " + instr.type().accept(this, h);
} else {
return INDENT + "ret " + instr.type().accept(this, h) + " " + instr.e().accept(this, h);
}
}
@Override
public String visitAssignLLVM(AssignLLVMImp instr, String h) {
return INDENT+instr.var().accept(this, h) + " = " + instr.e().accept(this, h);
}
@Override
public String visitStoreLLVM(StoreLLVMImp instr, String h) {
return INDENT+"store " + instr.type().accept(this, "") + " " + instr.e().accept(this, "") + ", " + new PointerLLVMImp(instr.type()).accept(this, "") + " " + instr.var().accept(this,"");
}
@Override
public String visitAssignLLVM(AssignLVMImp instr, String h) {
return INDENT+instr.var().accept(this, h) + " = " + instr.e().accept(this, h);
public String visitPrintLLVM(PrintLLVMImp instr, String h) { //TODO
DefineLLVMImp printLLVM = new DefineLLVMImp("printf", new IntLLVMImp(), new ArrayList<>(), new ArrayList<>());
CallVoidLLVMImp callPrint = new CallVoidLLVMImp(printLLVM, instr.l(),"(i8*, ...)");
return callPrint.accept(this, h);
}
@Override
public String visitScanLLVM(ScanLLVMImp instr, String h) { //TODO
DefineLLVMImp readLLVM = new DefineLLVMImp("scanf", new IntLLVMImp(), new ArrayList<>(), new ArrayList<>());
CallVoidLLVMImp callRead = new CallVoidLLVMImp(readLLVM, instr.l(),"(i8*, ...)");
return callRead.accept(this, h);
}
//label
@Override
public String visitLabelLLVM(LabelLLVMImp instr, String h) {
return instr.name()+":";
}
@Override
public String visitBrLLVM(BrLLVMImp instr, String h) {
return INDENT+"br label %" + instr.label();
}
@Override
public String visitBrCondLLVM(BrCondLLVMImp instr, String h) {
return INDENT+"br " + instr.var().type().accept(this, h) +" "+ instr.var().accept(this, h) + ", label %" + instr.label() + ", label %" + instr.labelElse() ;
}
@Override
public String visitCallVoidLLVM(CallVoidLLVMImp instr, String h) {
String str = INDENT+ "call " + instr.f().type().accept(this, h) + " " + instr.str() + " @"+instr.f().name() + "(";
for(int i = 0; i<instr.params().size(); i++){
str += instr.params().get(i).getType().accept(this, h) + " " + instr.params().get(i).accept(this,h);
if(i<instr.params().size()-1) str += ", ";
}
return str + ")";
}
@Override
public String visitDeclarGlobalLLVM(DeclarGlobalLLVMImp instr, String h) {
String str = "@"+instr.var().nom() + " = global";
str += " [" + instr.size() + " x "+ instr.type().accept(this, h) + "] ";
str+= "c\""+ instr.str()+"\"\n";
return str;
}
//EXPRESSION ---------------------------------------------
@Override
public String visitBinOpLLVM(BinOpLLVMImp e, String h) {
String str = "";
@@ -94,79 +169,61 @@ TypeLLVMVisitor<String,String>
return str + e.type().accept(this,h) + " " + e.val1().accept(this,h) + ", " + e.val2().accept(this,h);
}
@Override
public String visitIcmpLLVM(IcmpLLVMImp e, String h) {
return "icmp ne " + e.val1().getType().accept(this, h) +" "+ e.val1().accept(this, h) + ", " + e.val2().accept(this, h);
}
@Override
public String visitAllocaLLVM(allocaLLVMImp e, String h) {
return "alloca " + e.type().accept(this, h);
}
@Override
public String visitStoreLLVM(StoreLLVMImp instr, String h) {
return INDENT+"store " + instr.valType().accept(this, "") + " " + instr.e().accept(this, "") + ", " + instr.varType().accept(this, "") + "* " + instr.var().accept(this,"");
}
@Override
public String visitLoadLLVM(LoadLLVMImp e, String h) {
return "load" + " " + e.getType().accept(this, h) + ", "+ e.getType().accept(this, h) + "* " + e.val().accept(this, h);
return "load" + " " + e.getType().accept(this, h) + ", "+ new PointerLLVMImp(e.getType()).accept(this, h) + " " + e.val().accept(this, h);
}
@Override
public String visitCallLLVM(CallLLVMImp instr, String h) {
String str = INDENT+ "call " + instr.str() + instr.f().type().accept(this, h) + " @"+instr.f().name() + "(";
for(int i = 0; i<instr.params().size(); i++){
str += instr.params().get(i).getType().accept(this, h) + " " + instr.params().get(i).accept(this,h);
if(i<instr.params().size()-1) str += ", ";
}
return str + ")";
}
@Override
public String visitPrintLLVM(PrintLLVMImp instr, String h) { //TODO
DefineLLVMImp printLLVM = new DefineLLVMImp("printf", new IntLLVMImp(), new ArrayList<>(), new ArrayList<>());
CallLLVMImp callPrint = new CallLLVMImp(printLLVM, new ArrayList<>(),"(i8*,...) ");
return callPrint.accept(this, h);
}
@Override
public String visitReadLLVM(ReadLLVMImp instr, String h) { //TODO
DefineLLVMImp readLLVM = new DefineLLVMImp("scanf", new IntLLVMImp(), new ArrayList<>(), new ArrayList<>());
CallLLVMImp callRead = new CallLLVMImp(readLLVM, instr.l(),"(i8*,...) ");
return callRead.accept(this, h);
}
//label
@Override
public String visitLabelLLVM(LabelLLVMImp instr, String h) {
return instr.name()+":";
}
@Override
public String visitBrLLVM(BrLLVMImp instr, String h) {
return INDENT+"br label %" + instr.label();
}
@Override
public String visitBrCondLLVM(BrCondLLVMImp instr, String h) {
return INDENT+"br " + instr.var().type().accept(this, h) +" "+ instr.var().accept(this, h) + ", label %" + instr.label() + ", label %" + instr.labelElse() ;
}
//var et val
@Override
public String visitValLLVM(ValLLVMImp e, String h) {
return e.val() + "";
}
@Override
public String visitVarLLVM(VarLLVMImp e, String h) {
return "%"+e.nom();
String prefix = "%";
if(e.isGlobal()) prefix = "@";
return prefix+e.nom();
}
@Override
public String visitIcmpLLVM(IcmpLLVMImp e, String h) {
return "icmp ne " + e.val1().getType().accept(this, h) +" "+ e.val1().accept(this, h) + ", " + e.val2().accept(this, h);
}
@Override
public String visitCallLLVM(CallLLVMImp instr, String h) {
String str = "call " + instr.f().type().accept(this, h) + " " + instr.str() + " @" + instr.f().name() + "(";
for (int i = 0; i < instr.params().size(); i++) {
str += instr.params().get(i).getType().accept(this, h) + " " + instr.params().get(i).accept(this, h);
if (i < instr.params().size() - 1) str += ", ";
}
return str + ")";
}
@Override
public String visitGetElementPtrLLVM(GetElementPtr exp, String h) {
PointerLLVMImp type = (PointerLLVMImp)exp.getType();
//getelementptr <type de sortie>, <type d'entrée> <Var d'entrée>, <type de l'indice> <indice>
return "getelementptr " + type.type().accept(this, h)+ ", " + exp.ptrVar().type().accept(this, h) + " " + exp.ptrVar().accept(this, h) + ", " + exp.i().getType().accept(this, h) + exp.i().accept(this, h);
}
//TYPE ---------------------------------------------
@Override
public String visitIntLLVM(IntLLVMImp e, String h) {
return "i32";
@@ -183,8 +240,17 @@ TypeLLVMVisitor<String,String>
}
@Override
public String visitStringLLVM(StringLLVMImp e, String h) {
return "i8*";
public String visitCharLLVM(CharLLVMImp e, String h) {
return "i8";
}
@Override
public String visitPointerLLVM(PointerLLVMImp e, String h) {
return e.type().accept(this, h) + "*";
}
@Override
public String visitArrayLLVM(ArrayLLVMImp e, String h){
return "";
}
}

View File

@@ -9,7 +9,7 @@ import TP2.llvm.Interface.*;
public class ProgramLLVM {
//Program
public static record ProgramLLVMImp(ArrayList<Integer> declration ,ArrayList<DefineLLVM> fonctions) implements ProgLLVM{
public static record ProgramLLVMImp(ArrayList<DeclarGlobalLLVMImp> declarGlobal ,ArrayList<DefineLLVM> fonctions) implements ProgLLVM{
public <H, S> S accept(ProgramLLVMVisitor<H, S> v, H h) {
return v.visitProgramLLVM(this, h);
}
@@ -53,7 +53,7 @@ public class ProgramLLVM {
}
public static record AssignLVMImp(VarLLVMImp var, ExpressionLLVM e) implements InstructionLLVM{
public static record AssignLLVMImp(VarLLVMImp var, ExpressionLLVM e) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitAssignLLVM(this, h);
@@ -67,32 +67,40 @@ public class ProgramLLVM {
}
}
public static record StoreLLVMImp(TypeLLVM valType, ExpressionLLVM e,TypeLLVM varType, ValLLVM var) implements InstructionLLVM{
public static record StoreLLVMImp(TypeLLVM type, ExpressionLLVM e, ValLLVM var) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitStoreLLVM(this, h);
}
}
public static record CallLLVMImp(DefineLLVMImp f, ArrayList<ValLLVM> params, String str) implements InstructionLLVM{
public static record CallVoidLLVMImp(DefineLLVMImp f, ArrayList<ValLLVM> params, String str) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitCallLLVM(this, h);
return v.visitCallVoidLLVM(this, h);
}
}
public static record PrintLLVMImp(ArrayList<ValLLVM> l) implements InstructionLLVM{ //TODO c'est un Call qui appel la fonction print
public static record PrintLLVMImp(DeclarGlobalLLVMImp fmt,ArrayList<ValLLVM> l) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitPrintLLVM(this, h);
}
}
public static record ReadLLVMImp(ArrayList<ValLLVM> l) implements InstructionLLVM{ //TODO c'est un Call qui appel la fonction read
public static record ScanLLVMImp(DeclarGlobalLLVMImp fmt,ArrayList<ValLLVM> l) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitReadLLVM(this, h);
return v.visitScanLLVM(this, h);
}
}
public static record DeclarGlobalLLVMImp(VarLLVMImp var,TypeLLVM type,String str, int size) implements InstructionLLVM{
@Override
public <H, S> S accept(InstructionLLVMVisitor<H, S> v, H h) {
return v.visitDeclarGlobalLLVM(this, h);
}
}
@@ -110,19 +118,6 @@ public class ProgramLLVM {
}
/*public static record ConstLLVMImp(TypeLLVM type, int val) implements ExpressionLLVM{
public <H, S> S accept(ExpressionLLVMVisitor<H, S> v, H h) {
return v.visitConstLLVM(this, h);
}
@Override
public String prettyprinter() {
return val+"";
}
}*/
public static record allocaLLVMImp(TypeLLVM type) implements ExpressionLLVM{
@Override
public <H, S> S accept(ExpressionLLVMVisitor<H, S> v, H h) {
@@ -161,6 +156,32 @@ public class ProgramLLVM {
}
public static record CallLLVMImp(DefineLLVMImp f, ArrayList<ValLLVM> params, String str) implements ExpressionLLVM{
@Override
public <H, S> S accept(ExpressionLLVMVisitor<H, S> v, H h) {
return v.visitCallLLVM(this, h);
}
@Override
public TypeLLVM getType() {
return f.type();
}
}
public static record GetElementPtr(VarLLVMImp ptrVar, ExpressionLLVM i) implements ExpressionLLVM{
@Override
public <H, S> S accept(ExpressionLLVMVisitor<H, S> v, H h) {
return v.visitGetElementPtrLLVM(this, h);
}
@Override
public TypeLLVM getType() {
return ptrVar.type();
}
}
//Val
public static record ValLLVMImp(TypeLLVM type, int val) implements ValLLVM{
@@ -176,7 +197,7 @@ public class ProgramLLVM {
}
public static record VarLLVMImp(TypeLLVM type, String nom) implements ValLLVM{
public static record VarLLVMImp(TypeLLVM type, String nom, Boolean isGlobal) implements ValLLVM{
@Override
public <H, S> S accept(ExpressionLLVMVisitor<H, S> v, H h) {
return v.visitVarLLVM(this, h);
@@ -211,10 +232,22 @@ public class ProgramLLVM {
}
}
public static record StringLLVMImp() implements TypeLLVM{
public static record CharLLVMImp() implements TypeLLVM{
@Override
public <H, S> S accept(TypeLLVMVisitor<H, S> v, H h) {
return v.visitStringLLVM(this, h);
return v.visitCharLLVM(this, h);
}
}
}
public static record PointerLLVMImp(TypeLLVM type) implements TypeLLVM{
public <H, S> S accept(TypeLLVMVisitor<H, S> v, H h) {
return v.visitPointerLLVM(this, h);
}
}
public static record ArrayLLVMImp(TypeLLVM type, Expression size) implements TypeLLVM{
public <H,S> S accept(TypeLLVMVisitor<H, S> v, H h) {
return v.visitArrayLLVM(this, h);
}
}
}

View File

@@ -1,28 +1,6 @@
PROTO INT add()
FUNC INT add() {
INT z
z := 1
RETURN z
}
FUNC INT main(x,y) {
INT a,b,c,minh
x := 5
minh := x * y
b:=3
c:=add()
PRINT "coucou, tu peux réparer le visitPrint dans LLVM stp","il manque virgule au milieu", c*5+b
WHILE b - 1
DO{
b := b - 1
c := c + 1
}
DONE
IF c -1
THEN READ a ELSE READ b
FI
b:=c+1
RETURN 4 + 6 * 5 + 2 }
PROTO INT type(x,y)
FUNC INT main() {
INT a,b[10],c,d[11]
a:=1
c:=2
b[1] := 2
}

View File

@@ -1,58 +1 @@
PROTO INT add(x,y)
FUNC INT add(x,y,z) {
INT z,a,b,c
y := x+y
RETURN z
}
FUNC INT main(x,y) {
INT a,b,c,minh
x := 5
minh := x * y
b:=3
c:=1
PRINT "coucou, tu peux réparer le visitPrint dans LLVM stp","il manque virgule au milieu", c*5+b
WHILE b - 1
DO{
b := b - 1
c := c + 1
WHILE b -1
DO{
b:= b - 1
c:= c + 1
WHILE b -1
DO{
b:= b - 1
c:= c + 1
}
DONE
}
DONE
}
DONE
WHILE b - 1
DO{
b := b - 1
c := c + 1
WHILE b -1
DO{
b:= b - 1
c:= c + 1
WHILE b -1
DO{
b:= b - 1
c:= c + 1
}
DONE
}
DONE
}
DONE
IF c -1
THEN READ a ELSE READ b
FI
b:=c+1
RETURN 4 + 6 * 5 + 2 }
PROTO INT type(x,y)
FUNC VOID main() PRINT 1

BIN
tests/fragment0/add0 Executable file

Binary file not shown.

BIN
tests/fragment0/add1 Executable file

Binary file not shown.

BIN
tests/fragment0/const0 Executable file

Binary file not shown.

BIN
tests/fragment0/const1 Executable file

Binary file not shown.

BIN
tests/fragment0/div0 Executable file

Binary file not shown.

BIN
tests/fragment0/div1 Executable file

Binary file not shown.

BIN
tests/fragment0/mod Executable file

Binary file not shown.

BIN
tests/fragment0/mult1 Executable file

Binary file not shown.

BIN
tests/fragment0/mult2 Executable file

Binary file not shown.

BIN
tests/fragment0/paren Executable file

Binary file not shown.

BIN
tests/fragment0/priority1 Executable file

Binary file not shown.

BIN
tests/fragment0/priority2 Executable file

Binary file not shown.

BIN
tests/fragment0/sub0 Executable file

Binary file not shown.

BIN
tests/fragment0/sub1 Executable file

Binary file not shown.

BIN
tests/fragment1/assign1 Executable file

Binary file not shown.

BIN
tests/fragment1/assign2 Executable file

Binary file not shown.

BIN
tests/fragment1/block Executable file

Binary file not shown.

BIN
tests/fragment1/decl Executable file

Binary file not shown.

BIN
tests/fragment1/hello_world Executable file

Binary file not shown.

BIN
tests/fragment1/if1 Executable file

Binary file not shown.

BIN
tests/fragment1/if2 Executable file

Binary file not shown.

BIN
tests/fragment1/print1 Executable file

Binary file not shown.

BIN
tests/fragment1/print2 Executable file

Binary file not shown.

BIN
tests/fragment1/print3 Executable file

Binary file not shown.

BIN
tests/fragment1/print4 Executable file

Binary file not shown.

BIN
tests/fragment1/sequence Executable file

Binary file not shown.

BIN
tests/fragment1/while1 Executable file

Binary file not shown.

BIN
tests/fragment1/while2 Executable file

Binary file not shown.

BIN
tests/fragment2/call Executable file

Binary file not shown.

BIN
tests/fragment2/call2 Executable file

Binary file not shown.

BIN
tests/fragment2/call3expr Executable file

Binary file not shown.

BIN
tests/fragment2/call4if Executable file

Binary file not shown.

BIN
tests/fragment2/proto1 Executable file

Binary file not shown.

BIN
tests/fragment2/proto2 Executable file

Binary file not shown.

BIN
tests/testsAdvanced/carre Executable file

Binary file not shown.

BIN
tests/testsAdvanced/diverge Executable file

Binary file not shown.

Binary file not shown.

BIN
tests/testsAdvanced/portee2 Executable file

Binary file not shown.