1 // Logic for formatting types
4 #include "../stdlib/datatypes.h"
5 #include "../stdlib/stdlib.h"
6 #include "../stdlib/text.h"
10 Text_t format_type(type_ast_t *type) {
12 case VarTypeAST: return Text$from_str(Match(type, VarTypeAST)->name);
13 case PointerTypeAST: {
14 DeclareMatch(ptr, type, PointerTypeAST);
15 return Texts(ptr->is_stack ? Text("&") : Text("@"), format_type(ptr->pointed));
18 return Texts("[", format_type(Match(type, ListTypeAST)->item), "]");
21 DeclareMatch(table, type, TableTypeAST);
22 Text_t code = Texts("{", format_type(table->key));
23 if (table->value != NULL) code = Texts(code, ":", format_type(table->value));
24 if (table->default_value) {
25 OptionalText_t val = format_inline_code(table->default_value, (Table_t){});
26 assert(val.tag != TEXT_NONE);
27 code = Texts(code, "=", val);
29 return Texts(code, "}");
31 case FunctionTypeAST: {
32 DeclareMatch(func, type, FunctionTypeAST);
33 Text_t code = Texts("func(", format_inline_args(func->args, (Table_t){}));
34 if (func->ret) code = Texts(code, func->args ? Text(" -> ") : Text("-> "), format_type(func->ret));
35 return Texts(code, ")");
37 case OptionalTypeAST: {
38 return Texts(format_type(Match(type, OptionalTypeAST)->type), "?");
41 default: fail("Invalid Type AST");