Created function for command struct initialization, fixed a couple of issues

This commit is contained in:
Dmitriy Shishkov 2021-04-16 23:53:23 +05:00
parent 12f904ef7a
commit e59754b206
No known key found for this signature in database
GPG Key ID: 7CAE12ED13853CAC
6 changed files with 30 additions and 19 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
build/
.vscode/
vgcore*

View File

@ -1,4 +1,4 @@
CFLAG=-Wall
CFLAG=-Wall -ggdb3
BUILD_DIR=build
all: build_dir stack_vm
@ -6,8 +6,8 @@ all: build_dir stack_vm
build_dir:
mkdir -p $(BUILD_DIR)
stack_vm: main.o run.o stack.o
$(CC) $(BUILD_DIR)/main.o $(BUILD_DIR)/run.o $(BUILD_DIR)/stack.o -o $(BUILD_DIR)/$@
stack_vm: main.o run.o stack.o command.o
$(CC) $(BUILD_DIR)/main.o $(BUILD_DIR)/run.o $(BUILD_DIR)/stack.o $(BUILD_DIR)/command.o -o $(BUILD_DIR)/$@
main.o:
$(CC) -c main.c $(CFLAG) -o $(BUILD_DIR)/$@
@ -21,7 +21,7 @@ stack.o:
command.o:
$(CC) -c command.c $(CFLAG) -o $(BUILD_DIR)/$@
clear:
clean:
rm -rf $(BUILD_DIR)
.PHONY: all clear
.PHONY: all clean

View File

@ -12,4 +12,17 @@ cmd_desc_t cmd_desc[] = {
{IN, 0, "IN"},
{OUT, 0, "OUT"},
#endif
{NONE, 0, "NONE"}}
{NONE, 0, "NONE"}};
command_t *command_new(cmd_code_t type, int args[])
{
command_t *cmd = (command_t *)malloc(sizeof(command_t));
cmd->code = type;
cmd->arg_v = malloc(sizeof(int) * cmd_desc[type].argc);
for (int i = 0; i < cmd_desc[type].argc; i++)
cmd->arg_v[i] = args[i];
return cmd;
}

View File

@ -1,6 +1,8 @@
#ifndef COMMAND_H
#define COMMAND_H
#include <stdlib.h>
enum command_e
{
PUSH,
@ -26,12 +28,14 @@ typedef struct
char name[10];
} cmd_desc_t;
cmd_desc_t cmd_desc[];
extern cmd_desc_t cmd_desc[];
typedef struct
{
cmd_code_t code;
int args[];
int *arg_v;
} command_t;
command_t *command_new(cmd_code_t type, int args[]);
#endif

5
run.c
View File

@ -10,6 +10,7 @@ int run(command_t **buff, stack_t *stack)
res = exec(*(buff[pos]), stack);
if (res)
break;
pos++;
}
return res;
@ -17,7 +18,7 @@ int run(command_t **buff, stack_t *stack)
int exec(command_t cmd, stack_t *stack)
{
int *res;
int *res = NULL;
switch (cmd.code)
{
@ -31,7 +32,7 @@ int exec(command_t cmd, stack_t *stack)
*/
case PUSH:
{
stack_push(stack, cmd.args[0], res);
stack_push(stack, cmd.arg_v[0], res);
if (res != NULL)
return *res;

View File

@ -2,8 +2,6 @@
stack_t *stack_new(int size, int *result)
{
result = NULL;
stack_t *stack = (stack_t *)malloc(sizeof(stack_t));
if (stack == NULL)
{
@ -26,8 +24,6 @@ stack_t *stack_new(int size, int *result)
int stack_push(stack_t *stack, int value, int *result)
{
result = NULL;
if (stack->cursor > stack->size - 1)
{
*result = 2;
@ -42,8 +38,6 @@ int stack_push(stack_t *stack, int value, int *result)
int stack_pop(stack_t *stack, int *result)
{
result = NULL;
if (stack->cursor == -1)
{
*result = 1;
@ -58,8 +52,6 @@ int stack_pop(stack_t *stack, int *result)
int stack_get(stack_t *stack, int pos, int *result)
{
result = NULL;
if (pos < 0 || pos >= stack->size)
{
*result = 1;