Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix variable type inference precedence #18691

Merged

Conversation

MartinGC94
Copy link
Contributor

@MartinGC94 MartinGC94 commented Nov 30, 2022

PR Summary

Fixes #18689
So instead of using the first variable assignment before the cursor to infer the type, it instead takes the last variable assignment before the cursor.
Removed a condition that could never be true because the loop before it always ensures that the parent property is null.

PR Context

PR Checklist

@AndrewJoncas
Copy link

AndrewJoncas commented Nov 30, 2022

Doesn't this approach of reversing the order break this pattern of coding common to ps1 scripts?

$script = '[CmdletBinding()]

param (

    # PS1 Script Parameter

    [Parameter()]

    [hashtable]

    $ParameterName

)

 

function Verb-Noun {

    [CmdletBinding()]

    param (

        # PS1 Function Parameter

        [Parameter()]

        [string]

        $ParameterName

    )

   

}

 

$ParameterName.'

 

TabExpansion2 -inputScript $script -cursorColumn $script.Length | select -expandproperty CompletionMatches

@MartinGC94
Copy link
Contributor Author

MartinGC94 commented Nov 30, 2022

So, apparently VisitAssignmentStatement returns whatever is on the left: https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs#L977
This caused some issues in my first test [string]$TestVar = "";[hashtable]$TestVar = @{};$TestVar where the typeinference saw it like the ast returned 3 types (string, hashtable x2) which was obviously not correct. If I fix that so AssignmentStatements return nothing then it's incorrect when used inside parentheses like this: $Var1 = ($Var2 = ls) because in that case the AssignmentStatement does return something.

@SeeminglyScience What's your thoughts on this? How do I fix this properly?

GitHub
PowerShell for every system! Contribute to PowerShell/PowerShell development by creating an account on GitHub.

@MartinGC94
Copy link
Contributor Author

Doesn't this approach of reversing the order break this pattern of coding common to ps1 scripts?

Not this exact scenario because parameters are handled before variable assignments, so it will see the hashtable parameter before the other function parameter. But you are right that the approach isn't perfect. If you define a variable, and then a function like this:

[hashtable]$ParameterName=@{}
function Verb-Noun {
    [CmdletBinding()]
    param
    (
        [Parameter()]
        [string]
        $ParameterName
    )
}
$ParameterName.<Tab>

then it will see the function parameter instead of the script variable. I will need to look into that.

@MartinGC94 MartinGC94 changed the title Fix variable type inference precedence WIP: Fix variable type inference precedence Nov 30, 2022
@SeeminglyScience
Copy link
Collaborator

Mmmm tricky! I'm inclined to think that it should continue to infer the type on the RHS, but only of the closest assignment.

But then if you do

[string] $thing = 'something'
$thing = 10
$thing.<tab>

then you'll get int. And maybe that's fine but it sure doesn't feel good. The ideal thing would be if it looped through parents and looked through assignments to find the closest "declaration" but not recurse into the parent's children. That way you could avoid & { [string] $a = 10 }; $a = gci; $a.<tab> finding string.

Though even that's not necessarily perfect because then you'd miss declarations in a foreach loop. BUT you could argue that you should have the declaration outside of the loop, and it's fine to miss it in this case.

Sorry I got kind of ramble-y there, but does that make sense? Not in a "just go do that" kind of way, I'm still thinking over exactly what should be done, just kind of talking it out.

…ix type inference for variables that have the same name as unrelated parameters
@MartinGC94
Copy link
Contributor Author

I found a simple solution, just add a special case for AssignmentStatements inside ParenExpressions. On a related note, do we have an official name for this: $Var1 = ($Var2 = ls). People on the internet call it "variable squeezing" but I haven't seen any official documents with this name.

@MartinGC94 MartinGC94 changed the title WIP: Fix variable type inference precedence Fix variable type inference precedence Dec 2, 2022
@ghost ghost added the Review - Needed The PR is being reviewed label Dec 9, 2022
@ghost
Copy link

ghost commented Dec 9, 2022

This pull request has been automatically marked as Review Needed because it has been there has not been any activity for 7 days.
Maintainer, please provide feedback and/or mark it as Waiting on Author

@SeeminglyScience
Copy link
Collaborator

I found a simple solution, just add a special case for AssignmentStatements inside ParenExpressions. On a related note, do we have an official name for this: $Var1 = ($Var2 = ls). People on the internet call it "variable squeezing" but I haven't seen any official documents with this name.

So Paren can force it in scenarios where it doesn't typically happen, but it's implicit with $var1 = $var2 = ls. I'm inclined to say the best solution would be to only look at the closest assignment prior to itself if that makes sense

@pull-request-quantifier-deprecated

This PR has 22 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Small
Size       : +17 -5
Percentile : 8.8%

Total files changed: 2

Change summary by file extension:
.cs : +4 -5
.ps1 : +13 -0

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detected.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@MartinGC94
Copy link
Contributor Author

I've reverted the changes related to the assignmentstatementast type inference. I will (probably) look into fixing it in the future but it doesn't belong in this PR.

@daxian-dbw daxian-dbw added WG-Engine core PowerShell engine, interpreter, and runtime CL-Engine Indicates that a PR should be marked as an engine change in the Change Log Needs-Triage The issue is new and needs to be triaged by a work group. labels May 1, 2023
@@ -1367,6 +1367,24 @@ Describe "Type inference Tests" -tags "CI" {
$res.Name -join ' ' | Should -Be "System.IO.FileInfo System.IO.DirectoryInfo"
}

It 'Infers closest variable type' {
$res = [AstTypeInference]::InferTypeOf( { [string]$TestVar = "";[hashtable]$TestVar = @{};$TestVar }.Ast)
Copy link
Member

Choose a reason for hiding this comment

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

should there be some sort of order checking here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No. There shouldn't even be multiple inferred types but because assignments are included when inferring the output from a scriptblock I need that Select -Last 1 statement.
I tried fixing the issue earlier but it's tricky because sometimes assignments actually do output something.

@@ -2490,7 +2485,8 @@ public static bool AstAssignsToSameVariable(this VariableExpressionAst variableA
if (parameterAst != null)
{
return variableAstVariablePath.IsUnscopedVariable &&
parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase);
parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase) &&
parameterAst.Parent.Parent.Extent.EndOffset > variableAst.Extent.StartOffset;
Copy link
Member

@daxian-dbw daxian-dbw Jun 5, 2023

Choose a reason for hiding this comment

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

@MartinGC94 This change came from the commit c91e29f, which was reverted by 1289c4e. However, this change was left behind. Did you mean to revert this change as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, that was a fix for this: #18691 (comment) I was just lazy and put 2 changes in 1 commit which was clearly a bad idea 😄

@daxian-dbw daxian-dbw added Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept and removed Review - Needed The PR is being reviewed Needs-Triage The issue is new and needs to be triaged by a work group. labels Jun 5, 2023
@ghost ghost removed the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label Jun 6, 2023
Copy link
Member

@daxian-dbw daxian-dbw left a comment

Choose a reason for hiding this comment

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

LGTM

@daxian-dbw daxian-dbw merged commit f093f53 into PowerShell:master Jun 12, 2023
@ghost
Copy link

ghost commented Jun 29, 2023

🎉v7.4.0-preview.4 has been released which incorporates this pull request.:tada:

Handy links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CL-Engine Indicates that a PR should be marked as an engine change in the Change Log Extra Small WG-Engine core PowerShell engine, interpreter, and runtime
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Completion type inference infers from the first declaration in a document rather than the closest
6 participants