forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenOperations.cs
More file actions
409 lines (366 loc) · 15.5 KB
/
TokenOperations.cs
File metadata and controls
409 lines (366 loc) · 15.5 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
// TODO Move all token query related methods here
/// <summary>
/// A class to encapsulate all the token querying operations.
/// </summary>
public class TokenOperations
{
private readonly Token[] tokens;
private readonly Lazy<LinkedList<Token>> tokensLL;
private readonly Ast ast;
public Ast Ast { get { return ast; } }
/// <summary>
/// Initializes the fields of the TokenOperations class.
/// </summary>
/// <param name="tokens">Tokens referring to the input AST.</param>
/// <param name="ast">AST that needs to be analyzed.</param>
public TokenOperations(Token[] tokens, Ast ast)
{
if (tokens == null)
{
throw new ArgumentNullException(nameof(tokens));
}
if (ast == null)
{
throw new ArgumentNullException(nameof(ast));
}
this.tokens = tokens;
this.ast = ast;
this.tokensLL = new Lazy<LinkedList<Token>>(() => new LinkedList<Token>(this.tokens));
}
/// <summary>
/// Return tokens of kind LCurly that begin a scriptblock expression in an command element.
///
/// E.g. Get-Process * | where { $_.Name -like "powershell" }
/// In the above example it will return the open brace following the where command.
/// </summary>
/// <returns>An enumerable of type Token</returns>
public IEnumerable<Token> GetOpenBracesInCommandElements()
{
return GetBraceInCommandElement(TokenKind.LCurly);
}
/// <summary>
/// Return tokens of kind RCurly that end a scriptblock expression in an command element.
///
/// E.g. Get-Process * | where { $_.Name -like "powershell" }
/// In the above example it will return the close brace following "powershell".
/// </summary>
/// <returns>An enumerable of type Token</returns>
public IEnumerable<Token> GetCloseBracesInCommandElements()
{
return GetBraceInCommandElement(TokenKind.RCurly);
}
/// <summary>
/// Returns pairs of associatd braces.
/// </summary>
/// <returns>Tuples of tokens such that item1 is LCurly token and item2 is RCurly token.</returns>
public IEnumerable<Tuple<Token, Token>> GetBracePairs()
{
var openBraceStack = new Stack<Token>();
IEnumerable<Ast> hashtableAsts = ast.FindAll(oneAst => oneAst is HashtableAst, searchNestedScriptBlocks: true);
foreach (var token in tokens)
{
if (token.Kind == TokenKind.LCurly)
{
openBraceStack.Push(token);
continue;
}
if (token.Kind == TokenKind.RCurly
&& openBraceStack.Count > 0)
{
bool closeBraceBelongsToHashTable = hashtableAsts.Any(hashtableAst =>
{
return hashtableAst.Extent.EndLineNumber == token.Extent.EndLineNumber
&& hashtableAst.Extent.EndColumnNumber == token.Extent.EndColumnNumber;
});
if (!closeBraceBelongsToHashTable)
{
yield return new Tuple<Token, Token>(openBraceStack.Pop(), token);
}
}
}
}
/// <summary>
/// Returns brace pairs that are on the same line.
/// </summary>
/// <returns>Tuples of tokens such that item1 is LCurly token and item2 is RCurly token.</returns>
public IEnumerable<Tuple<Token, Token>> GetBracePairsOnSameLine()
{
foreach (var bracePair in GetBracePairs())
{
if (bracePair.Item1.Extent.StartLineNumber == bracePair.Item2.Extent.StartLineNumber)
{
yield return bracePair;
}
}
}
private IEnumerable<Token> GetBraceInCommandElement(TokenKind tokenKind)
{
var cmdElemAsts = ast.FindAll(x => x is CommandElementAst && x is ScriptBlockExpressionAst, true);
if (cmdElemAsts == null)
{
yield break;
}
Func<Token, Ast, bool> predicate;
switch (tokenKind)
{
case TokenKind.LCurly:
predicate = (x, cmdElemAst) =>
x.Kind == TokenKind.LCurly && x.Extent.StartOffset == cmdElemAst.Extent.StartOffset;
break;
case TokenKind.RCurly:
predicate = (x, cmdElemAst) =>
x.Kind == TokenKind.RCurly && x.Extent.EndOffset == cmdElemAst.Extent.EndOffset;
break;
default:
throw new ArgumentException("", nameof(tokenKind));
}
foreach (var cmdElemAst in cmdElemAsts)
{
var tokenFound = tokens.FirstOrDefault(token => predicate(token, cmdElemAst));
if (tokenFound != null)
{
yield return tokenFound;
}
}
}
public static IEnumerable<Token> GetTokens(Ast outerAst, Ast innerAst, Token[] outerTokens)
{
ThrowIfNull(outerAst, nameof(outerAst));
ThrowIfNull(innerAst, nameof(innerAst));
ThrowIfNull(outerTokens, nameof(outerTokens));
// check if inner ast belongs in outerAst
var foundAst = outerAst.Find(x => x.Equals(innerAst), true);
if (foundAst == null)
{
// todo localize
throw new ArgumentException(String.Format("innerAst cannot be found within outerAst"));
}
var tokenOps = new TokenOperations(outerTokens, outerAst);
return tokenOps.GetTokens(innerAst);
}
private static void ThrowIfNull<T>(T param, string paramName)
{
if (param == null)
{
throw new ArgumentNullException(paramName);
}
}
private IEnumerable<Token> GetTokens(Ast ast)
{
int k = 0;
while (k < tokens.Length && tokens[k].Extent.EndOffset <= ast.Extent.StartOffset)
{
k++;
}
while (k < tokens.Length && tokens[k].Extent.EndOffset <= ast.Extent.EndOffset)
{
var token = tokens[k++];
if (token.Extent.StartOffset >= ast.Extent.StartOffset)
{
yield return token;
}
}
}
public IEnumerable<LinkedListNode<Token>> GetTokenNodes(TokenKind kind)
{
return GetTokenNodes((token) => token.Kind == kind);
}
public IEnumerable<LinkedListNode<Token>> GetTokenNodes(Func<Token, bool> predicate)
{
var token = tokensLL.Value.First;
while (token != null)
{
if (predicate(token.Value))
{
yield return token;
}
token = token.Next;
}
}
private IEnumerable<Tuple<Token, int>> GetTokenAndPrecedingWhitespace(TokenKind kind)
{
var lCurlyTokens = GetTokenNodes(TokenKind.LCurly);
foreach (var item in lCurlyTokens)
{
if (item.Previous == null
|| !OnSameLine(item.Previous.Value, item.Value))
{
continue;
}
yield return new Tuple<Token, int>(
item.Value,
item.Value.Extent.StartColumnNumber - item.Previous.Value.Extent.EndColumnNumber);
}
}
private bool OnSameLine(Token token1, Token token2)
{
return token1.Extent.StartLineNumber == token2.Extent.EndLineNumber;
}
/// <summary>
/// Finds the position of a given token in the AST.
/// </summary>
/// <param name="token">The <see cref="Token"/> to search for.</param>
/// <returns>The Ast node directly containing the provided <see cref="Token"/>.</returns>
public Ast GetAstPosition(Token token)
{
FindAstPositionVisitor findAstVisitor = new FindAstPositionVisitor(token.Extent.StartScriptPosition);
ast.Visit(findAstVisitor);
return findAstVisitor.AstPosition;
}
/// <summary>
/// Returns a list of non-overlapping ranges (startOffset,endOffset) representing the start
/// and end of braced member access expressions. These are member accesses where the name is
/// enclosed in braces. The contents of such braces are treated literally as a member name.
/// Altering the contents of these braces by formatting is likely to break code.
/// </summary>
public List<Tuple<int, int>> GetBracedMemberAccessRanges()
{
// A list of (startOffset, endOffset) pairs representing the start
// and end braces of braced member access expressions.
var ranges = new List<Tuple<int, int>>();
var node = tokensLL.Value.First;
while (node != null)
{
switch (node.Value.Kind)
{
#if CORECLR
// TokenKind added in PS7
case TokenKind.QuestionDot:
#endif
case TokenKind.Dot:
break;
default:
node = node.Next;
continue;
}
// Note: We don't check if the dot is part of an existing range. When we find
// a valid range, we skip all tokens inside it - so we won't ever evaluate a token
// which already part of a previously found range.
// Backward scan:
// Determine if this 'dot' is part of a member access.
// Walk left over contiguous comment tokens that are 'touching'.
// After skipping comments, the preceding non-comment token must also be 'touching'
// and one of the expected TokenKinds.
var leftToken = node.Previous;
var rightToken = node;
while (leftToken != null && leftToken.Value.Kind == TokenKind.Comment)
{
if (leftToken.Value.Extent.EndOffset != rightToken.Value.Extent.StartOffset)
{
leftToken = null;
break;
}
rightToken = leftToken;
leftToken = leftToken.Previous;
}
if (leftToken == null)
{
// We ran out of tokens before finding a non-comment token to the left or there
// was intervening whitespace.
node = node.Next;
continue;
}
if (leftToken.Value.Extent.EndOffset != rightToken.Value.Extent.StartOffset)
{
// There's whitespace between the two tokens
node = node.Next;
continue;
}
// Limit to valid token kinds that can precede a 'dot' in a member access.
switch (leftToken.Value.Kind)
{
// Note: TokenKind.Number isn't in the list as 5.{Prop} is a syntax error
// (Unexpected token). Numbers also have no properties - only methods.
case TokenKind.Variable:
case TokenKind.Identifier:
case TokenKind.StringLiteral:
case TokenKind.StringExpandable:
case TokenKind.HereStringLiteral:
case TokenKind.HereStringExpandable:
case TokenKind.RParen:
case TokenKind.RCurly:
case TokenKind.RBracket:
// allowed
break;
default:
// not allowed
node = node.Next;
continue;
}
// Forward Scan:
// Check that the next significant token is an LCurly
// Starting from the token after the 'dot', walk right skipping trivia tokens:
// - Comment
// - NewLine
// - LineContinuation (`)
// These may be multi-line and need not be 'touching' the dot.
// The first non-trivia token encountered must be an opening curly brace (LCurly) for
// this dot to begin a braced member access. If it is not LCurly or we run out
// of tokens, this dot is ignored.
var scan = node.Next;
while (scan != null)
{
if (
scan.Value.Kind == TokenKind.Comment ||
scan.Value.Kind == TokenKind.NewLine ||
scan.Value.Kind == TokenKind.LineContinuation
)
{
scan = scan.Next;
continue;
}
break;
}
// If we reached the end without finding a significant token, or if the found token
// is not LCurly, continue.
if (scan == null || scan.Value.Kind != TokenKind.LCurly)
{
node = node.Next;
continue;
}
// We have a valid token, followed by a dot, followed by an LCurly.
// Find the matching RCurly and create the range.
var lCurlyNode = scan;
// Depth count braces to find the RCurly which closes the LCurly.
int depth = 0;
LinkedListNode<Token> rcurlyNode = null;
while (scan != null)
{
if (scan.Value.Kind == TokenKind.LCurly) depth++;
else if (scan.Value.Kind == TokenKind.RCurly)
{
depth--;
if (depth == 0)
{
rcurlyNode = scan;
break;
}
}
scan = scan.Next;
}
// If we didn't find a matching RCurly, something has gone wrong.
// Should an unmatched pair be caught by the parser as a parse error?
if (rcurlyNode == null)
{
node = node.Next;
continue;
}
ranges.Add(new Tuple<int, int>(
lCurlyNode.Value.Extent.StartOffset,
rcurlyNode.Value.Extent.EndOffset
));
// Skip all tokens inside the excluded range.
node = rcurlyNode.Next;
}
return ranges;
}
}
}