decl.c (1635B)
1 #include "../parser.h" 2 #include "../utils.h" 3 4 #include <stdio.h> 5 #include <string.h> 6 #include <stdbool.h> 7 #include <assert.h> 8 9 Node* 10 parse_type(Parser* par) 11 { 12 Token tok = expect(par, TOKEN_IDENT); 13 14 // @later we will resolve types later, incl. custom vs. system, allow for now 15 // 16 // const char firstChar = par->src[t.start]; 17 // if (firstChar >= 'A' && firstChar <= 'Z') { 18 // // assume this is a user type 19 // } 20 21 Node* node = calloc(1, sizeof(Node)); 22 if (node == NULL) panic("parse_type: alloc failed"); 23 node->type = NODE_TYPE; 24 node->scope = NULL; 25 node->data.ident.name = (Span) { .start = tok.start, .end = tok.end }; 26 return node; 27 } 28 29 // <TYPE> name:<IDENT> 30 Node* 31 make_param_decl(Parser* par) 32 { 33 Node* type = parse_type(par); 34 Token param_name = expect(par, TOKEN_IDENT); 35 Span ident_name = { .start = param_name.start, .end = param_name.end }; 36 Node* param = (Node*)calloc(1, sizeof(Node)); 37 if (param == NULL) panic("make_param_decl alloc failed"); 38 param->type = NODE_PARAM; 39 param->scope = NULL; 40 param->data.param.name = ident_name; 41 param->data.param.type = type; 42 return param; 43 } 44 45 NodeVec 46 parse_param_list(Parser* par) 47 { 48 NodeVec v = { 0 }; 49 if (peek(par).type == TOKEN_RPAREN) return v; // found `)` no parameters 50 51 v.cap = 4; 52 v.items = (Node**)calloc(v.cap, sizeof(Node*)); 53 54 if (v.items == NULL) panic("parse_param_list: could not alloc"); 55 56 for (;;) { 57 Node* param = make_param_decl(par); 58 59 if (v.len == v.cap) { 60 v.cap *= 2; 61 v.items = (Node**)realloc(v.items, v.cap * sizeof(Node*)); 62 } 63 64 v.items[v.len++] = param; 65 66 if (!match(par, TOKEN_COMMA)) break; // found `)` instead of `,` 67 } 68 return v; 69 }