]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/atn/ArrayPredictionContext.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / atn / ArrayPredictionContext.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 "support/Arrays.h"
7 #include "atn/SingletonPredictionContext.h"
8
9 #include "atn/ArrayPredictionContext.h"
10
11 using namespace antlr4::atn;
12
13 ArrayPredictionContext::ArrayPredictionContext(Ref<SingletonPredictionContext> const& a)
14   : ArrayPredictionContext({ a->parent }, { a->returnState }) {
15 }
16
17 ArrayPredictionContext::ArrayPredictionContext(std::vector<Ref<PredictionContext>> const& parents_,
18                                                std::vector<size_t> const& returnStates)
19   : PredictionContext(calculateHashCode(parents_, returnStates)), parents(parents_), returnStates(returnStates) {
20     assert(parents.size() > 0);
21     assert(returnStates.size() > 0);
22 }
23
24 ArrayPredictionContext::~ArrayPredictionContext() {
25 }
26
27 bool ArrayPredictionContext::isEmpty() const {
28   // Since EMPTY_RETURN_STATE can only appear in the last position, we don't need to verify that size == 1.
29   return returnStates[0] == EMPTY_RETURN_STATE;
30 }
31
32 size_t ArrayPredictionContext::size() const {
33   return returnStates.size();
34 }
35
36 Ref<PredictionContext> ArrayPredictionContext::getParent(size_t index) const {
37   return parents[index];
38 }
39
40 size_t ArrayPredictionContext::getReturnState(size_t index) const {
41   return returnStates[index];
42 }
43
44 bool ArrayPredictionContext::operator == (PredictionContext const& o) const {
45   if (this == &o) {
46     return true;
47   }
48
49   const ArrayPredictionContext *other = dynamic_cast<const ArrayPredictionContext*>(&o);
50   if (other == nullptr || hashCode() != other->hashCode()) {
51     return false; // can't be same if hash is different
52   }
53
54   return antlrcpp::Arrays::equals(returnStates, other->returnStates) &&
55     antlrcpp::Arrays::equals(parents, other->parents);
56 }
57
58 std::string ArrayPredictionContext::toString() const {
59   if (isEmpty()) {
60     return "[]";
61   }
62
63   std::stringstream ss;
64   ss << "[";
65   for (size_t i = 0; i < returnStates.size(); i++) {
66     if (i > 0) {
67       ss << ", ";
68     }
69     if (returnStates[i] == EMPTY_RETURN_STATE) {
70       ss << "$";
71       continue;
72     }
73     ss << returnStates[i];
74     if (parents[i] != nullptr) {
75       ss << " " << parents[i]->toString();
76     } else {
77       ss << "nul";
78     }
79   }
80   ss << "]";
81   return ss.str();
82 }