aboutsummaryrefslogtreecommitdiff
path: root/src/token.cc
blob: ad9dd9244cab912df37b273aaf567de04270426a (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <token.h>

void
Token::init(TokenType type, char *lexeme, unsigned int line)
{
  this->type = type;
  this->lexeme = lexeme;
  this->line = line;
  this->string = NULL;
}

char *
Token::to_string(void)
{
  unsigned int line_length = snprintf(NULL, 0, "%ul", line) - 1;
  /* 2: ": ", 1: "\0" */
  unsigned int final_size = strlen(lexeme) + line_length + 2 + 1;

  char *result = (char *) calloc(1, final_size);
  snprintf(result, final_size, "%d: %s", line, lexeme);
  string = result;

  return result;
}

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