llm
Download
53 lines 1.9 KiBCModified 2026-08-31 raw
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
// Logic for formatting types

#include "../ast.h"
#include "../stdlib/datatypes.h"
#include "../stdlib/stdlib.h"
#include "../stdlib/table.h"
#include "../stdlib/text.h"
#include "args.h"
#include "enums.h"
#include "formatter.h"

Text_t format_type(type_ast_t *type) {
    switch (type->tag) {
    case VarTypeAST: return Text$from_str(Match(type, VarTypeAST)->name);
    case PointerTypeAST: {
        DeclareMatch(ptr, type, PointerTypeAST);
        return Texts(ptr->is_stack ? Text("&") : Text("@"), format_type(ptr->pointed));
    }
    case ListTypeAST: {
        return Texts("[", format_type(Match(type, ListTypeAST)->item), "]");
    }
    case TableTypeAST: {
        DeclareMatch(table, type, TableTypeAST);
        Text_t code = Texts("{", format_type(table->key));
        if (table->value != NULL) code = Texts(code, ":", format_type(table->value));
        if (table->default_value) {
            OptionalText_t val = format_inline_code(table->default_value, (Table_t){});
            assert(val.tag != TEXT_NONE);
            code = Texts(code, "=", val);
        }
        return Texts(code, "}");
    }
    case FunctionTypeAST: {
        DeclareMatch(func, type, FunctionTypeAST);
        Text_t code = Texts("func(", format_inline_args(func->args, (Table_t){}));
        if (func->ret) code = Texts(code, func->args ? Text(" -> ") : Text("-> "), format_type(func->ret));
        return Texts(code, ")");
    }
    case OptionalTypeAST: {
        return Texts(format_type(Match(type, OptionalTypeAST)->type), "?");
    }
    case EnumTypeAST: {
        DeclareMatch(e, type, EnumTypeAST);
        if (Text$starts_with(e->name, Text("enum$"), NULL)) {
            return Texts("enum(", format_inline_tags(e->tags, EMPTY_TABLE), ")");
        } else {
            return Texts("enum ", e->name, "(", format_inline_tags(e->tags, EMPTY_TABLE), ")");
        }
    }
    case UnknownTypeAST:
    default: fail("Invalid Type AST");
    }
}