-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
PipeScript.ps1.psm1
271 lines (226 loc) · 10.3 KB
/
PipeScript.ps1.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
[Include('*-*')]$psScriptRoot
$transpilerNames = @(@(Get-Transpiler).DisplayName) -ne ''
$aliasList +=
[SmartAlias(Command='Use-PipeScript',Prefix='.>',PassThru)]$transpilerNames
$aliasList +=
[SmartAlias(Command='Use-PipeScript',Prefix='.<',Suffix='>',PassThru)]$transpilerNames
$pipeScriptKeywords = @(
foreach ($transpiler in Get-Transpiler) {
if ($transpiler.Metadata.'PipeScript.Keyword' -and $transpiler.DisplayName) {
$transpiler.DisplayName
}
}
)
$aliasList +=
[SmartAlias(Command='Use-PipeScript',PassThru)]$pipeScriptKeywords
$MyModule = $MyInvocation.MyCommand.ScriptBlock.Module
$aliasList +=
[GetExports("Alias")]$MyModule
try {
$ExecutionContext.SessionState.PSVariable.Set(
$MyModule.Name,
$MyModule
)
} catch {
# There is the slimmest of chances we might not be able to set the variable, because it was already constrained by something else.
# If this happens, we still want to load the module, and we still want to know, so put it out to Verbose.
Write-Verbose "Could not assign module variable: $($_ | Out-String)"
}
# If New-PSDrive exists
if ($ExecutionContext.SessionState.InvokeCommand.GetCommand('New-PSDrive', 'Cmdlet')) {
try {
# mount the module as a drive
New-PSDrive -Name $MyModule.Name -PSProvider FileSystem -Root ($MyModule.Path | Split-Path) -Description $MyModule.Description -Scope Global -ErrorAction Ignore
} catch {
Write-Verbose "Could not add drive: $($_ | Out-String)"
}
}
$typesFilePath = (Join-Path $psScriptRoot "PipeScript.types.ps1xml")
Update-TypeData -AppendPath $typesFilePath
$typesXmlNoteProperties = Select-Xml -Path $typesFilePath -XPath '//NoteProperty'
$typeAccelerators = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
foreach ($typesXmlNoteProperty in $typesXmlNoteProperties){
if ($typesXmlNoteProperty.Node.Name -notmatch '\.class\.ps1$') {
continue
}
$classScriptBlock =
try {
([scriptblock]::create($typesXmlNoteProperty.Node.Value))
} catch {
Write-Warning "Could not define '$($typesXmlNoteProperty.Node.Name)': $($_ | Out-String)"
}
if (-not $classScriptBlock) { continue }
$typeDefinitionsAst = $classScriptBlock.Ast.FindAll({param($ast) $ast -is [Management.Automation.Language.TypeDefinitionAst]}, $true)
if (-not $typeDefinitionsAst) { continue }
. $classScriptBlock
foreach ($typeDefinitionAst in $typeDefinitionsAst) {
$resolvedType = $typeDefinitionAst.Name -as [type]
if (-not $resolvedType) { continue }
$typeAccelerators::Add("$($MyModule.Name).$($typeDefinitionAst.Name)", $resolvedType)
$typeAccelerators::Add("$($typeDefinitionAst.Name)", $resolvedType)
}
}
# A few extension types we want to publish as variables
$PipeScript.Extensions |
. {
begin {
# Languages will populate `$psLanguage(s)`
$LanguagesByName = [Ordered]@{}
# Interpreters will populate `$psInterpreter(s)`
$InterpretersByName = [Ordered]@{}
# Parsers will populate `$psParsers`
$ParsersByName = [Ordered]@{}
}
process {
if ($_.Name -notlike 'Language*') {
if ($_.pstypenames -contains 'Parser.Command') {
$ParsersByName[$_.Name] = $_
}
return
}
$languageObject = & $_
if (-not $languageObject.LanguageName) {
return
}
$LanguagesByName[$languageObject.LanguageName] = $languageObject
if ($languageObject.Interpreter) {
$InterpretersByName[$languageObject.LanguageName] = $languageObject
}
}
end {
$PSLanguage = $PSLanguages = [PSCustomObject]$LanguagesByName
$PSLanguage.pstypenames.clear()
$PSLanguage.pstypenames.insert(0,'PipeScript.Languages')
$PSInterpreter = $PSInterpreters = [PSCustomObject]$InterpretersByName
$PSInterpreter.pstypenames.clear()
$PSInterpreter.pstypenames.insert(0,'PipeScript.Interpreters')
$PSParser = $PSParsers = [PSCustomObject]$ParsersByName
$PSParser.pstypenames.clear()
$PSParser.pstypenames.insert(0,'PipeScript.Parsers')
}
}
Export-ModuleMember -Function * -Alias * -Variable $MyInvocation.MyCommand.ScriptBlock.Module.Name,
'PSLanguage', 'PSLanguages',
'PSInterpreter', 'PSInterpreters',
'PSParser','PSParsers'
$PreCommandAction = {
param($LookupArgs)
if (-not $global:NewModule -or -not $global:ImportModule) {
$global:ImportModule, $global:NewModule =
$global:ExecutionContext.SessionState.InvokeCommand.GetCommands('*-Module', 'Cmdlet', $true) -match '^(?>New|Import)'
}
if (-not $global:AllFunctionsAndAliases) {
$global:AllFunctionsAndAliases =
$global:ExecutionContext.SessionState.InvokeCommand.GetCommands('*', 'Alias,Function', $true)
}
$invocationName = $LookupArgs
if ($PSInterpreters) {
$interpreterForName = $PSInterpreters.ForFile($invocationName)
if ($interpreterForName -and
-not ($global:AllFunctionsAndAliases -match $([Regex]::Escape($invocationName)))) {
foreach ($maybeInterprets in $interpreterForName) {
$adHocModule = & $newModule -ScriptBlock (
[ScriptBlock]::Create(
@(
"Set-Alias '$($invocationName -replace "'","''")' 'Invoke-Interpreter'"
"Export-ModuleMember -Alias *"
) -join ';'
)
) -Name @($invocationName -split '[\\/]')[-1] | & $importModule -Global -PassThru
$null = New-Event -SourceIdentifier "PipeScript.Interpreter.Found" -Sender $maybeInterprets -EventArguments $adHocModule, $invocationName -MessageData $adHocModule, $invocationName
return $invocationName
}
}
}
}
$global:ExecutionContext.InvokeCommand.PreCommandLookupAction = $PreCommandAction
$CommandNotFoundAction = {
param($sender, $eventArgs)
# Rather than be the only thing that can handle command not found, we start by broadcasting an event.
$null = New-Event -SourceIdentifier "PowerShell.CommandNotFound" -MessageData $eventArgs -Sender $sender -EventArguments $eventArgs
# Then we determine our own script block.
$myScriptBlock = $MyInvocation.MyCommand.ScriptBlock
# Then, we do a bit of callstack peeking
$callstack = @(Get-PSCallStack)
$myCallCount = 0
foreach ($call in $callstack) {
if ($call.InvocationInfo.MyCommand.ScriptBlock -eq $myScriptBlock) {
$myCallCount++
}
}
# If we're being called more than once
if ($myCallCount -gt 1) {
return # we're done.
}
$callstackPeek = $callstack[-1]
# When peeking in on a dynamic script block, the offsets may lie.
$column = [Math]::Max($callstackPeek.InvocationInfo.OffsetInLine, 1)
$line = [Math]::Max($callstackPeek.InvocationInfo.ScriptLineNumber, 1)
$callingScriptBlock = $callstackPeek.InvocationInfo.MyCommand.ScriptBlock
# Now find all of the AST elements at this location.
$astFound = @($callingScriptBlock.Ast.FindAll({
param($ast)
$ast.Extent.StartLineNumber -eq $line -and
$ast.Extent.StartColumnNumber -eq $column
}, $true))
if (-not $script:LastCommandNotFoundScript) {
$script:LastCommandNotFoundScript = $callingScriptBlock
} elseif ($script:LastCommandNotFoundScript -eq $callingScriptBlock) {
return
} else {
$script:LastCommandNotFoundScript = $callingScriptBlock
}
if (-not $callingScriptBlock) {
return
}
$transpiledScriptBlock =
try {
$callingScriptBlock.Transpile()
} catch {
Write-Error $_
return
}
if ($transpiledScriptBlock -and
($transpiledScriptBlock.ToString().Length -ne $callingScriptBlock.ToString().Length)) {
$endStatements = $transpiledScriptBlock.Ast.EndBlock.Statements
$FirstExpression =
if ($endStatements -and (
$endStatements[0] -is
[Management.Automation.Language.PipelineAst]
) -and (
$endStatements[0].PipelineElements[0] -is
[Management.Automation.Language.CommandExpressionAst]
)
) {
$endStatements[0].PipelineElements[0].Expression
} else { $null }
if ($astFound -and
$astFound[-1].Parent -is [Management.Automation.Language.AssignmentStatementAst] -and
(
$FirstExpression -is [Management.Automation.Language.BinaryExpressionAst] -or
$FirstExpression -is [Management.Automation.Language.ParenExpressionAst]
)
) {
Write-Error "
Will not interactively transpile {$callingScriptBlock} ( because it would overwrite $($astFound[-1].Parent.Left.Extent) )"
return
}
if ($astFound -and
$astFound[-1].Parent -is [Management.Automation.Language.AssignmentStatementAst] -and
$endStatements -and
$endStatements[0] -is [Management.Automation.Language.AssignmentStatementAst] -and
$astFound[-1].Parent.Left.ToString() -eq $endStatements[0].Left.ToString()) {
$eventArgs.CommandScriptBlock = [ScriptBlock]::Create($endStatements[0].Right.ToString())
$eventArgs.StopSearch = $true
} else {
$eventArgs.CommandScriptBlock = $transpiledScriptBlock
$eventArgs.StopSearch = $true
}
}
return
}
$global:ExecutionContext.SessionState.InvokeCommand.CommandNotFoundAction = $CommandNotFoundAction
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
$global:ExecutionContext.SessionState.InvokeCommand.CommandNotFoundAction = $null
$global:ExecutionContext.SessionState.InvokeCommand.PreCommandLookupAction = $null
}