Skip to content

Fix RuleContext invariant violations in test code#40

Draft
Copilot wants to merge 2 commits intodevelopfrom
copilot/fix-rulecontext-invariant
Draft

Fix RuleContext invariant violations in test code#40
Copilot wants to merge 2 commits intodevelopfrom
copilot/fix-rulecontext-invariant

Conversation

Copy link

Copilot AI commented Feb 12, 2026

RuleContext documents that root nodes must have parent == null AND invokingState == -1, but test code was creating contexts with parent == null and invokingState >= 0, violating this invariant.

Changes

Test fixes:

  • TreesTest.java: Changed root context creation from invokingState=0 to -1 (lines 55, 170)
  • ExpectedTokensTest.java: Fixed call stack simulation to use ParserRuleContext.emptyContext() as proper root (lines 163-164, 170)

Documentation:

  • RuleContext.java: Clarified invariant applies to "actual parse tree" roots and removed TODO comments acknowledging the confusion

Example

Before:

// Violates invariant: parent=null but invokingState=0
ParserRuleContext root = new TestParserRuleContext(null, 0, 0);
ParserRuleContext callStack = new ParserRuleContext(null, 9);

After:

// Respects invariant: parent=null implies invokingState=-1
ParserRuleContext root = new TestParserRuleContext(null, -1, 0);
ParserRuleContext callStack = new ParserRuleContext(ParserRuleContext.emptyContext(), 9);

The isEmpty() method (which checks invokingState == -1) and ATN.getExpectedTokens() (which walks contexts while invokingState >= 0) now work correctly with all test contexts.

Original prompt

This section details on the original issue you should resolve

<issue_title>Нарушение инварианта класса RuleContext: parent==null, но invokingState!=-1</issue_title>
<issue_description>## Описание проблемы

В классе RuleContext документирован инвариант, согласно которому корневые узлы должны иметь parent == null И invokingState == -1. Однако, в тестовом коде обнаружены случаи нарушения этого инварианта.

Документация утверждает

Из Javadoc класса RuleContext:

  • Строка 42: "If parent is null, this should be -1"
  • Строка 36: "The root node always has a null pointer and invokingState of -1"

Обнаруженные нарушения

Найдены случаи создания контекстов с parent == null, но invokingState != -1:

  1. src/test/java/org/antlr/v4/test/tool/ExpectedTokensTest.java:163new ParserRuleContext(null, 4)
  2. src/test/java/org/antlr/v4/test/tool/ExpectedTokensTest.java:170new ParserRuleContext(null, 9)
  3. src/test/java/org/antlr/v4/runtime/tree/TreesTest.java:55new TestParserRuleContext(null, 0, 0)
  4. src/test/java/org/antlr/v4/runtime/tree/TreesTest.java:170new TestParserRuleContext(null, 0, 0)

Последствия

  1. Метод isEmpty() (строки 95-97 в RuleContext.java) проверяет только invokingState == -1, что может дать неправильный результат для контекстов с parent == null и invokingState != -1
  2. Отсутствует валидация в конструкторе, позволяющая создавать такие объекты, нарушающие инвариант
  3. Неясно, является ли это преднамеренной особенностью или багом

Необходимые действия

  1. Выяснить, почему тесты создают такие контексты и является ли это корректным поведением
  2. Если это баг в тестах — исправить тесты
  3. Если это преднамеренное поведение — обновить документацию и пересмотреть метод isEmpty() для ясности его семантики
  4. Рассмотреть добавление валидации в конструктор для обеспечения инварианта

Ссылки

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: nixel2007 <1132840+nixel2007@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix RuleContext invariant violations with parent and invokingState Fix RuleContext invariant violations in test code Feb 12, 2026
Copilot AI requested a review from nixel2007 February 12, 2026 18:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Нарушение инварианта класса RuleContext: parent==null, но invokingState!=-1

2 participants