PowerShell icon indicating copy to clipboard operation
PowerShell copied to clipboard

Shared immutable storage for function and attributes

Open sharpchen opened this issue 2 weeks ago • 0 comments

Summary of the new feature / enhancement

Motivation

Sometimes I'd like to use same source for both validation attributes and function implementation. However pwsh doesn't allow to share them as a variable.

For example, to have a function with both tab completion and interactive completion, you have to hard-code the same candidate source twice (I know this is not a good example but demonstrates the idea)

function foo {
    param(
        [ValidateSet('foo', 'bar')] # candidates written for the first time
        $foo
    )
    if (-not $foo) {
        # hard-coded candidates again
        $foo = 'foo', 'bar' | fzf --prompt 'pick one'
    }
}

So allowing attributes to access a shared storage is needed in such case, and such storage should be readonly.

Proposed technical implementation details (optional)

Solution Proposal

The solution I can think of is to add a new named block readonly, variables declared in readonly block are immutable. Such variables should be initialized on the first invocation of the function, and should be available for attributes/scriptblock in attributes.

function foo {
    param(
        [ValidateSet($candidates)] # attributes are aware of readonly variables
        $foo
    )

    readonly {
        $candidates = 'foo', 'bar'
    }

    begin {
        if (-not $foo) {
            $foo = $candidates | fzf --prompt 'pick one'
        }
    }

    end {
        $candidates = $null # ERROR: can't mutate readonly variables
        $candidates[0] = 'baz' # ERROR: can't mutate readonly variables
    }
}

sharpchen avatar Dec 10 '25 05:12 sharpchen