Skip to content

Commit 23be9fb

Browse files
committed
feat(main): fazer pequeno passo de transpilação com uns extras
1 parent 2db08b9 commit 23be9fb

File tree

2 files changed

+113
-4
lines changed

2 files changed

+113
-4
lines changed

src/main.c

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#include <ctype.h>
2+
#include <errno.h>
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
#include <string.h>
6+
7+
#define MAX_LINE 1024
8+
9+
static void transpile_stream(FILE *in);
10+
static void emit_line(char *line);
11+
static void trim_trailing(char *line);
12+
13+
int main(int argc, char **argv)
14+
{
15+
FILE *in = stdin;
16+
17+
if (argc > 2)
18+
{
19+
fprintf(stderr, "Uso: %s [arquivo.c]\n", argv[0]);
20+
return EXIT_FAILURE;
21+
}
22+
23+
if (argc == 2)
24+
{
25+
in = fopen(argv[1], "r");
26+
if (!in)
27+
{
28+
fprintf(stderr, "Erro ao abrir %s: %s\n", argv[1], strerror(errno));
29+
return EXIT_FAILURE;
30+
}
31+
}
32+
33+
transpile_stream(in);
34+
35+
if (in != stdin)
36+
{
37+
fclose(in);
38+
}
39+
40+
return EXIT_SUCCESS;
41+
}
42+
43+
static void transpile_stream(FILE *in)
44+
{
45+
char buffer[MAX_LINE];
46+
47+
while (fgets(buffer, sizeof(buffer), in))
48+
{
49+
trim_trailing(buffer);
50+
emit_line(buffer);
51+
}
52+
}
53+
54+
static void emit_line(char *line)
55+
{
56+
char *cursor = line;
57+
58+
while (*cursor && isspace((unsigned char)*cursor))
59+
{
60+
cursor++;
61+
}
62+
63+
if (*cursor == '\0')
64+
{
65+
return;
66+
}
67+
68+
trim_trailing(cursor);
69+
70+
size_t len = strlen(cursor);
71+
if (len == 0)
72+
{
73+
return;
74+
}
75+
76+
if (cursor[len - 1] == ';')
77+
{
78+
cursor[len - 1] = '\0';
79+
trim_trailing(cursor);
80+
}
81+
82+
if (strncmp(cursor, "int ", 4) == 0)
83+
{
84+
char *rest = cursor + 4;
85+
while (*rest && isspace((unsigned char)*rest))
86+
{
87+
rest++;
88+
}
89+
if (*rest == '\0')
90+
{
91+
return;
92+
}
93+
printf("local %s\n", rest);
94+
return;
95+
}
96+
97+
printf("%s\n", cursor);
98+
}
99+
100+
static void trim_trailing(char *line)
101+
{
102+
size_t len = strlen(line);
103+
104+
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
105+
{
106+
line[--len] = '\0';
107+
}
108+
109+
while (len > 0 && isspace((unsigned char)line[len - 1]))
110+
{
111+
line[--len] = '\0';
112+
}
113+
}

src/parser.y

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,6 @@ expr:
7676

7777
%%
7878

79-
int main(void) {
80-
return yyparse();
81-
}
82-
8379
void yyerror(const char *s) {
8480
fprintf(stderr, "Erro sintático: %s\n", s);
8581
}

0 commit comments

Comments
 (0)