aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/antlr4_cpp_runtime/src/CommonTokenStream.cpp
blob: 02a2e55af3e541f53954a205e248a2cc38907361 (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
/* 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 "CommonTokenStream.h"

using namespace antlr4;

CommonTokenStream::CommonTokenStream(TokenSource *tokenSource) : CommonTokenStream(tokenSource, Token::DEFAULT_CHANNEL) {
}

CommonTokenStream::CommonTokenStream(TokenSource *tokenSource, size_t channel_)
: BufferedTokenStream(tokenSource), channel(channel_) {
}

ssize_t CommonTokenStream::adjustSeekIndex(size_t i) {
  return nextTokenOnChannel(i, channel);
}

Token* CommonTokenStream::LB(size_t k) {
  if (k == 0 || k > _p) {
    return nullptr;
  }

  ssize_t i = static_cast<ssize_t>(_p);
  size_t n = 1;
  // find k good tokens looking backwards
  while (n <= k) {
    // skip off-channel tokens
    i = previousTokenOnChannel(i - 1, channel);
    n++;
  }
  if (i < 0) {
    return nullptr;
  }

  return _tokens[i].get();
}

Token* CommonTokenStream::LT(ssize_t k) {
  lazyInit();
  if (k == 0) {
    return nullptr;
  }
  if (k < 0) {
    return LB(static_cast<size_t>(-k));
  }
  size_t i = _p;
  ssize_t n = 1; // we know tokens[p] is a good one
                 // find k good tokens
  while (n < k) {
    // skip off-channel tokens, but make sure to not look past EOF
    if (sync(i + 1)) {
      i = nextTokenOnChannel(i + 1, channel);
    }
    n++;
  }

  return _tokens[i].get();
}

int CommonTokenStream::getNumberOfOnChannelTokens() {
  int n = 0;
  fill();
  for (size_t i = 0; i < _tokens.size(); i++) {
    Token *t = _tokens[i].get();
    if (t->getChannel() == channel) {
      n++;
    }
    if (t->getType() == Token::EOF) {
      break;
    }
  }
  return n;
}