context.cc 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <ruby_parser/context.hh>
  2. using namespace ruby_parser;
  3. using State = Context::State;
  4. std::optional<int> Context::firstIndexOfState(State state) {
  5. for (int i = 0; i < stack.size(); i++) {
  6. if (stack[i] == state) {
  7. return i;
  8. }
  9. }
  10. return std::nullopt;
  11. }
  12. std::optional<int> Context::lastIndexOfState(State state) {
  13. for (int i = stack.size() - 1; i >= 0; i--) {
  14. if (stack[i] == state) {
  15. return i;
  16. }
  17. }
  18. return std::nullopt;
  19. }
  20. bool Context::contains(State state) {
  21. return firstIndexOfState(state) != std::nullopt;
  22. }
  23. void Context::push(State state) {
  24. stack.push_back(state);
  25. }
  26. void Context::pop() {
  27. stack.pop_back();
  28. }
  29. void Context::reset() {
  30. stack.clear();
  31. }
  32. bool Context::inClass() {
  33. return !stack.empty() && stack[stack.size() - 1] == State::CLASS;
  34. }
  35. bool Context::indirectlyInDef() {
  36. return contains(State::DEF) || contains(State::DEFS);
  37. }
  38. bool Context::classDefintinionAllowed() {
  39. auto defIndex = std::max(lastIndexOfState(State::DEF), lastIndexOfState(State::DEFS));
  40. auto sclassIndex = lastIndexOfState(State::SCLASS);
  41. if (!defIndex) {
  42. return true;
  43. }
  44. return sclassIndex && defIndex && (*sclassIndex) > (*defIndex);
  45. }
  46. bool Context::moduleDefintinionAllowed() {
  47. return classDefintinionAllowed();
  48. }
  49. bool Context::dynamicConstDefintinionAllowed() {
  50. return classDefintinionAllowed();
  51. }