]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/ListTokenSource.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / ListTokenSource.cpp
1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2  * Use of this file is governed by the BSD 3-clause license that
3  * can be found in the LICENSE.txt file in the project root.
4  */
5
6 #include "Token.h"
7 #include "CommonToken.h"
8 #include "CharStream.h"
9
10 #include "ListTokenSource.h"
11
12 using namespace antlr4;
13
14 ListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_) : ListTokenSource(std::move(tokens_), "") {
15 }
16
17 ListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_, const std::string &sourceName_)
18   : tokens(std::move(tokens_)), sourceName(sourceName_) {
19   InitializeInstanceFields();
20   if (tokens.empty()) {
21     throw "tokens cannot be null";
22   }
23
24   // Check if there is an eof token and create one if not.
25   if (tokens.back()->getType() != Token::EOF) {
26     Token *lastToken = tokens.back().get();
27     size_t start = INVALID_INDEX;
28     size_t previousStop = lastToken->getStopIndex();
29     if (previousStop != INVALID_INDEX) {
30       start = previousStop + 1;
31     }
32
33     size_t stop = std::max(INVALID_INDEX, start - 1);
34     tokens.emplace_back((_factory->create({ this, getInputStream() }, Token::EOF, "EOF",
35       Token::DEFAULT_CHANNEL, start, stop, static_cast<int>(lastToken->getLine()), lastToken->getCharPositionInLine())));
36   }
37 }
38
39 size_t ListTokenSource::getCharPositionInLine() {
40   if (i < tokens.size()) {
41     return tokens[i]->getCharPositionInLine();
42   }
43   return 0;
44 }
45
46 std::unique_ptr<Token> ListTokenSource::nextToken() {
47   if (i < tokens.size()) {
48     return std::move(tokens[i++]);
49   }
50   return nullptr;
51 }
52
53 size_t ListTokenSource::getLine() const {
54   if (i < tokens.size()) {
55     return tokens[i]->getLine();
56   }
57
58   return 1;
59 }
60
61 CharStream *ListTokenSource::getInputStream() {
62   if (i < tokens.size()) {
63     return tokens[i]->getInputStream();
64   } else if (!tokens.empty()) {
65     return tokens.back()->getInputStream();
66   }
67
68   // no input stream information is available
69   return nullptr;
70 }
71
72 std::string ListTokenSource::getSourceName() {
73   if (sourceName != "") {
74     return sourceName;
75   }
76
77   CharStream *inputStream = getInputStream();
78   if (inputStream != nullptr) {
79     return inputStream->getSourceName();
80   }
81
82   return "List";
83 }
84
85 TokenFactory<CommonToken>* ListTokenSource::getTokenFactory() {
86   return _factory;
87 }
88
89 void ListTokenSource::InitializeInstanceFields() {
90   i = 0;
91   _factory = CommonTokenFactory::DEFAULT.get();
92 }