forked from luiseduardohdbackup/Sporth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
100 lines (84 loc) · 2.33 KB
/
stack.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "sporth.h"
int sporth_stack_push_float(sporth_stack *stack, float val)
{
if(stack->error > 0) return SPORTH_NOTOK;
if(stack->pos <= 32) {
//printf("Pushing value %g.\n", val);
stack->pos++;
stack->stack[stack->pos - 1].fval = val;
stack->stack[stack->pos - 1].type = SPORTH_FLOAT;
return SPORTH_OK;
} else {
fprintf(stderr, "Stack limit of %d reached, cannot push float value.\n", stack->pos);
stack->error++;
return SPORTH_NOTOK;
}
return SPORTH_OK;
}
int sporth_stack_push_string(sporth_stack *stack, const char *str)
{
if(stack->error > 0) return SPORTH_NOTOK;
sporth_stack_val *pstack;
if(stack->pos <= 32) {
stack->pos++;
pstack = &stack->stack[stack->pos - 1];
strncpy(pstack->sval, str, SPORTH_MAXCHAR);
pstack->fval = strlen(str);
pstack->type = SPORTH_STRING;
return SPORTH_OK;
} else {
fprintf(stderr, "Stack limit of %d reached, cannot push float value.\n", stack->pos);
stack->error++;
return SPORTH_NOTOK;
}
return SPORTH_OK;
}
float sporth_stack_pop_float(sporth_stack *stack)
{
if(stack->error > 0) return 0;
sporth_stack_val *pstack;
if(stack->pos == 0) {
fprintf(stderr, "Stack is empty.\n");
stack->error++;
return SPORTH_NOTOK;
}
pstack = &stack->stack[stack->pos - 1];
if(pstack->type != SPORTH_FLOAT) {
fprintf(stderr, "Value is not a float.\n");
stack->error++;
return SPORTH_NOTOK;
}
stack->pos--;
return pstack->fval;
}
char * sporth_stack_pop_string(sporth_stack *stack)
{
if(stack->error > 0) return NULL;
char *str;
sporth_stack_val *pstack;
if(stack->pos == 0) {
fprintf(stderr, "Stack is empty.\n");
stack->error++;
return NULL;
}
pstack = &stack->stack[stack->pos - 1];
if(pstack->type != SPORTH_STRING) {
fprintf(stderr, "Value is not a string.\n");
stack->error++;
return NULL;
}
str = malloc(sizeof(char) * (pstack->fval + 1));
strcpy(str, pstack->sval);
stack->pos--;
return str;
}
int sporth_stack_init(sporth_stack *stack)
{
stack->pos = 0;
stack->error = 0;
return SPORTH_OK;
}