-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProjectInstance.cs
3462 lines (3032 loc) · 164 KB
/
ProjectInstance.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Definition;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Evaluation.Context;
using Microsoft.Build.Experimental.BuildCheck.Infrastructure;
using Microsoft.Build.FileSystem;
using Microsoft.Build.Framework;
using Microsoft.Build.Instance;
using Microsoft.Build.Instance.ImmutableProjectCollections;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using ObjectModel = System.Collections.ObjectModel;
using ProjectItemInstanceFactory = Microsoft.Build.Execution.ProjectItemInstance.TaskItem.ProjectItemInstanceFactory;
using SdkResult = Microsoft.Build.BackEnd.SdkResolution.SdkResult;
#nullable disable
namespace Microsoft.Build.Execution
{
using Utilities = Microsoft.Build.Internal.Utilities;
/// <summary>
/// Enum for controlling project instance creation
/// </summary>
[Flags]
[SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags", Justification = "ImmutableWithFastItemLookup is a variation on Immutable")]
public enum ProjectInstanceSettings
{
/// <summary>
/// no options
/// </summary>
None = 0x0,
/// <summary>
/// create immutable version of project instance
/// </summary>
Immutable = 0x1,
/// <summary>
/// create project instance with some look up table that improves performance
/// </summary>
ImmutableWithFastItemLookup = Immutable | 0x2
}
/// <summary>
/// What the user gets when they clone off a ProjectInstance.
/// They can hold onto this, change/query items and properties,
/// and call it several times to build it.
/// </summary>
/// <comments>
/// Neither this class nor any of its constituents are allowed to have
/// references to any of the Construction or Evaluation objects.
/// This class is immutable except for adding instance items and setting instance properties.
/// It only exposes items and properties: targets, host services, and the task registry are not exposed as they are only the concern of build.
/// Constructors are internal in order to direct users to Project class instead; these are only createable via Project objects.
/// </comments>
[DebuggerDisplay(@"{FullPath} #Targets={TargetsCount} DefaultTargets={(DefaultTargets == null) ? System.String.Empty : System.String.Join("";"", DefaultTargets.ToArray())} ToolsVersion={Toolset.ToolsVersion} InitialTargets={(InitialTargets == null) ? System.String.Empty : System.String.Join("";"", InitialTargets.ToArray())} #GlobalProperties={GlobalProperties.Count} #Properties={Properties.Count} #ItemTypes={ItemTypes.Count} #Items={Items.Count}")]
public class ProjectInstance : IPropertyProvider<ProjectPropertyInstance>, IItemProvider<ProjectItemInstance>, IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance, ProjectItemDefinitionInstance>, ITranslatable
{
/// <summary>
/// Targets in the project after overrides have been resolved.
/// This is an unordered collection keyed by target name.
/// Only the wrapper around this collection is exposed.
/// </summary>
private RetrievableEntryHashSet<ProjectTargetInstance> _actualTargets;
/// <summary>
/// Targets in the project after overrides have been resolved.
/// This is an immutable, unordered collection keyed by target name.
/// It is just a wrapper around <see cref="_actualTargets">actualTargets</see>.
/// </summary>
private IDictionary<string, ProjectTargetInstance> _targets;
private List<string> _defaultTargets;
private List<string> _initialTargets;
private IList<string> _importPaths;
private IList<string> _importPathsIncludingDuplicates;
/// <summary>
/// The global properties evaluation occurred with.
/// Needed by the build as they traverse between projects.
/// </summary>
private PropertyDictionary<ProjectPropertyInstance> _globalProperties;
/// <summary>
/// List of names of the properties that, while global, are still treated as overridable
/// </summary>
private ISet<string> _globalPropertiesToTreatAsLocal;
/// <summary>
/// Whether the tools version used originated from an explicit specification,
/// for example from an MSBuild task or /tv switch.
/// </summary>
private bool _explicitToolsVersionSpecified;
/// <summary>
/// Properties in the project. This is a dictionary of name, value pairs.
/// </summary>
private PropertyDictionary<ProjectPropertyInstance> _properties;
/// <summary>
/// Properties originating from environment variables, gotten from the project collection
/// </summary>
private PropertyDictionary<ProjectPropertyInstance> _environmentVariableProperties;
/// <summary>
/// Items in the project. This is a dictionary of ordered lists of a single type of items keyed by item type.
/// </summary>
private IItemDictionary<ProjectItemInstance> _items;
/// <summary>
/// Items organized by evaluatedInclude value
/// </summary>
private IMultiDictionary<string, ProjectItemInstance> _itemsByEvaluatedInclude;
/// <summary>
/// The project's root directory, for evaluation of relative paths and
/// setting the current directory during build.
/// Is never null.
/// If the project has not been loaded from disk and has not been given a path, returns the current directory from
/// the time the project was loaded - this is the same behavior as Whidbey/Orcas.
/// If the project has not been loaded from disk but has been given a path, this path may not exist.
/// </summary>
private string _directory;
/// <summary>
/// The project file location, for logging.
/// If the project has not been loaded from disk and has not been given a path, returns null.
/// If the project has not been loaded from disk but has been given a path, this path may not exist.
/// </summary>
private ElementLocation _projectFileLocation;
/// <summary>
/// The item definitions from the parent Project.
/// </summary>
private IRetrievableEntryHashSet<ProjectItemDefinitionInstance> _itemDefinitions;
/// <summary>
/// The HostServices to use during a build.
/// </summary>
private HostServices _hostServices;
/// <summary>
/// Whether when we read a ToolsVersion that is not equivalent to the current one on the Project tag, we
/// treat it as the current one.
/// </summary>
private bool _usingDifferentToolsVersionFromProjectFile;
/// <summary>
/// The toolsversion that was originally on the project's Project root element
/// </summary>
private string _originalProjectToolsVersion;
/// <summary>
/// Whether the instance is immutable.
/// The object is always mutable during evaluation.
/// </summary>
private bool _isImmutable;
private IDictionary<string, List<TargetSpecification>> _beforeTargets;
private IDictionary<string, List<TargetSpecification>> _afterTargets;
private Toolset _toolset;
private string _subToolsetVersion;
private TaskRegistry _taskRegistry;
private bool _translateEntireState;
private int _evaluationId = BuildEventContext.InvalidEvaluationId;
/// <summary>
/// The property and item filter used when creating this instance, or null if this is not a filtered copy
/// of another ProjectInstance. <seealso cref="ProjectInstance(ProjectInstance, bool, RequestedProjectState)"/>
/// </summary>
private RequestedProjectState _requestedProjectStateFilter;
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Uses the default project collection.
/// </summary>
/// <param name="projectFile">The name of the project file.</param>
/// <returns>A new project instance</returns>
public ProjectInstance(string projectFile)
: this(projectFile, null, (string)null)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Uses the default project collection.
/// </summary>
/// <param name="projectFile">The name of the project file.</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <returns>A new project instance</returns>
public ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion)
: this(projectFile, globalProperties, toolsVersion, ProjectCollection.GlobalProjectCollection)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// </summary>
/// <param name="projectFile">The name of the project file.</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="projectCollection">Project collection</param>
/// <returns>A new project instance</returns>
public ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion, ProjectCollection projectCollection)
: this(projectFile, globalProperties, toolsVersion, null /* no sub-toolset version */, projectCollection)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// </summary>
/// <param name="projectFile">The name of the project file.</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="subToolsetVersion">The sub-toolset version, used in tandem with the ToolsVersion to determine the set of toolset properties.</param>
/// <param name="projectCollection">Project collection</param>
/// <returns>A new project instance</returns>
public ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion, string subToolsetVersion, ProjectCollection projectCollection)
: this(projectFile, globalProperties, toolsVersion, subToolsetVersion, projectCollection, projectLoadSettings: null, evaluationContext: null, directoryCacheFactory: null, interactive: false)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// </summary>
/// <param name="projectFile">The path to the project file.</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version. May be <see langword="null"/>.</param>
/// <param name="subToolsetVersion">The sub-toolset version, used in tandem with <paramref name="toolsVersion"/> to determine the set of toolset properties. May be <see langword="null"/>.</param>
/// <param name="projectCollection">Project collection</param>
/// <param name="context">Context to evaluate inside, potentially sharing caches with other evaluations.</param>
/// <param name="interactive">Indicates if loading the project is allowed to interact with the user.</param>
internal ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion, string subToolsetVersion, ProjectCollection projectCollection, EvaluationContext context, bool interactive = false)
: this(projectFile, globalProperties, toolsVersion, subToolsetVersion, projectCollection, projectLoadSettings: null, evaluationContext: context, directoryCacheFactory: null, interactive: interactive)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// Evaluation context may be null.
/// </summary>
/// <param name="projectFile">The name of the project file.</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="subToolsetVersion">The sub-toolset version, used in tandem with the ToolsVersion to determine the set of toolset properties.</param>
/// <param name="projectCollection">Project collection</param>
/// <param name="projectLoadSettings">Project load settings</param>
/// <param name="evaluationContext">The context to use for evaluation.</param>
/// <param name="directoryCacheFactory">The directory cache factory to use for file I/O.</param>
/// <param name="interactive">Indicates if loading the project is allowed to interact with the user.</param>
/// <returns>A new project instance</returns>
private ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion, string subToolsetVersion, ProjectCollection projectCollection,
ProjectLoadSettings? projectLoadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, bool interactive)
{
ErrorUtilities.VerifyThrowArgumentLength(projectFile);
ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(toolsVersion, nameof(toolsVersion));
// We do not control the current directory at this point, but assume that if we were
// passed a relative path, the caller assumes we will prepend the current directory.
projectFile = FileUtilities.NormalizePath(projectFile);
BuildParameters buildParameters = new BuildParameters(projectCollection)
{
Interactive = interactive
};
BuildEventContext buildEventContext = new BuildEventContext(buildParameters.NodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId);
ProjectRootElement xml = ProjectRootElement.OpenProjectOrSolution(projectFile, globalProperties, toolsVersion, buildParameters.ProjectRootElementCache, true /*Explicitly Loaded*/);
Initialize(xml, globalProperties, toolsVersion, subToolsetVersion, 0 /* no solution version provided */, buildParameters, projectCollection.LoggingService, buildEventContext,
projectLoadSettings: projectLoadSettings, evaluationContext: evaluationContext, directoryCacheFactory: directoryCacheFactory);
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Uses the default project collection.
/// </summary>
/// <param name="xml">The project root element</param>
/// <returns>A new project instance</returns>
public ProjectInstance(ProjectRootElement xml)
: this(xml, null, null, ProjectCollection.GlobalProjectCollection)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// </summary>
/// <param name="xml">The project root element</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="projectCollection">Project collection</param>
/// <returns>A new project instance</returns>
public ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, ProjectCollection projectCollection)
: this(xml, globalProperties, toolsVersion, null, projectCollection)
{
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// Sub-toolset version may be null, but if specified will override all other methods of determining the sub-toolset.
/// </summary>
/// <param name="xml">The project root element</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="subToolsetVersion">The sub-toolset version, used in tandem with the ToolsVersion to determine the set of toolset properties.</param>
/// <param name="projectCollection">Project collection</param>
/// <returns>A new project instance</returns>
public ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, string subToolsetVersion, ProjectCollection projectCollection)
: this(xml, globalProperties, toolsVersion, subToolsetVersion, projectCollection, projectLoadSettings: null, evaluationContext: null, directoryCacheFactory: null, interactive: false)
{
}
/// <summary>
/// Creates a ProjectInstance from an external created <see cref="Project"/>.
/// Properties and items are cloned immediately and only the instance data is stored.
/// </summary>
public ProjectInstance(Project project, ProjectInstanceSettings settings)
{
ErrorUtilities.VerifyThrowInternalNull(project);
var projectPath = project.FullPath;
_directory = Path.GetDirectoryName(projectPath);
_projectFileLocation = ElementLocation.Create(projectPath);
_hostServices = project.ProjectCollection.HostServices;
EvaluationId = project.EvaluationCounter;
var immutable = (settings & ProjectInstanceSettings.Immutable) == ProjectInstanceSettings.Immutable;
this.CreatePropertiesSnapshot(project.Properties, immutable);
this.CreateItemDefinitionsSnapshot(project.ItemDefinitions);
var keepEvaluationCache = (settings & ProjectInstanceSettings.ImmutableWithFastItemLookup) == ProjectInstanceSettings.ImmutableWithFastItemLookup;
var projectItemToInstanceMap = this.CreateItemsSnapshot(project.Items, project.ItemTypes.Count, keepEvaluationCache);
this.CreateEvaluatedIncludeSnapshotIfRequested(keepEvaluationCache, project.Items, projectItemToInstanceMap);
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(project.GlobalPropertiesCount);
foreach (var property in project.GlobalPropertiesEnumerable)
{
_globalProperties.Set(ProjectPropertyInstance.Create(property.Key, property.Value));
}
this.CreateEnvironmentVariablePropertiesSnapshot(project.ProjectCollection.EnvironmentProperties);
this.CreateTargetsSnapshot(project.Targets, null, null, null, null);
this.CreateImportsSnapshot(project.Imports, project.ImportsIncludingDuplicates);
this.Toolset = project.ProjectCollection.GetToolset(project.ToolsVersion);
this.SubToolsetVersion = project.SubToolsetVersion;
this.TaskRegistry = new TaskRegistry(Toolset, project.ProjectCollection.ProjectRootElementCache);
this.ProjectRootElementCache = project.ProjectCollection.ProjectRootElementCache;
this.EvaluatedItemElements = new List<ProjectItemElement>(project.Items.Count);
foreach (var item in project.Items)
{
this.EvaluatedItemElements.Add(item.Xml);
}
_usingDifferentToolsVersionFromProjectFile = false;
_originalProjectToolsVersion = project.ToolsVersion;
_explicitToolsVersionSpecified = project.SubToolsetVersion != null;
_isImmutable = immutable;
}
/// <summary>
/// Creates a ProjectInstance from an immutable <see cref="Project"/>.
/// The resulting <see cref="ProjectInstance"/> object wraps the <see cref="Project"/>
/// object. Unlike the ProjectInstance(Project project, ProjectInstanceSettings settings)
/// constructor, the properties and items are not cloned.
/// </summary>
/// <param name="linkedProject">The immutable <see cref="Project"/>.</param>
/// <param name="fastItemLookupNeeded">Whether the fast item lookup cache is required.</param>
private ProjectInstance(Project linkedProject, bool fastItemLookupNeeded)
{
ErrorUtilities.VerifyThrowInternalNull(linkedProject);
var projectPath = linkedProject.FullPath;
_directory = Path.GetDirectoryName(projectPath);
_projectFileLocation = ElementLocation.Create(projectPath);
_hostServices = linkedProject.ProjectCollection.HostServices;
_isImmutable = true;
EvaluationId = linkedProject.EvaluationCounter;
// ProjectProperties
_properties = GetImmutablePropertyDictionaryFromImmutableProject(linkedProject);
// ProjectItemDefinitions
_itemDefinitions = GetImmutableItemDefinitionsHashSetFromImmutableProject(linkedProject);
// ProjectItems
_items = GetImmutableItemsDictionaryFromImmutableProject(linkedProject, this);
// ItemsByEvaluatedInclude
if (fastItemLookupNeeded)
{
_itemsByEvaluatedInclude = new ImmutableLinkedMultiDictionaryConverter<string, ProjectItem, ProjectItemInstance>(
linkedProject.GetItemsByEvaluatedInclude,
item => ConvertCachedProjectItemToInstance(linkedProject, this, item));
}
// GlobalProperties
var globalPropertiesRetrievableHashSet = new ImmutableGlobalPropertiesCollectionConverter(linkedProject.GlobalProperties, _properties);
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(globalPropertiesRetrievableHashSet);
// EnvironmentVariableProperties
_environmentVariableProperties = linkedProject.ProjectCollection.SharedReadOnlyEnvironmentProperties;
// Targets
_targets = linkedProject.Targets;
InitializeTargetsData(null, null, null, null);
// Imports
var importsListConverter = new ImmutableStringValuedListConverter<ResolvedImport>(linkedProject.Imports, GetImportFullPath);
_importPaths = importsListConverter;
ImportPaths = importsListConverter;
importsListConverter = new ImmutableStringValuedListConverter<ResolvedImport>(linkedProject.ImportsIncludingDuplicates, GetImportFullPath);
_importPathsIncludingDuplicates = importsListConverter;
ImportPathsIncludingDuplicates = importsListConverter;
Toolset = linkedProject.ProjectCollection.GetToolset(linkedProject.ToolsVersion);
SubToolsetVersion = linkedProject.SubToolsetVersion;
TaskRegistry = new TaskRegistry(Toolset, linkedProject.ProjectCollection.ProjectRootElementCache);
ProjectRootElementCache = linkedProject.ProjectCollection.ProjectRootElementCache;
EvaluatedItemElements = new List<ProjectItemElement>(linkedProject.Items.Count);
foreach (var item in linkedProject.Items)
{
EvaluatedItemElements.Add(item.Xml);
}
_usingDifferentToolsVersionFromProjectFile = false;
_originalProjectToolsVersion = linkedProject.ToolsVersion;
_explicitToolsVersionSpecified = linkedProject.SubToolsetVersion != null;
_isImmutable = true;
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// Sub-toolset version may be null, but if specified will override all other methods of determining the sub-toolset.
/// </summary>
/// <param name="xml">The project root element</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="subToolsetVersion">The sub-toolset version, used in tandem with the ToolsVersion to determine the set of toolset properties.</param>
/// <param name="projectCollection">Project collection</param>
/// <param name="projectLoadSettings">Project load settings</param>
/// <param name="evaluationContext">The context to use for evaluation.</param>
/// <param name="directoryCacheFactory">The directory cache factory to use for file I/O.</param>
/// <param name="interactive">Indicates if loading the project is allowed to interact with the user.</param>
/// <returns>A new project instance</returns>
private ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, string subToolsetVersion, ProjectCollection projectCollection,
ProjectLoadSettings? projectLoadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, bool interactive)
{
BuildEventContext buildEventContext = new BuildEventContext(0, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId);
BuildParameters buildParameters = new BuildParameters(projectCollection)
{
Interactive = interactive
};
Initialize(xml, globalProperties, toolsVersion, subToolsetVersion, 0 /* no solution version specified */, buildParameters, projectCollection.LoggingService, buildEventContext,
projectLoadSettings: projectLoadSettings, evaluationContext: evaluationContext, directoryCacheFactory: directoryCacheFactory);
}
/// <summary>
/// Creates a ProjectInstance directly. Used to generate solution metaprojects.
/// </summary>
/// <param name="projectFile">The full path to give to this project.</param>
/// <param name="projectToInheritFrom">The traversal project from which global properties and tools version will be inherited.</param>
/// <param name="globalProperties">An <see cref="IDictionary{String,String}"/> containing global properties.</param>
internal ProjectInstance(string projectFile, ProjectInstance projectToInheritFrom, IDictionary<string, string> globalProperties)
{
_projectFileLocation = ElementLocation.Create(projectFile);
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(globalProperties.Count);
this.Toolset = projectToInheritFrom.Toolset;
this.SubToolsetVersion = projectToInheritFrom.SubToolsetVersion;
_explicitToolsVersionSpecified = projectToInheritFrom._explicitToolsVersionSpecified;
_properties = new PropertyDictionary<ProjectPropertyInstance>(projectToInheritFrom._properties); // This brings along the reserved properties, which are important.
_items = new ItemDictionary<ProjectItemInstance>(); // We don't want any of the items. That would include things like ProjectReferences, which would just pollute our own.
_actualTargets = new RetrievableEntryHashSet<ProjectTargetInstance>(StringComparer.OrdinalIgnoreCase);
_targets = new ObjectModel.ReadOnlyDictionary<string, ProjectTargetInstance>(_actualTargets);
_environmentVariableProperties = projectToInheritFrom._environmentVariableProperties;
_itemDefinitions = new RetrievableEntryHashSet<ProjectItemDefinitionInstance>(projectToInheritFrom._itemDefinitions, MSBuildNameIgnoreCaseComparer.Default);
_hostServices = projectToInheritFrom._hostServices;
this.ProjectRootElementCache = projectToInheritFrom.ProjectRootElementCache;
_explicitToolsVersionSpecified = projectToInheritFrom._explicitToolsVersionSpecified;
this.InitialTargets = new List<string>();
this.DefaultTargets = new List<string>();
this.DefaultTargets.Add("Build");
this.TaskRegistry = projectToInheritFrom.TaskRegistry;
_isImmutable = projectToInheritFrom._isImmutable;
_importPaths = projectToInheritFrom._importPaths;
ImportPaths = new ObjectModel.ReadOnlyCollection<string>(_importPaths);
_importPathsIncludingDuplicates = projectToInheritFrom._importPathsIncludingDuplicates;
ImportPathsIncludingDuplicates = new ObjectModel.ReadOnlyCollection<string>(_importPathsIncludingDuplicates);
this.EvaluatedItemElements = new List<ProjectItemElement>();
IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance, ProjectItemDefinitionInstance> thisAsIEvaluatorData = this;
thisAsIEvaluatorData.AfterTargets = new Dictionary<string, List<TargetSpecification>>();
thisAsIEvaluatorData.BeforeTargets = new Dictionary<string, List<TargetSpecification>>();
foreach (KeyValuePair<string, string> property in globalProperties)
{
_globalProperties[property.Key] = ProjectPropertyInstance.Create(property.Key, property.Value, false /* may not be reserved */, _isImmutable);
}
}
/// <summary>
/// Creates a ProjectInstance directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// Used by SolutionProjectGenerator so that it can explicitly pass the vsVersionFromSolution in for use in
/// determining the sub-toolset version.
/// </summary>
/// <param name="xml">The project root element</param>
/// <param name="globalProperties">The global properties to use.</param>
/// <param name="toolsVersion">The tools version.</param>
/// <param name="visualStudioVersionFromSolution">The version of the solution, used to help determine which sub-toolset to use.</param>
/// <param name="projectCollection">Project collection</param>
/// <param name="sdkResolverService">An <see cref="ISdkResolverService"/> instance to use when resolving SDKs.</param>
/// <param name="submissionId">The current build submission ID.</param>
/// <returns>A new project instance</returns>
internal ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, int visualStudioVersionFromSolution, ProjectCollection projectCollection, ISdkResolverService sdkResolverService, int submissionId)
{
BuildEventContext buildEventContext = new BuildEventContext(0, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId);
Initialize(xml, globalProperties, toolsVersion, null, visualStudioVersionFromSolution, new BuildParameters(projectCollection), projectCollection.LoggingService, buildEventContext, sdkResolverService, submissionId);
}
/// <summary>
/// Initializes a new instance of the <see cref="ProjectInstance"/> class directly.
/// No intermediate Project object is created.
/// This is ideal if the project is simply going to be built, and not displayed or edited.
/// Global properties may be null.
/// Tools version may be null.
/// Used by SolutionProjectGenerator so that it can explicitly pass the vsVersionFromSolution in for use in
/// determining the sub-toolset version.
/// </summary>
internal ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, ILoggingService loggingService, int visualStudioVersionFromSolution, ProjectCollection projectCollection, ISdkResolverService sdkResolverService, int submissionId)
{
BuildEventContext buildEventContext = new BuildEventContext(submissionId, 0, BuildEventContext.InvalidProjectInstanceId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidTaskId);
Initialize(xml, globalProperties, toolsVersion, null, visualStudioVersionFromSolution, new BuildParameters(projectCollection), loggingService, buildEventContext, sdkResolverService, submissionId);
}
/// <summary>
/// Creates a mutable ProjectInstance directly, using the specified logging service.
/// Assumes the project path is already normalized.
/// Used by the RequestBuilder.
/// </summary>
internal ProjectInstance(string projectFile, IDictionary<string, string> globalProperties, string toolsVersion, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, int submissionId, ProjectLoadSettings? projectLoadSettings)
{
ErrorUtilities.VerifyThrowArgumentLength(projectFile);
ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(toolsVersion, nameof(toolsVersion));
ErrorUtilities.VerifyThrowArgumentNull(buildParameters);
ProjectRootElement xml = ProjectRootElement.OpenProjectOrSolution(projectFile, globalProperties, toolsVersion, buildParameters.ProjectRootElementCache, false /*Not explicitly loaded*/);
Initialize(xml, globalProperties, toolsVersion, null, 0 /* no solution version specified */, buildParameters, loggingService, buildEventContext, sdkResolverService, submissionId, projectLoadSettings);
}
/// <summary>
/// Creates a mutable ProjectInstance directly, using the specified logging service.
/// Assumes the project path is already normalized.
/// Used by this class when generating legacy solution wrappers.
/// </summary>
internal ProjectInstance(ProjectRootElement xml, IDictionary<string, string> globalProperties, string toolsVersion, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, int submissionId)
{
ErrorUtilities.VerifyThrowArgumentNull(xml);
ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(toolsVersion, nameof(toolsVersion));
ErrorUtilities.VerifyThrowArgumentNull(buildParameters);
Initialize(xml, globalProperties, toolsVersion, null, 0 /* no solution version specified */, buildParameters, loggingService, buildEventContext, sdkResolverService, submissionId);
}
/// <summary>
/// Constructor called by Project's constructor to create a fresh instance.
/// Properties and items are cloned immediately and only the instance data is stored.
/// </summary>
internal ProjectInstance(Evaluation.Project.Data data, string directory, string fullPath, HostServices hostServices, PropertyDictionary<ProjectPropertyInstance> environmentVariableProperties, ProjectInstanceSettings settings)
{
ErrorUtilities.VerifyThrowInternalNull(data);
ErrorUtilities.VerifyThrowInternalLength(directory, nameof(directory));
ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(fullPath, nameof(fullPath));
_directory = directory;
_projectFileLocation = ElementLocation.Create(fullPath);
_hostServices = hostServices;
EvaluationId = data.EvaluationId;
var immutable = (settings & ProjectInstanceSettings.Immutable) == ProjectInstanceSettings.Immutable;
this.CreatePropertiesSnapshot(new ReadOnlyCollection<ProjectProperty>(data.Properties), immutable);
this.CreateItemDefinitionsSnapshot(data.ItemDefinitions);
var keepEvaluationCache = (settings & ProjectInstanceSettings.ImmutableWithFastItemLookup) == ProjectInstanceSettings.ImmutableWithFastItemLookup;
var projectItemToInstanceMap = this.CreateItemsSnapshot(new ReadOnlyCollection<ProjectItem>(data.Items), data.ItemTypes.Count, keepEvaluationCache);
this.CreateEvaluatedIncludeSnapshotIfRequested(keepEvaluationCache, new ReadOnlyCollection<ProjectItem>(data.Items), projectItemToInstanceMap);
this.CreateGlobalPropertiesSnapshot(data.GlobalPropertiesDictionary);
this.CreateEnvironmentVariablePropertiesSnapshot(environmentVariableProperties);
this.CreateTargetsSnapshot(data.Targets, data.DefaultTargets, data.InitialTargets, data.BeforeTargets, data.AfterTargets);
this.CreateImportsSnapshot(data.ImportClosure, data.ImportClosureWithDuplicates);
// Toolset and task registry are logically immutable after creation, and shareable by project instances
// with same evaluation (global/local properties) - which is guaranteed here (the passed in data is recreated on evaluation if needed)
this.Toolset = data.Toolset;
this.SubToolsetVersion = data.SubToolsetVersion;
this.TaskRegistry = data.TaskRegistry;
this.ProjectRootElementCache = data.Project.ProjectCollection.ProjectRootElementCache;
this.EvaluatedItemElements = new List<ProjectItemElement>(data.EvaluatedItemElements);
_usingDifferentToolsVersionFromProjectFile = data.UsingDifferentToolsVersionFromProjectFile;
_originalProjectToolsVersion = data.OriginalProjectToolsVersion;
_explicitToolsVersionSpecified = data.ExplicitToolsVersion != null;
_isImmutable = immutable;
}
/// <summary>
/// Constructor for deserialization.
/// </summary>
private ProjectInstance(ITranslator translator)
{
((ITranslatable)this).Translate(translator);
}
/// <summary>
/// Deep clone of this object.
/// Useful for compiling a single file; or for keeping resolved assembly references between builds.
/// </summary>
private ProjectInstance(ProjectInstance that, bool isImmutable, RequestedProjectState filter = null)
{
ErrorUtilities.VerifyThrow(filter == null || isImmutable,
"The result of a filtered ProjectInstance clone must be immutable.");
_directory = that._directory;
_projectFileLocation = that._projectFileLocation;
_hostServices = that._hostServices;
_isImmutable = isImmutable;
_evaluationId = that.EvaluationId;
_translateEntireState = that._translateEntireState;
_requestedProjectStateFilter = filter?.DeepClone();
if (filter == null)
{
_properties = new PropertyDictionary<ProjectPropertyInstance>(that._properties.Count);
foreach (ProjectPropertyInstance property in that.Properties)
{
_properties.Set(property.DeepClone(_isImmutable));
}
_items = new ItemDictionary<ProjectItemInstance>(that._items.Count);
foreach (ProjectItemInstance item in that.Items)
{
_items.Add(item.DeepClone(this));
}
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(that._globalProperties.Count);
foreach (ProjectPropertyInstance globalProperty in that.GlobalPropertiesDictionary)
{
_globalProperties.Set(globalProperty.DeepClone(_isImmutable));
}
_environmentVariableProperties =
new PropertyDictionary<ProjectPropertyInstance>(that._environmentVariableProperties.Count);
foreach (ProjectPropertyInstance environmentProperty in that._environmentVariableProperties)
{
_environmentVariableProperties.Set(environmentProperty.DeepClone(_isImmutable));
}
this.DefaultTargets = new List<string>(that.DefaultTargets);
this.InitialTargets = new List<string>(that.InitialTargets);
((IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance,
ProjectItemDefinitionInstance>)this).BeforeTargets = CreateCloneDictionary(
((IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance,
ProjectItemDefinitionInstance>)that).BeforeTargets, StringComparer.OrdinalIgnoreCase);
((IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance,
ProjectItemDefinitionInstance>)this).AfterTargets = CreateCloneDictionary(
((IEvaluatorData<ProjectPropertyInstance, ProjectItemInstance, ProjectMetadataInstance,
ProjectItemDefinitionInstance>)that).AfterTargets, StringComparer.OrdinalIgnoreCase);
// These are immutable (or logically immutable after creation) so we don't need to clone them:
this.TaskRegistry = that.TaskRegistry;
this.Toolset = that.Toolset;
this.SubToolsetVersion = that.SubToolsetVersion;
_targets = that._targets;
_itemDefinitions = that._itemDefinitions;
_explicitToolsVersionSpecified = that._explicitToolsVersionSpecified;
_importPaths = that._importPaths;
ImportPaths = new ObjectModel.ReadOnlyCollection<string>(_importPaths);
_importPathsIncludingDuplicates = that._importPathsIncludingDuplicates;
ImportPathsIncludingDuplicates = new ObjectModel.ReadOnlyCollection<string>(_importPathsIncludingDuplicates);
this.EvaluatedItemElements = that.EvaluatedItemElements;
this.ProjectRootElementCache = that.ProjectRootElementCache;
}
else
{
if (filter.PropertyFilters != null)
{
// If PropertyFilters is defined, filter all types of property to contain
// only those explicitly specified.
// Reserve space assuming all specified properties exist.
_properties = new PropertyDictionary<ProjectPropertyInstance>(filter.PropertyFilters.Count);
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(filter.PropertyFilters.Count);
_environmentVariableProperties =
new PropertyDictionary<ProjectPropertyInstance>(filter.PropertyFilters.Count);
// Filter each type of property.
foreach (var desiredProperty in filter.PropertyFilters)
{
var regularProperty = that.GetProperty(desiredProperty);
if (regularProperty != null)
{
_properties.Set(regularProperty.DeepClone(isImmutable: true));
}
var globalProperty = that.GetProperty(desiredProperty);
if (globalProperty != null)
{
_globalProperties.Set(globalProperty.DeepClone(isImmutable: true));
}
var environmentProperty = that.GetProperty(desiredProperty);
if (environmentProperty != null)
{
_environmentVariableProperties.Set(environmentProperty.DeepClone(isImmutable: true));
}
}
}
if (filter.ItemFilters != null)
{
// If ItemFilters is defined, filter items down to the list
// specified, optionally also filtering metadata.
// Temporarily allow editing items to remove metadata that
// wasn't explicitly asked for.
_isImmutable = false;
_items = new ItemDictionary<ProjectItemInstance>(that.Items.Count);
foreach (var itemFilter in filter.ItemFilters)
{
foreach (var actualItem in that.GetItems(itemFilter.Key))
{
var filteredItem = actualItem.DeepClone(this);
if (itemFilter.Value == null)
{
// No specified list of metadata names, so include all metadata.
// The returned list of items is still filtered by item name.
}
else
{
// Include only the explicitly-asked-for metadata by removing
// any extant metadata.
// UNDONE: This could be achieved at lower GC cost by applying
// the metadata filter at DeepClone time above.
foreach (var metadataName in filteredItem.MetadataNames)
{
if (!itemFilter.Value.Contains(metadataName, StringComparer.OrdinalIgnoreCase))
{
filteredItem.RemoveMetadata(metadataName);
}
}
}
_items.Add(filteredItem);
}
}
// Restore immutability after editing newly cloned items.
_isImmutable = isImmutable;
// A filtered result is not useful for building anyway; ensure that
// it has minimal IPC wire cost.
_translateEntireState = false;
}
}
}
/// <summary>
/// Create a file based ProjectInstance.
/// </summary>
/// <param name="file">The file to evaluate the ProjectInstance from.</param>
/// <param name="options">The <see cref="ProjectOptions"/> to use.</param>
/// <returns></returns>
public static ProjectInstance FromFile(string file, ProjectOptions options)
{
return new ProjectInstance(
file,
options.GlobalProperties,
options.ToolsVersion,
options.SubToolsetVersion,
options.ProjectCollection ?? ProjectCollection.GlobalProjectCollection,
options.LoadSettings,
options.EvaluationContext,
options.DirectoryCacheFactory,
options.Interactive);
}
/// <summary>
/// Create a <see cref="ProjectRootElement"/> based ProjectInstance.
/// </summary>
/// <param name="rootElement">The <see cref="ProjectRootElement"/> to evaluate the ProjectInstance from.</param>
/// <param name="options">The <see cref="ProjectOptions"/> to use.</param>
public static ProjectInstance FromProjectRootElement(ProjectRootElement rootElement, ProjectOptions options)
{
return new ProjectInstance(
rootElement,
options.GlobalProperties,
options.ToolsVersion,
options.SubToolsetVersion,
options.ProjectCollection ?? ProjectCollection.GlobalProjectCollection,
options.LoadSettings,
options.EvaluationContext,
options.DirectoryCacheFactory,
options.Interactive);
}
/// <summary>
/// Create a ProjectInstance from an immutable project source.
/// </summary>
/// <param name="project">The immutable <see cref="Project"/> on which the ProjectInstance is based.</param>
/// <param name="settings">The <see cref="ProjectInstanceSettings"/> to use.</param>
public static ProjectInstance FromImmutableProjectSource(Project project, ProjectInstanceSettings settings)
{
bool fastItemLookupNeeded = settings.HasFlag(ProjectInstanceSettings.ImmutableWithFastItemLookup);
return new ProjectInstance(project, fastItemLookupNeeded);
}
private static IRetrievableEntryHashSet<ProjectItemDefinitionInstance> GetImmutableItemDefinitionsHashSetFromImmutableProject(Project linkedProject)
{
IDictionary<string, ProjectItemDefinition> linkedProjectItemDefinitions = linkedProject.ItemDefinitions;
VerifyCollectionImplementsRequiredDictionaryInterfaces(
linkedProjectItemDefinitions,
out IDictionary<string, ProjectItemDefinition> elementsDictionary,
out IDictionary<(string, int, int), ProjectItemDefinition> constrainedElementsDictionary);
var hashSet = new ImmutableElementCollectionConverter<ProjectItemDefinition, ProjectItemDefinitionInstance>(
elementsDictionary,
constrainedElementsDictionary,
ConvertCachedItemDefinitionToInstance);
return hashSet;
}
private static ImmutableItemDictionary<ProjectItem, ProjectItemInstance> GetImmutableItemsDictionaryFromImmutableProject(
Project linkedProject,
ProjectInstance owningProjectInstance)
{
var itemsByType = linkedProject.Items as IDictionary<string, ICollection<ProjectItem>>;
if (itemsByType == null)
{
throw new ArgumentException(nameof(linkedProject));
}
Func<ProjectItem, ProjectItemInstance> convertCachedItemToInstance =
projectItem => ConvertCachedProjectItemToInstance(linkedProject, owningProjectInstance, projectItem);
var itemDictionary = new ImmutableItemDictionary<ProjectItem, ProjectItemInstance>(
linkedProject.Items,
itemsByType,
convertCachedItemToInstance,
projectItemInstance => projectItemInstance.ItemType);
return itemDictionary;
}
private static ProjectItemInstance ConvertCachedProjectItemToInstance(
Project linkedProject,
ProjectInstance owningProjectInstance,
ProjectItem projectItem)
{
ProjectItemInstance result = null;
if (projectItem is IImmutableInstanceProvider<ProjectItemInstance> instanceProvider)
{
result = instanceProvider.ImmutableInstance;
if (result == null)
{
var newInstance = InstantiateProjectItemInstanceFromImmutableProjectSource(
linkedProject,
owningProjectInstance,
projectItem);
result = instanceProvider.GetOrSetImmutableInstance(newInstance);
}
}
return result;
}
private static ProjectItemDefinitionInstance ConvertCachedItemDefinitionToInstance(ProjectItemDefinition projectItemDefinition)
{
ProjectItemDefinitionInstance result = null;
if (projectItemDefinition is IImmutableInstanceProvider<ProjectItemDefinitionInstance> instanceProvider)
{
result = instanceProvider.ImmutableInstance;
if (result == null)
{
IDictionary<string, ProjectMetadataInstance> metadata = null;
if (projectItemDefinition.Metadata is IDictionary<string, ProjectMetadata> linkedMetadataDict)
{
metadata = new ImmutableElementCollectionConverter<ProjectMetadata, ProjectMetadataInstance>(
linkedMetadataDict,
constrainedProjectElements: null,
ConvertCachedProjectMetadataToInstance);
}
result = instanceProvider.GetOrSetImmutableInstance(
new ProjectItemDefinitionInstance(projectItemDefinition.ItemType, metadata));
}
}
return result;
}
private static ProjectMetadataInstance ConvertCachedProjectMetadataToInstance(ProjectMetadata projectMetadata)
{
ProjectMetadataInstance result = null;
if (projectMetadata is IImmutableInstanceProvider<ProjectMetadataInstance> instanceProvider)
{
result = instanceProvider.ImmutableInstance;
if (result == null)
{
result = instanceProvider.GetOrSetImmutableInstance(new ProjectMetadataInstance(projectMetadata));
}