Skip to content

Add validation for mismatched control flow words #21

@tetsuo-cpp

Description

@tetsuo-cpp

Problem

The Forth translator's control flow stack (cfStack and loopStack) lacks defensive validation when popping entries. Mismatched control flow words like IF REPEAT, THEN without IF, or BEGIN THEN will either crash on pop_back_val() (empty stack) or silently produce garbage IR (wrong tag).

Currently only LOOP checks loopStack.empty() before popping.

Expected behavior

Clear error diagnostics for malformed input, e.g.:

  • THEN without IF"THEN without matching IF"
  • REPEAT without WHILE"REPEAT without matching WHILE"
  • UNTIL without BEGIN"UNTIL without matching BEGIN"
  • ELSE without IF"ELSE without matching IF"
  • LOOP without DO → already handled

Suggested fix

  1. Add empty-stack guards before every cfStack.pop_back_val() call (similar to the existing LOOP check)
  2. Validate the popped tag matches expectations:
    • THEN/ELSE expect CFTag::Orig (from IF)
    • UNTIL expects CFTag::Dest (from BEGIN)
    • WHILE expects CFTag::Dest (from BEGIN)
    • REPEAT expects CFTag::Dest then CFTag::Orig (from WHILE)
  3. Add negative tests for each case in test/Translation/Forth/

Context

Introduced in #20 (refactor: lower control flow to cf dialect instead of scf). The cf-stack approach is correct but the validation was deferred.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions