]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/CommonTokenStream.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / CommonTokenStream.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
8 #include "CommonTokenStream.h"
9
10 using namespace antlr4;
11
12 CommonTokenStream::CommonTokenStream(TokenSource *tokenSource) : CommonTokenStream(tokenSource, Token::DEFAULT_CHANNEL) {
13 }
14
15 CommonTokenStream::CommonTokenStream(TokenSource *tokenSource, size_t channel_)
16 : BufferedTokenStream(tokenSource), channel(channel_) {
17 }
18
19 ssize_t CommonTokenStream::adjustSeekIndex(size_t i) {
20   return nextTokenOnChannel(i, channel);
21 }
22
23 Token* CommonTokenStream::LB(size_t k) {
24   if (k == 0 || k > _p) {
25     return nullptr;
26   }
27
28   ssize_t i = static_cast<ssize_t>(_p);
29   size_t n = 1;
30   // find k good tokens looking backwards
31   while (n <= k) {
32     // skip off-channel tokens
33     i = previousTokenOnChannel(i - 1, channel);
34     n++;
35   }
36   if (i < 0) {
37     return nullptr;
38   }
39
40   return _tokens[i].get();
41 }
42
43 Token* CommonTokenStream::LT(ssize_t k) {
44   lazyInit();
45   if (k == 0) {
46     return nullptr;
47   }
48   if (k < 0) {
49     return LB(static_cast<size_t>(-k));
50   }
51   size_t i = _p;
52   ssize_t n = 1; // we know tokens[p] is a good one
53                  // find k good tokens
54   while (n < k) {
55     // skip off-channel tokens, but make sure to not look past EOF
56     if (sync(i + 1)) {
57       i = nextTokenOnChannel(i + 1, channel);
58     }
59     n++;
60   }
61
62   return _tokens[i].get();
63 }
64
65 int CommonTokenStream::getNumberOfOnChannelTokens() {
66   int n = 0;
67   fill();
68   for (size_t i = 0; i < _tokens.size(); i++) {
69     Token *t = _tokens[i].get();
70     if (t->getChannel() == channel) {
71       n++;
72     }
73     if (t->getType() == Token::EOF) {
74       break;
75     }
76   }
77   return n;
78 }