aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/antlr4_cpp_runtime/src/ListTokenSource.cpp
blob: 45372808e5e8153c956572c9f43100da46181345 (plain) (blame)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

#include "Token.h"
#include "CommonToken.h"
#include "CharStream.h"

#include "ListTokenSource.h"

using namespace antlr4;

ListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_) : ListTokenSource(std::move(tokens_), "") {
}

ListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_, const std::string &sourceName_)
  : tokens(std::move(tokens_)), sourceName(sourceName_) {
  InitializeInstanceFields();
  if (tokens.empty()) {
    throw "tokens cannot be null";
  }

  // Check if there is an eof token and create one if not.
  if (tokens.back()->getType() != Token::EOF) {
    Token *lastToken = tokens.back().get();
    size_t start = INVALID_INDEX;
    size_t previousStop = lastToken->getStopIndex();
    if (previousStop != INVALID_INDEX) {
      start = previousStop + 1;
    }

    size_t stop = std::max(INVALID_INDEX, start - 1);
    tokens.emplace_back((_factory->create({ this, getInputStream() }, Token::EOF, "EOF",
      Token::DEFAULT_CHANNEL, start, stop, static_cast<int>(lastToken->getLine()), lastToken->getCharPositionInLine())));
  }
}

size_t ListTokenSource::getCharPositionInLine() {
  if (i < tokens.size()) {
    return tokens[i]->getCharPositionInLine();
  }
  return 0;
}

std::unique_ptr<Token> ListTokenSource::nextToken() {
  if (i < tokens.size()) {
    return std::move(tokens[i++]);
  }
  return nullptr;
}

size_t ListTokenSource::getLine() const {
  if (i < tokens.size()) {
    return tokens[i]->getLine();
  }

  return 1;
}

CharStream *ListTokenSource::getInputStream() {
  if (i < tokens.size()) {
    return tokens[i]->getInputStream();
  } else if (!tokens.empty()) {
    return tokens.back()->getInputStream();
  }

  // no input stream information is available
  return nullptr;
}

std::string ListTokenSource::getSourceName() {
  if (sourceName != "") {
    return sourceName;
  }

  CharStream *inputStream = getInputStream();
  if (inputStream != nullptr) {
    return inputStream->getSourceName();
  }

  return "List";
}

TokenFactory<CommonToken>* ListTokenSource::getTokenFactory() {
  return _factory;
}

void ListTokenSource::InitializeInstanceFields() {
  i = 0;
  _factory = CommonTokenFactory::DEFAULT.get();
}