aboutsummaryrefslogtreecommitdiff
path: root/src/token.cc
blob: 6e6a3a866848eeb9b6bd0252f045f2339aa88f25 (plain)
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
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <token.h>

void
Token::init(token_type_e type, char *lexeme, unsigned int line)
{
  m_type = type;
  m_lexeme = lexeme;
  m_line = line;
  m_string = NULL;
}

char *
Token::to_string(void)
{
  unsigned int line_length = snprintf(NULL, 0, "%ul", m_line) - 1;
  unsigned int token_type_length = strlen(TOKEN_STRING[m_type]);

  unsigned int final_size
      = line_length + 2 + token_type_length + 3 + strlen(m_lexeme) + 1;

  char *result = (char *) calloc(1, final_size);
  snprintf(result,
           final_size,
           "%d: %s - %s",
           m_line,
           TOKEN_STRING[m_type],
           m_lexeme);

  m_string = result;

  return result;
}

void
Token::clean(void)
{
  if (m_string != NULL)
    free(m_string);
}