-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmopcode.c
More file actions
105 lines (99 loc) · 2.13 KB
/
mopcode.c
File metadata and controls
105 lines (99 loc) · 2.13 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 "monty.h"
/**
* tokenize - tokenize the opcode
* @opcom: operation command
* @stack: ...
*
* Return: pointer to pointer of
* tokenized command
*/
char **tokenize(char *opcom, stack_t **stack)
{
int i = 0, j = 0;
char *token = NULL, *dupcom, *delim = " \t\n$", **args;
dupcom = malloc(sizeof(char) * (strlen(opcom) + 1));
if (dupcom == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
clear_all(stack);
exit(EXIT_FAILURE);
}
strcpy(dupcom, opcom);
token = strtok(opcom, delim);
while (token)
token = strtok(NULL, delim);
i++;
args = malloc(sizeof(char *) * (i + 1));
if (args == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
clear_all(stack), free(dupcom);
exit(EXIT_FAILURE);
}
token = strtok(dupcom, delim);
while (token)
{
args[j] = malloc(sizeof(char) * (strlen(token) + 1));
if (args[j] == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
clear_all(stack), free(dupcom);
exit(EXIT_FAILURE);
}
strcpy(args[j], token);
token = strtok(NULL, delim);
j++;
}
args[j] = NULL;
free(dupcom);
return (args);
}
/**
* opcheck - checks if command is a
* monty operation
* @opcom: operation command
* @top_t: top of the stack
* @line_c: line count
*/
void opcheck(char *opcom, unsigned int line_c, stack_t **top_t)
{
int i = 0;
instruction_t list[] = {
{"pall", pall}, {"pint", pint},
{"pop", pop}, {"swap", swap},
{"add", add}, {"nop", nop},
{"sub", sub}, {"div", div_s},
{"mul", mul_s}, {"mod", mod_s},
{"pchar", pchar}, {"pstr", pstr},
{"rotl", rotl}, {"rotr", rotr},
{NULL, NULL}
};
montinf.args = tokenize(opcom, top_t);
if (montinf.args == NULL || montinf.args[0] == NULL)
{
free_vec(montinf.args);
return;
}
if (montinf.args[0][0] == '#')
{
free_vec(montinf.args);
return;
}
if (!(strcmp("push", montinf.args[0])))
{
push(top_t, line_c);
free_vec(montinf.args);
return;
}
for (i = 0; list[i].opcode; i++)
{
if (!(strcmp(list[i].opcode, montinf.args[0])))
{
list[i].f(top_t, line_c);
free_vec(montinf.args);
return;
}
}
fprintf(stderr, "L%u: unknown instruction %s\n", line_c, montinf.args[0]);
clear_all(top_t), exit(EXIT_FAILURE);
}