-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper_functions.c
127 lines (114 loc) · 2.16 KB
/
helper_functions.c
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
118
119
120
121
122
123
124
125
126
127
#include "monty.h"
/**
* select_operation_func - select the operation to use it in stack.
*
* @op_code: operation code.
* @ln: line number.
*
* Return: function pointer for the selected function.
*/
void (*select_operation_func(char *op_code, int ln))(stack_t **, unsigned int)
{
int i, flag = 0;
instruction_t func_list[] = {
{"push", add_to_stack},
{"pall", print_all},
{"pint", print_int},
{"pop", pop},
{"swap", swap},
{"nop", nop},
{"add", add},
{NULL, NULL},
};
if (op_code[0] == '#')
return (NULL);
for (flag = 1, i = 0; func_list[i].opcode != NULL; i++)
{
if (strcmp(op_code, func_list[i].opcode) == 0)
{
flag = 0;
return (func_list[i].f);
}
}
if (flag == 1)
error(4, ln, op_code);
return (NULL);
}
/**
* valitdate_value - validate the value for push statement.
*
* @value: value to be validated.
* @line_number: line that has this value.
* @result: pointer to variable i will put result on it.
*
* Return: (0) on success, (1) on fail.
*/
int valitdate_value(char *value, int line_number, int *result)
{
int i, flag = 1;
if (value != NULL && value[0] == '-')
{
value = value + 1;
flag = -1;
}
if (value == NULL)
{
error(5, line_number);
return (0);
}
for (i = 0; value[i] != '\0'; i++)
{
if (isdigit(value[i]) == 0)
{
error(5, line_number);
return (0);
}
}
*result = atoi(value) * flag;
return (1);
}
/**
* call_func - call function.
*
* @func: function pointer.
* @op_code: operation code.
* @value: value.
* @line_number: line number.
* @mode: pointer to mode.
*
* Return: (void).
*/
void call_func(
operation_func func,
char *op_code,
char *value,
int line_number,
int *mode
)
{
int result, status;
stack_t *new_node;
if (strcmp(op_code, "push") == 0)
{
status = valitdate_value(value, line_number, &result);
if (status)
{
new_node = create_node(result);
func(&new_node, line_number);
}
else
*mode = 3;
}
else
{
if (
((head == NULL && strcmp(op_code, "pall") != 0)
&& strcmp(op_code, "nop") != 0)
|| (
(strcmp(op_code, "swap") == 0 || strcmp(op_code, "add") == 0)
&& head->next == NULL)
)
*mode = 3;
func(&head, line_number);
}
}