Files
fz-lang/src/compiler/analyzer/an_declaration.c
T

77 lines
2.4 KiB
C

#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
// Analyze variable/field/argument declaration
fzl_an_res_t analyze_declaration(fzl_analyzer_t *analyzer, fzl_node_t *decl)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!decl || decl->type != FZL_NODETYPE_DECLARATION)
{
an_push_error(analyzer, NULL, "node is not a declaration");
return (fzl_an_res_t){.error = true};
}
char *name = (char *)decl->var.identifier->token->value;
bool type_found = false;
fzl_type_t type = an_toktotype(analyzer, decl->var.type, &type_found);
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)decl->var.type->value);
an_push_error(analyzer, decl->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
char *classname = NULL;
if (type == FZL_TYPE_OBJECT)
classname = decl->var.type->value;
fzl_symtable_res_t res = fzl_symt_put(
analyzer->symbols[analyzer->symbols_top - 1], decl, name, type, 0);
if (res != FZL_SYMTABLE_RESULT_OK)
{
if (res == FZL_SYMTABLE_RESULT_EXISTS)
snprintf(an_problem, sizeof(an_problem), "'%s' already has been declared",
name);
else
snprintf(an_problem, sizeof(an_problem), "cannot store '%s'", name);
an_push_error(analyzer, decl->token, an_problem);
return (fzl_an_res_t){.error = true};
}
if (type == FZL_TYPE_OBJECT)
{
fzl_sym_t class;
bool class_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((class_found = fzl_symt_get(analyzer->symbols[i],
decl->var.type->value, &class)))
break;
}
if (!class_found || class.node->type != FZL_NODETYPE_CLASS)
{
snprintf(an_problem, sizeof(an_problem), "class '%s' does not exists",
(char *)decl->var.type->value);
an_push_error(analyzer, decl->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
fzl_symt_setobjclass(analyzer->symbols[analyzer->symbols_top - 1], name,
classname);
}
return (fzl_an_res_t){.error = false, .type = type, .classname = classname};
}