-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Expander.cs
5213 lines (4612 loc) · 255 KB
/
Expander.cs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation.Context;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Win32;
using AvailableStaticMethods = Microsoft.Build.Internal.AvailableStaticMethods;
using ReservedPropertyNames = Microsoft.Build.Internal.ReservedPropertyNames;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using TaskItemFactory = Microsoft.Build.Execution.ProjectItemInstance.TaskItem.TaskItemFactory;
using Microsoft.NET.StringTools;
using Microsoft.Build.BackEnd.Logging;
#nullable disable
namespace Microsoft.Build.Evaluation
{
/// <summary>
/// Indicates to the expander what exactly it should expand.
/// </summary>
[Flags]
internal enum ExpanderOptions
{
/// <summary>
/// Invalid
/// </summary>
Invalid = 0x0,
/// <summary>
/// Expand bare custom metadata, like %(foo), but not built-in
/// metadata, such as %(filename) or %(identity)
/// </summary>
ExpandCustomMetadata = 0x1,
/// <summary>
/// Expand bare built-in metadata, such as %(filename) or %(identity)
/// </summary>
ExpandBuiltInMetadata = 0x2,
/// <summary>
/// Expand all bare metadata
/// </summary>
ExpandMetadata = ExpandCustomMetadata | ExpandBuiltInMetadata,
/// <summary>
/// Expand only properties
/// </summary>
ExpandProperties = 0x4,
/// <summary>
/// Expand only item list expressions
/// </summary>
ExpandItems = 0x8,
/// <summary>
/// If the expression is going to not be an empty string, break
/// out early
/// </summary>
BreakOnNotEmpty = 0x10,
/// <summary>
/// When an error occurs expanding a property, just leave it unexpanded.
/// </summary>
/// <remarks>
/// This should only be used in cases where property evaluation isn't critcal, such as when attempting to log a
/// message with a best effort expansion of a string, or when discovering partial information during lazy evaluation.
/// </remarks>
LeavePropertiesUnexpandedOnError = 0x20,
/// <summary>
/// When an expansion occurs, truncate it to Expander.DefaultTruncationCharacterLimit or Expander.DefaultTruncationItemLimit.
/// </summary>
Truncate = 0x40,
/// <summary>
/// Expand only properties and then item lists
/// </summary>
ExpandPropertiesAndItems = ExpandProperties | ExpandItems,
/// <summary>
/// Expand only bare metadata and then properties
/// </summary>
ExpandPropertiesAndMetadata = ExpandMetadata | ExpandProperties,
/// <summary>
/// Expand only bare custom metadata and then properties
/// </summary>
ExpandPropertiesAndCustomMetadata = ExpandCustomMetadata | ExpandProperties,
/// <summary>
/// Expand bare metadata, then properties, then item expressions
/// </summary>
ExpandAll = ExpandMetadata | ExpandProperties | ExpandItems
}
/// <summary>
/// Expands item/property/metadata in expressions.
/// Encapsulates the data necessary for expansion.
/// </summary>
/// <remarks>
/// Requires the caller to explicitly state what they wish to expand at the point of expansion (explicitly does not have a field for ExpanderOptions).
/// Callers typically use a single expander in many locations, and this forces the caller to make explicit what they wish to expand at the point of expansion.
///
/// Requires the caller to have previously provided the necessary material for the expansion requested.
/// For example, if the caller requests ExpanderOptions.ExpandItems, the Expander will throw if it was not given items.
/// </remarks>
/// <typeparam name="P">Type of the properties used.</typeparam>
/// <typeparam name="I">Type of the items used.</typeparam>
internal class Expander<P, I>
where P : class, IProperty
where I : class, IItem
{
/// <summary>
/// A helper struct wrapping a <see cref="SpanBasedStringBuilder"/> and providing file path conversion
/// as used in e.g. property expansion.
/// </summary>
/// <remarks>
/// If exactly one value is added and no concatenation takes places, this value is returned without
/// conversion. In other cases values are stringified and attempted to be interpreted as file paths
/// before concatenation.
/// </remarks>
private struct SpanBasedConcatenator : IDisposable
{
/// <summary>
/// The backing <see cref="SpanBasedStringBuilder"/>, null until the second value is added.
/// </summary>
private SpanBasedStringBuilder _builder;
/// <summary>
/// The first value added to the concatenator. Tracked in its own field so it can be returned
/// without conversion if no concatenation takes place.
/// </summary>
private object _firstObject;
/// <summary>
/// The first value added to the concatenator if it is a span. Tracked in its own field so the
/// <see cref="SpanBasedStringBuilder"/> functionality doesn't have to be invoked if no concatenation
/// takes place.
/// </summary>
private ReadOnlyMemory<char> _firstSpan;
/// <summary>
/// True if this instance is already disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Adds an object to be concatenated.
/// </summary>
public void Add(object obj)
{
CheckDisposed();
FlushFirstValueIfNeeded();
if (_builder != null)
{
_builder.Append(FileUtilities.MaybeAdjustFilePath(obj.ToString()));
}
else
{
_firstObject = obj;
}
}
/// <summary>
/// Adds a span to be concatenated.
/// </summary>
public void Add(ReadOnlyMemory<char> span)
{
CheckDisposed();
FlushFirstValueIfNeeded();
if (_builder != null)
{
_builder.Append(FileUtilities.MaybeAdjustFilePath(span));
}
else
{
_firstSpan = span;
}
}
/// <summary>
/// Returns the result of the concatenation.
/// </summary>
/// <returns>
/// If only one value has been added and it is not a string, it is returned unchanged.
/// In all other cases (no value, one string value, multiple values) the result is a
/// concatenation of the string representation of the values, each additionally subjected
/// to file path adjustment.
/// </returns>
public object GetResult()
{
CheckDisposed();
if (_firstObject != null)
{
return (_firstObject is string stringValue) ? FileUtilities.MaybeAdjustFilePath(stringValue) : _firstObject;
}
return _firstSpan.IsEmpty
? _builder?.ToString() ?? string.Empty
: FileUtilities.MaybeAdjustFilePath(_firstSpan).ToString();
}
/// <summary>
/// Disposes of the struct by delegating the call to the underlying <see cref="SpanBasedStringBuilder"/>.
/// </summary>
public void Dispose()
{
CheckDisposed();
_builder?.Dispose();
_disposed = true;
}
/// <summary>
/// Throws <see cref="ObjectDisposedException"/> if this concatenator is already disposed.
/// </summary>
private void CheckDisposed() =>
ErrorUtilities.VerifyThrowObjectDisposed(!_disposed, nameof(SpanBasedConcatenator));
/// <summary>
/// Lazily initializes <see cref="_builder"/> and populates it with the first value
/// when the second value is being added.
/// </summary>
private void FlushFirstValueIfNeeded()
{
if (_firstObject != null)
{
_builder = Strings.GetSpanBasedStringBuilder();
_builder.Append(FileUtilities.MaybeAdjustFilePath(_firstObject.ToString()));
_firstObject = null;
}
else if (!_firstSpan.IsEmpty)
{
_builder = Strings.GetSpanBasedStringBuilder();
#if FEATURE_SPAN
_builder.Append(FileUtilities.MaybeAdjustFilePath(_firstSpan));
#else
_builder.Append(FileUtilities.MaybeAdjustFilePath(_firstSpan.ToString()));
#endif
_firstSpan = new ReadOnlyMemory<char>();
}
}
}
/// <summary>
/// A limit for truncating string expansions within an evaluated Condition. Properties, item metadata, or item groups will be truncated to N characters such as 'N...'.
/// Enabled by ExpanderOptions.Truncate.
/// </summary>
private const int CharacterLimitPerExpansion = 1024;
/// <summary>
/// A limit for truncating string expansions for item groups within an evaluated Condition. N items will be evaluated such as 'A;B;C;...'.
/// Enabled by ExpanderOptions.Truncate.
/// </summary>
private const int ItemLimitPerExpansion = 3;
private static readonly char[] s_singleQuoteChar = { '\'' };
private static readonly char[] s_backtickChar = { '`' };
private static readonly char[] s_doubleQuoteChar = { '"' };
/// <summary>
/// Those characters which indicate that an expression may contain expandable
/// expressions.
/// </summary>
private static char[] s_expandableChars = { '$', '%', '@' };
/// <summary>
/// The CultureInfo from the invariant culture. Used to avoid allocations for
/// perfoming IndexOf etc.
/// </summary>
private static CompareInfo s_invariantCompareInfo = CultureInfo.InvariantCulture.CompareInfo;
/// <summary>
/// Properties to draw on for expansion.
/// </summary>
private IPropertyProvider<P> _properties;
/// <summary>
/// Items to draw on for expansion.
/// </summary>
private IItemProvider<I> _items;
/// <summary>
/// Metadata to draw on for expansion.
/// </summary>
private IMetadataTable _metadata;
/// <summary>
/// Set of properties which are null during expansion.
/// </summary>
private UsedUninitializedProperties _usedUninitializedProperties;
private readonly IFileSystem _fileSystem;
/// <summary>
/// Non-null if the expander was constructed for evaluation.
/// </summary>
internal EvaluationContext EvaluationContext { get; }
/// <summary>
/// Creates an expander passing it some properties to use.
/// Properties may be null.
/// </summary>
internal Expander(IPropertyProvider<P> properties, IFileSystem fileSystem)
{
_properties = properties;
_usedUninitializedProperties = new UsedUninitializedProperties();
_fileSystem = fileSystem;
}
/// <summary>
/// Creates an expander passing it some properties to use and the evaluation context.
/// Properties may be null.
/// </summary>
internal Expander(IPropertyProvider<P> properties, EvaluationContext evaluationContext)
{
_properties = properties;
_usedUninitializedProperties = new UsedUninitializedProperties();
_fileSystem = evaluationContext.FileSystem;
EvaluationContext = evaluationContext;
}
/// <summary>
/// Creates an expander passing it some properties and items to use.
/// Either or both may be null.
/// </summary>
internal Expander(IPropertyProvider<P> properties, IItemProvider<I> items, IFileSystem fileSystem)
: this(properties, fileSystem)
{
_items = items;
}
/// <summary>
/// Creates an expander passing it some properties and items to use, and the evaluation context.
/// Either or both may be null.
/// </summary>
internal Expander(IPropertyProvider<P> properties, IItemProvider<I> items, EvaluationContext evaluationContext)
: this(properties, evaluationContext)
{
_items = items;
}
/// <summary>
/// Creates an expander passing it some properties, items, and/or metadata to use.
/// Any or all may be null.
/// </summary>
internal Expander(IPropertyProvider<P> properties, IItemProvider<I> items, IMetadataTable metadata, IFileSystem fileSystem)
: this(properties, items, fileSystem)
{
_metadata = metadata;
}
/// <summary>
/// Whether to warn when we set a property for the first time, after it was previously used.
/// Default is false, unless MSBUILDWARNONUNINITIALIZEDPROPERTY is set.
/// </summary>
internal bool WarnForUninitializedProperties
{
get { return _usedUninitializedProperties.Warn; }
set { _usedUninitializedProperties.Warn = value; }
}
/// <summary>
/// Accessor for the metadata.
/// Set temporarily during item metadata evaluation.
/// </summary>
internal IMetadataTable Metadata
{
get { return _metadata; }
set { _metadata = value; }
}
/// <summary>
/// If a property is expanded but evaluates to null then it is considered to be un-initialized.
/// We want to keep track of these properties so that we can warn if the property gets set later on.
/// </summary>
internal UsedUninitializedProperties UsedUninitializedProperties
{
get { return _usedUninitializedProperties; }
set { _usedUninitializedProperties = value; }
}
/// <summary>
/// Tests to see if the expression may contain expandable expressions, i.e.
/// contains $, % or @.
/// </summary>
internal static bool ExpressionMayContainExpandableExpressions(string expression)
{
return expression.IndexOfAny(s_expandableChars) > -1;
}
/// <summary>
/// Returns true if the expression contains an item vector pattern, else returns false.
/// Used to flag use of item expressions where they are illegal.
/// </summary>
internal static bool ExpressionContainsItemVector(string expression)
{
List<ExpressionShredder.ItemExpressionCapture> transforms = ExpressionShredder.GetReferencedItemExpressions(expression);
return transforms != null;
}
/// <summary>
/// Expands embedded item metadata, properties, and embedded item lists (in that order) as specified in the provided options.
/// This is the standard form. Before using the expanded value, it must be unescaped, and this does that for you.
///
/// If ExpanderOptions.BreakOnNotEmpty was passed, expression was going to be non-empty, and it broke out early, returns null. Otherwise the result can be trusted.
/// </summary>
internal string ExpandIntoStringAndUnescape(string expression, ExpanderOptions options, IElementLocation elementLocation, LoggingContext loggingContext = null)
{
string result = ExpandIntoStringLeaveEscaped(expression, options, elementLocation, loggingContext);
return (result == null) ? null : EscapingUtilities.UnescapeAll(result);
}
/// <summary>
/// Expands embedded item metadata, properties, and embedded item lists (in that order) as specified in the provided options.
/// Use this form when the result is going to be processed further, for example by matching against the file system,
/// so literals must be distinguished, and you promise to unescape after that.
///
/// If ExpanderOptions.BreakOnNotEmpty was passed, expression was going to be non-empty, and it broke out early, returns null. Otherwise the result can be trusted.
/// </summary>
internal string ExpandIntoStringLeaveEscaped(string expression, ExpanderOptions options, IElementLocation elementLocation, LoggingContext loggingContext = null)
{
if (expression.Length == 0)
{
return String.Empty;
}
ErrorUtilities.VerifyThrowInternalNull(elementLocation, nameof(elementLocation));
string result = MetadataExpander.ExpandMetadataLeaveEscaped(expression, _metadata, options, elementLocation);
result = PropertyExpander<P>.ExpandPropertiesLeaveEscaped(result, _properties, options, elementLocation, _usedUninitializedProperties, _fileSystem, loggingContext);
result = ItemExpander.ExpandItemVectorsIntoString<I>(this, result, _items, options, elementLocation);
result = FileUtilities.MaybeAdjustFilePath(result);
return result;
}
/// <summary>
/// Used only for unit tests. Expands the property expression (including any metadata expressions) and returns
/// the result typed (i.e. not converted into a string if the result is a function return).
/// </summary>
internal object ExpandPropertiesLeaveTypedAndEscaped(string expression, ExpanderOptions options, IElementLocation elementLocation)
{
if (expression.Length == 0)
{
return String.Empty;
}
ErrorUtilities.VerifyThrowInternalNull(elementLocation, nameof(elementLocation));
string metaExpanded = MetadataExpander.ExpandMetadataLeaveEscaped(expression, _metadata, options, elementLocation);
return PropertyExpander<P>.ExpandPropertiesLeaveTypedAndEscaped(metaExpanded, _properties, options, elementLocation, _usedUninitializedProperties, _fileSystem);
}
/// <summary>
/// Expands embedded item metadata, properties, and embedded item lists (in that order) as specified in the provided options,
/// then splits on semi-colons into a list of strings.
/// Use this form when the result is going to be processed further, for example by matching against the file system,
/// so literals must be distinguished, and you promise to unescape after that.
/// </summary>
internal SemiColonTokenizer ExpandIntoStringListLeaveEscaped(string expression, ExpanderOptions options, IElementLocation elementLocation, LoggingContext loggingContext = null)
{
ErrorUtilities.VerifyThrow((options & ExpanderOptions.BreakOnNotEmpty) == 0, "not supported");
return ExpressionShredder.SplitSemiColonSeparatedList(ExpandIntoStringLeaveEscaped(expression, options, elementLocation, loggingContext));
}
/// <summary>
/// Expands embedded item metadata, properties, and embedded item lists (in that order) as specified in the provided options
/// and produces a list of TaskItems.
/// If the expression is empty, returns an empty list.
/// If ExpanderOptions.BreakOnNotEmpty was passed, expression was going to be non-empty, and it broke out early, returns null. Otherwise the result can be trusted.
/// </summary>
internal IList<TaskItem> ExpandIntoTaskItemsLeaveEscaped(string expression, ExpanderOptions options, IElementLocation elementLocation)
{
return ExpandIntoItemsLeaveEscaped(expression, (IItemFactory<I, TaskItem>)TaskItemFactory.Instance, options, elementLocation);
}
/// <summary>
/// Expands embedded item metadata, properties, and embedded item lists (in that order) as specified in the provided options
/// and produces a list of items of the type for which it was specialized.
/// If the expression is empty, returns an empty list.
/// If ExpanderOptions.BreakOnNotEmpty was passed, expression was going to be non-empty, and it broke out early, returns null. Otherwise the result can be trusted.
///
/// Use this form when the result is going to be processed further, for example by matching against the file system,
/// so literals must be distinguished, and you promise to unescape after that.
/// </summary>
/// <typeparam name="T">Type of items to return.</typeparam>
internal IList<T> ExpandIntoItemsLeaveEscaped<T>(string expression, IItemFactory<I, T> itemFactory, ExpanderOptions options, IElementLocation elementLocation)
where T : class, IItem
{
if (expression.Length == 0)
{
return Array.Empty<T>();
}
ErrorUtilities.VerifyThrowInternalNull(elementLocation, nameof(elementLocation));
expression = MetadataExpander.ExpandMetadataLeaveEscaped(expression, _metadata, options, elementLocation);
expression = PropertyExpander<P>.ExpandPropertiesLeaveEscaped(expression, _properties, options, elementLocation, _usedUninitializedProperties, _fileSystem);
expression = FileUtilities.MaybeAdjustFilePath(expression);
List<T> result = new List<T>();
if (expression.Length == 0)
{
return result;
}
var splits = ExpressionShredder.SplitSemiColonSeparatedList(expression);
foreach (string split in splits)
{
bool isTransformExpression;
IList<T> itemsToAdd = ItemExpander.ExpandSingleItemVectorExpressionIntoItems<I, T>(this, split, _items, itemFactory, options, false /* do not include null items */, out isTransformExpression, elementLocation);
if ((itemsToAdd == null /* broke out early non empty */ || (itemsToAdd.Count > 0)) && (options & ExpanderOptions.BreakOnNotEmpty) != 0)
{
return null;
}
if (itemsToAdd != null)
{
result.AddRange(itemsToAdd);
}
else
{
// The expression is not of the form @(itemName). Therefore, just
// treat it as a string, and create a new item from that string.
T itemToAdd = itemFactory.CreateItem(split, elementLocation.File);
result.Add(itemToAdd);
}
}
return result;
}
/// <summary>
/// This is a specialized method for the use of TargetUpToDateChecker and Evaluator.EvaluateItemXml only.
///
/// Extracts the items in the given SINGLE item vector.
/// For example, expands @(Compile->'%(foo)') to a set of items derived from the items in the "Compile" list.
///
/// If there is in fact more than one vector in the expression, throws InvalidProjectFileException.
///
/// If there are no item expressions in the expression (for example a literal "foo.cpp"), returns null.
/// If expression expands to no items, returns an empty list.
/// If item expansion is not allowed by the provided options, returns null.
/// If ExpanderOptions.BreakOnNotEmpty was passed, expression was going to be non-empty, and it broke out early, returns null. Otherwise the result can be trusted.
///
/// If the expression is a transform, any transformations to an expression that evaluates to nothing (i.e., because
/// an item has no value for a piece of metadata) are optionally indicated with a null entry in the list. This means
/// that the length of the returned list is always the same as the length of the referenced item list in the input string.
/// That's important for any correlation the caller wants to do.
///
/// If expression was a transform, 'isTransformExpression' is true, otherwise false.
///
/// Item type of the items returned is determined by the IItemFactory passed in; if the IItemFactory does not
/// have an item type set on it, it will be given the item type of the item vector to use.
/// </summary>
/// <typeparam name="T">Type of the items that should be returned.</typeparam>
internal IList<T> ExpandSingleItemVectorExpressionIntoItems<T>(string expression, IItemFactory<I, T> itemFactory, ExpanderOptions options, bool includeNullItems, out bool isTransformExpression, IElementLocation elementLocation)
where T : class, IItem
{
if (expression.Length == 0)
{
isTransformExpression = false;
return Array.Empty<T>();
}
ErrorUtilities.VerifyThrowInternalNull(elementLocation, nameof(elementLocation));
return ItemExpander.ExpandSingleItemVectorExpressionIntoItems(this, expression, _items, itemFactory, options, includeNullItems, out isTransformExpression, elementLocation);
}
internal static ExpressionShredder.ItemExpressionCapture ExpandSingleItemVectorExpressionIntoExpressionCapture(
string expression, ExpanderOptions options, IElementLocation elementLocation)
{
return ItemExpander.ExpandSingleItemVectorExpressionIntoExpressionCapture(expression, options, elementLocation);
}
internal IList<T> ExpandExpressionCaptureIntoItems<S, T>(
ExpressionShredder.ItemExpressionCapture expressionCapture, IItemProvider<S> items, IItemFactory<S, T> itemFactory,
ExpanderOptions options, bool includeNullEntries, out bool isTransformExpression, IElementLocation elementLocation)
where S : class, IItem
where T : class, IItem
{
return ItemExpander.ExpandExpressionCaptureIntoItems<S, T>(expressionCapture, this, items, itemFactory, options,
includeNullEntries, out isTransformExpression, elementLocation);
}
internal bool ExpandExpressionCapture(
ExpressionShredder.ItemExpressionCapture expressionCapture,
IElementLocation elementLocation,
ExpanderOptions options,
bool includeNullEntries,
out bool isTransformExpression,
out List<Pair<string, I>> itemsFromCapture)
{
return ItemExpander.ExpandExpressionCapture(this, expressionCapture, _items, elementLocation, options, includeNullEntries, out isTransformExpression, out itemsFromCapture);
}
/// <summary>
/// Returns true if the supplied string contains a valid property name.
/// </summary>
private static bool IsValidPropertyName(string propertyName)
{
if (propertyName.Length == 0 || !XmlUtilities.IsValidInitialElementNameCharacter(propertyName[0]))
{
return false;
}
for (int n = 1; n < propertyName.Length; n++)
{
if (!XmlUtilities.IsValidSubsequentElementNameCharacter(propertyName[n]))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if ExpanderOptions.Truncate is set and EscapeHatches.DoNotTruncateConditions is not set.
/// </summary>
private static bool IsTruncationEnabled(ExpanderOptions options)
{
return (options & ExpanderOptions.Truncate) != 0 && !Traits.Instance.EscapeHatches.DoNotTruncateConditions;
}
/// <summary>
/// Scan for the closing bracket that matches the one we've already skipped;
/// essentially, pushes and pops on a stack of parentheses to do this.
/// Takes the expression and the index to start at.
/// Returns the index of the matching parenthesis, or -1 if it was not found.
/// Also returns flags to indicate if a propertyfunction or registry property is likely
/// to be found in the expression.
/// </summary>
private static int ScanForClosingParenthesis(string expression, int index, out bool potentialPropertyFunction, out bool potentialRegistryFunction)
{
int nestLevel = 1;
int length = expression.Length;
potentialPropertyFunction = false;
potentialRegistryFunction = false;
// Scan for our closing ')'
while (index < length && nestLevel > 0)
{
char character = expression[index];
switch (character)
{
case '\'':
case '`':
case '"':
{
index++;
index = ScanForClosingQuote(character, expression, index);
if (index < 0)
{
return -1;
}
break;
}
case '(':
{
nestLevel++;
break;
}
case ')':
{
nestLevel--;
break;
}
case '.':
case '[':
case '$':
{
potentialPropertyFunction = true;
break;
}
case ':':
{
potentialRegistryFunction = true;
break;
}
}
index++;
}
// We will have parsed past the ')', so step back one character
index--;
return (nestLevel == 0) ? index : -1;
}
/// <summary>
/// Skip all characters until we find the matching quote character.
/// </summary>
private static int ScanForClosingQuote(char quoteChar, string expression, int index)
{
// Scan for our closing quoteChar
return expression.IndexOf(quoteChar, index);
}
/// <summary>
/// Add the argument in the StringBuilder to the arguments list, handling nulls
/// appropriately.
/// </summary>
private static void AddArgument(List<string> arguments, SpanBasedStringBuilder argumentBuilder)
{
// we reached the end of an argument, add the builder's final result
// to our arguments.
argumentBuilder.Trim();
string argValue = argumentBuilder.ToString();
// We support passing of null through the argument constant value null
if (String.Equals("null", argValue, StringComparison.OrdinalIgnoreCase))
{
arguments.Add(null);
}
else
{
if (argValue.Length > 0)
{
if (argValue[0] == '\'' && argValue[argValue.Length - 1] == '\'')
{
arguments.Add(argValue.Trim(s_singleQuoteChar));
}
else if (argValue[0] == '`' && argValue[argValue.Length - 1] == '`')
{
arguments.Add(argValue.Trim(s_backtickChar));
}
else if (argValue[0] == '"' && argValue[argValue.Length - 1] == '"')
{
arguments.Add(argValue.Trim(s_doubleQuoteChar));
}
else
{
arguments.Add(argValue);
}
}
else
{
arguments.Add(argValue);
}
}
}
/// <summary>
/// Extract the first level of arguments from the content.
/// Splits the content passed in at commas.
/// Returns an array of unexpanded arguments.
/// If there are no arguments, returns an empty array.
/// </summary>
private static string[] ExtractFunctionArguments(IElementLocation elementLocation, string expressionFunction, string argumentsString)
{
int argumentsContentLength = argumentsString.Length;
List<string> arguments = new List<string>();
using SpanBasedStringBuilder argumentBuilder = Strings.GetSpanBasedStringBuilder();
int? argumentStartIndex = null;
// We iterate over the string in the for loop below. When we find an argument, instead of adding it to the argument
// builder one-character-at-a-time, we remember the start index and then call this function when we find the end of
// the argument. This appends the entire {start, end} span to the builder in one call.
void FlushCurrentArgumentToArgumentBuilder(int argumentEndIndex)
{
if (argumentStartIndex.HasValue)
{
argumentBuilder.Append(argumentsString, argumentStartIndex.Value, argumentEndIndex - argumentStartIndex.Value);
argumentStartIndex = null;
}
}
// Iterate over the contents of the arguments extracting the
// the individual arguments as we go
for (int n = 0; n < argumentsContentLength; n++)
{
// We found a property expression.. skip over all of it.
if ((n < argumentsContentLength - 1) && (argumentsString[n] == '$' && argumentsString[n + 1] == '('))
{
int nestedPropertyStart = n;
n += 2; // skip over the opening '$('
// Scan for the matching closing bracket, skipping any nested ones
n = ScanForClosingParenthesis(argumentsString, n, out _, out _);
if (n == -1)
{
ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "InvalidFunctionPropertyExpression", expressionFunction, AssemblyResources.GetString("InvalidFunctionPropertyExpressionDetailMismatchedParenthesis"));
}
FlushCurrentArgumentToArgumentBuilder(argumentEndIndex: nestedPropertyStart);
argumentBuilder.Append(argumentsString, nestedPropertyStart, (n - nestedPropertyStart) + 1);
}
else if (argumentsString[n] == '`' || argumentsString[n] == '"' || argumentsString[n] == '\'')
{
int quoteStart = n;
n++; // skip over the opening quote
n = ScanForClosingQuote(argumentsString[quoteStart], argumentsString, n);
if (n == -1)
{
ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "InvalidFunctionPropertyExpression", expressionFunction, AssemblyResources.GetString("InvalidFunctionPropertyExpressionDetailMismatchedQuote"));
}
FlushCurrentArgumentToArgumentBuilder(argumentEndIndex: quoteStart);
argumentBuilder.Append(argumentsString, quoteStart, (n - quoteStart) + 1);
}
else if (argumentsString[n] == ',')
{
FlushCurrentArgumentToArgumentBuilder(argumentEndIndex: n);
// We have reached the end of the current argument, go ahead and add it
// to our list
AddArgument(arguments, argumentBuilder);
// Clear out the argument builder ready for the next argument
argumentBuilder.Clear();
}
else
{
argumentStartIndex ??= n;
}
}
// We reached the end of the string but we may have seen the start but not the end of the last (or only) argument so flush it now.
FlushCurrentArgumentToArgumentBuilder(argumentEndIndex: argumentsContentLength);
// This will either be the one and only argument, or the last one
// so add it to our list
AddArgument(arguments, argumentBuilder);
return arguments.ToArray();
}
/// <summary>
/// Expands bare metadata expressions, like %(Compile.WarningLevel), or unqualified, like %(Compile).
/// </summary>
/// <remarks>
/// This is a private nested class, exposed only through the Expander class.
/// That allows it to hide its private methods even from Expander.
/// </remarks>
private static class MetadataExpander
{
/// <summary>
/// Expands all embedded item metadata in the given string, using the bucketed items.
/// Metadata may be qualified, like %(Compile.WarningLevel), or unqualified, like %(Compile).
/// </summary>
/// <param name="expression">The expression containing item metadata references.</param>
/// <param name="metadata">The metadata to be expanded.</param>
/// <param name="options">Used to specify what to expand.</param>
/// <param name="elementLocation">The location information for error reporting purposes.</param>
/// <returns>The string with item metadata expanded in-place, escaped.</returns>
internal static string ExpandMetadataLeaveEscaped(string expression, IMetadataTable metadata, ExpanderOptions options, IElementLocation elementLocation)
{
try
{
if ((options & ExpanderOptions.ExpandMetadata) == 0)
{
return expression;
}
ErrorUtilities.VerifyThrow(metadata != null, "Cannot expand metadata without providing metadata");
// PERF NOTE: Regex matching is expensive, so if the string doesn't contain any item metadata references, just bail
// out -- pre-scanning the string is actually cheaper than running the Regex, even when there are no matches!
if (s_invariantCompareInfo.IndexOf(expression, "%(", CompareOptions.Ordinal) == -1)
{
return expression;
}
string result = null;
if (s_invariantCompareInfo.IndexOf(expression, "@(", CompareOptions.Ordinal) == -1)
{
// if there are no item vectors in the string
// run a simpler Regex to find item metadata references
MetadataMatchEvaluator matchEvaluator = new MetadataMatchEvaluator(metadata, options);
result = RegularExpressions.ItemMetadataPattern.Value.Replace(expression, new MatchEvaluator(matchEvaluator.ExpandSingleMetadata));
}
else
{
List<ExpressionShredder.ItemExpressionCapture> itemVectorExpressions = ExpressionShredder.GetReferencedItemExpressions(expression);
// The most common case is where the transform is the whole expression
// Also if there were no valid item vector expressions found, then go ahead and do the replacement on
// the whole expression (which is what Orcas did).
if (itemVectorExpressions?.Count == 1 && itemVectorExpressions[0].Value == expression && itemVectorExpressions[0].Separator == null)
{
return expression;
}
// otherwise, run the more complex Regex to find item metadata references not contained in transforms
using SpanBasedStringBuilder finalResultBuilder = Strings.GetSpanBasedStringBuilder();
int start = 0;
MetadataMatchEvaluator matchEvaluator = new MetadataMatchEvaluator(metadata, options);
if (itemVectorExpressions != null)
{
// Move over the expression, skipping those that have been recognized as an item vector expression
// Anything other than an item vector expression we want to expand bare metadata in.
for (int n = 0; n < itemVectorExpressions.Count; n++)
{
string vectorExpression = itemVectorExpressions[n].Value;
// Extract the part of the expression that appears before the item vector expression
// e.g. the ABC in ABC@(foo->'%(FullPath)')
string subExpressionToReplaceIn = expression.Substring(start, itemVectorExpressions[n].Index - start);
string replacementResult = RegularExpressions.NonTransformItemMetadataPattern.Value.Replace(subExpressionToReplaceIn, new MatchEvaluator(matchEvaluator.ExpandSingleMetadata));
// Append the metadata replacement
finalResultBuilder.Append(replacementResult);
// Expand any metadata that appears in the item vector expression's separator
if (itemVectorExpressions[n].Separator != null)
{
vectorExpression = RegularExpressions.NonTransformItemMetadataPattern.Value.Replace(itemVectorExpressions[n].Value, new MatchEvaluator(matchEvaluator.ExpandSingleMetadata), -1, itemVectorExpressions[n].SeparatorStart);
}
// Append the item vector expression as is
// e.g. the @(foo->'%(FullPath)') in ABC@(foo->'%(FullPath)')
finalResultBuilder.Append(vectorExpression);
// Move onto the next part of the expression that isn't an item vector expression
start = (itemVectorExpressions[n].Index + itemVectorExpressions[n].Length);
}
}
// If there's anything left after the last item vector expression
// then we need to metadata replace and then append that
if (start < expression.Length)
{
string subExpressionToReplaceIn = expression.Substring(start);
string replacementResult = RegularExpressions.NonTransformItemMetadataPattern.Value.Replace(subExpressionToReplaceIn, new MatchEvaluator(matchEvaluator.ExpandSingleMetadata));
finalResultBuilder.Append(replacementResult);
}
result = finalResultBuilder.ToString();
}
// Don't create more strings
if (String.Equals(result, expression, StringComparison.Ordinal))
{
result = expression;
}
return result;
}
catch (InvalidOperationException ex)
{
ProjectErrorUtilities.ThrowInvalidProject(elementLocation, "CannotExpandItemMetadata", expression, ex.Message);
}
return null;
}
/// <summary>
/// A functor that returns the value of the metadata in the match
/// that is contained in the metadata dictionary it was created with.
/// </summary>
private class MetadataMatchEvaluator
{
/// <summary>
/// Source of the metadata.
/// </summary>
private IMetadataTable _metadata;
/// <summary>
/// Whether to expand built-in metadata, custom metadata, or both kinds.
/// </summary>
private ExpanderOptions _options;
/// <summary>
/// Constructor taking a source of metadata.
/// </summary>
internal MetadataMatchEvaluator(IMetadataTable metadata, ExpanderOptions options)