codegen

Module <cweb/codegen.h> — template engine (lexer, parser, codegen)

API for build time: reading .cweb-like templates, tokenization, AST, and generation of C headers and C source. Typically invoked by the CWEB CLI, but can be linked into your own build tool.

Constants

MAX_BUFFER_SIZE, MAX_TAG_NAME, MAX_ATTRIBUTE_NAME, MAX_ATTRIBUTE_VALUE


Lexer

lexer_t *cweb_lexer_create(const char *input)

  • Purpose: Creates a lexer over the template source text.
  • Parameters: input — full template content (expected null-terminated).
  • Return: heap object or NULL.

void cweb_lexer_destroy(lexer_t *lexer)

  • Purpose: Frees lexer resources.

token_t lexer_next_token(lexer_t *lexer)

  • Purpose: Returns the next token (TOKEN_HTML, TOKEN_C_CODE, variables, control structures, TOKEN_EOF, TOKEN_ERROR, …).

Parser

parser_t *cweb_parser_create(lexer_t *lexer)

  • Purpose: Binds lexer → parser with current token.

void cweb_parser_destroy(parser_t *parser)

  • Purpose: Frees parser (AST may be freed separately).

ast_node_t *cweb_parser_parse(parser_t *parser)

  • Purpose: Builds the AST root node or NULL on syntax error.

AST

ast_node_t *cweb_ast_node_create(ast_node_type_t type)

  • Purpose: New node of type (AST_HTML, AST_C_CODE, loops, conditionals, …).

void cweb_ast_node_destroy(ast_node_t *node)

  • Purpose: Recursive free of subtree.

bool cweb_ast_node_add_child(ast_node_t *parent, ast_node_t *child)

  • Purpose: Appends child node; false on failure (memory).

Code generation

bool cweb_compile_template(const char *template_file, const char *output_base)

  • Purpose: High level: reads template file and writes generated artifacts with basename output_base.
  • Return: true on success.

bool cweb_generate_header(const char *template_content, const char *header_filename)

  • Purpose: Generates only the header file from template text.

bool cweb_generate_c_file(const char *template_content, const char *c_filename, const char *header_filename)

  • Purpose: Generates the C implementation including reference to the generated header.

Security / escaping

char *cweb_escape_html(const char *input)

  • Purpose: Escapes dynamic text for safe HTML embedding.
  • Return: newly allocated string — caller must free.

bool cweb_validate_tag_name(const char *tag)

  • Purpose: Validates allowed tag names (character/length limits).

bool cweb_sanitize_c_code(const char *code)

  • Purpose: Heuristic check of embedded C code before emitting generated files.

See also

  • template.md — runtime output
  • CLI / console/build.c — how routes and templates are built