Skip to content

Commit 3bc5304

Browse files
author
James Brundage
committed
Formatting the AST (Fixes #166)
1 parent 65083c8 commit 3bc5304

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

Formatting/Ast.format.ps1

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Write-FormatView -TypeName 'System.Management.Automation.Language.Ast' -Action {
2+
Write-FormatViewExpression -Enumerate -Property Tokens -ControlName PSToken
3+
}

Formatting/PSToken.control.ps1

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Write-FormatView -AsControl -Name "PSToken" -TypeName "n/a" -Action {
2+
Write-FormatViewExpression -If {
3+
$_.PreviousToken -and $_.Text
4+
} -ScriptBlock {
5+
$token = $_
6+
$prevEnd = $_.PreviousToken.Start + $_.PreviousToken.Length
7+
$substring = $_.Text.Substring($prevEnd, $token.Start - $prevEnd)
8+
if ($substring) { $substring} else { ''}
9+
}
10+
11+
Write-FormatViewExpression -If {
12+
$_.Type -eq 'Comment'
13+
} -ForegroundColor Success -Property Content
14+
15+
Write-FormatViewExpression -If {
16+
$_.Type -in 'Keyword', 'String'
17+
} -ForegroundColor Verbose -Property Content
18+
19+
Write-FormatViewExpression -If {
20+
$_.Type -in 'Variable', 'Command'
21+
} -ForegroundColor Warning -ScriptBlock {
22+
$_.Content
23+
}
24+
25+
Write-FormatViewExpression -If {
26+
$_.Type -in 'Operator','GroupStart', 'GroupEnd'
27+
} -ForegroundColor Blue -Property Content
28+
29+
Write-FormatViewExpression -If {
30+
$_.Type -notin 'Comment', 'GroupStart', 'GroupEnd', 'Variable', 'Operator', 'Command','Keyword', 'String'
31+
} -Property Content
32+
}

Types/AST/get_Tokens.ps1

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
$text = $this.Extent.ToString()
2+
3+
$previousToken = $null
4+
$tokenCount = 0
5+
@(foreach ($token in [Management.Automation.PSParser]::Tokenize($text, [ref]$null)) {
6+
Add-Member NoteProperty Text $text -Force -InputObject $token
7+
Add-Member NoteProperty PreviousToken $previousToken -Force -InputObject $token
8+
if ($token.Type -in 'Variable', 'String') {
9+
$realContent = $text.Substring($token.Start, $token.Length)
10+
Add-Member NoteProperty Content $realContent -Force -InputObject $token
11+
}
12+
$previousToken = $token
13+
$tokenCount++
14+
$token
15+
})

0 commit comments

Comments
 (0)