Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
iSazonov merged 28 commits intoPowerShell:masterfromMartinGC94:ImproveVarInference
Mar 13, 2025

Conversation

MartinGC94
Copy link
Contributor

@MartinGC94MartinGC94 commentedJun 20, 2023
edited
Loading

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

0xfeeddeadbeef reacted with thumbs up emoji
@ghostghost added the Review - NeededThe PR is being reviewed labelJun 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 for7 days.
Maintainer, please provide feedback and/or mark it asWaiting on Author

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

This PR has405 quantified lines of changes. In general, a change size of upto200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra LargeSize       : +289 -116Percentile : 80.17%Total files changed: 3Change summary by file extension:.cs : +229 -116.ps1 : +60 -0

Change counts above are quantified counts, based on thePullRequestQuantifier 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 thecontext 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 theExcluded section from yourprquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in yourprquantifier.yaml context profile.
    • Only use the labels that matter to you,see context specification to customize yourprquantifier.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 requestJan 26, 2024
22 tasks
@pull-request-quantifier-deprecatedPull Request Quantifier (deprecated)

This PR has405 quantified lines of changes. In general, a change size of upto200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra LargeSize       : +289 -116Percentile : 80.17%Total files changed: 3Change summary by file extension:.cs : +229 -116.ps1 : +60 -0

Change counts above are quantified counts, based on thePullRequestQuantifier 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 thecontext 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 theExcluded section from yourprquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in yourprquantifier.yaml context profile.
    • Only use the labels that matter to you,see context specification to customize yourprquantifier.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 - NeededThe PR is being reviewed labelFeb 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 reacted with eyes emoji

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonoviSazonov added the CL-GeneralIndicates that a PR should be marked as a general cmdlet change in the Change Log labelFeb 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 thisMar 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 forBody it cannot move toCondition.

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 typeconstraint definedoutside ofscope'{        $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 theInner function will also be inferred as an int32 in this scenario because there's an assignment insideInner 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 theInner 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 asafe 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.)

MartinGC94 reacted with thumbs up emoji

@iSazonov

This comment was marked as outdated.

@azure-pipelinesAzure Pipelines

This comment was marked as outdated.

@iSazonoviSazonovenabled auto-merge (squash)March 13, 2025 09:45
@iSazonoviSazonov merged commitbecdd61 intoPowerShell:masterMar 13, 2025
40 of 42 checks passed
@iSazonoviSazonov removed the WG-Interactive-IntelliSensetab completion labelMar 13, 2025
@microsoft-github-policy-serviceMicrosoft GitHub Policy Service
Copy link
Contributor

microsoft-github-policy-servicebot commentedMar 13, 2025
edited by unfurl-linksbot
Loading

📣 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
Reviewers

@iSazonoviSazonoviSazonov approved these changes

@daxian-dbwdaxian-dbwAwaiting requested review from daxian-dbwdaxian-dbw is a code owner

@SeeminglyScienceSeeminglyScienceAwaiting requested review from SeeminglyScienceSeeminglyScience is a code owner

Assignees

@iSazonoviSazonov

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
Projects
None yet
Milestone
No milestone
5 participants
@MartinGC94@iSazonov@doctordns@JustinGrote@StevenBucher98

[8]ページ先頭

©2009-2025 Movatter.jp