Bison Grammar for Gathering Arguments

I have a bison grammar to collect function arguments. This is what so far:

args: arg               {$$ = intArray($1);} //pseudo-code function
    | args arg          {$$ = $1 + $2;}       //pseudo-code array addition
arg : NUM               {$$ = $1;}
    | exp               {$$ = $1;}

How to create an array of integers without a fixed length that can be used like a regular C array in Bison?

+3
source share
1 answer

You can not.

However, you can create something similar using data structures.

struct vector {
     void* data;
     size_t size;
     size_t capacity
};

, , int* . realloc, . "" - , - . ( , 1 - ).

, :

struct linked_list_node {
     void* data;
     struct linked_list_node* next;
};

, int, ( , ).

. , :

struct linked_list {
     struct linked_list_node* start;
     struct linked_list_node* end;
};

.

-

args: /* empty */ {
     struct linked_list* list = malloc(sizeof(struct linked_list));
     struct linked_list_node* node = malloc(sizeof(struct linked_list_node));
     list->start = node;
     list->end = node;

     $$ = list;
}
|
args arg {
     struct linked_list_node* node = malloc(sizeof(struct linked_list_node));
     int val = $2; /* assuming arg is of type int */
     node->data = &val;

     struct linked_list* list = $1;
     list->end->next = node;
     list->end = node;

     $$ = list;
}
;

( )

, . . , , .

O(1) , ( , ). , , O(n). , , O(n) . O(1).

+3

Source: https://habr.com/ru/post/1760610/


All Articles