Skip to content

Commit e0f0b50

Browse files
author
James Brundage
committed
Adding VariableExpressionAst.GetAssignments() (#155)
1 parent 0e60907 commit e0f0b50

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<#
2+
.SYNOPSIS
3+
Gets assignments of a variable
4+
.DESCRIPTION
5+
Searches the abstract syntax tree for assignments of the variable.
6+
.EXAMPLE
7+
{
8+
$x = 1
9+
$y = 2
10+
$x * $y
11+
}.Ast.EndBlock.Statements[-1].PipelineElements[0].Expression.Left.GetAssignments()
12+
.EXAMPLE
13+
{
14+
[int]$x, [int]$y = 1, 2
15+
$x * $y
16+
}.Ast.EndBlock.Statements[-1].PipelineElements[0].Expression.Left.GetAssignments()
17+
.EXAMPLE
18+
{
19+
param($x, $y)
20+
$x * $y
21+
}.Ast.EndBlock.Statements[-1].PipelineElements[0].Expression.Left.GetAssignments()
22+
#>
23+
param()
24+
25+
$astVariableName = "$this"
26+
$variableFoundAt = @{}
27+
foreach ($parent in $this.GetLineage()) {
28+
$parent.FindAll({
29+
param($ast)
30+
$IsAssignment =
31+
(
32+
$ast -is [Management.Automation.Language.AssignmentStatementAst] -and
33+
$ast.Left.Find({
34+
param($leftAst)
35+
$leftAst -is [Management.Automation.Language.VariableExpressionAST] -and
36+
$leftAst.Extent.ToString() -eq $astVariableName
37+
}, $false)
38+
) -or (
39+
$ast -is [Management.Automation.Language.ParameterAst] -and
40+
$ast.Name.ToString() -eq $astVariableName
41+
)
42+
43+
if ($IsAssignment -and -not $variableFoundAt[$ast.Extent.StartOffset]) {
44+
$variableFoundAt[$ast.Extent.StartOffset] = $ast
45+
$ast
46+
}
47+
}, $false)
48+
}

0 commit comments

Comments
 (0)