Skip to content

fix(parser): support optional chaining on slice expressions - #945

Open
eyupcanakman wants to merge 1 commit into
expr-lang:masterfrom
eyupcanakman:fix/optional-chain-slice-822
Open

fix(parser): support optional chaining on slice expressions#945
eyupcanakman wants to merge 1 commit into
expr-lang:masterfrom
eyupcanakman:fix/optional-chain-slice-822

Conversation

@eyupcanakman

Copy link
Copy Markdown

foo?.[0:1] panics at runtime when foo is nil. Optional chaining works for member access (foo?.bar) through MemberNode.Optional + OpJumpIfNil, but SliceNode had no equivalent.

Added the same Optional + OpJumpIfNil pattern to SliceNode.

Fixes #822

@eyupcanakman
eyupcanakman force-pushed the fix/optional-chain-slice-822 branch from cf006b6 to d239381 Compare May 7, 2026 14:01

@sanmaxdev sanmaxdev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The nil case works, but this also moves concrete non-slice values past the checker. I reproduced it with let x = 1; x?.[0:1]: compilation succeeds, then execution returns cannot slice 0. Please keep concrete non-slice values as compile-time errors and add a regression case.

Comment thread checker/checker.go Outdated
case reflect.String, reflect.Array, reflect.Slice:
// ok
default:
if node.Optional {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This suppresses the checker error for every concrete non-slice type, not only nil. Since OpJumpIfNil only skips nil values, let x = 1; x?.[0:1] compiles and then fails during execution with cannot slice 0. Please preserve the compile-time error for concrete non-slice values and add a regression case.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The checker now only skips the error for a nil nature, so concrete non-slice types fail at compile time again. Regression cases are in test/issues/822.

Allow nil?.[from:to] to return nil instead of erroring with "cannot
slice unknown". Add Optional field to SliceNode, propagate it through
parser, checker, and compiler using the same pattern as MemberNode
optional chaining.

In the checker the bypass is limited to a nil nature, so a concrete
non-sliceable type is still a compile-time error, and the slice bounds
are still checked.

Fixes expr-lang#822
@eyupcanakman
eyupcanakman force-pushed the fix/optional-chain-slice-822 branch from d239381 to 8b4f396 Compare August 16, 2026 07:39
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.

Unexpected behaviour - cannot slice unkown with ?.

2 participants