Skip to content

fix: preserve Scratch arithmetic semantics in identity folding - #393

Closed
HimanshuDeshbhratar wants to merge 1 commit into
aspizu:mainfrom
HimanshuDeshbhratar:fix/arithmetic-identity-folding
Closed

HimanshuDeshbhratar wants to merge 1 commit into
aspizu:mainfrom
HimanshuDeshbhratar:fix/arithmetic-identity-folding

Conversation

@HimanshuDeshbhratar

Copy link
Copy Markdown

Summary

Arithmetic identity optimizations in Pass 2 can silently change the behavior of valid Scratch programs.

The optimizer currently rewrites expressions such as:

  • 0 + x → x
  • x - 0 → x
  • x * 1 → x
  • x / 1 → x
  • 0 * x → 0

without proving that the operands are numeric.

Scratch arithmetic uses Cast.toNumber, so these transformations are not generally semantics-preserving. For example, "apple" is converted to 0 in arithmetic.

Example

onflag {
    x = "apple";
    say 0 + x;
    say x - 0;
    say x * 1;
    say x / 1;
}
```goboscript

###Tests

Added regression tests covering:

-arithmetic identities with dynamic operands
-constant folding with Scratch Cast.toNumber semantics

Validation performed:

-cargo test
-cargo clippy --all-targets
-all existing tests/* projects compile successfully

@aspizu aspizu closed this Oct 2, 2026
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.

2 participants