[go: up one dir, main page]

Skip to content

Instantly share code, notes, and snippets.

@Chubek
Created December 15, 2023 04:51
Show Gist options
  • Save Chubek/f97c665d83bcd300ff9e7b2dd38022a5 to your computer and use it in GitHub Desktop.
Save Chubek/f97c665d83bcd300ff9e7b2dd38022a5 to your computer and use it in GitHub Desktop.
Yacc Boilerplate

This is a simple YACC boilerplate you can extend on your own. It has a memory allocation table and a symbol table. Nothing else!

%{
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <signal.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/wait.h>
/*======== Memory allocation table =======*/
// This struct is a value on its own, a singly-linked list, it holds the allocation table
static struct Memory
{
struct Memory* next;
void* memv; // allocated value
size_t size; // its size
int nmem; // number of members
bool free; // whether it's freed (unused)
}
*MEMORY;
// this function is used to allocate memory and get the pointer
static inline void*
allocate_memory(void* value, int nmem, size_t size)
{
struct Memory* node = calloc(1, sizeof(*MEMORY));
node->memv = calloc(nmem, size);
node->nmem = nmem;
node->free = false;
node->next = MEMORY;
memmove(&node->memv, &value, nmem * size);
MEMORY = node;
}
// This function is used to dump the static allocation table (the allocation table is static, not the allocated values!)
static inline void
dump_memory(void)
{
for (struct Memory* mem = MEMORY;
mem != NULL;
mem = mem->next)
{
if (!mem->free)
{
free(mem->memv);
mem->free = true;}
}
}
/*======== Symbols table ========*/
// This is another list structure, it holds the symbols and their values. All symbols are strings
static struct Symtab
{
struct Symtab* next;
char* symr; // symbol representation
char* symv; // symbol value
size_t rlen; // representation length
size_t vlen; // value length
}
*SYMTAB;
// allocate a symbol in the table
static inline void
allocate_symbol(char* symr, char* symv)
{
size_t lr, lv;
lr = strlen(symr);
lv = strlen(symv);
struct Symtab* = calloc(1, sizeof(*SYMTAB));
node->symr = allocate_memory(symr, lr, 1);
node->symv = allocate_memory(symv, lv, 1);
node->rlen = lr;
node->vlen = lv;
node->next = SYMTAB;
SYMTAB = node;
}
// get the symbol back
static inline char*
get_symbol(char* symr)
{
for (struct Symtab* stab = SYMTAB;
stab != NULL;
stab = stab->next)
{
if (!strncmp(stab->symr, symr, stab->rlen))
return stab->symv;
}
return NULL;
}
%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment