implemented scanner and parser with c

This commit is contained in:
Aaro Koivukangas
2024-08-11 19:33:27 +02:00
parent 7e765db6ae
commit f38b43774e
6 changed files with 263 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
#include "token.h"
#include <stdio.h>
#define FILENAME "../docs/example-file-harder.k91"
// scanner
extern FILE *yyin;
extern int yylex();
extern char *yytext;
// parser
extern int yyparse();
int main()
{
yyin = fopen(FILENAME, "r");
if (!yyin) {
printf("Couldn't open file\n");
return 1;
}
if (yyparse() == 0) {
printf("Parse succesful :)\n");
} else {
printf("Parse failed\n");
return 1;
}
return 0;
}
+81
View File
@@ -0,0 +1,81 @@
/* TODO support tags to jump to different sections */
%{
#include <stdio.h>
extern int yylineno;
%}
%define parse.error verbose
%token TOKEN_REGISTER
%token TOKEN_STACK_REGISTER
%token TOKEN_NUMBER
%token TOKEN_LABEL
%token TOKEN_ADDR_M
%token TOKEN_OPER_DATA
%token TOKEN_OPER_AR
%token TOKEN_OPER_LOGIC
%token TOKEN_OPER_BRANCH
%token TOKEN_OPER_STACK
%token TOKEN_OPER_SYS
%token TOKEN_SYS_NUM
%token TOKEN_COMP_OPER
%token TOKEN_SIGN
%token TOKEN_COMMA
%token TOKEN_PAREN_L
%token TOKEN_PAREN_R
%token TOKEN_COMMENT
%token TOKEN_ERROR
%%
program : expr
| program expr
;
expr : oper register TOKEN_COMMA second_arg
| oper value
| TOKEN_LABEL TOKEN_COMP_OPER num_value
| TOKEN_LABEL expr
| comment
;
oper : TOKEN_OPER_DATA
| TOKEN_OPER_AR
| TOKEN_OPER_LOGIC
| TOKEN_OPER_BRANCH
| TOKEN_OPER_STACK
| TOKEN_OPER_SYS
;
register : TOKEN_REGISTER
| TOKEN_STACK_REGISTER
;
second_arg : value TOKEN_PAREN_L register TOKEN_PAREN_R
| value
| TOKEN_ADDR_M value TOKEN_PAREN_L register TOKEN_PAREN_R
| TOKEN_ADDR_M value
| TOKEN_PAREN_L register TOKEN_PAREN_R
;
value : register
| num_value
| TOKEN_LABEL
| TOKEN_SYS_NUM
;
num_value : TOKEN_SIGN TOKEN_NUMBER
| TOKEN_NUMBER
;
comment : TOKEN_COMMENT
;
%%
int yyerror ( const char *s )
{
printf("ERROR: Parser error: %s at line %d\n", s, yylineno);
return 1;
}
+38
View File
@@ -0,0 +1,38 @@
%{
#include "token.h"
%}
%option yylineno
%%
(" "|\t|\n) /* skip whitespace */
(@|=) { return TOKEN_ADDR_M; }
\( { return TOKEN_PAREN_L; }
\) { return TOKEN_PAREN_R; }
, { return TOKEN_COMMA; }
;.*$ { return TOKEN_COMMENT; }
(LOAD|STORE|IN|OUT) { return TOKEN_OPER_DATA; } /* TODO, currently only in uppercase */
(ADD|SUB|MUL|DIV|MOD) { return TOKEN_OPER_AR; }
(AND|OR|XOR|NOT|SHL|SHR|SHRA|COMP) { return TOKEN_OPER_LOGIC; }
(JUMP|JNEG|JZER|JPOS|JNNEG|JNZER|JNPOS|JLES|JEQU|JGRE|JNLES|JNEQU|JNGRE) { return TOKEN_OPER_BRANCH; }
(PUSH|POP|PUSHR|POPR) { return TOKEN_OPER_STACK; }
(CALL|EXIT|SVC|NOP) { return TOKEN_OPER_SYS; }
(HALT|TIME|DATE|READ|WRITE) { return TOKEN_SYS_NUM; }
(EQU|DC|DS|DEF) { return TOKEN_COMP_OPER; }
(SP|FP|PC) { return TOKEN_STACK_REGISTER; }
R[0-8] { return TOKEN_REGISTER; }
[0-9]+ { return TOKEN_NUMBER; }
[a-öA-Ö]([a-öA-Ö0-9_])* { return TOKEN_LABEL; }
- { return TOKEN_SIGN; }
. { return TOKEN_ERROR; }
%%
int yywrap() { return 1; }