From eeea75fa7820f1a7ee4958b65667d0078e01f3bd Mon Sep 17 00:00:00 2001 From: ubq323 Date: Mon, 10 Jul 2023 12:25:53 +0100 Subject: initial --- Makefile | 13 +++++++++++++ ast.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ ast.h | 39 +++++++++++++++++++++++++++++++++++++++ grammar.peg | 27 +++++++++++++++++++++++++++ 4 files changed, 125 insertions(+) create mode 100644 Makefile create mode 100644 ast.c create mode 100644 ast.h create mode 100644 grammar.peg diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..71bcbce --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +CS=parser.c ast.c +CFLAGS=-Wall -Wpedantic -std=c99 + +badthing: $(CS) + $(CC) $(CFLAGS) -o badthing $(CS) + +parser.c: grammar.peg + minipeg -o parser.c grammar.peg + +clean: + rm badthing parser.c + +.PHONY: clean diff --git a/ast.c b/ast.c new file mode 100644 index 0000000..07c0f34 --- /dev/null +++ b/ast.c @@ -0,0 +1,46 @@ +#include "ast.h" +#include +#include +#include + +AstVec astvec_new() { + AstNode *vals = malloc(2 * sizeof(AstNode)); + return (AstVec){ + .len = 0, + .cap = 2, + vals = vals + }; +} + +void astvec_append(AstVec *v, AstNode val) { + if (v->len == v->cap) { + size_t newcap = v->cap * 2; + printf("%ld to %ld\n", v->cap, newcap); + v->vals = realloc(v->vals, newcap * sizeof(AstNode)); + v->cap = newcap; + } + v->vals[v->len] = val; + v->len ++; +} + +AstNode astnode_new_num(int n) { + return (AstNode){ + .ty = AST_NUM, + .as = { + .num = n, + }, + }; +} + +AstNode astnode_new_list() { + return (AstNode){ + .ty = AST_LIST, + .as = { + .list = astvec_new() + } + }; +} + + + + diff --git a/ast.h b/ast.h new file mode 100644 index 0000000..84a3341 --- /dev/null +++ b/ast.h @@ -0,0 +1,39 @@ +#ifndef _ast_h +#define _ast_h + +#include +#include + +typedef enum { + AST_NUM, + AST_LIST, +} AstTy; + +struct _astnode; +typedef struct _astnode AstNode; + +typedef struct { + size_t len; + size_t cap; + AstNode *vals; +} AstVec; + +struct _astnode { + AstTy ty; + union { + int num; + AstVec list; + } as; +}; + + +AstVec astvec_new(); +void astvec_append(AstVec *v, AstNode val); + +AstNode astnode_new_num(int n); +AstNode astnode_new_list(); + + + + +#endif diff --git a/grammar.peg b/grammar.peg new file mode 100644 index 0000000..fc7db48 --- /dev/null +++ b/grammar.peg @@ -0,0 +1,27 @@ +%{ +#include +#include +#include "ast.h" + +AstVec numbers; +%} + + +Numberlist = ( n:NUMBER { astvec_append(&numbers, astnode_new_num(n)); } + )+ + + +NUMBER = < [0-9]+ > [ \t]* { $$ = atoi(yytext); } + +%% + +int main() { + printf("len %ld cap %ld vals %p\n", numbers.len, numbers.cap, numbers.vals); + while (yyparse()) ; + printf("len %ld cap %ld vals %p\n", numbers.len, numbers.cap, numbers.vals); + for (int i = 0; i < numbers.len; i++) { + printf("[%d] ",numbers.vals[i].as.num); + } + + return 0; +} -- cgit v1.2.3