-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
105 lines (79 loc) · 1.86 KB
/
Copy pathparser.c
File metadata and controls
105 lines (79 loc) · 1.86 KB
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
#include <stdio.h>
#include <stdlib.h>
#include "parser.h"
Token *peek(Parser *parser)
{
return &parser->stream->tokens[parser->current];
}
bool isAtEnd(Parser *parser)
{
return peek(parser)->type == TOKEN_EOF;
}
void advance(Parser *parser)
{
if (!isAtEnd(parser))
parser->current++;
}
ASTNode *parseCommand(Parser *parser)
{
ASTNode *node;
Token *token;
if (peek(parser)->type != TOKEN_WORD)
{
fprintf(stderr, "Syntax error: expected command.\n");
return NULL;
}
node = malloc(sizeof(*node));
if (node == NULL)
{
fprintf(stderr, "Parser error: memory allocation failed.\n");
return NULL;
}
node->type = NODE_COMMAND;
node->command.argc = 0;
node->left = NULL;
node->right = NULL;
node->child = NULL;
while (!isAtEnd(parser) && peek(parser)->type == TOKEN_WORD)
{
if (node->command.argc >= MAX_ARGS - 1)
{
fprintf( stderr, "Parser error: too many command arguments.\n");
free(node);
return NULL;
}
token = peek(parser);
node->command.argv[node->command.argc] =
&parser->stream->pool[token->start];
node->command.argc++;
advance(parser);
}
node->command.argv[node->command.argc] = NULL;
return node;
}
ASTNode *parseExpression(Parser *parser)
{
return parseCommand(parser);
}
ASTNode *parse(TokenStream *stream)
{
Parser parser;
ASTNode *root;
if (stream == NULL)
return NULL;
parser.stream = stream;
parser.current = 0;
root = parseExpression(&parser);
if (root == NULL)
return NULL;
if (!isAtEnd(&parser))
{
fprintf(
stderr,
"Syntax error: unsupported token after command.\n"
);
free(root);
return NULL;
}
return root;
}