Compare commits

...

70 commits

Author SHA1 Message Date
67bda53ce0 add license 2023-06-01 00:00:42 +02:00
Raphaël LACROIX
794add9e34 last commit 2023-05-31 23:59:24 +02:00
Raphaël LACROIX
315602a36f last commit 2023-05-31 23:55:26 +02:00
Raphaël LACROIX
6085f51211 removed unused code 2023-05-31 23:30:39 +02:00
Raphaël LACROIX
202c903459 big overhaul (2) 2023-05-31 23:21:40 +02:00
Raphaël LACROIX
5e4be22e3d big overhaul 2023-05-31 23:20:18 +02:00
Raphaël LACROIX
30d2d7577d Merge remote-tracking branch 'origin/master' 2023-05-31 22:10:40 +02:00
Raphaël LACROIX
f1671ba4b6 added the new testFile's ASMs 2023-05-31 22:05:48 +02:00
Raphaël LACROIX
a6735071ad fixed typo 2023-05-31 22:03:32 +02:00
Raphaël LACROIX
52ea586362 fixed missing store in post process 2023-05-31 22:01:23 +02:00
Raphaël LACROIX
eb384e3018 wrapped import in order to check for the installation of packages 2023-05-31 22:00:18 +02:00
Raphaël LACROIX
4529d87b04 Added vhdl/inter make options 2023-05-31 21:59:52 +02:00
Raphaël LACROIX
0642e1bab6 Added fibonacci test file 2023-05-31 21:59:39 +02:00
Lacroix Raphael
b3d75a1a46 Fixed typos 2023-05-31 18:38:35 +02:00
Raphaël LACROIX
365376fcfd asm for previous commit's testFile 2023-05-31 16:48:24 +02:00
Raphaël LACROIX
cb61c7d395 testFile with fibonacci program 2023-05-31 16:47:20 +02:00
Raphaël LACROIX
62f9580aee added style.css (the graphical interpreter's stylesheet) because code is better when it looks cool 2023-05-31 16:46:49 +02:00
Raphaël LACROIX
cf04e317f7 Merge remote-tracking branch 'origin/master' 2023-05-31 16:45:53 +02:00
Raphaël LACROIX
c8f53d34b8 fixed the yacc JMF without boolean variable 2023-05-31 16:45:03 +02:00
Raphaël LACROIX
2c9bb64de1 added the new interpreters 2023-05-31 16:44:29 +02:00
Lacroix Raphael
834c2b01df added jmp, jmf support, speculative execution of LI DI then flushing, boolean conditions 2023-05-30 16:29:31 +02:00
Lacroix Raphael
576b41da4d fixed data path and aleas 2023-05-30 13:38:05 +02:00
Lacroix Raphael
8a7685b049 xilinx generqted files 2023-05-30 08:46:35 +02:00
Lacroix Raphael
1a7e84b6d3 started preparing tests 2023-05-30 00:49:56 +02:00
Raphaël LACROIX
f6a33bfaf0 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	VHDL/ALU/ALU.srcs/sources_1/new/Pipeline.vhd
2023-05-29 23:49:23 +02:00
Raphaël LACROIX
b6c719eb89 the rest of the ams steps 2023-05-29 23:47:17 +02:00
Raphaël LACROIX
c0b06b9565 added hardcoded operations (from cross compiler) in the InstructionMemory.vhd 2023-05-29 23:46:32 +02:00
Raphaël LACROIX
68b0a2ea01 added new testfiles 2023-05-29 23:45:50 +02:00
Raphaël LACROIX
3885da0ea5 added more operand (again) 2023-05-29 23:45:26 +02:00
Raphaël LACROIX
e621b754bf finished cross compiler for test 2023-05-29 23:43:29 +02:00
Raphaël LACROIX
8f5be60008 updated opcodes 2023-05-29 23:43:05 +02:00
Lacroix Raphael
c462cd7fe7 WIP tried stuff 2023-05-29 21:57:46 +02:00
Lacroix Raphael
12859bebe9 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	VHDL/ALU/ALU.cache/wt/project.wpc
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/Test_Alu_behav.wdb
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/compile.log
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/compile.sh
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/elaborate.sh
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/simulate.sh
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/obj/xsim_0.lnx64.o
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/obj/xsim_1.c
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/obj/xsim_1.lnx64.o
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/webtalk/.xsim_webtallk.info
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/webtalk/xsim_webtalk.tcl
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.dbg
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.mem
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.reloc
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.rlx
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.rtti
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.type
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsim.xdbg
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsimk
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/Test_Alu_behav/xsimkernel.log
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/xil_defaultlib/alu.vdb
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/xil_defaultlib/test_alu.vdb
#	VHDL/ALU/ALU.sim/sim_1/behav/xsim/xsim.dir/xil_defaultlib/xil_defaultlib.rlx
2023-05-29 21:42:46 +02:00
alejeune
134db4c2c9 Update ALU 2023-05-29 21:39:05 +02:00
Lacroix Raphael
474ba6b265 added test files for full CPU 2023-05-29 21:37:49 +02:00
Raphaël LACROIX
873502243b Merge remote-tracking branch 'origin/ALU' 2023-05-29 20:33:37 +02:00
alejeune
6997cf24e8 work in progress ALU 2023-05-29 20:30:32 +02:00
Raphaël LACROIX
ae447be456 added the alea handling and IP implementation 2023-05-29 19:54:40 +02:00
alejeune
46465784b8 added IP 2023-05-29 14:28:17 +02:00
alejeune
ce3fda3a4e Merge branch 'master' of https://git.etud.insa-toulouse.fr/rlacroix/Projet-Systemes-Informatiques 2023-05-29 13:59:24 +02:00
alejeune
22c945e716 Added VHDL part of the project 2023-05-29 13:58:26 +02:00
Raphaël LACROIX
c369d180b0 branch merge 2023-05-12 16:03:47 +02:00
Raphaël LACROIX
019a8c506e corrected typo in yacc 2023-05-12 16:03:28 +02:00
alejeune
1f8fa678bc Added translation registers (2) 2023-05-12 15:57:55 +02:00
alejeune
f006ac975a Added translation registers 2023-05-12 15:43:03 +02:00
alejeune
360f3d29eb Added translation registers 2023-05-12 15:37:57 +02:00
Raphaël LACROIX
88cc4fe7e7 first draft of the script to translate the code 2023-05-04 12:15:28 +02:00
Raphaël LACROIX
f3ac463013 updated asm format 2023-05-04 12:14:50 +02:00
Raphaël LACROIX
c34150e026 final conditions and loops tested 2023-04-20 11:48:47 +02:00
Raphaël LACROIX
ff74c5be44 While done (and tested) 2023-04-20 11:29:52 +02:00
alejeune
6661eb3865 Added conditional functions 2023-04-20 11:12:14 +02:00
Raphaël LACROIX
b354d938ea While done 2023-04-20 11:05:52 +02:00
Raphaël LACROIX
6927b7da82 If Done (and todo cleaned up) 2023-04-20 10:23:57 +02:00
Raphaël LACROIX
358e98d6d6 If Done 2023-04-20 10:23:32 +02:00
Raphaël LACROIX
18f64a1653 NOT A COMMIT 2023-04-20 08:15:13 +02:00
Raphaël LACROIX
39bad0048b changed asmTable way 2023-04-18 16:55:52 +02:00
Raphaël LACROIX
86af52f0ac added basic asmTable functionalities 2023-04-18 16:27:50 +02:00
Raphaël LACROIX
c71e340389 NOT REAL PUSH 2023-04-18 16:13:40 +02:00
Raphaël LACROIX
5d7d2a82f9 removed old files 2023-04-18 11:45:30 +02:00
Raphaël LACROIX
ced95f1a97 updated gitignore and blocs 2023-04-18 11:44:32 +02:00
Raphaël LACROIX
5d0902c868 start of control/loops 2023-04-18 11:36:44 +02:00
Raphaël LACROIX
dad1f6d927 Added operations (.c) 2023-04-18 09:44:41 +02:00
Raphaël LACROIX
42e264b8d5 Added operations 2023-04-18 09:44:04 +02:00
Raphaël LACROIX
322afd388c added flush 2023-04-14 15:37:57 +02:00
Raphaël LACROIX
977d225f25 fixed gitignore and files 2023-04-13 11:37:17 +02:00
Raphaël LACROIX
be674bf59e fixed little problems 2023-04-13 11:35:06 +02:00
Raphaël LACROIX
9cc28c32c2 Merge remote-tracking branch 'origin/aurelia'
# Conflicts:
#	Makefile
#	yacc.y
2023-04-13 11:20:19 +02:00
Raphaël LACROIX
8da76e2ec2 removed provides 2023-04-13 11:15:52 +02:00
Raphaël LACROIX
9439274586 fixed last bugs 2023-04-13 11:11:16 +02:00
Raphaël LACROIX
6bbc6c2d30 added code provides and fixed .h inclusion 2023-04-13 11:01:17 +02:00
62 changed files with 7697 additions and 2353 deletions

6
.gitignore vendored
View file

@ -1,2 +1,8 @@
.gitignore
.idea
out
yacc.tab.c
yacc.tab.h
yacc.output
testFile
testFile.old

View file

@ -1,29 +0,0 @@
GRM=yacc.y
LEX=lex.l
BIN=out
CC=gcc
CFLAGS=-Wall -g
OBJ=y.tab.o lex.yy.o table.o
all: $(BIN)
@touch testFile # to prevent an error in case of deletion
./out < testFile
%.o: %.c
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
y.tab.c: $(GRM)
bison -d -t -v $<
lex.yy.c: $(LEX)
flex $<
$(BIN): $(OBJ)
$(CC) $(CFLAGS) $(CPPFLAGS) $^ -o $@
clean:
rm $(OBJ) y.tab.c y.tab.h lex.yy.c

Binary file not shown.

View file

@ -1,2 +1,18 @@
# Projet-Systemes-Informatiques
**LEJEUNE AURÉLIA - LACROIX RAPHAËL**
*This project was carried out as part of our computer engineering training.
The aim of this project is to design a C compiler and a microprocessor, the former being thought with the latter in mind.*
The compiler is based on a simplified version of the C language. It supports basic arithmetic operations (addition, subtraction, integer division, multiplication), Boolean operations, while loops and complex conditions. It has been coded using Lex, Yacc and C. The resulting assembly code and object code can be produced using the cross-assembler (itself coded in Python).
An interpreter is available in a GUI version to follow assembly code execution step by step in memory.
## Compilation
- `$ make vhdl` : compiles and run the compiler then convert its binary into VHDL format
- `$ make cli-inter` : compiles and run the compiler then interprets its binary (GUI)
- `$ make gui-inter` :compiles and run the compiler then interprets its binary
## Microprocessor
The VHDL folder contains all the files needed to build our microprocessor. It also contains two test files, `test_alu` and `test_cpu`, for testing all ALU operations and simulating program execution, respectively.

13
asm/asm Normal file
View file

@ -0,0 +1,13 @@
AFC 1 5
COP 0 1
AFC 1 8
EQ 2 0 1
NOT 3 2
JMF 3 13
AFC 4 20
INF 2 0 4
JMF 2 13
AFC 1 2
ADD 4 0 1
COP 0 4
JMP 6

31
asm/asm2 Normal file
View file

@ -0,0 +1,31 @@
AFC 0 5
STORE 1 0
LOAD 0 1
STORE 0 0
AFC 0 8
STORE 1 0
LOAD 0 0
LOAD 1 1
EQ 2 1 0
STORE 2 2
LOAD 0 2
NOT 2 0
STORE 3 2
JMF 3 30
AFC 0 20
STORE 4 0
LOAD 0 0
LOAD 1 4
INF 2 0 1
STORE 2 2
JMF 2 30
AFC 0 2
STORE 1 0
LOAD 0 0
LOAD 1 1
ADD 0 0 1
STORE 4 0
LOAD 0 4
STORE 0 0
JMP 14
NOP

1
asm/asm3 Normal file
View file

@ -0,0 +1 @@
((x"06000500"),(x"08010000"),(x"07000100"),(x"08000000"),(x"06000800"),(x"08010000"),(x"07000000"),(x"07010100"),(x"0B020100"),(x"08020200"),(x"07000200"),(x"0C020000"),(x"08030200"),(x"10031E00"),(x"06001400"),(x"08040000"),(x"07000000"),(x"07010400"),(x"09020001"),(x"08020200"),(x"10021E00"),(x"06000200"),(x"08010000"),(x"07000000"),(x"07010100"),(x"01000001"),(x"08040000"),(x"07000400"),(x"08000000"),(x"0F0E0000"),(x"FF000000"),others => (x"ff000000"))

39
compilateur/Makefile Normal file
View file

@ -0,0 +1,39 @@
GRM=yacc.y
LEX=lex.l
BIN=out
CC=gcc
CFLAGS=-Wall -g
OBJ=yacc.tab.o lex.yy.o table.o operations.o blocs.o asmTable.o
asm: $(BIN)
@touch ../tests/testFile # to prevent an error in case of deletion
./out < ../tests/testFile
build: $(BIN)
%.o: %.c
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
yacc.tab.c: $(GRM)
bison -d -t -v $<
lex.yy.c: $(LEX)
flex $<
$(BIN): $(OBJ)
$(CC) $(CFLAGS) $(CPPFLAGS) $^ -o $@
clean:
rm $(OBJ) yacc.tab.c yacc.tab.h lex.yy.c
vhdl: clean asm
python3 ../cross-Compiler/cross-compiler.py
cli-inter: clean asm
python3 ../interpreter/interpreter.py
gui-inter: clean asm
python3 ../interpreter/graph_interpreter.py

13
compilateur/asm Normal file
View file

@ -0,0 +1,13 @@
AFC 1 5
COP 0 1
AFC 1 8
EQ 2 0 1
NOT 3 2
JMF 3 13
AFC 4 20
INF 2 0 4
JMF 2 13
AFC 1 2
ADD 4 0 1
COP 0 4
JMP 6

31
compilateur/asm2 Normal file
View file

@ -0,0 +1,31 @@
AFC 0 5
STORE 1 0
LOAD 0 1
STORE 0 0
AFC 0 8
STORE 1 0
LOAD 0 0
LOAD 1 1
EQ 2 1 0
STORE 2 2
LOAD 0 2
NOT 2 0
STORE 3 2
JMF 3 30
AFC 0 20
STORE 4 0
LOAD 0 0
LOAD 1 4
INF 2 0 1
STORE 2 2
JMF 2 30
AFC 0 2
STORE 1 0
LOAD 0 0
LOAD 1 1
ADD 0 0 1
STORE 4 0
LOAD 0 4
STORE 0 0
JMP 14
NOP

1
compilateur/asm3 Normal file
View file

@ -0,0 +1 @@
((x"06000500"),(x"08010000"),(x"07000100"),(x"08000000"),(x"06000800"),(x"08010000"),(x"07000000"),(x"07010100"),(x"0B020100"),(x"08020200"),(x"07000200"),(x"0C020000"),(x"08030200"),(x"10031E00"),(x"06001400"),(x"08040000"),(x"07000000"),(x"07010400"),(x"09020001"),(x"08020200"),(x"10021E00"),(x"06000200"),(x"08010000"),(x"07000000"),(x"07010100"),(x"01000001"),(x"08040000"),(x"07000400"),(x"08000000"),(x"0F0E0000"),(x"FF000000"),others => (x"ff000000"))

109
compilateur/asmTable.c Normal file
View file

@ -0,0 +1,109 @@
#include <stdio.h>
#include "asmTable.h"
#include "stdlib.h"
#include <string.h>
static int labelCounter = 0;
/*At the start of the execution : the whole array is empty*/
static ASMLine* asmTable;
static int lineCounter = 0;
static int maxIndex = START_TABLE_SIZE;
#include "asmTable.h"
#include "table.h"
/* /!\ To be called at the beginning
* Initializes the array of Symbols*/
void initASMTable(){
asmTable = malloc(sizeof(ASMLine) * START_TABLE_SIZE);
}
/*Checks for the length of the array and reallocates if necessary*/
void checkASMArraySanity(){
if (lineCounter == maxIndex){
reallocateASMArray(maxIndex * 2);
}
}
/*reallocates the array with the specified size*/
void reallocateASMArray(int size){
ASMLine *temp = (ASMLine*) realloc(asmTable, (sizeof(ASMLine) * size));
if (temp != NULL){
asmTable = temp;
}
else {
error("Cannot allocate more memory.\n");
}
}
/*inserts an asm code line at the current index*/
void addLine(char* s) {
strcpy(asmTable[lineCounter].name,s);
asmTable[lineCounter].jumpLine = -1;
asmTable[lineCounter].conditionAddr = -1;
lineCounter++;
checkASMArraySanity();
displayASMTable();
}
/*inserts the address in case of jumps*/
void setJumpLine(int index, int addr) {
asmTable[index].jumpLine = addr;
displayASMTable();
}
/*inserts the condition's address in case of jumps*/
void setConditionAddr(int index, int addr) {
asmTable[index].conditionAddr = addr;
displayASMTable();
}
/*returns the current line (i.e. next one to insert)*/
int getCurrentLineNumber() {
return lineCounter;
}
/*displays the entire table at this moment*/
void displayASMTable(){
printf("\n");
doubleLine();
for (int i = 0; i < lineCounter; ++i) {
ASMLine a = asmTable[i];
if(a.jumpLine == -1) {
printf("%d | %s\n", i, a.name);
} else {
if(a.conditionAddr == -1) {
printf("%d | %s %d\n", i, a.name,a.jumpLine);
} else {
printf("%d | %s %d %d\n", i, a.name,a.conditionAddr,a.jumpLine);
}
}
if (i != lineCounter -1) {
line();
}
}
doubleLine();
}
/*exports the entire table to asm*/
void exportASMTable(){
FILE* fp;
fp = fopen("asm", "a");
for (int i = 0; i < lineCounter; ++i) {
ASMLine a = asmTable[i];
if(a.jumpLine == -1) {
fprintf(fp,"%s\n", a.name);
} else {
if(a.conditionAddr == -1) {
fprintf(fp,"%s %d\n", a.name,a.jumpLine);
} else {
fprintf(fp,"%s %d %d\n", a.name,a.conditionAddr,a.jumpLine);
}
}
}
fclose(fp);
}

48
compilateur/asmTable.h Normal file
View file

@ -0,0 +1,48 @@
//
// Created by chepycou on 4/18/23.
//
#ifndef PROJET_SYSTEMES_INFORMATIQUES_ASMTABLE_H
#define PROJET_SYSTEMES_INFORMATIQUES_ASMTABLE_H
#define START_TABLE_SIZE 128
#define LINE_MAX_LENGTH 50
typedef struct {
char name[LINE_MAX_LENGTH];
int conditionAddr;
int jumpLine;
} ASMLine;
/*============================
Array and Reallocation
============================*/
/*reallocates the array with the specified size*/
void reallocateASMArray(int size);
/*Checks for the length of the array and reallocates if necessary*/
void checkASMArraySanity();
/*inserts an asm code line at the current index*/
void addLine(char* s);
/* /!\ To be called at the beginning
* Initializes the array of Symbols*/
void initASMTable();
/*inserts the address in case of jumps*/
void setJumpLine(int index, int addr);
/*inserts the condition's address in case of jumps*/
void setConditionAddr(int index, int addr);
/*returns the current line (i.e. next one to insert)*/
int getCurrentLineNumber();
/*displays the entire table at this moment*/
void displayASMTable();
/*exports the entire table to asm*/
void exportASMTable();
#endif //PROJET_SYSTEMES_INFORMATIQUES_ASMTABLE_H

BIN
compilateur/asmTable.o Normal file

Binary file not shown.

59
compilateur/blocs.c Normal file
View file

@ -0,0 +1,59 @@
//
// Created by chepycou on 4/18/23.
//
#include "blocs.h"
#include "operations.h"
#include <stdio.h>
#include <string.h>
/*TODO on écrit tout dans un fichier asm extérieur puis on :
* - fait un parcours pour stocker dans une liste chaînée par exemple les valeur de ligne des labels
* - faire un parcours pour retirer les labels au début des lignes
* - faire un parcours pour remplacer les labels par leur valeur
* */
/*
int labelCount = 0;
int getNextLabel(){
return(labelCount++);
}
void printLabel(int labelWhile){
char label[LABEL_MAX_LENGTH];
sprintf(label,"%d_LABEL\n",labelWhile);
printf("%s",label);
FILE* fp;
fp = fopen("asm", "a");
fputs(label, fp);
fclose(fp);
}
int printNewLabel(){
int l = getNextLabel();
printLabel(l);
return l;
}
void printJumpToLabel(int labelWhile) {
char instr[ASM_TEXT_LEN];
sprintf(instr,"JMP %d_LABEL\n",labelWhile);
printf("%s",instr);
FILE* fp;
fp = fopen("asm", "a");
fputs(instr, fp);
fclose(fp);
}
void printJumpFToLabel(int labelWhile) {
char label[LABEL_MAX_LENGTH];
sprintf(label,"%d_LABEL\n",labelWhile);
printf("JMF %s",label);
FILE* fp;
fp = fopen("asm", "a");
fputs(label, fp);
fclose(fp);
}*/

26
compilateur/blocs.h Normal file
View file

@ -0,0 +1,26 @@
//
// Created by chepycou on 4/18/23.
//
#ifndef PROJET_SYSTEMES_INFORMATIQUES_BLOCS_H
#define PROJET_SYSTEMES_INFORMATIQUES_BLOCS_H
#define LABEL_MAX_LENGTH 20
/*======================
Label Management
======================*/
/*returns the next label*/
int getNextLabel();
// prints a new label and returns the index of it
int printNewLabel();
// prints a label and returns the index of it
void printLabel(int labelWhile);
// prints a jump to the label and returns the index of it
void printJumpToLabel(int labelWhile);
#endif //PROJET_SYSTEMES_INFORMATIQUES_BLOCS_H

BIN
compilateur/blocs.o Normal file

Binary file not shown.

View file

@ -3,7 +3,6 @@
#include "yacc.tab.h"
%}
/*options for compiling*/
%option noyywrap
%option noinput
@ -53,9 +52,9 @@ INT_HEX 0x[0-9a-fA-F]+
";" return(tSEMI);
"," return(tCOMMA);
{ID} return(tID);
{INT_DEC} return(tNB);
{INT_HEX} return(tNB);
{ID} {strncpy(yylval.str, yytext, NAME_MAX_LENGTH); return(tID);}
{INT_DEC} {yylval.nbInt = atoi(yytext); return(tNB);}
{INT_HEX} {yylval.nbInt = atoi(yytext); return(tNB);}
/*comments are ignored, same for spaces and lines*/

1941
compilateur/lex.yy.c Normal file

File diff suppressed because it is too large Load diff

BIN
compilateur/lex.yy.o Normal file

Binary file not shown.

168
compilateur/operations.c Normal file
View file

@ -0,0 +1,168 @@
//
// Created by chepycou on 4/14/23.
//
#include <stdio.h>
#include "table.h"
#include "operations.h"
#include "asmTable.h"
/*prints to the stdout and the out asm file*/
void printOp(char* s){
//printf("%s",s);
addLine(s);
/*FILE* fp;
fp = fopen("asm", "a");
fputs(s, fp);
fclose(fp);*/
}
/*clears the out asm file*/
void clearOp(){
FILE* fp;
fp = fopen("asm", "w");
fclose(fp);
}
/*prints the ASM instruction for the addition computation
* and returns the address of the temporary variable*/
int operation_add(int addr1, int addr2){
int addr = addTempINTAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "ADD %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the subtraction computation
* and returns the address of the temporary variable*/
int operation_sub(int addr1, int addr2){
int addr = addTempINTAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "SUB %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the multiplication computation
* and returns the address of the temporary variable*/
int operation_mul(int addr1, int addr2){
int addr = addTempINTAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "MUL %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the integer division computation
* and returns the address of the temporary variable*/
int operation_divInt(int addr1, int addr2){
int addr = addTempINTAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "DIV_INT %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the remainder computation
* and returns the address of the temporary variable*/
int operation_divRem(int addr1, int addr2){
int addr = addTempINTAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "DIV_REM %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the affection of a variable
* EX :
* a = 2;
*/
void operation_afc_nb(int addr, int value){
char s[ASM_TEXT_LEN];
sprintf(s, "AFC %d %d", addr, value);
printOp(s);
}
/*prints the ASM instruction for the affection of a temporary variable
* EX :
* "1_TEMP = 2"
* and returns the address of the temp variable*/
int operation_afc_nb_tmp(int value){
int addr = addTempINTAndGetAddress();
operation_afc_nb(addr, value);
return addr;
}
/*prints the ASM instruction for the affection of a temporary variable
* EX :
* a = b;
*/
void operation_copy(int addr1, int addr2){
char s[ASM_TEXT_LEN];
sprintf(s, "COP %d %d", addr1, addr2);
printOp(s);
}
/*prints the ASM instruction for the inferior condition
* and returns the address of the temporary variable*/
int cond_inf(int addr1, int addr2){
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "INF %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the superior condition
* and returns the address of the temporary variable*/
int cond_sup(int addr1, int addr2){
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "SUP %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the equality condition
* and returns the address of the temporary variable*/
int cond_eq(int addr1, int addr2) {
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "EQ %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the negation condition
* and returns the address of the temporary variable*/
int cond_not(int addr1){
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "NOT %d %d", addr, addr1);
printOp(s);
return addr;
}
/*prints the ASM instruction for the and condition
* and returns the address of the temporary variable*/
int cond_and(int addr1, int addr2){
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "AND %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}
/*prints the ASM instruction for the or condition
* and returns the address of the temporary variable*/
int cond_or(int addr1, int addr2){
int addr = addTempCONDAndGetAddress();
char s[ASM_TEXT_LEN];
sprintf(s, "OR %d %d %d", addr, addr1, addr2);
printOp(s);
return addr;
}

78
compilateur/operations.h Normal file
View file

@ -0,0 +1,78 @@
//
// Created by chepycou on 4/14/23.
//
#ifndef PROJET_SYSTEMES_INFORMATIQUES_OPERATIONS_H
#define PROJET_SYSTEMES_INFORMATIQUES_OPERATIONS_H
#define ASM_TEXT_LEN 40
/*clears the out asm file*/
void clearOp();
/*prints to the stdout and the out asm file*/
void printOp(char* s);
/*prints the ASM instruction for the addition computation
* and returns the address of the temporary variable*/
int operation_add(int addr1, int addr2);
/*prints the ASM instruction for the subtraction computation
* and returns the address of the temporary variable*/
int operation_sub(int addr1, int addr2);
/*prints the ASM instruction for the multiplication computation
* and returns the address of the temporary variable*/
int operation_mul(int addr1, int addr2);
/*prints the ASM instruction for the integer division computation
* and returns the address of the temporary variable*/
int operation_divInt(int addr1, int addr2);
/*prints the ASM instruction for the remainder computation
* and returns the address of the temporary variable*/
int operation_divRem(int addr1, int addr2);
/*prints the ASM instruction for the affection of a variable
* EX :
* a = 2;
*/
void operation_afc_nb(int addr, int value);
/*prints the ASM instruction for the affection of a temporary variable
* EX :
* "1_TEMP = 2"
* and returns the address of the temp variable*/
int operation_afc_nb_tmp(int value);
/*prints the ASM instruction for the affection of a temporary variable
* EX :
* a = b;
*/
void operation_copy(int addr1, int addr2);
/*prints the ASM instruction for the inferior condition
* and returns the address of the temporary variable*/
int cond_inf(int addr1, int addr2);
/*prints the ASM instruction for the superior condition
* and returns the address of the temporary variable*/
int cond_sup(int addr1, int addr2);
/*prints the ASM instruction for the equality condition
* and returns the address of the temporary variable*/
int cond_eq(int addr1, int addr2);
/*prints the ASM instruction for the negation condition
* and returns the address of the temporary variable*/
int cond_not(int addr1);
/*prints the ASM instruction for the and condition
* and returns the address of the temporary variable*/
int cond_and(int addr1, int addr2);
/*prints the ASM instruction for the or condition
* and returns the address of the temporary variable*/
int cond_or(int addr1, int addr2);
#endif //PROJET_SYSTEMES_INFORMATIQUES_OPERATIONS_H

BIN
compilateur/operations.o Normal file

Binary file not shown.

BIN
compilateur/out Executable file

Binary file not shown.

View file

@ -1,8 +1,12 @@
#include "table.h"
#include <stdlib.h>
#include <string.h>
#include "table.h"
#define VERBOSITY 0 // 1 -> displays the table, 0 no display
int memorySizes[2] = {1,1};
int tempCounter = 0;
int condCounter = 0; // to store whether there is a conditional variable
/*At the start of the execution : the whole array is empty*/
static Symbol* symbolTable;
@ -23,6 +27,18 @@ void initSymbolTable(){
symbolTable = malloc(sizeof(Symbol) * START_TABLE_SIZE);
}
/*resets the symbol table*/
void resetSymboltable(){
currentIndex = 0;
maxIndex = START_TABLE_SIZE;
// stack pointers
esp = 0;
ebp = 0;
currentDepth = 0;
}
/* Error display */
void error(char* mess){
@ -38,10 +54,14 @@ int getOffset(char* name){
/* Returns the structure with this name */
Symbol getStruct(char* name){
for(int i=0; i < currentIndex; i++){
if (symbolTable[i].name == name){
if (strcmp(symbolTable[i].name, name) == 0){
return symbolTable[i];
}
}
if (VERBOSITY) {
printf("\n\n%s not found \n\n", name);
displayTable();
}
error("No structure found");
return (createNewStructure("error", 0));
}
@ -53,6 +73,7 @@ int getIndex(char* name){
return i;
}
}
printf("%s",name);
error("No index found");
return (0);
}
@ -83,12 +104,22 @@ void clearOutOfScopeVariable(){
// and we free their memory (i.e. decrease esp)
esp -= memoryFreed;
if (VERBOSITY) {
printf("\n\nclearOutOfScopeVariable::After");
displayTable();
}
}
/* sets the init state of the symbol to true */
void setInit(char *name){
symbolTable[getIndex(name)].init = true;
if (VERBOSITY) {
printf("\n\nsetInit %s", name);
displayTable();
}
}
/*creates a new structure and updates variables*/
@ -115,14 +146,55 @@ void addElement(char* name, enumVarType type){
currentIndex ++;
esp += memorySizes[type];
if (VERBOSITY) {
printf("\n\nAddElement %s", name);
displayTable();
}
}
/* Adds an element and returns the offset of it */
int addElementAndGetAddress(char* name, enumVarType type){
addElement(name,type);
return getOffset(name);
}
/* Adds a temporary Int element and returns the offset of it */
int addTempINTAndGetAddress(){
char name[NAME_MAX_LENGTH];
if (tempCounter == 0){
// we create the first temporary variable and use it
addElement("0_TEMP_INT",INT);
strcpy(name, "0_TEMP_INT");
} else if (tempCounter == 1) {
// we create the second temporary variable and use it
addElement("1_TEMP_INT",INT);
strcpy(name, "1_TEMP_INT");
} else {
// we use the right temporary variable
sprintf(name, "%d_TEMP_INT", tempCounter % 2);
}
tempCounter++;
return getOffset(name);
}
/* removes all symbols */
void flushSymbolTable(){
currentIndex = 0;
checkArraySanity();
if (VERBOSITY) {
printf("\n\nflushSymbolTable::After");
displayTable();
}
}
/*Checks for the length of the array and reallocates if necessary*/
void checkArraySanity(){
if (currentIndex == maxIndex){
reallocateArray(maxIndex * 2);
} else {
if (currentIndex < maxIndex / 2){
if (currentIndex < maxIndex / 4 && maxIndex / 4 > START_TABLE_SIZE){
reallocateArray(maxIndex / 2);
}
}
@ -170,9 +242,67 @@ void displayTable(){
doubleLine();
}
/*removes all temporary variables used for INTs*/
void suppressTempINTElements(){
if (tempCounter == 1){
suppressElement("0_TEMP_INT");
esp--;
} else {
if (tempCounter > 1){
suppressElement("0_TEMP_INT");
suppressElement("1_TEMP_INT");
esp-= 2;
}
}
tempCounter = 0;
}
/*removes one element*/
void suppressElement(char* name){
for(int i = getIndex(name); i < (currentIndex - 1); i ++){
symbolTable[i] = symbolTable[i+1];
}
currentIndex--;
checkArraySanity();
}
void line(){
printf("---------------------------------\n");
}
void doubleLine(){
printf("============================================================\n");
}
}
/*removes all temporary variables used for CONDITIONS*/
void suppressCONDElements(){
if (condCounter == 1){
suppressElement("0_TEMP_COND");
esp--;
} else {
if (condCounter > 1){
suppressElement("0_TEMP_COND");
suppressElement("1_TEMP_COND");
esp-= 2;
}
}
condCounter = 0;
}
/* Adds a temporary Conditional element and returns the offset of it */
int addTempCONDAndGetAddress(){
char name[NAME_MAX_LENGTH];
if (condCounter == 0){
// we create the first temporary variable and use it
addElement("0_TEMP_COND",INT);
strcpy(name, "0_TEMP_COND");
} else if (condCounter == 1) {
// we create the second temporary variable and use it
addElement("1_TEMP_COND",INT);
strcpy(name, "1_TEMP_COND");
} else {
// we use the right temporary variable
sprintf(name, "%d_TEMP_COND", condCounter % 2);
}
condCounter++;
return getOffset(name);
}

View file

@ -12,7 +12,7 @@
typedef enum enumVarType {INT, FLOAT} enumVarType;
// a list of all type's sizes
extern int memorySizes[2]; // TODO : PROBLEM DOES'NT COMPILE
extern int memorySizes[2];
typedef struct {
char name[NAME_MAX_LENGTH];
@ -36,6 +36,14 @@ void checkArraySanity();
* Initializes the array of Symbols*/
void initSymbolTable();
/*resets the symbol table*/
void resetSymboltable();
/*inserts an asm code line at the current index*/
void addLine(char* s);
/*returns the current line (i.e. next one to insert)*/
int getCurrentLineNumber();
/*============================
Element Management
@ -44,14 +52,24 @@ void initSymbolTable();
/* removes all symbols associated with the current Depth*/
void clearOutOfScopeVariable();
/* removes all symbols */
void flushSymbolTable();
/* Adds an element */
void addElement(char* name, enumVarType type);
/* Adds an element and returns the offset of it */
int addElementAndGetAddress(char* name, enumVarType type);
/* Adds a temporary Int element and returns the offset of it */
int addTempINTAndGetAddress();
/* Adds a temporary Conditional element and returns the offset of it */
int addTempCONDAndGetAddress();
/*creates a new structure and updates variables*/
Symbol createNewStructure(char* name, enumVarType type);
/*============================
Element Edition
============================*/
@ -59,6 +77,15 @@ Symbol createNewStructure(char* name, enumVarType type);
/* sets the init state of the symbol to true */
void setInit(char *name);
/*removes one element*/
void suppressElement(char* name);
/*removes all temporary variables used for INTs*/
void suppressTempINTElements();
/*removes all temporary variables used for CONDITIONS*/
void suppressCONDElements();
/*============================
Element Access
============================*/

BIN
compilateur/table.o Normal file

Binary file not shown.

0
compilateur/testFile Normal file
View file

1459
compilateur/yacc.output Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

120
compilateur/yacc.tab.h Normal file
View file

@ -0,0 +1,120 @@
/* A Bison parser, made by GNU Bison 3.8.2. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual,
especially those whose name start with YY_ or yy_. They are
private implementation details that can be changed or removed. */
#ifndef YY_YY_YACC_TAB_H_INCLUDED
# define YY_YY_YACC_TAB_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 1
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Token kinds. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
YYEMPTY = -2,
YYEOF = 0, /* "end of file" */
YYerror = 256, /* error */
YYUNDEF = 257, /* "invalid token" */
tELSE = 258, /* tELSE */
tRETURN = 259, /* tRETURN */
tPRINT = 260, /* tPRINT */
tFLOAT = 261, /* tFLOAT */
tINT = 262, /* tINT */
tVOID = 263, /* tVOID */
tSUB = 264, /* tSUB */
tADD = 265, /* tADD */
tMUL = 266, /* tMUL */
tDIV = 267, /* tDIV */
tASSIGN = 268, /* tASSIGN */
tLT = 269, /* tLT */
tGT = 270, /* tGT */
tNE = 271, /* tNE */
tEQ = 272, /* tEQ */
tGE = 273, /* tGE */
tLE = 274, /* tLE */
tAND = 275, /* tAND */
tOR = 276, /* tOR */
tNOT = 277, /* tNOT */
tLBRACE = 278, /* tLBRACE */
tRBRACE = 279, /* tRBRACE */
tLPAR = 280, /* tLPAR */
tRPAR = 281, /* tRPAR */
tSEMI = 282, /* tSEMI */
tCOMMA = 283, /* tCOMMA */
tID = 284, /* tID */
tNB = 285, /* tNB */
tIF = 286, /* tIF */
tWHILE = 287 /* tWHILE */
};
typedef enum yytokentype yytoken_kind_t;
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 22 "yacc.y"
char str[NAME_MAX_LENGTH]; int nbInt; int addr; enumVarType type;
#line 99 "yacc.tab.h"
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
int yyparse (void);
/* "%code provides" blocks. */
#line 17 "yacc.y"
int yylex (void);
void yyerror (const char *);
#line 119 "yacc.tab.h"
#endif /* !YY_YY_YACC_TAB_H_INCLUDED */

BIN
compilateur/yacc.tab.o Normal file

Binary file not shown.

209
compilateur/yacc.y Normal file
View file

@ -0,0 +1,209 @@
%define parse.error detailed
%{
#include <stdio.h>
#include <stdlib.h>
#include "table.h"
#include "operations.h"
#include "blocs.h"
#include "asmTable.h"
int t;
int labelWhileStart;
int labelWhileEnd;
int whileJumpAddr;
%}
%code provides{
int yylex (void);
void yyerror (const char *);
}
%union {char str[NAME_MAX_LENGTH]; int nbInt; int addr; enumVarType type; }
/*loops keywords*/
%token /*tWHILE tIF declared below*/ tELSE
/*reserved keywords*/
%token tRETURN tPRINT
/*types : integers, floats or void*/
%token tFLOAT tINT tVOID
/*operations, mul and div are precedent to sub and add*/
%left tSUB tADD
%left tMUL tDIV
/*Assignment*/
%left tASSIGN
/*comparisons*/
%left tLT tGT tNE tEQ tGE tLE
/*boolean operators*/
%left tAND tOR tNOT
/*syntaxic symbols*/
%token tLBRACE tRBRACE tLPAR tRPAR tSEMI tCOMMA
/*nametags and values*/
%token <str> tID
%token <nbInt> tNB
/* represents types with the values used in the table, see table.h */
%type <type> Type
%type <addr> Expression
%type <addr> ConditionalExpression
%type <addr> Declaration
%type <addr> NbOrVariable
%type <nbInt> IfStatement1
%type <addr> Condition
%type <nbInt> InnerBlock
%token <nbInt> tIF
%token <nbInt> tWHILE
%start Program
%%
Program : FunctionDef
| FunctionDef Program;
/* Lines = Any line in the code that is not within an if/while statement*/
Lines : Line
| Line Lines;
Line : IfStatement
| WhileStatement
| Assignment
| Declarations
| FunctionCall
| Return
| Print;
/*Innerblock = the inside of an if/else/while statement = { ... } or function = f(){...}*/
InnerBlock : tLBRACE tRBRACE // a function or while loop can be empty cf GCC
| tLBRACE {increaseDepth();} Lines tRBRACE {decreaseDepth();};
/*Condition = the evaluated boolean expression for an if or while = ( ... ) */
Condition : tLPAR ConditionalExpression tRPAR {$$ = $2;};
/*ConditionalExpression = expression that evaluates to a boolean*/
ConditionalExpression : tID { $$ = getOffset($1);}
| tNB {$$ = operation_afc_nb_tmp($1);}
| tLPAR ConditionalExpression tRPAR {$$ = $2;}// for cases like if((a or b) and (a or c)) where there are parenthesis inside
| NbOrVariable tLE NbOrVariable {$$ = cond_not(cond_sup($1, $3));}
| NbOrVariable tGE NbOrVariable {$$ = cond_not(cond_inf($1, $3));}
| NbOrVariable tEQ NbOrVariable {$$ = cond_eq($1, $3);}
| NbOrVariable tNE NbOrVariable {$$ = cond_not(cond_eq($1, $3));}
| NbOrVariable tLT NbOrVariable {$$ = cond_inf($1, $3);}
| NbOrVariable tGT NbOrVariable {$$ = cond_sup($1, $3);}
| tNOT ConditionalExpression {$$ = cond_not($2);}
| ConditionalExpression tOR ConditionalExpression {$$ = cond_or($1, $3);}
| ConditionalExpression tAND ConditionalExpression {$$ = cond_and($1, $3);};
/*end of added bloat*/
/*NbOrVariable is either a number or a variable of type int*/
NbOrVariable : tID { $$ = getOffset($1);}
| tNB {$$ = operation_afc_nb_tmp($1);};
/*List of all numerical operators*/
/*
NumericalOperator : tLE | tGE | tEQ | tNE | tLT | tGT;
*/
/*any arithmetic operation
Operation: tADD | tMUL | tSUB | tDIV;
*/
IfStatement1 : %empty {
int ligne =getCurrentLineNumber(); addLine("JMF"); $<nbInt>$ = ligne ;
};
IfStatement : tIF Condition IfStatement1 InnerBlock tELSE {
setConditionAddr($3,$2); int current = getCurrentLineNumber(); printf("current Line %d", current); addLine("JMP"); $1 = current; setJumpLine($3, current+1);
} InnerBlock {
int current = getCurrentLineNumber() ; printf("%d, %d",$1, current);setJumpLine($1, current);
}
| tIF Condition IfStatement1 InnerBlock {
setConditionAddr($3,$2); int current = getCurrentLineNumber(); printf("current Line %d", current); setJumpLine($3, current);
};
WhileStatement : tWHILE {
$1 = getCurrentLineNumber();
} Condition {
int current = getCurrentLineNumber();
addLine("JMF");
setConditionAddr(current,$3);
whileJumpAddr = current;
suppressCONDElements();
} InnerBlock {
addLine("JMP");
int current = getCurrentLineNumber();
setJumpLine(whileJumpAddr, current);
setJumpLine(current-1, $1);
};
Assignment : tID tASSIGN Expression tSEMI {
setInit($1); operation_copy(getOffset($1),$3); suppressTempINTElements();
};
/*Expression operation applied on variables or values*/
Expression : NbOrVariable {$$ = $1;}
| FunctionCall{$$ = 0;} // TODO : wait untile functions are implemented
| tLPAR Expression tRPAR {$$ = $2;}
/* replaced by the four following lines
//| Expression Operation Expression
*/
| Expression tADD Expression {$$ = operation_add($1, $3);}
| Expression tSUB Expression {$$ = operation_sub($1, $3);}
| Expression tMUL Expression {$$ = operation_mul($1, $3);}
| Expression tDIV Expression {$$ = operation_divInt($1, $3);};
/*end of added bloat*/
Expressions : Expression
| Expression tCOMMA Expressions;
FunctionCall : tID tLPAR Expressions tRPAR;
FunctionDef : Type tID FunctionParams InnerBlock {resetSymboltable();}
| tVOID tID FunctionParams InnerBlock {resetSymboltable();};
/*FunctionParams = the parameters of a function*/
FunctionParams : tLPAR tRPAR
| tLPAR tVOID tRPAR
| tLPAR VarsWithType tRPAR
VarsWithType : VarWithType
| VarWithType tCOMMA VarsWithType;
/*VarWithType = a variable associated to its type = int a*/
VarWithType : Type tID {addElement($2,$1);setInit($2);};
/*the return type or argument type*/
Type : tINT {$$ = INT;}
| tFLOAT {$$ = FLOAT;};
Declarations : Type { t = $1; } Declaration Declarations1 tSEMI ;
Declaration : tID {addElement($1, (enumVarType) t);}
| tID {addElement($1, (enumVarType) t); setInit($1);} tASSIGN Expression {operation_copy(getOffset($1),$4); suppressTempINTElements();} ;
Declarations1 : tCOMMA Declaration Declarations1 | %empty ;
Return : tRETURN Expression tSEMI {};
Print : tPRINT tLPAR Expression tRPAR tSEMI;
%%
void yyerror(const char *msg) {
fprintf(stderr, "\033[1m\033[31m[/!\\]\033[0m Error : %s\n", msg);
exit(1);
}
int main(void) {
clearOp();
initSymbolTable();
initASMTable();
yyparse();
exportASMTable();
}
// SI >> SC

View file

@ -0,0 +1,182 @@
import re
opToBinOP = {
"ADD": "01",
"MUL": "02",
"SUB": "03",
"DIV": "04",
"COP": "05",
"AFC": "06",
"LOAD": "07",
"STORE": "08",
"INF": "09",
"SUP": "0A",
"EQ": "0B",
"NOT": "0C",
"AND": "0D",
"OR": "0E",
"JMP": "0F",
"JMF": "10",
"CAL": "11",
"RET": "12",
"PRI": "13",
"NOP": "FF"
}
def output(s, num, oneline=False):
fileOutput = open(f'asm{num}', 'w')
if oneline:
fileOutput.write(s)
else :
fileOutput.write("\n".join(s))
fileOutput.close()
def convertToRegister(s):
l = []
if not re.match(r"\d_LABEL", s[0]):
optionalFlag = ""
incr = 0
op = s[0]
else:
optionalFlag = s[0] + " "
incr = 1
op = s[1]
match op:
case "ADD":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("ADD 0 0 1")
l.append("STORE " + s[1 + incr] + " 0")
case "MUL":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("MUL 0 0 1")
l.append("STORE " + s[1 + incr] + " 0")
case "SUB":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("SUB 0 0 1")
l.append("STORE " + s[1 + incr] + " 0")
case "DIV_INT":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("DIV 0 0 1")
l.append("STORE " + s[1 + incr] + " 0")
case "COP":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("STORE " + s[1 + incr] + " 0")
case "AFC":
l.append(optionalFlag + "AFC 0 " + s[2 + incr])
l.append("STORE " + s[1 + incr] + " 0")
case "JMP":
l.append(" ".join(s))
case "JMF":
if len(s) == 3:
l.append(" ".join(s))
else :
l.append(s[0]+ " 0 " + s[1])
case "INF":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("INF 2 0 1")
l.append("STORE " + s[1 + incr] + " 2")
case "SUP":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("SUP 2 1 0")
l.append("STORE " + s[1 + incr] + " 2")
case "EQ":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("EQ 2 1 0")
l.append("STORE " + s[1 + incr] + " 2")
case "PRI":
l.append(optionalFlag + "PRI " + s[2 + incr])
case "AND":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("AND 2 0 1")
l.append("STORE " + s[1 + incr] + " 2")
case "OR":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("LOAD 1 " + s[3 + incr])
l.append("OR 2 0 1")
l.append("STORE " + s[1 + incr] + " 2")
case "NOT":
l.append(optionalFlag + "LOAD 0 " + s[2 + incr])
l.append("NOT 2 0")
l.append("STORE " + s[1 + incr] + " 2")
case default:
l.append(" ".join(s))
""" R2 will contain the information whether to jump or not"""
return l
totalLine = 0
labelCount = 0 # used to create a new label each time
fileInput = open("asm", "r")
ASMLines = list(map(lambda e: e.rstrip("\n"), fileInput.readlines()))
fileInput.close()
# added to prevent problems when cross compiling some code representing a jump to after the last line
ASMLines.append("NOP")
ASMLinesLabel = ASMLines[:] # will contain at the end of the first loop the code with labels inserted
ASMLinesRegister = [] # will contain at the end of the 2nd loop the registry-based code with labels
ASMLinesFinal = [] # will contain the output, register-based, code
for i, l in enumerate(ASMLines):
items = l.split(" ")
if items[0] in ["JMP", "JMF"]:
lineToJumpTo = int(items[-1])
if re.match(r"\d_LABEL .*", ASMLinesLabel[lineToJumpTo]):
ASMLinesLabel[i] = " ".join(ASMLines[i].split()[:-1] + [ASMLinesLabel[lineToJumpTo].split()[0]])
else:
ASMLinesLabel[lineToJumpTo] = f"{labelCount}_LABEL " + ASMLines[lineToJumpTo]
ASMLinesLabel[i] = " ".join(ASMLinesLabel[i].split()[:-1] + [f"{labelCount}_LABEL"])
labelCount += 1
print("labels : ", ASMLinesLabel)
for i, l in enumerate(ASMLinesLabel):
ASMLinesRegister.extend(convertToRegister(l.split()))
print("regs : ", ASMLinesRegister)
labels = {}
for i, l in enumerate(ASMLinesRegister):
if re.match(r"\d_LABEL .*", l):
labels[l.split()[0]] = i
ASMLinesRegister[i] = " ".join(ASMLinesRegister[i].split()[1:])
print(ASMLinesRegister)
for i, l in enumerate(ASMLinesRegister):
label = re.match(r"\d_LABEL", l.split()[-1])
if label:
ASMLinesFinal.append(" ".join(l.split()[:-1] + [str(labels[label[0]])]))
else:
ASMLinesFinal.append(l)
print(ASMLinesFinal)
output(ASMLinesFinal, 2)
lines = []
for i, l in enumerate(ASMLinesFinal):
arr = l.split()
while len(arr) < 4:
arr.append(0)
lines.append(f"(x\"{opToBinOP[arr[0]]}{int(arr[1]):02X}{int(arr[2]):02X}{int(arr[3]):02X}\")")
ASMLinesConverted = "(" + ",".join(lines) + ",others => (x\"ff000000\"))"
print("converted to VHDL-friendly format : " + ASMLinesConverted)
output(ASMLinesConverted, 3, True)
""" Used to generate the beautiful table in the report
for i in range(10):
print(f"{ASMLines[i]} & {ASMLinesFinal[i]} & {ASMLinesConverted.split(',')[i]} \\\\")
"""

View file

@ -0,0 +1,139 @@
import sys
try:
from textual.color import Color
from textual import events
from textual.app import App, ComposeResult
from textual.containers import Container, VerticalScroll
from textual.widgets import Footer, Header, Static
except:
print("\n\n=====================\n\nplease install textual and rich !\n\n=====================\n\n")
def getLinesToShow(ip, lines):
if ip > 1 and ip + 2 < len(lines):
l= lines[ip - 2: ip + 3]
l[2] = "> " + l[2] + " <"
elif ip <= 1:
l= lines[0: 5]
l[ip] = "> " + l[ip] + " <"
else:
l= lines[-5:]
l[ip-len(lines)] = "> " + l[ip-len(lines)] + " <"
return l
def update_interpreter(self):
global ip
global ASMLines
global dataMem
if "NOP" not in ASMLines[ip]:
incr = 1
currLine = ASMLines[ip].split()
match currLine[0]:
case "ADD":
dataMem[currLine[1]] = dataMem[currLine[2]] + dataMem[currLine[3]]
case "MUL":
dataMem[currLine[1]] = dataMem[currLine[2]] * dataMem[currLine[3]]
case "SUB":
dataMem[currLine[1]] = dataMem[currLine[2]] - dataMem[currLine[3]]
case "DIV":
dataMem[currLine[1]] = dataMem[currLine[2]] / dataMem[currLine[3]]
case "COP":
dataMem[currLine[1]] = dataMem[currLine[2]]
case "AFC":
dataMem[currLine[1]] = int(currLine[2])
case "SUP":
dataMem[currLine[1]] = dataMem[currLine[2]] > dataMem[currLine[3]]
case "EQ":
dataMem[currLine[1]] = dataMem[currLine[2]] == dataMem[currLine[3]]
case "NOT":
dataMem[currLine[1]] = not dataMem[currLine[2]]
case "INF":
dataMem[currLine[1]] = dataMem[currLine[2]] < dataMem[currLine[3]]
case "AND":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "OR":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "JMP":
ip = int(currLine[1])
incr = 0
case "JMF":
if not dataMem[currLine[1]]:
incr = 0
ip = int(currLine[2])
print(ip)
case "CAL":
pass
case "RET":
pass
case "PRI":
pass
case default:
pass
print(ASMLines[ip], ", ".join([f"{i}:{dataMem.get(i)}" for i in dataMem]))
ip += incr
else:
cont = self.query_one("#cont", Container)
cont.styles.background = Color.parse("#151E3D")
code = self.query_one("#code", Static)
code.update(" ")
class codeLines(Static):
"""one line of assembly code"""
def update_code(self, line) -> None:
self.update(line)
class registers(Static):
"""one line of assembly code"""
def update_regs(self, line) -> None:
self.update(line)
class interpreter(App):
"""A Textual app to see your asm code run !."""
TITLE = "A Textual app to see your asm code run !."
CSS_PATH = "style.css"
BINDINGS = [
("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
"""Compose our UI."""
yield Header()
with Container(id="cont"):
with VerticalScroll(id="code-view"):
yield codeLines("\n".join(getLinesToShow(ip, ASMLines)),id="code", expand=True)
yield registers(id="regs", expand=True)
yield Footer()
def on_key(self, event: events.Key) -> None:
code = self.query_one("#code", Static)
regs = self.query_one("#regs", Static)
update_interpreter(self)
global ip, ASMLines
code.update_code("\n".join(getLinesToShow(ip, ASMLines)))
l = []
for i in range(max([int(i)+1 for i in dataMem.keys()])):
if str(i) in dataMem.keys():
l.append([i, dataMem[str(i)]])
regs.update_regs("\n".join([f"@{k[0]} : {k[1]}" for k in l]))
if __name__ == "__main__":
fileInput = open("asm", "r")
global ASMLines
ASMLines = list(map(lambda e: e.rstrip("\n"), fileInput.readlines()))
fileInput.close()
ASMLines.append("NOP")
global dataMem
dataMem = {}
global ip
ip = 0
interpreter().run()

View file

@ -0,0 +1,53 @@
fileInput = open("asm", "r")
ASMLines = list(map(lambda e: e.rstrip("\n"), fileInput.readlines()))
fileInput.close()
ASMLines.append("NOP")
dataMem = {}
ip = 0
while ip < len(ASMLines):
incr = 1
currLine = ASMLines[ip].split()
match currLine[0]:
case "ADD":
dataMem[currLine[1]] = dataMem[currLine[2]] + dataMem[currLine[3]]
case "MUL":
dataMem[currLine[1]] = dataMem[currLine[2]] * dataMem[currLine[3]]
case "SUB":
dataMem[currLine[1]] = dataMem[currLine[2]] - dataMem[currLine[3]]
case "DIV":
dataMem[currLine[1]] = dataMem[currLine[2]] / dataMem[currLine[3]]
case "COP":
dataMem[currLine[1]] = dataMem[currLine[2]]
case "AFC":
dataMem[currLine[1]] = int(currLine[2])
case "SUP":
dataMem[currLine[1]] = dataMem[currLine[2]] > dataMem[currLine[3]]
case "EQ":
dataMem[currLine[1]] = dataMem[currLine[2]] == dataMem[currLine[3]]
case "NOT":
dataMem[currLine[1]] = not dataMem[currLine[2]]
case "INF":
dataMem[currLine[1]] = dataMem[currLine[2]] < dataMem[currLine[3]]
case "AND":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "OR":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "JMP":
ip = int(currLine[1])
incr = 0
case "JMF":
if not dataMem[currLine[1]]:
incr = 0
ip = int(currLine[2])
case "CAL":
pass
case "RET":
pass
case "PRI":
pass
case default:
pass
print(ASMLines[ip], ", ".join([f"{i}:{dataMem.get(i)}" for i in dataMem]))
ip += incr

View file

@ -0,0 +1,67 @@
try:
from rich.console import Console
from rich.table import Table
except:
print("\n\n=====================\n\nplease install rich !\n You can also run \"python3 interpreter/interpreter.old.py\" if you want something that does not use any non-core package\n\n=====================\n\n")
table = Table()
table.add_column("Operation", justify="left", style="red", no_wrap=True)
table.add_column("Register State", justify="center", style="green")
fileInput = open("asm", "r")
ASMLines = list(map(lambda e: e.rstrip("\n"), fileInput.readlines()))
fileInput.close()
ASMLines.append("NOP")
dataMem = {}
ip = 0
while ip < len(ASMLines):
incr = 1
currLine = ASMLines[ip].split()
match currLine[0]:
case "ADD":
dataMem[currLine[1]] = dataMem[currLine[2]] + dataMem[currLine[3]]
case "MUL":
dataMem[currLine[1]] = dataMem[currLine[2]] * dataMem[currLine[3]]
case "SUB":
dataMem[currLine[1]] = dataMem[currLine[2]] - dataMem[currLine[3]]
case "DIV":
dataMem[currLine[1]] = dataMem[currLine[2]] / dataMem[currLine[3]]
case "COP":
dataMem[currLine[1]] = dataMem[currLine[2]]
case "AFC":
dataMem[currLine[1]] = int(currLine[2])
case "SUP":
dataMem[currLine[1]] = dataMem[currLine[2]] > dataMem[currLine[3]]
case "EQ":
dataMem[currLine[1]] = dataMem[currLine[2]] == dataMem[currLine[3]]
case "NOT":
dataMem[currLine[1]] = not dataMem[currLine[2]]
case "INF":
dataMem[currLine[1]] = dataMem[currLine[2]] < dataMem[currLine[3]]
case "AND":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "OR":
dataMem[currLine[1]] = dataMem[currLine[2]] and dataMem[currLine[3]]
case "JMP":
ip = int(currLine[1])
incr = 0
case "JMF":
if not dataMem[currLine[1]]:
incr = 0
ip = int(currLine[2])
case "CAL":
pass
case "RET":
pass
case "PRI":
pass
case default:
pass
table.add_row(ASMLines[ip], ", ".join([f"{i}:{dataMem.get(i)}" for i in dataMem]))
ip += incr
console = Console()
console.print(table)

7
interpreter/style.css Normal file
View file

@ -0,0 +1,7 @@
#code {
overflow: auto scroll;
text-align: center;
padding-top: 3;
width: 100%;
}

674
license Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

BIN
out

Binary file not shown.

View file

@ -1,20 +0,0 @@
int compute(int a, int d) {
int b;
int c;
b = a;
while (c > 0) {
b = b + a * 4;
}
return b;
}
void main(void) {
int a;
if (a == 3) {
print(a);
} else {
int b = compute(a, 2 * a);
print(b);
}
}

9
tests/testFile Normal file
View file

@ -0,0 +1,9 @@
int main() {
int a;
a = 5;
if (a != 8) {
while(a < 20){
a = a+2;
}
}
}

20
tests/testFile_fibo Normal file
View file

@ -0,0 +1,20 @@
int main() {
int i, n, nextTerm, t1, t2;
i = 0;
n = 20; // put here the number you want !
t1 = 0;
t2 = 1;
nextTerm = t1 + t2;
n = n - 3; // cause nextTerm already contains the 3rd term
while (i <= n){
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
i = i+1;
}
}

9
tests/testFile_no_jmp Normal file
View file

@ -0,0 +1,9 @@
int main(){
int a, d;
int b, c = 2;
b = a;
a = b +2;
a = c;
a = 5;
c = 19 + 2 - (5 * a + 8) * 2;
}

13
tests/testFile_while Normal file
View file

@ -0,0 +1,13 @@
int compute(int a, int d) {
int b, c = a + d * 5;
b = a;
while(!(!(!(!((a > b)))))){
if (a == b){
a = b;
} else {
a = c;
}
}
a=5;
}

92
vhdl/ALU.vhd Normal file
View file

@ -0,0 +1,92 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 12.05.2023 16:14:24
-- Design Name:
-- Module Name: ALU - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity ALU is
Port ( A : in STD_LOGIC_VECTOR (7 downto 0);
B : in STD_LOGIC_VECTOR (7 downto 0);
Ctrl_Alu : in STD_LOGIC_VECTOR (7 downto 0);
S : out STD_LOGIC_VECTOR (7 downto 0);
N : out STD_LOGIC;
O : out STD_LOGIC;
Z : out STD_LOGIC;
C : out STD_LOGIC;
JumpFlagOut : out STD_LOGIC; -- 0 false 1 true
JumpFlagIn : in STD_LOGIC
);
end ALU;
-- Instruction code
-- ADD x"01"
-- MUL x"02"
-- SUB x"03"
-- DIV x"04"
-- INF x"09"
-- SUP x"0A"
-- EQ x"0B"
-- NOT x"0C"
-- AND x"0D"
-- OR x"0E"
-- XOR x"0F"
architecture Behavioral of ALU is
signal res : STD_LOGIC_VECTOR(15 downto 0):= x"0000";
signal flag : STD_LOGIC := '0';
begin
process(A, B, Ctrl_Alu)
begin
N <= '0';
O <= '0';
Z <= '0';
C <= '0';
flag <= JumpFlagIn;
case Ctrl_Alu is
when x"01" => res <= (x"00" & A) + (x"00" & B) ; if (((x"00" & A) + (x"00" & B)) > 255) then C <= '1'; elsif (A+B = 0) then Z <= '1'; end if; -- ADD
when x"02" => res <= A * B; if (A * B > 255) then O <= '1'; elsif A * B = 0 then Z <= '1'; end if; -- MUL
when x"03" => res <= (x"00" & A) - (x"00" & B) ; if (B > A) then N <= '1'; elsif (B = A) then Z <= '1'; end if; -- SUB
when x"04" => if (B /= 0) then res <= (x"00" & std_logic_vector(to_unsigned(to_integer(unsigned(A)) / to_integer(unsigned(B)),8))); else res <= x"0000"; end if; -- DIV
when x"09" => if A < B then res <= x"0001"; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0A" => if A > B then res <= x"0001"; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0B" => if A = B then res <= x"0001"; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0C" => if A > 0 then res <= x"0001"; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0D" => if (A > 0 and B > 0) then res <= x"0001" ; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0E" => if (A > 0 or B > 0) then res <= x"0001" ; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when x"0F" => if ((A > 0 and B = 0) or (A = 0 and B >0)) then res <= x"0001" ; flag <= '1'; else res <= x"0000"; flag <= '0'; end if;
when others => res <= x"0000";
end case;
end process;
JumpFlagOut <= flag;
S <= res(7 downto 0);
end Behavioral;

77
vhdl/AleaControler.vhd Normal file
View file

@ -0,0 +1,77 @@
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.all;
-- Instruction coEX
-- ADD 00000001
-- MUL 00000010
-- SUB 00000011
-- DIV 00000100
-- COP 00000101
-- AFC 00000110
-- LOAD 00000111
-- STORE 00001000
-- INF 00001001
-- SUP 00001010
-- EQ 00001011
-- NOT 00001100
-- AND 00001101
-- OR 00001110
-- NOP 11111111
-- when the just entered instruction causes a problem with an instruction already in the EX or Mem stage (a write-Back stage would not cause any harm) we:
-- we freeze IP on the current instruction
-- we insert NOPs in the LI_DI OP while there is a conflict in order to let the problematic instruction finish
entity AleaControler is
Port (
-- get the current op and variables from the 3 pipelines stages that can interract
Op_DI, Op_EX, Op_Mem, Op_Re : in STD_LOGIC_VECTOR (7 downto 0);
A_EX, A_Mem, A_Re : in STD_LOGIC_VECTOR (7 downto 0);
B_DI : in STD_LOGIC_VECTOR (7 downto 0);
C_DI : in STD_LOGIC_VECTOR (7 downto 0);
CNTRL : out STD_LOGIC);
end AleaControler;
architecture Behavioral of AleaControler is
signal alea_DI_EX, alea_DI_MEM: STD_LOGIC;
signal is_LI_arithmetic, is_DI_arithmetic: STD_LOGIC;
begin
CNTRL <= -- either a problem between the 1st and 2nd or 1st and 3rd
'1' when
-- read after write : Op1 other than STORE/NOP/JMP/JMF, op2 other than AFC/NOP/JMP/JMF, R(write) = R(read)
(
-- check Op1 & Op2
((OP_DI /= x"06" and OP_DI /= x"ff" and OP_Di /= x"0F" and OP_DI /= x"10") and (Op_EX /= x"08" and Op_EX /= x"ff" and Op_EX /= x"0f" and Op_EX /= x"10")) and
-- check Registers are the same
((A_Ex = B_DI) or (A_EX = C_DI))
) or
-- read after write : Op1 other than STORE/NOP/JMP/JMF, op3 other than AFC/NOP/JMP/JMF, R(write) = R(read)
(
-- check Op1 & Op2
((OP_DI /= x"06" and OP_DI /= x"ff" and OP_Di /= x"0F" and OP_DI /= x"10") and (Op_Mem /= x"08" and Op_Mem /= x"ff" and Op_Mem /= x"0f" and Op_Mem /= x"10")) and
-- check Registers are the same
((A_Mem = B_DI) or (A_Mem = C_DI))
) or
-- read after write : Op1 other than STORE/NOP/JMP/JMF, op4 other than AFC/NOP/JMP/JMF, R(write) = R(read)
(
-- check Op1 & Op2
((OP_DI /= x"06" and OP_DI /= x"ff" and OP_Di /= x"0F" and OP_DI /= x"10") and (Op_Re /= x"08" and Op_Re /= x"ff" and Op_Re /= x"0f" and Op_Re /= x"10")) and
-- check Registers are the same
((A_Re = B_DI) or (A_Re = C_DI))
)
or
(
Op_EX = x"10" -- or Op_Mem = x"10" or Op_Re = x"10"
)
else '0';
end Behavioral;

364
vhdl/CPU.vhd Normal file
View file

@ -0,0 +1,364 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 14:29:58
-- Design Name:
-- Module Name: CPU - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity CPU is
Port (Clk : in STD_LOGIC := '0';
reg_addr : in STD_LOGIC_VECTOR(3 downto 0) := "0000";
reg_val : out STD_LOGIC_VECTOR(7 downto 0));
end CPU;
architecture Behavioral of CPU is
component IP is
port ( CLK : in STD_LOGIC;
RST : in STD_LOGIC; -- rst when 1
LOAD : in STD_LOGIC;
EN : in STD_LOGIC; -- enable when 0
Din : in STD_LOGIC_VECTOR (7 downto 0);
Dout : out STD_LOGIC_VECTOR (7 downto 0));
end component;
signal IP_out : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
signal rst : STD_LOGIC := '0';
component InstructionMemory
Port ( Addr : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Inst_out : out STD_LOGIC_VECTOR (31 downto 0));
end component;
signal Li : STD_LOGIC_VECTOR (31 downto 0) := (others => '1');
component Stage_Li_Di
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_C : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0);
Out_C : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
component Registers
Port ( Addr_A : in STD_LOGIC_VECTOR (3 downto 0);
Addr_B : in STD_LOGIC_VECTOR (3 downto 0);
Addr_W : in STD_LOGIC_VECTOR (3 downto 0);
Addr_C : in STD_LOGIC_VECTOR (3 downto 0); -- display on FPGA
W : in STD_LOGIC;
Data : in STD_LOGIC_VECTOR (7 downto 0);
Rst : in STD_LOGIC;
Clk : in STD_LOGIC;
QA : out STD_LOGIC_VECTOR (7 downto 0);
QB : out STD_LOGIC_VECTOR (7 downto 0);
QC : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
signal Di_A, Di_Op, Di_B, Di_C : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
signal Di_RegB, Di_FinalB, Di_C2 : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
component Stage_Di_Ex
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_C : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0);
Out_C : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
signal Ex_A, Ex_Op, Ex_B, Ex_C : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
component ALU
Port ( A : in STD_LOGIC_VECTOR (7 downto 0);
B : in STD_LOGIC_VECTOR (7 downto 0);
Ctrl_Alu : in STD_LOGIC_VECTOR (7 downto 0);
S : out STD_LOGIC_VECTOR (7 downto 0);
N : out STD_LOGIC;
O : out STD_LOGIC;
Z : out STD_LOGIC;
C : out STD_LOGIC;
JumpFlagOut : out STD_LOGIC; -- 0 false 1 true
JumpFlagIn : in STD_LOGIC
);
end component;
signal Ex_Ctrl_ALu, Ex_Res_Alu, Ex_FinalB : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
signal S_NFlag, S_Oflag, S_CFlag, S_ZFlag, Jump_Flag : STD_LOGIC;
component Stage_Ex_Mem
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
signal Mem_A, Mem_Op, Mem_B : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
signal Mem_RW : STD_LOGIC;
signal Mem_Addr, Mem_Data_Out, Mem_FinalB : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
component DataMemory
Port ( Addr : in STD_LOGIC_VECTOR (7 downto 0);
Data_in : in STD_LOGIC_VECTOR (7 downto 0);
Rw : in STD_LOGIC;
Rst : in STD_LOGIC;
Clk : in STD_LOGIC;
Data_out : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
component Stage_Mem_Re
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0)
);
end component;
component AleaControler is
Port ( Op_DI, Op_EX, Op_Mem, Op_Re : in STD_LOGIC_VECTOR (7 downto 0);
A_EX, A_Mem, A_Re : in STD_LOGIC_VECTOR (7 downto 0);
B_DI : in STD_LOGIC_VECTOR (7 downto 0);
C_DI : in STD_LOGIC_VECTOR (7 downto 0);
CNTRL : out STD_LOGIC
);
end component;
signal Re_A, Re_Op, Re_B : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
signal Re_W : STD_LOGIC;
-- to control jumping and where to jump
signal addr_to_jump : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
signal jump : STD_LOGIC := '0';
signal nop_Cntrl : STD_LOGIC;
signal OP_LI_DI : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
signal Di_Op_Final : STD_LOGIC_VECTOR (7 downto 0) := (others => '1');
begin
-- instructionPointer
inst_point : IP port map (
CLK=> clk,
Dout=> IP_out,
Din => addr_to_jump,
RST => rst,
EN => nop_Cntrl,
LOAD => jump);
-- instructionMemory
MemInst : InstructionMemory PORT MAP (
Addr => IP_out,
Clk => Clk,
Inst_out => Li);
-- Stage_Li_Di
Stage1 : Stage_Li_Di PORT MAP (
In_A => Li(23 downto 16),
In_B => Li(15 downto 8),
In_C => Li(7 downto 0),
In_Op => OP_LI_DI,
Clk => Clk,
Out_A => Di_A,
Out_B => Di_B,
Out_Op => Di_Op,
Out_C => Di_C);
-- Registers
RegisterFile : Registers PORT MAP (
Addr_A => Di_B(3 downto 0), -- because the registers are on 4 bits
Addr_B => Di_C(3 downto 0),
Addr_W => Re_A(3 downto 0),
Addr_C => reg_addr,
W => Re_W,
Data => Re_B,
Rst => Rst,
Clk => Clk,
QA => Di_RegB,
QB => Di_C2,
QC => reg_val);
-- Stage DI/EX
Stage2 : Stage_Di_Ex PORT MAP (
In_A => Di_A,
In_B => Di_FinalB,
In_C => Di_C2,
In_Op => Di_Op_Final,
Clk => Clk,
Out_A => Ex_A,
Out_B => Ex_B,
Out_Op => Ex_Op,
Out_C => Ex_C);
-- ALU
Ual : ALU PORT MAP (
A => Ex_B,
B => Ex_C,
Ctrl_Alu => Ex_Ctrl_ALu,
S => Ex_Res_Alu,
N => S_NFlag,
O => S_OFlag,
Z => S_ZFlag,
C => S_CFlag,
JumpFlagOut => Jump_Flag,
JumpFlagIn => Jump_Flag);
-- Stage Ex/Mem
Stage3 : Stage_Ex_Mem PORT MAP (
In_A => Ex_A,
In_B => Ex_FinalB,
In_Op => Ex_Op,
Clk => Clk,
Out_A => Mem_A,
Out_B => Mem_B,
Out_Op => Mem_Op);
-- DataMemory
DataMem : DataMemory PORT MAP (
Addr => Mem_Addr,
Data_in => Mem_B,
Rw => Mem_RW,
Rst => Rst,
Clk => Clk,
Data_out => Mem_Data_Out);
-- Stage Mem/RE
Stage4 : Stage_Mem_Re PORT MAP (
In_A => Mem_A,
In_B => Mem_FinalB,
In_Op => Mem_Op,
Clk => Clk,
Out_A => Re_A,
Out_B => Re_B,
Out_Op => Re_Op);
-- Instruction code
-- ADD x"01"
-- MUL x"02"
-- SUB x"03"
-- DIV x"04"
-- COP x"05"
-- AFC x"06"
-- LOAD x"07"
-- STORE x"08"
-- INF x"09"
-- SUP x"0A"
-- EQ x"0B"
-- NOT x"0C"
-- AND x"0D"
-- OR x"0E"
-- JMP x"0F"
-- JMF x"10"
-- CAL x"11"
-- RET x"12"
-- PRI x"13"
-- NOP x"FF"
-- Mux post registers
Di_FinalB <= Di_B when
Di_OP = x"06" or -- AFC
Di_OP = x"07" -- LOAD
else Di_RegB;
-- Mux post ALU
Ex_FinalB <= Ex_B when
Ex_Op = x"06" --AFC
or Ex_Op = x"05" --COP
or Ex_Op = x"07" --LOAD
or Ex_Op = x"08" --STORE
else Ex_Res_Alu;
-- LC pre ALU
Ex_Ctrl_ALu <= x"00" when Ex_Op = x"05" or Ex_Op = x"06" or Ex_Op = x"07" or Ex_Op = x"08" --(not using ALU)
else Ex_Op;
-- Mux post data memory
Mem_FinalB <= Mem_B when
Mem_Op = x"06" --AFC
or Mem_Op = x"05" --COP
or Mem_Op = x"01" --ADD
or Mem_Op = x"03" -- SUB
or Mem_Op = x"02" -- MUL
or Mem_Op = x"04" -- DIV
else Mem_Data_out ; --LOAD & STORE
-- Mux pre data memory
Mem_Addr <= Mem_B when Mem_Op = x"07" --LOAD
else Mem_A; --STORE
-- LC pre data memory
Mem_RW <= '0' when Mem_Op = x"08" --STORE
else '1'; --STORE
-- LC post Pip_Mem_Re
Re_W <= '0' when Re_Op = x"08" or Re_Op = x"ff" --STORE
else '1';
ControlUnit : AleaControler port map (
Op_DI => Li(31 downto 24), Op_EX => Di_Op, Op_Mem => Ex_Op, Op_Re => Mem_Op,
A_EX => Di_A, A_Mem => Ex_A, A_Re => Mem_A,
B_DI => Li(15 downto 8),
C_DI => Li(7 downto 0),
CNTRL => nop_Cntrl);
-- in case of alea : replace li(31 downto 24) by NOP
OP_LI_DI <= X"ff" when (nop_Cntrl='1' or
(Di_Op = x"10" and Jump_Flag = '1')) -- to prevent JMF
else Li(31 downto 24);
-- jump JMP
addr_to_jump <= DI_A when (DI_OP = x"0F") -- JMP
else Di_B when (Di_Op = x"10" and Jump_Flag = '0') -- JMF
else (others => '0');
jump <= '1' when DI_OP = x"0F" -- JMP
or (Di_Op = x"10" and Jump_Flag = '0') -- JMF
else '0';
-- case of JMF not triggering
Di_Op_Final <= x"ff" when (Di_Op = x"10" and Jump_Flag = '1')
else Di_Op;
end Behavioral;

61
vhdl/IP.vhd Normal file
View file

@ -0,0 +1,61 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 21.03.2023 15:57:28
-- Design Name:
-- Module Name: compteur_8bits - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity IP is
Port ( CLK : in STD_LOGIC;
RST : in STD_LOGIC; -- rst when 1
LOAD : in STD_LOGIC;
EN : in STD_LOGIC; -- enable when 0
Din : in STD_LOGIC_VECTOR (7 downto 0);
Dout : out STD_LOGIC_VECTOR (7 downto 0));
end IP;
architecture Behavioral of IP is
signal aux: STD_LOGIC_VECTOR (7 downto 0) := x"00";
begin
process
begin
wait until rising_edge(CLK);
if (RST = '1') then
aux <= x"00";
elsif (LOAD = '1') then
aux <= Din;
elsif (EN = '0') then
aux <= aux + x"01";
end if;
end process;
Dout <= aux;
end Behavioral;

View file

@ -0,0 +1,53 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 13:55:29
-- Design Name:
-- Module Name: InstructionMemory - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity InstructionMemory is
Port ( Addr : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Inst_out : out STD_LOGIC_VECTOR (31 downto 0));
end InstructionMemory;
architecture Behavioral of InstructionMemory is
type Mem_array is array (0 to 255) of STD_LOGIC_VECTOR (31 downto 0);
-- signal Mem : Mem_array := ((x"06000200"),(x"08020000"),(x"07000200"),(x"08000000"),(x"06000200"),(x"08020000"),(x"07000000"),(x"07010200"),(x"01000001"),(x"08030000"),(x"07000300"),(x"08010000"),others => (x"ff000000"));
-- signal Mem : Mem_array := ((x"06000200"),(x"08030000"),(x"07000300"),(x"08000000"),(x"06000600"),(x"08030000"),(x"07000000"),(x"07010300"),(x"02000001"),(x"08040000"),(x"07000400"),(x"08010000"),(x"06000200"),(x"08030000"),(x"07000100"),(x"07010300"),(x"04000001"),(x"08040000"),(x"07000400"),(x"07010000"),(x"01000001"),(x"08030000"),(x"07000300"),(x"08020000"),others => (x"ff000000"));
-- test JMP signal Mem : Mem_array := ((x"06000200"),(x"08030000"),(x"07000300"),(x"08000000"),(x"06000500"),(x"08030000"),(x"07000300"),(x"08010000"),(x"0F0D0000"),(x"06000800"),(x"08030000"),(x"07000300"),(x"08020000"),(x"06000900"),(x"08030000"),(x"07000300"),(x"08020000"),others => (x"ff000000"));
-- test JMF signal Mem : Mem_array := ((x"06000500"),(x"08010000"),(x"07000100"),(x"08000000"),(x"06000500"),(x"08010000"),(x"07000000"),(x"07010100"),(x"0B020100"),(x"08020200"),(x"100F0000"),(x"06000800"),(x"08030000"),(x"07000300"),(x"08000000"),(x"FF000000"),others => (x"ff000000"));
-- test if else signal Mem : Mem_array := ((x"06000200"),(x"08010000"),(x"07000100"),(x"08000000"),(x"06000500"),(x"08010000"),(x"07000000"),(x"07010100"),(x"0B020100"),(x"08020200"),(x"10021000"),(x"06000800"),(x"08030000"),(x"07000300"),(x"08000000"),(x"0F140000"),(x"06000C00"),(x"08020000"),(x"07000200"),(x"08000000"),(x"FF000000"),others => (x"ff000000"));
-- test boucle while
signal Mem : Mem_array := ((x"06000500"),(x"08010000"),(x"07000100"),(x"08000000"),(x"06000500"),(x"08010000"),(x"07000000"),(x"07010100"),(x"0B020100"),(x"08020200"),(x"10001B00"),(x"06001400"),(x"08030000"),(x"07000000"),(x"07010300"),(x"09020001"),(x"08040200"),(x"10041B00"),(x"06000200"),(x"08010000"),(x"07000000"),(x"07010100"),(x"01000001"),(x"08030000"),(x"07000300"),(x"08000000"),(x"0F0B0000"),(x"FF000000"),others => (x"ff000000"));
-- signal Mem : Mem_array := ((x"06000200"),(x"08040000"),(x"07000400"),(x"08030000"),(x"07000000"),(x"08020000"),(x"06000200"),(x"08040000"),(x"07000200"),(x"07010400"),(x"01000001"),(x"08050000"),(x"07000500"),(x"08000000"),(x"07000300"),(x"08000000"),(x"06000500"),(x"08040000"),(x"07000400"),(x"08000000"),(x"06001300"),(x"08040000"),(x"06000200"),(x"08050000"),(x"07000400"),(x"07010500"),(x"01000001"),(x"08040000"),(x"06000500"),(x"08050000"),(x"07000500"),(x"07010000"),(x"02000001"),(x"08040000"),(x"06000800"),(x"08050000"),(x"07000400"),(x"07010500"),(x"01000001"),(x"08040000"),(x"06000200"),(x"08050000"),(x"07000400"),(x"07010500"),(x"02000001"),(x"08040000"),(x"07000400"),(x"07010400"),(x"03000001"),(x"08050000"),(x"07000500"),(x"08030000"), others => (x"ff000000"));
begin
Inst_out <= Mem(to_integer(unsigned(Addr)));
end Behavioral;

60
vhdl/Memory.vhd Normal file
View file

@ -0,0 +1,60 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 13:37:41
-- Design Name:
-- Module Name: DataMemory - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity DataMemory is
Port ( Addr : in STD_LOGIC_VECTOR (7 downto 0);
Data_in : in STD_LOGIC_VECTOR (7 downto 0);
Rw : in STD_LOGIC;
Rst : in STD_LOGIC;
Clk : in STD_LOGIC;
Data_out : out STD_LOGIC_VECTOR (7 downto 0));
end DataMemory;
architecture Behavioral of DataMemory is
type Mem_array is array (0 to 255) of STD_LOGIC_VECTOR (7 downto 0);
signal Mem : Mem_array := (others => x"00");
begin
process
begin
wait until clk'event and clk = '1';
if Rst = '1' then -- Reset
mem <= (others => x"00");
else if Rw = '0' then --writing
Mem(to_integer(unsigned(Addr))) <= Data_in;
end if;
end if;
end process;
Data_out <= Mem(to_integer(unsigned(Addr))); --reading
end Behavioral;

79
vhdl/Registers.vhd Normal file
View file

@ -0,0 +1,79 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 12:56:05
-- Design Name:
-- Module Name: registers - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Registers is
Port ( Addr_A : in STD_LOGIC_VECTOR (3 downto 0);
Addr_B : in STD_LOGIC_VECTOR (3 downto 0);
Addr_W : in STD_LOGIC_VECTOR (3 downto 0);
Addr_C : in STD_LOGIC_VECTOR (3 downto 0); -- display on FPGA
W : in STD_LOGIC;
Data : in STD_LOGIC_VECTOR (7 downto 0);
Rst : in STD_LOGIC;
Clk : in STD_LOGIC;
QA : out STD_LOGIC_VECTOR (7 downto 0);
QB : out STD_LOGIC_VECTOR (7 downto 0);
QC : out STD_LOGIC_VECTOR (7 downto 0));
end Registers;
architecture Behavioral of Registers is
type Reg_array is array (0 to 15) of STD_LOGIC_VECTOR (7 downto 0);
signal Regs : Reg_array := (others => x"00");
begin
process
begin
wait until clk'event and clk = '1';
if Rst = '1' then -- Reset
Regs <= (others => x"00");
elsif W = '1' then -- Writing
Regs(to_integer(unsigned(Addr_W))) <= Data;
end if;
end process;
QA <= Regs(to_integer(unsigned(Addr_A)))
when W = '0' or Addr_W /= Addr_A
else Regs(to_integer(unsigned(Addr_W))) ; -- to bypass D --> Q
QB <= Regs(to_integer(unsigned(Addr_B)))
when W = '0' or Addr_W /= Addr_B
else Regs(to_integer(unsigned(Addr_W))) ; -- to bypass D --> Q
QC <= Regs(to_integer(unsigned(Addr_C)))
when W = '0' or Addr_W /= Addr_C
--else Regs(to_integer(unsigned(Addr_W)))
else
x"11" ; -- to bypass D --> Q
end Behavioral;

59
vhdl/Stage_Di_Ex.vhd Normal file
View file

@ -0,0 +1,59 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 14:09:59
-- Design Name:
-- Module Name: Pipeline - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Stage_Di_Ex is
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_C : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0);
Out_C : out STD_LOGIC_VECTOR (7 downto 0)
);
end Stage_Di_Ex;
architecture Behavioral of Stage_Di_Ex is
begin
process
begin
wait until clk'event and clk = '1';
Out_A <= In_A;
Out_B <= In_B;
Out_C <= In_C;
Out_Op <= In_Op;
end process;
end Behavioral;

56
vhdl/Stage_Ex_Mem.vhd Normal file
View file

@ -0,0 +1,56 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 14:09:59
-- Design Name:
-- Module Name: Pipeline - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Stage_Ex_Mem is
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0)
);
end Stage_Ex_Mem;
architecture Behavioral of Stage_Ex_Mem is
begin
process
begin
wait until clk'event and clk = '1';
Out_A <= In_A;
Out_B <= In_B;
Out_Op <= In_Op;
end process;
end Behavioral;

59
vhdl/Stage_Li_Di.vhd Normal file
View file

@ -0,0 +1,59 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 14:09:59
-- Design Name:
-- Module Name: Pipeline - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Stage_Li_Di is
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_C : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0);
Out_C : out STD_LOGIC_VECTOR (7 downto 0)
);
end Stage_Li_Di;
architecture Behavioral of Stage_Li_Di is
begin
process
begin
wait until clk'event and clk = '1';
Out_A <= In_A;
Out_B <= In_B;
Out_C <= In_C;
Out_Op <= In_Op;
end process;
end Behavioral;

56
vhdl/Stage_Mem_Re.vhd Normal file
View file

@ -0,0 +1,56 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 15.05.2023 14:09:59
-- Design Name:
-- Module Name: Pipeline - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Stage_Mem_Re is
Port ( In_A : in STD_LOGIC_VECTOR (7 downto 0);
In_B : in STD_LOGIC_VECTOR (7 downto 0);
In_Op : in STD_LOGIC_VECTOR (7 downto 0);
Clk : in STD_LOGIC;
Out_A : out STD_LOGIC_VECTOR (7 downto 0);
Out_B : out STD_LOGIC_VECTOR (7 downto 0);
Out_Op : out STD_LOGIC_VECTOR (7 downto 0)
);
end Stage_Mem_Re;
architecture Behavioral of Stage_Mem_Re is
begin
process
begin
wait until clk'event and clk = '1';
Out_A <= In_A;
Out_B <= In_B;
Out_Op <= In_Op;
end process;
end Behavioral;

145
vhdl/test_alu.vhd Normal file
View file

@ -0,0 +1,145 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 12.05.2023 17:40:52
-- Design Name:
-- Module Name: Test_Alu - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Test_Alu is
-- Port ( );
end Test_Alu;
architecture Behavioral of Test_Alu is
component ALU
Port ( A : in STD_LOGIC_VECTOR (7 downto 0);
B : in STD_LOGIC_VECTOR (7 downto 0);
Ctrl_Alu : in STD_LOGIC_VECTOR (7 downto 0); -- 000 + / 001 - / 010 * / 100 Div
S : out STD_LOGIC_VECTOR (7 downto 0);
N : out STD_LOGIC;
O : out STD_LOGIC;
Z : out STD_LOGIC;
C : out STD_LOGIC);
end component;
-- inputs
signal local_A : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
signal local_B : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
signal local_Ctrl_Alu : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
--outputs
signal local_S : STD_LOGIC_VECTOR (7 downto 0) := (others => '0');
signal local_N : STD_LOGIC := '0';
signal local_O : STD_LOGIC := '0';
signal local_Z : STD_LOGIC := '0';
signal local_C : STD_LOGIC := '0';
-- constant Clock_period : time := 10ns;
begin
-- instantiate
instance : ALU PORT MAP (
A => local_A,
B => local_B,
Ctrl_Alu => local_Ctrl_Alu,
S => local_S,
N => local_N,
O => local_O,
Z => local_Z,
C => local_C
);
local_Ctrl_Alu <= x"01", -- ADD
x"02" after 40 ns, -- MUL
x"03" after 60 ns, -- SUB
x"04" after 90 ns, -- DIV
x"09" after 120 ns, -- INF
x"0A" after 140 ns, -- SUP
x"0B" after 160 ns, -- EQ
x"0C" after 180 ns, -- NOT
x"0D" after 210 ns, -- XOR
x"0E" after 240 ns, -- OR
x"0F" after 270 ns; -- XOR
local_A <= x"00",
x"00" after 10 ns,
x"0A" after 20 ns,
x"96" after 30 ns,
x"1D" after 40 ns,
x"0A" after 50 ns,
x"0B" after 60 ns,
x"0F" after 70 ns,
x"19" after 80 ns,
x"12" after 90 ns,
x"18" after 100 ns,
x"19" after 110 ns,
x"10" after 120 ns,
x"20" after 130 ns,
x"10" after 150 ns,
x"0A" after 160 ns,
x"0B" after 170 ns,
x"01" after 180 ns,
x"25" after 190 ns,
x"00" after 200 ns,
x"0A" after 210 ns,
x"00" after 230 ns,
x"0A" after 240 ns,
x"00" after 260 ns,
x"0A" after 270 ns,
x"00" after 290 ns;
local_B <= x"00",
x"00" after 10 ns,
x"82" after 20 ns,
x"A0" after 30 ns,
x"09" after 40 ns,
x"04" after 50 ns,
x"0B" after 60 ns,
x"12" after 70 ns,
x"0B" after 80 ns,
x"00" after 90 ns,
x"06" after 100 ns,
x"07" after 110 ns,
x"20" after 120 ns,
x"10" after 130 ns,
x"20" after 150 ns,
x"0A" after 160 ns,
x"02" after 170 ns,
x"00" after 190 ns,
x"0B" after 210 ns,
x"00" after 220 ns,
x"0B" after 240 ns,
x"00" after 250 ns,
x"0B" after 270 ns,
x"00" after 280 ns;
end Behavioral;

65
vhdl/test_cpu.vhd Normal file
View file

@ -0,0 +1,65 @@
----------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date: 12.05.2023 17:40:52
-- Design Name:
-- Module Name: Test_cpu - Behavioral
-- Project Name:
-- Target Devices:
-- Tool Versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity Test_CPU is
-- Port ( );
end Test_CPU;
architecture Behavioral of test_total is
component CPU
Port (Clk : in STD_LOGIC;
reg_addr : in STD_LOGIC_VECTOR(3 downto 0);
reg_val : out STD_LOGIC_VECTOR(7 downto 0));
end component;
constant clock_period : time := 10 ns;
signal clock : Std_logic := '0';
signal a : STD_LOGIC_VECTOR(7 downto 0);
begin
-- instantiate
Pl : CPU PORT MAP (
Clk => clock,
reg_addr => x"0",
reg_val => a
);
Clock_process : process
begin
clock <= not(clock);
wait for 100ns;
end process;
end Behavioral;

26
vhdl/test_cpu.xdc Normal file
View file

@ -0,0 +1,26 @@
set_property PACKAGE_PIN R2 [get_ports CLK]
set_property IOSTANDARD LVCMOS33 [get_ports CLK]
#set_property CLOCK_DEDICATED_ROUTE FALSE [get_nets CLK]
#set_property -dicset_property -dict {PACKAGE_PIN T18 IOSTANDARD LVCMOS33} [get_ports CLK]
#set_property -dict {PACKAGE_PIN T17 IOSTANDARD LVCMOS33} [get_ports CLK]
#create_clock -period 10.000 -name -sysclk_pin -waveform {0.000 5.000} [get_ports CLK]
set_property ALLOW_COMBINATORIAL_LOOPS TRUE [get_nets {Stage2/Jump_Flag}]
set_property -dict {PACKAGE_PIN V17 IOSTANDARD LVCMOS33} [get_ports {reg_addr[0]}]
set_property -dict {PACKAGE_PIN V16 IOSTANDARD LVCMOS33} [get_ports {reg_addr[1]}]
set_property -dict {PACKAGE_PIN W16 IOSTANDARD LVCMOS33} [get_ports {reg_addr[2]}]
set_property -dict {PACKAGE_PIN W17 IOSTANDARD LVCMOS33} [get_ports {reg_addr[3]}]
set_property -dict {PACKAGE_PIN U16 IOSTANDARD LVCMOS33} [get_ports {reg_val[0]}]
set_property -dict {PACKAGE_PIN E19 IOSTANDARD LVCMOS33} [get_ports {reg_val[1]}]
set_property -dict {PACKAGE_PIN U19 IOSTANDARD LVCMOS33} [get_ports {reg_val[2]}]
set_property -dict {PACKAGE_PIN V19 IOSTANDARD LVCMOS33} [get_ports {reg_val[3]}]
set_property -dict {PACKAGE_PIN W18 IOSTANDARD LVCMOS33} [get_ports {reg_val[4]}]
set_property -dict {PACKAGE_PIN U15 IOSTANDARD LVCMOS33} [get_ports {reg_val[5]}]
set_property -dict {PACKAGE_PIN U14 IOSTANDARD LVCMOS33} [get_ports {reg_val[6]}]
set_property -dict {PACKAGE_PIN V14 IOSTANDARD LVCMOS33} [get_ports {reg_val[7]}]
set_property SEVERITY {Warning} [get_drc_checks NSTD-1]
set_property SEVERITY {Warning} [get_drc_checks UCIO-1]

File diff suppressed because it is too large Load diff

View file

@ -1,105 +0,0 @@
/* A Bison parser, made by GNU Bison 3.5.1. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Undocumented macros, especially those whose name start with YY_,
are private implementation details. Do not rely on them. */
#ifndef YY_YY_YACC_TAB_H_INCLUDED
# define YY_YY_YACC_TAB_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 1
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
tWHILE = 258,
tIF = 259,
tELSE = 260,
tRETURN = 261,
tPRINT = 262,
tFLOAT = 263,
tINT = 264,
tVOID = 265,
tDIV = 266,
tMUL = 267,
tADD = 268,
tSUB = 269,
tASSIGN = 270,
tLT = 271,
tGT = 272,
tNE = 273,
tEQ = 274,
tGE = 275,
tLE = 276,
tAND = 277,
tOR = 278,
tNOT = 279,
tLBRACE = 280,
tRBRACE = 281,
tLPAR = 282,
tRPAR = 283,
tSEMI = 284,
tCOMMA = 285,
tID = 286,
tNB = 287
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 12 "yacc.y"
int nbInt; /*enumVarType*/ int type; char* string;
#line 93 "yacc.tab.h"
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
int yyparse (void);
#endif /* !YY_YY_YACC_TAB_H_INCLUDED */

172
yacc.y
View file

@ -1,172 +0,0 @@
%{
#include <stdio.h>
#include <stdlib.h>
#include "table.h"
int t;
int yylex (void);
void yyerror (const char *);
%}
// TODO : PROBLEM DOES'NT COMPILE (enumVarType doesn't exist)
%union {int nbInt; /*enumVarType*/ int type; char* string;}
/*loops keywords*/
%token tWHILE tIF tELSE
/*reserved keywords*/
%token tRETURN tPRINT
/*types : integers, floats or void*/
%token tFLOAT tINT tVOID
/*operations*/
%left tDIV tMUL tADD tSUB
/*Assignment*/
%left tASSIGN
/*comparisons*/
%left tLT tGT tNE tEQ tGE tLE
/*boolean operators*/
%left tAND tOR tNOT
/*syntaxic symbols*/
%token tLBRACE tRBRACE tLPAR tRPAR tSEMI tCOMMA
/*nametags and values*/
%token <string> tID
%token <nbInt> tNB
/* represents types with the values used in the table, see table.h */
%type <type> Type
%start Program
%%
Program : FunctionDef ;
/* Lines = Any line in the code that is not within an if/while statement*/
Lines : Line
| Line Lines;
Line : IfStatement
| WhileStatement
| Assignment
| Declarations
| FunctionCall
| Return
| Print;
/*Innerblock = the inside of an if/else/while statement = { ... } or function = f(){...}*/
InnerBlock : tLBRACE tRBRACE // a function or while loop can be empty cf GCC
| tLBRACE {increaseDepth();} Lines tRBRACE {decreaseDepth();};
/*Condition = the evaluated boolean expression for an if or while = ( ... ) */
Condition : tLPAR ConditionalExpression tRPAR;
/*ConditionalExpression = expression that evaluates to a boolean*/
ConditionalExpression : tID
| tNB
| tLPAR ConditionalExpression tRPAR // for cases like if((a or b) and (a or c)) where there are parenthesis inside
| NbOrVariable NumericalOperator NbOrVariable
| tNOT ConditionalExpression
/* replaced by the two following lines
| ConditionalExpression BinaryLogicalOperator ConditionalExpression
*/
| ConditionalExpression tOR ConditionalExpression
| ConditionalExpression tAND ConditionalExpression;
/*end of added bloat*/
/*NbOrVariable is either a number or a variable of type int*/
NbOrVariable : tID {/* copy */}
| tNB {/* Affectation */};
/*List of all numerical operators*/
NumericalOperator : tLE | tGE | tEQ | tNE | tLT | tGT;
/*any arithmetic operation
Operation: tADD | tMUL | tSUB | tDIV;
*/
IfStatement : tIF Condition InnerBlock
| tIF Condition InnerBlock tELSE InnerBlock
WhileStatement : tWHILE Condition InnerBlock;
Assignment : tID tASSIGN Expression tSEMI {setInit($1);};
/*Expression operation applied on variables or values*/
Expression : NbOrVariable
| FunctionCall
| tLPAR Expression tRPAR
/* replaced by the four following lines
//| Expression Operation Expression
*/
| Expression tADD Expression
| Expression tSUB Expression
| Expression tMUL Expression
| Expression tDIV Expression;
/*end of added bloat*/
Expressions : Expression
| Expression tCOMMA Expressions;
FunctionCall : tID tLPAR Expressions tRPAR;
FunctionDef : Type tID FunctionParams InnerBlock;
/*FunctionParams = the parameters of a function*/
FunctionParams : tLPAR tRPAR
| tLPAR tVOID tRPAR
| tLPAR VarsWithType tRPAR
VarsWithType : VarWithType
| VarWithType tCOMMA VarsWithType;
/*VarWithType = a variable associated to its type = int a*/
VarWithType : Type tID;
/*the return type or argument type*/
Type : tINT {$$ = /*INT*/ 0;}
| tFLOAT {$$ = /*FLOAT*/ 1;};
Declarations : Type { t = $1; } Declaration Declarations1 tSEMI ;
Declaration : tID {addElement($1, (enumVarType) t);}
| tID tASSIGN Expression {addElement($1, (enumVarType) t);setInit($1);} ;
Declarations1 : tCOMMA Declaration Declarations1 | {} ;
Declaration : Type tID tSEMI {addElement($2, (enumVarType) $1);}
| Type tID tASSIGN Expression tSEMI {addElement($2, (enumVarType) $1);setInit($2);}
/* Potential improvement : take care of multiple definition on same line*/
| Type tID tCOMMA VarsCommaSeparated tSEMI {yyerror("[Beta] you cannot -still- define several variable on the same line");} /* addElement($2, (enumVarType) $1); */
| Type tID tCOMMA VarsCommaSeparated tASSIGN Expression tSEMI {yyerror("[Beta] you cannot -still- define several variable on the same line");};
// yes this is perfectly valid in C, the last variable will hold the value, the others won't
// this is only used in case of a declaration of several same-typed
// variables, ex : `int a,b,c;`
VarsCommaSeparated : tID
| tID tCOMMA VarsCommaSeparated ;
Return : tRETURN Expression tSEMI {decreaseDepth();};
Print : tPRINT tLPAR Expression tRPAR tSEMI;
%%
void yyerror(const char *msg) {
fprintf(stderr, "\033[1m\033[31m[/!\\]\033[0m Error : %s\n", msg);
exit(1);
}
int main(void) {
initSymbolTable();
yyparse();
}
// SI >> SC