Skip to content

fix: suppress false positive diagnostics for stored result references - #3

Merged
jbearak merged 1 commit into
mainfrom
stored-results-reference-false-positive
Jan 2, 2026
Merged

jbearak merged 1 commit into
mainfrom
stored-results-reference-false-positive

Conversation

@jbearak

@jbearak jbearak commented Jan 2, 2026 •

Copy link
Copy Markdown
Owner

Add detection logic to recognize Stata stored result references (r(), e(), c(), s()) within local macro reference tokens and suppress the invalid character diagnostic for these valid constructs.

Changes:

  • Add is_stored_result_reference() helper method to Analyzer
  • Modify check_token_macro_references() to skip stored result patterns
  • Add property tests for stored result detection

Stored result references like `r(values)' are valid Stata syntax for accessing return values, estimation results, system constants, and string scalars. The fix also handles nested macros and matrix subscripts.

Closes: stored-result-reference-false-positive spec

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Fixed false positives where stored result references (r(), e(), c(), s()) wrapped in backtick-apostrophe syntax were incorrectly flagged as invalid macro names. The analyzer now properly recognizes these valid Stata constructs, including nested macros and matrix subscripts, reducing diagnostic noise.

✏️ Tip: You can customize this high-level summary in your review settings.

Add detection logic to recognize Stata stored result references (r(), e(),
c(), s()) within local macro reference tokens and suppress the invalid
character diagnostic for these valid constructs.

Changes:
- Add is_stored_result_reference() helper method to Analyzer
- Modify check_token_macro_references() to skip stored result patterns
- Add property tests for stored result detection

Stored result references like `r(values)' are valid Stata syntax for
accessing return values, estimation results, system constants, and string
scalars. The fix also handles nested macros and matrix subscripts.

Closes: stored-result-reference-false-positive spec
@coderabbitai

coderabbitai Bot commented Jan 2, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces a fix for false positives where Stata stored result references (r(), e(), c(), s()) wrapped in backtick-apostrophe syntax are incorrectly flagged as invalid macro names. A new private helper method detects stored result patterns, and diagnostic logic is updated to skip invalid character checks for these valid references while preserving detection for actual invalid characters.

Changes

Cohort / File(s) Summary
Specification & Documentation
.kiro/specs/stored-result-reference-false-positive/*
Design, requirements, and task implementation documents outlining the stored result reference false positive fix, including detection logic for r/e/c/s patterns, edge cases (nested macros, matrix subscripts), and testing strategy with property-based test coverage.
Core Implementation
src/analyzer/index.ts
Adds private helper method is_stored_result_reference(content: string): boolean to detect stored result patterns with optional matrix subscripts; updates check_token_macro_references to skip invalid-macro diagnostics when references match stored result patterns.
Property-Based Tests
tests/property/stored-result-reference-detection.prop.test.ts
New test suite validating that stored result references with r/e/c/s prefixes are not flagged, invalid characters in non-stored references are still detected, and edge cases (nested macros, matrix subscripts) are handled correctly.

Poem

🐰 A rabbit hops through Stata's land,
Where r() references once seemed contraband—
But now with swift detection's might,
False positives vanish from the night,
Stored results shine, both pure and bright! 🌟

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: suppressing false positive diagnostics for stored result references in the Stata analyzer.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 17dd599 and 90a254f.

📒 Files selected for processing (5)
  • .kiro/specs/stored-result-reference-false-positive/design.md
  • .kiro/specs/stored-result-reference-false-positive/requirements.md
  • .kiro/specs/stored-result-reference-false-positive/tasks.md
  • src/analyzer/index.ts
  • tests/property/stored-result-reference-detection.prop.test.ts
🧰 Additional context used
📓 Path-based instructions (5)
src/{lexer,parser,analyzer}/**/*.ts

📄 CodeRabbit inference engine (GEMINI.md)

Use exact string comparison for Stata keywords and commands (e.g., display, if, foreach). Do NOT use toLowerCase() for keyword/command matching, as Stata is fully case-sensitive.

Files:

  • src/analyzer/index.ts
src/**/*.ts

📄 CodeRabbit inference engine (GEMINI.md)

src/**/*.ts: Use snake_case for local variables and helper functions: calculate_mean(), age_years. Use UPPER_SNAKE_CASE for constants: MAX_ITERATIONS. Include units in variable names: height_meters, time_seconds, age_years.
Prefix loop iterators and scoped variables with my_ (e.g., for (const my_participant of the_participants)), except for single-letter loop variables like i, j, k.
Use the_ prefix for arrays/vectors that exist solely for iteration (e.g., for (my_thing of the_things)). Do not use the_ for other variables.
Use underscores for array dimensions in matrix operations: matrix_ij.
Use 4 spaces indentation (unless a file already uses 2 spaces), no tabs.
Include space after commas: func(a, b, c) and space before opening parenthesis in control structures: for (let i = 0; i < 10; i++).
Enforce 80 character line limit for code, 72 characters for comments.
Match existing file/module naming conventions. In this codebase, local variables often follow snake_case with my_ / the_ prefixes, while exported APIs and class methods use camelCase (TypeScript convention).

src/**/*.ts: Use exact string comparison for Stata keywords and commands; do NOT use toLowerCase() for keyword/command matching (Stata is fully case-sensitive)
Case-insensitivity is acceptable for file extensions (.do, .DO) and LSP directives (@lsp-done-by), but NOT for Stata keywords/commands/variables/macros/program names
Use snake_case for variables/functions when adding new local helpers: calculate_mean(), age_years
Use UPPER_SNAKE_CASE for constants: MAX_ITERATIONS
Include units in variable names: height_meters, time_seconds, age_years
Prefer clear names over abbreviations: temperature > temp (common abbreviations like avg are acceptable)
Use my_ prefix for loop variables and scoped variables, except for single letter variables (i, j, k); use the_ prefix for arrays/vectors that exist solely for iteration
Use underscores for array dimensions: matrix_ij...

Files:

  • src/analyzer/index.ts
src/analyzer/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

src/analyzer/**/*.ts: Recognize c_local calls in programs to provide completions to callers, and detect macro-creating options like local() and global() in built-in commands and user-defined programs (via c_local option' and global option' patterns)
Forward reference detection: compare the reference position against the definition position; macros referenced before definition trigger warnings; positional args (0, 1...) bypass position checking; first definition wins for multiple definitions

Files:

  • src/analyzer/index.ts
tests/property/**/*.test.ts

📄 CodeRabbit inference engine (GEMINI.md)

When generating identifiers in property tests, prefer arbitrary_non_reserved_identifier() from tests/property/generators/ for positions that should not be parsed as qualifiers (e.g., varlist/expression contexts), because Stata treats if and in as qualifiers that can mislead test results.

Files:

  • tests/property/stored-result-reference-detection.prop.test.ts
tests/property/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Prefer the shared helpers arbitrary_non_reserved_identifier() and RESERVED_QUALIFIER_KEYWORDS when generating identifiers in property tests that should not be parsed as qualifiers like 'if' and 'in'

Files:

  • tests/property/stored-result-reference-detection.prop.test.ts
🧠 Learnings (6)
📚 Learning: 2026-01-02T19:17:42.555Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T19:17:42.555Z
Learning: Applies to src/analyzer/**/*.ts : Recognize c_local calls in programs to provide completions to callers, and detect macro-creating options like local() and global() in built-in commands and user-defined programs (via c_local option' and global option' patterns)

Applied to files:

  • .kiro/specs/stored-result-reference-false-positive/tasks.md
  • src/analyzer/index.ts
📚 Learning: 2026-01-02T19:17:15.152Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: GEMINI.md:0-0
Timestamp: 2026-01-02T19:17:15.152Z
Learning: Applies to src/{lexer,parser,analyzer}/**/*.ts : Use exact string comparison for Stata keywords and commands (e.g., `display`, `if`, `foreach`). Do NOT use `toLowerCase()` for keyword/command matching, as Stata is fully case-sensitive.

Applied to files:

  • .kiro/specs/stored-result-reference-false-positive/tasks.md
  • src/analyzer/index.ts
  • .kiro/specs/stored-result-reference-false-positive/design.md
  • tests/property/stored-result-reference-detection.prop.test.ts
📚 Learning: 2026-01-02T19:17:42.555Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T19:17:42.555Z
Learning: Applies to src/analyzer/**/*.ts : Forward reference detection: compare the reference position against the definition position; macros referenced before definition trigger warnings; positional args (0, 1...) bypass position checking; first definition wins for multiple definitions

Applied to files:

  • .kiro/specs/stored-result-reference-false-positive/tasks.md
  • src/analyzer/index.ts
  • .kiro/specs/stored-result-reference-false-positive/design.md
📚 Learning: 2026-01-02T19:17:42.555Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T19:17:42.555Z
Learning: Applies to src/**/*.ts : Use exact string comparison for Stata keywords and commands; do NOT use toLowerCase() for keyword/command matching (Stata is fully case-sensitive)

Applied to files:

  • .kiro/specs/stored-result-reference-false-positive/tasks.md
📚 Learning: 2026-01-02T19:17:15.152Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: GEMINI.md:0-0
Timestamp: 2026-01-02T19:17:15.152Z
Learning: Applies to tests/property/**/*.test.ts : When generating identifiers in property tests, prefer `arbitrary_non_reserved_identifier()` from tests/property/generators/ for positions that should not be parsed as qualifiers (e.g., varlist/expression contexts), because Stata treats `if` and `in` as qualifiers that can mislead test results.

Applied to files:

  • .kiro/specs/stored-result-reference-false-positive/design.md
  • tests/property/stored-result-reference-detection.prop.test.ts
📚 Learning: 2026-01-02T19:17:42.555Z
Learnt from: CR
Repo: jbearak/sight PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T19:17:42.555Z
Learning: Applies to tests/property/**/*.ts : Prefer the shared helpers arbitrary_non_reserved_identifier() and RESERVED_QUALIFIER_KEYWORDS when generating identifiers in property tests that should not be parsed as qualifiers like 'if' and 'in'

Applied to files:

  • tests/property/stored-result-reference-detection.prop.test.ts
🧬 Code graph analysis (1)
tests/property/stored-result-reference-detection.prop.test.ts (2)
src/providers/diagnostics.ts (1)
  • DiagnosticsProvider (40-1074)
src/types/index.ts (1)
  • StataLSPConfig (449-477)
🪛 LanguageTool
.kiro/specs/stored-result-reference-false-positive/design.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ... a false positive diagnostic where Stata stored result references like `` `r(valu...

(QB_NEW_EN_HYPHEN)


[style] ~134-~134: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ACRO_CHAR diagnostic is produced. 3. Property 3 Test: Generate stored result refere...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~136-~136: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...no INVALID_MACRO_CHAR diagnostic. 4. Property 4 Test: Generate stored result refere...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🪛 markdownlint-cli2 (0.18.1)
.kiro/specs/stored-result-reference-false-positive/design.md

11-11: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


96-96: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


102-102: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


108-108: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


114-114: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🔇 Additional comments (7)
src/analyzer/index.ts (2)

2242-2245: LGTM! Stored result reference skip logic is correctly placed.

The logic correctly identifies and skips stored result references before both the invalid character check and undefined macro check, aligning with the design intent to suppress false positives for valid Stata syntax.


2304-2319: LGTM! The stored result reference detection is correctly implemented.

The regex pattern /^[recs]\(.*\)(\[.*\])?$/ correctly handles:

  • Lowercase-only prefixes (r/e/c/s) per Stata case-sensitivity requirements
  • Arbitrary content inside parentheses (supports nested macros)
  • Optional matrix subscripts
  • All documented examples from the requirements

The JSDoc is comprehensive and the implementation aligns with the design specifications.

tests/property/stored-result-reference-detection.prop.test.ts (5)

18-76: LGTM! Test setup is comprehensive and follows coding guidelines.

The setup correctly:

  • Uses my_ prefix for scoped variables and the_ prefix for iteration arrays per coding guidelines
  • Provides a complete StataLSPConfig with all required fields
  • Creates appropriate mocks for DiagnosticsProvider

88-117: LGTM! Property 1 test correctly validates stored result references are not flagged.

The test:

  • Generates valid stored result patterns for all prefixes (r, e, c, s)
  • Uses arbitrary_identifier() appropriately (identifiers inside stored result parens are not parsed as qualifiers)
  • Correctly asserts no INVALID_MACRO_CHAR diagnostics are produced
  • Runs 100 iterations as specified in the design document

129-169: LGTM! Property 2 test correctly validates preservation of invalid character detection.

The test:

  • Generates macro names with invalid characters (dots, spaces, special chars)
  • Filters out stored result patterns to avoid false test failures
  • Correctly asserts that INVALID_MACRO_CHAR diagnostics are still produced for invalid names
  • Validates that the fix doesn't break existing diagnostic behavior

181-222: LGTM! Property 3 test comprehensively validates nested macro handling.

The test:

  • Covers three realistic nested macro patterns (entire identifier, suffix, prefix)
  • Correctly generates stored result references with nested macro syntax
  • Validates that nested macros do not trigger INVALID_MACRO_CHAR diagnostics
  • Aligns with Requirements 3.1 and 3.2

233-294: LGTM! Property 4 test thoroughly validates matrix subscript handling.

The test:

  • Covers both numeric subscripts [1,1] and variable subscripts with macros [1,i']`
  • Generates realistic matrix access patterns for stored results
  • Correctly asserts that matrix subscripts do not trigger INVALID_MACRO_CHAR diagnostics
  • Aligns with Requirements 4.1 and 4.2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@amazon-q-developer amazon-q-developer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This PR successfully implements a fix for false positive diagnostics when using Stata stored result references. The implementation correctly identifies stored result patterns (r(), e(), c(), s()) and suppresses invalid character diagnostics for these valid Stata constructs.

Key Changes

  • ✅ Added is_stored_result_reference() method to detect stored result patterns
  • ✅ Modified check_token_macro_references() to skip stored result references
  • ✅ Comprehensive property-based tests covering all requirements
  • ✅ Proper handling of nested macros and matrix subscripts

Issues Found

  • 🔧 Minor Logic Issue: The regex pattern uses .* which could match empty parentheses or malformed patterns. Should use .+ to ensure non-empty content.

The fix is well-designed and thoroughly tested. The only concern is a minor regex pattern issue that should be addressed to prevent edge cases with malformed stored result references.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

Comment thread src/analyzer/index.ts
Comment on lines +2317 to +2318
private is_stored_result_reference(content: string): boolean {
return /^[recs]\(.*\)(\[.*\])?$/.test(content);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛑 Logic Error: The regex pattern has a potential issue with empty parentheses handling. The current pattern /^[recs]\(.*\)(\[.*\])?$/ uses .* which matches zero or more characters, but this could incorrectly match malformed patterns like r() with empty parentheses or r( with missing closing parenthesis.

Consider making the pattern more restrictive to ensure there's actual content within the parentheses and proper balancing:

Suggested change
private is_stored_result_reference(content: string): boolean {
return /^[recs]\(.*\)(\[.*\])?$/.test(content);
private is_stored_result_reference(content: string): boolean {
return /^[recs]\(.+\)(\[.*\])?$/.test(content);
}

Comment on lines +141 to +143
.filter((my_name) => {
return !/^[recs]\(.*\)(\[.*\])?$/.test(my_name);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The regex pattern in the test duplicates the same potential issue found in the main implementation. The pattern should use .+ instead of .* to ensure non-empty content within parentheses, maintaining consistency with the fix suggested for the main implementation.

Suggested change
.filter((my_name) => {
return !/^[recs]\(.*\)(\[.*\])?$/.test(my_name);
});
.filter((my_name) => {
return !/^[recs]\(.+\)(\[.*\])?$/.test(my_name);
});

@jbearak

jbearak commented Jan 2, 2026

Copy link
Copy Markdown
Owner Author

Thanks for the review! Regarding the regex pattern suggestion:

The use of .* (allowing empty content) is intentional. In Stata, stored result references with empty parentheses like \r()'` are valid syntax. This is documented in the design document:

Empty parentheses: References like \r()'` will match the pattern and not be flagged, which is correct as Stata allows this syntax.

Stata allows r() to return all stored results as a list, so we should not flag it as invalid. The current implementation correctly handles this edge case.

@jbearak
jbearak merged commit e55e6cc into main Jan 2, 2026
@jbearak
jbearak deleted the stored-results-reference-false-positive branch January 2, 2026 20:26
jbearak added a commit that referenced this pull request Feb 11, 2026
Address all review comments from CodeRabbit, Amazon Q Developer, and Claude:

1. Amazon Q Developer (lines 462-465): Fixed logic error in command node if qualifier context detection
   - Added range check to verify operator is actually within the if qualifier range
   - Previously returned 'qualifier' for ANY operator in a command with ifExpression

2. Claude issue #2: Added missing while condition check
   - Added condition check for while nodes to properly classify C-style operators in while conditions
   - Now returns 'control_flow' context when operator is in while condition

3. Claude issue #3: Fixed incorrect classification of operators in body commands
   - Added body range check before falling through to condition check
   - Prevents operators in plain body commands from being incorrectly classified as 'control_flow'
   - Applied fix to both if/else nodes and foreach/forvalues/while/frame nodes

4. Claude issue #1: Removed unnecessary 'as' type casts
   - Removed 'as' casts from command and program nodes
   - TypeScript automatically narrows types after type checks

5. CodeRabbit issues: Fixed markdown formatting
   - Added language specifiers to fenced code blocks in design.md (typescript, markdown, text)
   - Verified pipe characters already escaped in README.md
   - Verified test config already has cStyleLogicalInControlFlow setting

All 85 operator sequence tests pass.
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.

1 participant