-
Notifications
You must be signed in to change notification settings - Fork 2
/
ctoy.lex
executable file
·117 lines (87 loc) · 2.59 KB
/
ctoy.lex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/* Scanner para uma linguagem Pascal simplificada */
%option noyywrap
%{
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
int numLines = 1;
char varIds[30][30] = {};
int actualId = 1;
bool breakStrcmp = false;
%}
ENDLINE \r?\n
WORD [A-Za-z_][A-Za-z_0-9]*
SPACE [ \t\f\r\n]*
ARRAY \[[^\][]*\]
VAR (\*{SPACE})*{WORD}({SPACE}{ARRAY})*
VAR_POINTER (\&){WORD}*
VAR_POINTER_PARENT \*{SPACE}\(([A-Za-z_0-9])+\)
VAR_NO_POINTER {WORD}({SPACE}{ARRAY})*
DIGIT [0-9]
STRING \"([^\\\"]|\\.)*\"
LIB_STDIO <stdio.h>
LIB_CONIO <conio.h>
EQUAL =
LOGICAL "||"|"&&"
RELATIONAL "!="|"<"|"<="|"=="|">="|">"
ARITMETIC "++"|"+"|"-"|"*"|"/"
COMMA ","
SEMICOLON ";"
L_BRACKET "{"
R_BRACKET "}"
L_PAREN "("
R_PAREN ")"
COMMENT "//"[^\n]*
%%
/* Ignore spaces and endline. */
{ENDLINE} numLines++;{ printf("\n\n------- Linha: %d\n", numLines); }
/* Reserved words. */
#include|scanf|printf|do|while|for|if|else|switch|case|void|return|NULL|null|int|float|double|String|string|bool|break { printf("[reserved_word, %s] ", yytext); }
{LIB_STDIO}|{LIB_CONIO} { printf("[external_library, %s] ", yytext); }
/* Functions. */
{R_BRACKET} { printf("[r_bracket, %s] ", yytext); }
{L_BRACKET} { printf("[l_bracket, %s] ", yytext); }
{L_PAREN} { printf("[l_paren, %s] ", yytext); }
{R_PAREN} { printf("[r_paren, %s] ", yytext); }
{COMMA} { printf("[comma, %s] ", yytext); }
{SEMICOLON} { printf("[semicolon, %s] ", yytext); }
/* Comments. */
{COMMENT} {}
"/*"([^*]|\*+[^*/])*\*+"/" {}
/* Numbers. */
{DIGIT}+ { printf("[num, %s] ", yytext);}
{DIGIT}+"."{DIGIT}+ {printf("[num, %s] ", yytext);}
/* Conditional statements. */
{EQUAL} { printf("[equal_op, %s] ", yytext); }
{LOGICAL} { printf("[logical_op, %s] ", yytext); }
{RELATIONAL} { printf("[relational_op, %s] ", yytext); }
{ARITMETIC} { printf("[arith_op, %s] ", yytext); }
/* String. */
{STRING} { printf("[string_literal, %s] ", yytext); }
/* Variables. */
{VAR}|{VAR_NO_POINTER}|{VAR_POINTER}|{VAR_POINTER_PARENT} {
int i;
for (i = 0; i < sizeof(varIds); i++){
if(strcmp(&yytext[0], varIds[i]) == 0){
printf("[id, %d] ", i);
breakStrcmp = true;
break;
}
}
if(!breakStrcmp){
strcpy(varIds[actualId], &yytext[0]);
printf("[id, %d] ", actualId);
actualId++;
}else{
breakStrcmp = false;
}
}
%%
int main(int argc, char *argv[]){
printf("----- Linha: 1\n", yytext);
yyin = fopen(argv[1], "r");
yylex();
fclose(yyin);
return 0;
}