Skip to content

Improve variable type inference#19830

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

Merged
merged 28 commits into from
Mar 13, 2025

Conversation

MartinGC94
Copy link
Contributor

@MartinGC94MartinGC94 commented Jun 20, 2023

PR Summary

Improves the type inference of variables in the following ways:

  1. Infer type from "ref" assignments, like: [System.Management.Automation.Language.Parser]::ParseFile("ls", [ref] $Tokens, [ref] $null)
  2. Infer type from the *Variable common parameters, like: New-Guid -WarningVariable MyVar
  3. Infer type for variables set by New/Set-Variable
  4. Infer type of variables set with the Data statement
  5. More accurate inference of variables assigned with the PipelineVariable common parameter (Now it correctly limits the type inference to the pipeline scope)
  6. Fix issue where the type of parameters and foreach statement variables were inferred based on the first assignment, rather than the closest
  7. Fix type inference crash when the inferred variable had a scope assigned, like: [AstTypeInference]::InferTypeOf({$Global:true}.Ast)
  8. Infer type of variables assigned with an attribute: [ValidateNotNull()]$Var1 = "Hello"
  9. Infer type of variables assigned with multiple type constraints: [int] [string] $Var1 = "10"
  10. Infers type of variables assigned with redirection: New-Guid 1>variable:RedirectedVar; $RedirectedVar

PR Context

Fixes#18759
Fixes#24205

PR Checklist

@ghostghost added the Review - Needed The PR is being reviewed label Jun 28, 2023
@ghost
Copy link

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

@StevenBucher98StevenBucher98 added the PowerShell-Docs not needed The PR was reviewed and doesn't appear to require a PowerShell Docs update label Jul 10, 2023
@pull-request-quantifier-deprecatedPull Request Quantifier (deprecated)

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


Quantification details

Label : Extra Large Size : +289 -116 Percentile : 80.17% Total files changed: 3 Change summary by file extension: .cs : +229 -116 .ps1 : +60 -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.

@MartinGC94MartinGC94 mentioned this pull request Jan 26, 2024
22 tasks
@pull-request-quantifier-deprecatedPull Request Quantifier (deprecated)

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


Quantification details

Label : Extra Large Size : +289 -116 Percentile : 80.17% Total files changed: 3 Change summary by file extension: .cs : +229 -116 .ps1 : +60 -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.

@iSazonov
Copy link
Collaborator

@MartinGC94 Is it possible to split the PR to some small ones? This would significantly speed up the review.

@microsoft-github-policy-servicemicrosoft-github-policy-servicebot removed the Review - Needed The PR is being reviewed label Feb 18, 2025
@MartinGC94
Copy link
ContributorAuthor

Not in a meaningful way. It's a new Ast visitor so we kinda need the whole thing for it to make sense.

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonoviSazonov added the CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log label Feb 18, 2025
@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonoviSazonov self-assigned this Mar 5, 2025
Co-authored-by: Ilya <darpa@yandex.ru>
// The condition itself may not be interesting if it's after the cursor, but the statement block could be.
return ast is PipelineBaseAst && ast.Parent is DoUntilStatementAst or DoWhileStatementAst
? AstVisitAction.SkipChildren
: AstVisitAction.StopVisit;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I wonder why not use VisitDoWhileStatement/VisitDoUntilStatement method directly? It would be more clear.

If SkipChildren is for condition - it is clear that we skip it, what is StopVisit for?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

It's not possible to do it from those methods because we can only tell it to continue, skip children, or stop completely. We want to skip the condition part of the loop (if it's after the variable being inferred) but we still want to process the body.

Copy link
Collaborator

Choose a reason for hiding this comment

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

My idea is that if we come in the methods we can return StopVisit but before directly call VisitStatementBlock for StatementBlockAst from Body.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

That doesn't work either. When calling VisitStatementBlock it will hit DefaultVisit which would return "Continue". Then it'd move on to the condition and hit the DefaultVisit again, and this time it will return "StopVisit" because it's after the cursor.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Then it'd move on to the condition

If we run for Body it cannot move to Condition.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

I tried it on a local build and it behaved the way I described.

Copy link
Collaborator

Choose a reason for hiding this comment

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

After further thought, I believe I can take this as a step forward. Although I am inclined to believe that a direct bypass would be more convenient, simple and extensible. I'm even inclined to think that this was originally intended.

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

Comment on lines +1521 to +1534
It 'Ignores type constraint defined outside of scope' {
$res = [AstTypeInference]::InferTypeOf(({
function Outer
{
[string] $Test = "Hello"
function Inner
{
$Test = 2
$Test
}
}
}.Ast.FindAll({param($Ast) $Ast -is [Language.VariableExpressionAst]}, $true) | Select-Object -Last 1 ))
$res.Name | Should -Be 'System.Int32'
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Will the inference work after follow swap?

It 'Ignores type constraint defined outside of scope' { $res =[AstTypeInference]::InferTypeOf(({function Outer { function Inner { $Test =2 $Test }[string] $Test="Hello" Inner } ... $res.Name|Should-Be 'System.Int32' }
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

Yes, $Test inside the Inner function will also be inferred as an int32 in this scenario because there's an assignment inside Inner so outer scope type constraints/assignments don't matter.

Copy link
Collaborator

Choose a reason for hiding this comment

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

And if we remove $Test = 2 the inference will stop?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

Yes. It would stop the search before it would reach the assignment because it's after the start of the Inner scope. This is not accurate to how PowerShell works, but trying to keep track of the variable values before each command invocation is quite difficult.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Thanks! For idea, we would need a safe interpreter.

@MartinGC94
Copy link
ContributorAuthor

@iSazonov Thanks for the approval. Is the plan to wait for MS to review it as well?

@iSazonov
Copy link
Collaborator

@MartinGC94 I need a time to check all before merge. (Remind me in a couple of days if you don't see my activity.)

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonoviSazonov enabled auto-merge (squash) March 13, 2025 09:45
@iSazonoviSazonov merged commit becdd61 into PowerShell:masterMar 13, 2025
40 of 42 checks passed
@iSazonoviSazonov removed the WG-Interactive-IntelliSense tab completion label Mar 13, 2025
@microsoft-github-policy-serviceMicrosoft GitHub Policy Service
Copy link
Contributor

microsoft-github-policy-servicebot commented Mar 13, 2025

📣 Hey @MartinGC94, how did we do? We would love to hear your feedback with the link below! 🗣️

🔗 https://aka.ms/PSRepoFeedback

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CL-GeneralIndicates that a PR should be marked as a general cmdlet change in the Change LogExtra LargePowerShell-Docs not neededThe PR was reviewed and doesn't appear to require a PowerShell Docs update
5 participants
@MartinGC94@iSazonov@doctordns@JustinGrote@StevenBucher98
close