Working design

The CTPL engine is split, as most parsers, in two distinct parts: the lexer and the parser.

The lexer

The lexer is the part that reads the actual input data, and tries to create a token tree (internal representation of the input) that the parser will use.

The parser

The parser reads a token tree and an environment, and outputs the computed template.

By exposing this separation of the tasks to the user, it is possible to parse a single template many times with a different environment without needing to re-lex it, which will save computation time and resources.

Example 1. Using the library to lex and parse a template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <ctpl/ctpl.h>

/**
 * procede_template:
 * @input:  The input template, needs to be readable.
 * @env:    The environment against which parse the input.
 * @output: The output buffer, needs to be writeable.
 * @error:  Return location for an error, or %NULL to ignore them.
 * 
 * Parses and lexes a template.
 * 
 * Returns: %TRUE on success, %FALSE on error.
 */
gboolean
procede_template (MB           *input,
                  CtplEnviron  *env,
                  MB           *output,
                  GError      **error)
{
  gboolean    success = FALSE;
  CtplToken  *tree;

  /* first, create a token tree from the input template */
  tree = ctpl_lexer_lex (input, error);
  if (tree != NULL) {
    /* then, parse this tree against the environment */
    success = ctpl_parser_parse (tree, env, output, error);
  }
  /* free the built tree */
  ctpl_lexer_free_tree (tree);

  return success;
}