]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/atn/SingletonPredictionContext.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / atn / SingletonPredictionContext.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 "atn/EmptyPredictionContext.h"
7
8 #include "atn/SingletonPredictionContext.h"
9
10 using namespace antlr4::atn;
11
12 SingletonPredictionContext::SingletonPredictionContext(Ref<PredictionContext> const& parent, size_t returnState)
13   : PredictionContext(parent ? calculateHashCode(parent, returnState) : calculateEmptyHashCode()),
14     parent(parent), returnState(returnState) {
15   assert(returnState != ATNState::INVALID_STATE_NUMBER);
16 }
17
18 SingletonPredictionContext::~SingletonPredictionContext() {
19 }
20
21 Ref<SingletonPredictionContext> SingletonPredictionContext::create(Ref<PredictionContext> const& parent, size_t returnState) {
22
23   if (returnState == EMPTY_RETURN_STATE && parent) {
24     // someone can pass in the bits of an array ctx that mean $
25     return std::dynamic_pointer_cast<SingletonPredictionContext>(EMPTY);
26   }
27   return std::make_shared<SingletonPredictionContext>(parent, returnState);
28 }
29
30 size_t SingletonPredictionContext::size() const {
31   return 1;
32 }
33
34 Ref<PredictionContext> SingletonPredictionContext::getParent(size_t index) const {
35   assert(index == 0);
36   ((void)(index)); // Make Release build happy.
37   return parent;
38 }
39
40 size_t SingletonPredictionContext::getReturnState(size_t index) const {
41   assert(index == 0);
42   ((void)(index)); // Make Release build happy.
43   return returnState;
44 }
45
46 bool SingletonPredictionContext::operator == (const PredictionContext &o) const {
47   if (this == &o) {
48     return true;
49   }
50
51   const SingletonPredictionContext *other = dynamic_cast<const SingletonPredictionContext*>(&o);
52   if (other == nullptr) {
53     return false;
54   }
55
56   if (this->hashCode() != other->hashCode()) {
57     return false; // can't be same if hash is different
58   }
59
60   if (returnState != other->returnState)
61     return false;
62
63   if (!parent && !other->parent)
64     return true;
65   if (!parent || !other->parent)
66     return false;
67
68    return *parent == *other->parent;
69 }
70
71 std::string SingletonPredictionContext::toString() const {
72   //std::string up = !parent.expired() ? parent.lock()->toString() : "";
73   std::string up = parent != nullptr ? parent->toString() : "";
74   if (up.length() == 0) {
75     if (returnState == EMPTY_RETURN_STATE) {
76       return "$";
77     }
78     return std::to_string(returnState);
79   }
80   return std::to_string(returnState) + " " + up;
81 }