Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DefaultMSBuildEngine.cs « MonoDevelop.Projects.MSBuild « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1d488525cf9dc911492388f02bc677d9bb2d6d77 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
//
// DefaultMSBuildEngine.cs
//
// Author:
//       Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using MonoDevelop.Core;
using MonoDevelop.Projects.MSBuild.Conditions;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using System.Collections.Immutable;

namespace MonoDevelop.Projects.MSBuild
{
	class DefaultMSBuildEngine: MSBuildEngine
	{
		Dictionary<FilePath, LoadedProjectInfo> loadedProjects = new Dictionary<FilePath, LoadedProjectInfo> ();

		// For test purposes.
		internal static Func<MSBuildProject, MSBuildEvaluationContext> GetEvaluationContext = null;

		class LoadedProjectInfo
		{
			public MSBuildProject Project;
			public DateTime LastWriteTime;
			public int ReferenceCount = 1;
			public bool NeedsLoad = false;
			public object LockObject = new object ();
		}

		class ProjectInfo
		{
			public ProjectInfo Parent;
			public MSBuildProject Project;
			public List<MSBuildItemEvaluated> EvaluatedItemsIgnoringCondition = new List<MSBuildItemEvaluated> ();
			public List<MSBuildItemEvaluated> EvaluatedItems = new List<MSBuildItemEvaluated> ();
			public List<MSBuildItemEvaluated> EvaluatedItemDefinitions = new List<MSBuildItemEvaluated> ();
			public Dictionary<string,PropertyInfo> Properties = new Dictionary<string, PropertyInfo> (StringComparer.OrdinalIgnoreCase);
			public Dictionary<MSBuildImport,string> Imports = new Dictionary<MSBuildImport, string> ();
			public Dictionary<string,string> GlobalProperties = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
			public List<MSBuildTarget> Targets = new List<MSBuildTarget> ();
			public List<MSBuildTarget> TargetsIgnoringCondition = new List<MSBuildTarget> ();
			public List<MSBuildProject> ReferencedProjects = new List<MSBuildProject> ();
			public Dictionary<MSBuildImport, List<ProjectInfo>> ImportedProjects = new Dictionary<MSBuildImport, List<ProjectInfo>> ();
			public ConditionedPropertyCollection ConditionedProperties = new ConditionedPropertyCollection ();
			public List<GlobInfo> GlobIncludes = new List<GlobInfo> ();
			public bool OnlyEvaluateProperties;

			public MSBuildProject GetRootMSBuildProject ()
			{
				if (Parent != null)
					return Parent.GetRootMSBuildProject ();
				return Project;
			}
        }

		class PropertyInfo
		{
			public string Name;
			public string Value;
			public string FinalValue;
			public bool IsImported;
			public bool DefinedMultipleTimes;
		}

		class GlobInfo
		{
			public MSBuildItem Item;
			public string Include;
			public Regex ExcludeRegex;
			public Regex DirectoryExcludeRegex;
			public Regex RemoveRegex;
			public bool Condition;
			public string [] IncludeSplit;

			public List<GlobInfo> Updates;
			public Regex UpdateRegex;
		}

		#region implemented abstract members of MSBuildEngine

		static HashSet<string> knownItemFunctions;
		static HashSet<string> knownStringItemFunctions;


		static DefaultMSBuildEngine ()
		{
			// List of string functions that can be used as item functions
			knownStringItemFunctions = new HashSet<string> (typeof (string).GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Select (m => m.Name));

			// List of known item functions
			knownItemFunctions = new HashSet<string> (new [] { "Count", "DirectoryName", "Distinct", "DistinctWithCase", "Reverse", "AnyHaveMetadataValue", "ClearMetadata", "HasMetadata", "Metadata", "WithMetadataValue" });

			// This collection will contain all item functions, including the string functions
			knownItemFunctions.UnionWith (knownStringItemFunctions);
		}

		public DefaultMSBuildEngine (MSBuildEngineManager manager): base (manager)
		{
		}

		public override object LoadProject (MSBuildProject project, string xml, FilePath fileName)
		{
			return project;
		}

		public override void UnloadProject (object project)
		{
		}

		MSBuildProject LoadProject (MSBuildEvaluationContext context, FilePath fileName)
		{
			fileName = fileName.CanonicalPath;

			LoadedProjectInfo pi;
			lock (loadedProjects) {
				if (!loadedProjects.TryGetValue (fileName, out pi)) {
					loadedProjects [fileName] = pi = new LoadedProjectInfo ();
				}
				pi.ReferenceCount++;
			}

			lock (pi.LockObject) {
				if (pi.Project == null) {
					pi.Project = new MSBuildProject (EngineManager);
					pi.NeedsLoad = true;
				}

				if (!pi.NeedsLoad)
					pi.NeedsLoad = pi.LastWriteTime != File.GetLastWriteTimeUtc (fileName);

				if (pi.NeedsLoad) {
					LogBeginProjectFileLoad (context, fileName);
					pi.LastWriteTime = File.GetLastWriteTimeUtc (fileName);
					pi.Project.Load (fileName, new MSBuildXmlReader { ForEvaluation = true });
					pi.NeedsLoad = false;
					LogEndProjectFileLoad (context);
				}

				return pi.Project;
			}
		}

		void UnloadProject (MSBuildProject project)
		{
			var fileName = project.FileName.CanonicalPath;
			LoadedProjectInfo pi;
			lock (loadedProjects) {
				if (!loadedProjects.TryGetValue (fileName, out pi))
					return;

				pi.ReferenceCount--;
				if (pi.ReferenceCount == 0) {
					loadedProjects.Remove (fileName);
					lock (pi.LockObject)
						pi.Project = null;
					project.Dispose ();
					//Console.WriteLine ("Unloaded: " + fileName);
				}
			}
		}

		public override object CreateProjectInstance (object project)
		{
			var pi = new ProjectInfo {
				Project = (MSBuildProject) project
			};
			return pi;
		}

		public override void DisposeProjectInstance (object projectInstance)
		{
			var pi = (ProjectInfo) projectInstance;
			foreach (var p in pi.ReferencedProjects)
				UnloadProject (p);
		}

		public override void Evaluate (object projectInstance)
		{
			Evaluate (projectInstance, false);
		}

		public override void Evaluate (object projectInstance, bool onlyEvaluateProperties)
		{
			var pi = (ProjectInfo) projectInstance;

			pi.EvaluatedItemsIgnoringCondition.Clear ();
			pi.EvaluatedItems.Clear ();
			pi.EvaluatedItemDefinitions.Clear ();
			pi.Properties.Clear ();
			pi.Imports.Clear ();
			pi.Targets.Clear ();
			pi.TargetsIgnoringCondition.Clear ();
			pi.OnlyEvaluateProperties = onlyEvaluateProperties;

			// Unload referenced projects after evaluating to avoid unnecessary unload + load
			var oldRefProjects = pi.ReferencedProjects;
			pi.ReferencedProjects = new List<MSBuildProject> ();

			try {
				var context = GetEvaluationContext?.Invoke (pi.Project) ?? new MSBuildEvaluationContext ();
				foreach (var p in pi.GlobalProperties) {
					context.SetPropertyValue (p.Key, p.Value);
					StoreProperty (pi, p.Key, p.Value, p.Value);
				}
#if MSBUILD_EVALUATION_STATS
				context.Log = new ConsoleMSBuildEngineLogger ();
#endif
				LogBeginEvaluationStage (context, "Evaluating Project: " + pi.Project.FileName);
				LogInitialEnvironment (context);
				EvaluateProject (pi, context);
				LogEndEvaluationStage (context);
			} finally {
				foreach (var p in oldRefProjects)
					UnloadProject (p);
				pi.ImportedProjects.Clear ();
			}
		}

		static char [] sdkPathSeparator = { ';' };
		void EvaluateProject (ProjectInfo pi, MSBuildEvaluationContext context)
		{
			context.InitEvaluation (pi.Project);
			var objects = pi.Project.GetAllObjects ();

			string[] implicitSdks = pi.Project.GetImplicitlyImportedSdks ();
			if (implicitSdks.Length > 0) {
				var rootProject = pi.GetRootMSBuildProject ();

				objects = implicitSdks.Select (sdkPath => new MSBuildImport { Sdk = sdkPath, Project = "Sdk.props" })
				                      .Concat (objects)
				                      .Concat (implicitSdks.Select (sdkPath => new MSBuildImport { Sdk = sdkPath, Project = "Sdk.targets" }));
			}

			// If there is a .user project file load it using a fake import item added at the end of the objects list
			if (File.Exists (pi.Project.FileName + ".user"))
				objects = objects.Concat (new MSBuildImport { Project = pi.Project.FileName + ".user" });

			objects = objects.ToList ();

			LogBeginEvaluationStage (context, "Evaluating Properties");
			LogBeginEvalProject (context, pi);

			EvaluateObjects (pi, context, objects, false);

			LogEndEvalProject (context, pi);
			LogEndEvaluationStage (context);

			if (!pi.OnlyEvaluateProperties) {
				LogBeginEvaluationStage (context, "Evaluating Items");
				LogBeginEvalProject (context, pi);

				EvaluateObjects (pi, context, objects, true);

				LogEndEvalProject (context, pi);
				LogEndEvaluationStage (context);
			}

			// Once items have been evaluated, we need to re-evaluate properties that contain item transformations
			// (or that contain references to properties that have transformations).

			foreach (var propName in context.GetPropertiesNeedingTransformEvaluation ()) {
				PropertyInfo prop;
				if (pi.Properties.TryGetValue (propName, out prop)) {
					// Execute the transformation
					prop.FinalValue = context.EvaluateWithItems (prop.FinalValue, pi.EvaluatedItems);

					// Set the resulting value back to the context, so other properties depending on this
					// one will get the new value when re-evaluated.
					context.SetPropertyValue (propName, prop.FinalValue);
				}
			}
		}

		void EvaluateProject (ProjectInfo pi, MSBuildEvaluationContext context, bool evalItems)
		{
			context.InitEvaluation (pi.Project);
			
			LogBeginEvalProject (context, pi);
			EvaluateObjects (pi, context, pi.Project.GetAllObjects (), evalItems);
			LogEndEvalProject (context, pi);
		}

		void EvaluateObjects (ProjectInfo pi, MSBuildEvaluationContext context, IEnumerable<MSBuildObject> objects, bool evalItems)
		{
			foreach (var ob in objects) {
				if (evalItems) {
					if (ob is MSBuildItemGroup)
						Evaluate (pi, context, (MSBuildItemGroup)ob);
					else if (ob is MSBuildTarget)
						Evaluate (pi, context, (MSBuildTarget)ob);
					else if (ob is MSBuildItemDefinitionGroup)
						Evaluate (pi, context, (MSBuildItemDefinitionGroup)ob);
				} else {
					if (ob is MSBuildPropertyGroup)
						Evaluate (pi, context, (MSBuildPropertyGroup)ob);
				}
				if (ob is MSBuildImportGroup)
					Evaluate (pi, context, (MSBuildImportGroup)ob, evalItems);
				else if (ob is MSBuildImport)
					Evaluate (pi, context, (MSBuildImport)ob, evalItems);
				else if (ob is MSBuildChoose)
					Evaluate (pi, context, (MSBuildChoose)ob, evalItems);
			}
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildPropertyGroup group)
		{
			if (!string.IsNullOrEmpty (group.Condition) && !SafeParseAndEvaluate (project, context, group.Condition, true))
				return;

			foreach (var prop in group.GetProperties ())
				Evaluate (project, context, prop);
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItemGroup items)
		{
			bool conditionIsTrue = true;

			if (!string.IsNullOrEmpty (items.Condition))
				conditionIsTrue = SafeParseAndEvaluate (project, context, items.Condition);

			foreach (var item in items.Items) {

				var trueCond = conditionIsTrue && (string.IsNullOrEmpty (item.Condition) || SafeParseAndEvaluate (project, context, item.Condition));

				if (!string.IsNullOrEmpty (item.Update)) {
					var update = context.EvaluateString (item.Update);

					var it = CreateEvaluatedItem (context, project, project.Project, item, update);

					var updateContext = new MSBuildEvaluationContext (context);
					if (update.IndexOf (';') == -1)
						UpdateItem (project, updateContext, item, update, trueCond, it);
					else {
						foreach (var inc in update.Split (new [] { ';' }, StringSplitOptions.RemoveEmptyEntries))
							UpdateItem (project, updateContext, item, inc, trueCond, it);
					}
				} else if (!string.IsNullOrEmpty (item.Remove)) {
					var remove = context.EvaluateString (item.Remove);

					if (remove.IndexOf (';') == -1)
						RemoveItem (project, item, remove, trueCond);
					else {
						foreach (var inc in remove.Split (new [] { ';' }, StringSplitOptions.RemoveEmptyEntries))
							RemoveItem (project, item, inc, trueCond);
					}
				} else if (!string.IsNullOrEmpty (item.Include)) {
					var include = context.EvaluateString (item.Include);
					var exclude = context.EvaluateString (item.Exclude);

					var it = CreateEvaluatedItem (context, project, project.Project, item, include);

					var excludeRegex = !string.IsNullOrEmpty (exclude) ? new Regex (ExcludeToRegex (exclude)) : null;

					Regex directoryExcludeRegex = null;
					if (!string.IsNullOrEmpty (exclude)) {
						string regex = ExcludeToRegex (exclude, true);
						if (!string.IsNullOrEmpty (regex)) {
							directoryExcludeRegex = new Regex (regex);
						}
					}

					if (it.Include.IndexOf (';') == -1)
						AddItem (project, context, item, it, it.Include, excludeRegex, directoryExcludeRegex, trueCond);
					else {
						foreach (var inc in it.Include.Split (new [] { ';' }, StringSplitOptions.RemoveEmptyEntries))
							AddItem (project, context, item, it, inc, excludeRegex, directoryExcludeRegex, trueCond);
					}
				}
			}
		}

		void UpdateItem (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, string update, bool trueCond, MSBuildItemEvaluated it)
		{
			if (IsWildcardInclude (update)) {
				var regex = new Regex (ExcludeToRegex (update));
				AddUpdateToGlobInclude (project, item, update, regex);
				var rootProject = project.GetRootMSBuildProject ();
				foreach (var f in GetIncludesForWildcardFilePath (rootProject, update)) {
					var fileName = rootProject.BaseDirectory.Combine (f.Replace ('\\', '/'));
					context.SetItemContext (update, fileName, null);
					UpdateEvaluatedItemInAllProjects (project, context, item, f, trueCond, it);
				}
			} else
				UpdateEvaluatedItemInAllProjects (project, null, item, update, trueCond, it);
		}

		void AddUpdateToGlobInclude (ProjectInfo project, MSBuildItem item, string update, Regex updateRegex)
		{
			do {
				foreach (var globInclude in project.GlobIncludes) {
					if (globInclude.Item.Name != item.Name)
						continue;

					if (globInclude.Updates == null)
						globInclude.Updates = new List<GlobInfo> ();
					globInclude.Updates.Add (new GlobInfo { Include = update, IncludeSplit = SplitWildcardFilePath (update), Item = item, UpdateRegex = updateRegex });
				}
				project = project.Parent;
			} while (project != null);
		}

		void UpdateEvaluatedItemInAllProjects (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, string include, bool trueCond, MSBuildItemEvaluated it)
		{
			do {
				UpdateEvaluatedItem (project, context, item, include, trueCond, it);
				project = project.Parent;
			} while (project != null);
		}

		void UpdateEvaluatedItem (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, string include, bool trueCond, MSBuildItemEvaluated it)
		{
			if (trueCond) {
				foreach (var item2 in project.EvaluatedItems) {
					if (item2.Name == item.Name && item2.Include == include) {
						if (context != null) {
							UpdateProperties (project, context, item, item2);
						} else {
							foreach (var evaluatedProp in ((MSBuildPropertyGroupEvaluated)it.Metadata).GetProperties ()) {
								((MSBuildPropertyGroupEvaluated)item2.Metadata).SetProperty (evaluatedProp.Name, evaluatedProp);
							}
						}
						item2.AddSourceItem (item);
					}
				}
			}

			foreach (var item2 in project.EvaluatedItemsIgnoringCondition) {
				if (item2.Name == item.Name && item2.Include == include) {
					if (context != null) {
						UpdateProperties (project, context, item, item2);
					} else {
						foreach (var evaluatedProp in ((MSBuildPropertyGroupEvaluated)it.Metadata).GetProperties ()) {
							((MSBuildPropertyGroupEvaluated)item2.Metadata).SetProperty (evaluatedProp.Name, evaluatedProp);
						}
					}
					item2.AddSourceItem (item);
				}
			}
		}

		void UpdateProperties (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, MSBuildItemEvaluated evaluatedItem)
		{
			var rootProject = project.GetRootMSBuildProject ();

			foreach (var p in item.Metadata.GetProperties ()) {
				if (string.IsNullOrEmpty (p.Condition) || SafeParseAndEvaluate (project, context, p.Condition, true)) {
					string evaluatedValue = context.EvaluateString (p.Value);
					string unevaluatedValue = p.Value;

					if (rootProject != item.ParentProject) {
						// Use the same evaluated value as the property value so expanded metadata properties from a wildcard
						// item are not saved in the project file.
						unevaluatedValue = evaluatedValue;
					}

					var evaluatedProp = new MSBuildPropertyEvaluated (project.Project, p.Name, unevaluatedValue, evaluatedValue) { Condition = p.Condition };
					((MSBuildPropertyGroupEvaluated)evaluatedItem.Metadata).SetProperty (evaluatedProp.Name, evaluatedProp);
				}
			}
		}

		/// <summary>
		/// Only supports exact match when looking for a glob.
		/// </summary>
		static Regex GetDirectoryExcludeRegex (ProjectInfo project, string wildcard)
		{
			return project.GlobIncludes.Where (g => g.Condition && g.Include == wildcard)
				.Select (g => g.DirectoryExcludeRegex)
				.FirstOrDefault ();
		}

		static void RemoveItem (ProjectInfo project, MSBuildItem item, string remove, bool trueCond)
		{
			if (IsWildcardInclude (remove)) {
				AddRemoveToGlobInclude (project, item, remove);
				var rootProject = project.GetRootMSBuildProject ();
				var directoryExcludeRegex = GetDirectoryExcludeRegex (project, remove);
				foreach (var f in GetIncludesForWildcardFilePath (rootProject, remove, directoryExcludeRegex))
					RemoveEvaluatedItemFromAllProjects (project, item, f, trueCond);
			} else
				RemoveEvaluatedItemFromAllProjects (project, item, remove, trueCond);
		}

		/// <summary>
		/// Adds a glob remove to the corresponding glob include. This remove is then checked
		/// in FindGlobItemsIncludingFile so that a glob item is not returned if the file was removed
		/// from that glob.
		/// </summary>
		static void AddRemoveToGlobInclude (ProjectInfo project, MSBuildItem item, string remove)
		{
			var exclude = ExcludeToRegex (remove);
			do {
				foreach (var globInclude in project.GlobIncludes) {
					if (globInclude.Item.Name != item.Name)
						continue;

					if (globInclude.RemoveRegex != null)
						exclude = globInclude.RemoveRegex + "|" + exclude;
					globInclude.RemoveRegex = new Regex (exclude);
				}
				project = project.Parent;
			} while (project != null);
		}

		static void RemoveEvaluatedItemFromAllProjects (ProjectInfo project, MSBuildItem item, string include, bool trueCond)
		{
			do {
				RemoveEvaluatedItem (project, item, include, trueCond);
				project = project.Parent;
			} while (project != null);
		}

		static void RemoveEvaluatedItem (ProjectInfo project, MSBuildItem item, string include, bool trueCond)
		{
			if (trueCond)
				project.EvaluatedItems.RemoveAll (it => it.Name == item.Name && it.Include == include);
			project.EvaluatedItemsIgnoringCondition.RemoveAll (it => it.Name == item.Name && it.Include == include);
		}

		void AddItem (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, MSBuildItemEvaluated it, string include, Regex excludeRegex, Regex directoryExcludeRegex, bool trueCond)
		{
			// Don't add the result from any item that has an empty include. MSBuild never returns those.
			if (include == string.Empty)
				return;
			
			if (IsIncludeTransform (include)) {
				// This is a transform
				List<MSBuildItemEvaluated> evalItems;
				var transformExp = include.AsSpan (2, include.Length - 3);
				if (ExecuteTransform (project, context, item, transformExp, out evalItems)) {
					foreach (var newItem in evalItems) {
						project.EvaluatedItemsIgnoringCondition.Add (newItem);
						if (trueCond)
							project.EvaluatedItems.Add (newItem);
					}
				}
			} else if (IsWildcardInclude (include)) {
				project.GlobIncludes.Add (new GlobInfo { Item = item, Include = include, IncludeSplit = SplitWildcardFilePath (include), ExcludeRegex = excludeRegex, DirectoryExcludeRegex = directoryExcludeRegex, Condition = trueCond });
				foreach (var eit in ExpandWildcardFilePath (project, context, item, include, directoryExcludeRegex)) {
					if (excludeRegex != null && excludeRegex.IsMatch (eit.Include))
						continue;
					project.EvaluatedItemsIgnoringCondition.Add (eit);
					if (trueCond)
						project.EvaluatedItems.Add (eit);
				}
			} else if (include != it.Include) {
				if (excludeRegex != null && excludeRegex.IsMatch (include))
					return;
				it = CreateEvaluatedItem (context, project, project.Project, item, include);
				project.EvaluatedItemsIgnoringCondition.Add (it);
				if (trueCond)
					project.EvaluatedItems.Add (it);
			} else {
				if (excludeRegex != null && excludeRegex.IsMatch (include))
					return;
				project.EvaluatedItemsIgnoringCondition.Add (it);
				if (trueCond)
					project.EvaluatedItems.Add (it);
			}
		}

		bool ExecuteTransform (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItem item, ReadOnlySpan<char> transformExp, out List<MSBuildItemEvaluated> items)
		{
			bool ignoreMetadata = false;

			items = new List<MSBuildItemEvaluated> ();
			string itemName, expression, itemFunction; object [] itemFunctionArgs;

			// This call parses the transforms and extracts: the name of the item list to transform, the whole transform expression (or null if there isn't). If the expression can be
			// parsed as an item funciton, then it returns the function name and the list of arguments. Otherwise those parameters are null.
			if (!ParseTransformExpression (context, transformExp, out itemName, out expression, out itemFunction, out itemFunctionArgs))
				return false;

			// Get the items mathing the referenced item list
			var transformItems = project.EvaluatedItems.Where (i => i.Name == itemName).ToArray ();

			if (itemFunction != null) {
				// First of all, try to execute the function as a summary function, that is, a function that returns a single value for
				// the whole list (such as Count).
				// After that, try executing as a list transformation function: a function that changes the order or filters out items from the list.

				string result;
				if (ExecuteSummaryItemFunction (transformItems, itemFunction, itemFunctionArgs, out result)) {
					// The item function returns a value. Just create an item with that value
					var newItem = new MSBuildItemEvaluated (project.Project, item.Name, item.Include, result);
					project.EvaluatedItemsIgnoringCondition.Add (newItem);
					items.Add (newItem);
					return true;
				} else if (ExecuteTransformItemListFunction (ref transformItems, itemFunction, itemFunctionArgs, out ignoreMetadata)) {
					expression = null;
					itemFunction = null;
				}
			}

			foreach (var eit in transformItems) {
				// Some item functions cause the erasure of metadata. Take that into account now.
				context.SetItemContext (null, eit.Include, null, ignoreMetadata || item == null ? null : eit.Metadata);
				try {
					// If there is a function that transforms the include of the item, it needs to be applied now. Otherwise just use the transform expression
					// as include, or the transformed item include if there is no expression.

					string evaluatedInclude; bool skip;
					if (itemFunction != null && ExecuteTransformIncludeItemFunction (context, eit, itemFunction, itemFunctionArgs, out evaluatedInclude, out skip)) {
						if (skip) continue;
					} else if (expression != null)
						evaluatedInclude = context.EvaluateString (expression);
					else
						evaluatedInclude = eit.Include;

					var newItem = new MSBuildItemEvaluated (project.Project, item.Name, item.Include, evaluatedInclude);
					if (!ignoreMetadata) {
						var md = new Dictionary<string, IMSBuildPropertyEvaluated> ();
						// Add metadata from the evaluated item
						var col = (MSBuildPropertyGroupEvaluated)eit.Metadata;
						foreach (var p in col.GetProperties ()) {
							md [p.Name] = new MSBuildPropertyEvaluated (project.Project, p.Name, p.UnevaluatedValue, p.Value);
						}
						// Now override metadata from the new item definition
						foreach (var c in item.Metadata.GetProperties ()) {
							if (string.IsNullOrEmpty (c.Condition) || SafeParseAndEvaluate (project, context, c.Condition, true))
								md [c.Name] = new MSBuildPropertyEvaluated (project.Project, c.Name, c.Value, context.EvaluateString (c.Value));
						}
						((MSBuildPropertyGroupEvaluated)newItem.Metadata).SetProperties (md);
					}
					newItem.AddSourceItem (item);
					newItem.Condition = item.Condition;
					items.Add (newItem);
				} finally {
					context.ClearItemContext ();
				}
			}
			return true;
		}

		internal static bool ExecuteStringTransform (List<MSBuildItemEvaluated> evaluatedItemsCollection, MSBuildEvaluationContext context, ReadOnlySpan<char> transformExp, out string items)
		{
			// This method works mostly like ExecuteTransform, but instead of returning a list of items, it returns a string as result.
			// Since there is no need to create full blown evaluated items, it can be more efficient than ExecuteTransform.

			items = "";

			string itemName, expression, itemFunction; object [] itemFunctionArgs;
			if (!ParseTransformExpression (context, transformExp, out itemName, out expression, out itemFunction, out itemFunctionArgs))
				return false;

			var transformItems = evaluatedItemsCollection.Where (i => i.Name == itemName).ToArray ();
			if (itemFunction != null) {
				string result; bool ignoreMetadata;
				if (ExecuteSummaryItemFunction (transformItems, itemFunction, itemFunctionArgs, out result)) {
					// The item function returns a value. Just return it.
					items = result;
					return true;
				} else if (ExecuteTransformItemListFunction (ref transformItems, itemFunction, itemFunctionArgs, out ignoreMetadata)) {
					var sb = StringBuilderCache.Allocate ();
					for (int n = 0; n < transformItems.Length; n++) {
						if (n > 0)
							sb.Append (';');
						sb.Append (transformItems[n].Include);
					}	
					items = StringBuilderCache.ReturnAndFree (sb);
					return true;
				}
			}

			var sbi = StringBuilderCache.Allocate ();

			int count = 0;
			foreach (var eit in transformItems) {
				context.SetItemContext (null, eit.Include, null, eit.Metadata);
				try {
					string evaluatedInclude; bool skip;
					if (itemFunction != null && ExecuteTransformIncludeItemFunction (context, eit, itemFunction, itemFunctionArgs, out evaluatedInclude, out skip)) {
						if (skip) continue;
					} else if (expression != null)
						evaluatedInclude = context.EvaluateString (expression);
					else
						evaluatedInclude = eit.Include;

					if (count++ > 0)
						sbi.Append (';');
					sbi.Append (evaluatedInclude);

				} finally {
					context.ClearItemContext ();
				}
			}
			items = Core.StringBuilderCache.ReturnAndFree (sbi);
			return true;
		}

		static bool ParseTransformExpression (MSBuildEvaluationContext context, ReadOnlySpan<char> include, out string itemName, out string expression, out string itemFunction, out object [] itemFunctionArgs)
		{
			// This method parses the transforms and extracts: the name of the item list to transform, the whole transform expression (or null if there isn't). If the expression can be
			// parsed as an item funciton, then it returns the function name and the list of arguments. Otherwise those parameters are null.
		
			expression = null;
			itemFunction = null;
			itemFunctionArgs = null;
		
			int i = include.IndexOf ("->".AsSpan (), StringComparison.Ordinal);
			if (i == -1) {
				itemName = include.Trim ().ToString ();
				return itemName.Length > 0;
			}
			itemName = include.Slice (0, i).Trim ().ToString ();
			if (itemName.Length == 0)
				return false;
			
			var expressionSpan = include.Slice (i + 2).Trim ();
			if (expressionSpan.Length > 1 && expressionSpan [0]=='\'' && expressionSpan [expressionSpan.Length - 1] == '\'') {
				expression = expressionSpan.Slice (1, expressionSpan.Length - 2).ToString ();
				return true;
			}
			expression = expressionSpan.ToString ();
			i = expressionSpan.IndexOf ('(');
			if (i == -1)
				return true;

			var func = expressionSpan.Slice (0, i).Trim ().ToString ();
			if (knownItemFunctions.Contains (func)) {
				itemFunction = func;
				i++;
				context.EvaluateParameters (expressionSpan, ref i, out itemFunctionArgs);
				return true;
			}
			return true;
		}

		static bool ExecuteTransformIncludeItemFunction (MSBuildEvaluationContext context, MSBuildItemEvaluated item, string itemFunction, object [] itemFunctionArgs, out string evaluatedInclude, out bool skip)
		{
			evaluatedInclude = null;
			skip = false;

			switch (itemFunction) {
			case "DirectoryName":
				var path = MSBuildProjectService.FromMSBuildPath (context.Project.BaseDirectory, item.Include);
				evaluatedInclude = Path.GetDirectoryName (path);
				return true;
			case "Metadata":
				if (itemFunctionArgs.Length != 1)
					return false;
				var p = item.Metadata.GetProperty (itemFunctionArgs [0].ToString ());
				if (p == null) {
					skip = true;
					return true;
				} else {
					evaluatedInclude = p.Value;
					return true;
				}
			}
			if (knownStringItemFunctions.Contains (itemFunction)) {
				object res;
				if (context.EvaluateMember (itemFunction.AsSpan (), typeof (string), itemFunction, item.Include, itemFunctionArgs, out res)) {
					evaluatedInclude = res.ToString ();
					return true;
				}
			}
			return false;
		}

		static bool ExecuteSummaryItemFunction (MSBuildItemEvaluated [] transformItems, string itemFunction, object [] itemFunctionArgs, out string result)
		{
			result = null;
			switch (itemFunction) {
			case "Count":
				result = transformItems.Length.ToString ();
				return true;
			case "AnyHaveMetadataValue":
				if (itemFunctionArgs.Length != 2)
					return false;
				result = transformItems.Any (it => string.Compare (it.Metadata.GetValue (itemFunctionArgs [0].ToString ()), itemFunctionArgs [1].ToString (), true) == 0).ToString ().ToLower ();
				return true;
			}
			return false;
		}

		static bool ExecuteTransformItemListFunction (ref MSBuildItemEvaluated[] transformItems, string itemFunction, object[] itemFunctionArgs, out bool ignoreMetadata)
		{
			switch (itemFunction) {
			case "Reverse":
				ignoreMetadata = false;
				transformItems = transformItems.Reverse ().ToArray ();
				return true;
			case "HasMetadata":
				ignoreMetadata = false;
				if (itemFunctionArgs.Length != 1)
					return false;
				transformItems = transformItems.Where (it => it.Metadata.HasProperty (itemFunctionArgs [0].ToString ())).ToArray ();
				return true;
			case "WithMetadataValue":
				ignoreMetadata = false;
				if (itemFunctionArgs.Length != 2)
					return false;
				transformItems = transformItems.Where (it => string.Compare (it.Metadata.GetValue (itemFunctionArgs [0].ToString ()), itemFunctionArgs [1].ToString (), true) == 0).ToArray ();
				return true;
			case "ClearMetadata":
				ignoreMetadata = true;
				return true;
			case "Distinct":
			case "DistinctWithCase":
				var values = new HashSet<string> (itemFunction == "Distinct" ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
				var result = new List<MSBuildItemEvaluated> ();
				foreach (var it in transformItems) {
					if (values.Add (it.Include))
						result.Add (it);
				}
				transformItems = result.ToArray ();
				ignoreMetadata = true;
				return true;
			}
			ignoreMetadata = false;
			return false;
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildImportGroup imports, bool evalItems)
		{
			if (!string.IsNullOrEmpty (imports.Condition) && !SafeParseAndEvaluate (project, context, imports.Condition, true))
				return;

			foreach (var item in imports.Imports)
				Evaluate (project, context, item, evalItems);
		}

		static bool IsWildcardInclude (string include)
		{
			return include.IndexOf ('*') != -1;
		}

		IEnumerable<MSBuildItemEvaluated> ExpandWildcardFilePath (ProjectInfo pinfo, MSBuildEvaluationContext context, MSBuildItem sourceItem, string path, Regex directoryExcludeRegex)
		{
			var subpath = SplitWildcardFilePath (path);
		
			MSBuildProject project = pinfo.Project;
			WildcardExpansionFunc<MSBuildItemEvaluated> func = delegate (string file, string include, string recursiveDir) {
				return CreateEvaluatedItem (context, pinfo, project, sourceItem, include, file, recursiveDir);
			};
			MSBuildProject rootProject = pinfo.GetRootMSBuildProject ();
			return ExpandWildcardFilePath (rootProject, rootProject.BaseDirectory, FilePath.Null, false, subpath.AsSpan (), func, directoryExcludeRegex);
		}

		static IEnumerable<string> GetIncludesForWildcardFilePath (MSBuildProject project, string path, Regex directoryExcludeRegex = null)
		{
			var subpath = SplitWildcardFilePath (path);

			WildcardExpansionFunc<string> func = (file, include, recursiveDir) => include;
			return ExpandWildcardFilePath (project, project.BaseDirectory, FilePath.Null, false, subpath.AsSpan (), func, directoryExcludeRegex);
		}

		static string[] SplitWildcardFilePath (string path)
		{
			path = path.Replace ('/', '\\');
			if (path == "**" || path.EndsWith ("\\**", StringComparison.Ordinal))
				path = path + "\\*";
			return path.Split ('\\');
		}

		delegate T WildcardExpansionFunc<T> (string filePath, string include, string recursiveDir);

		static IEnumerable<T> ExpandWildcardFilePath<T> (MSBuildProject project, FilePath basePath, FilePath baseRecursiveDir, bool recursive, Span<string> filePath, WildcardExpansionFunc<T> func, Regex directoryExcludeRegex)
		{
			var res = Enumerable.Empty<T> ();

			if (filePath.Length == 0)
				return res;

			var path = filePath [0];

			if (path == "..")
				return ExpandWildcardFilePath (project, basePath.ParentDirectory, baseRecursiveDir, recursive, filePath.Slice (1), func, directoryExcludeRegex);

			if (path == ".")
				return ExpandWildcardFilePath (project, basePath, baseRecursiveDir, recursive, filePath.Slice (1), func, directoryExcludeRegex);

			if (directoryExcludeRegex != null && directoryExcludeRegex.IsMatch (basePath.ToString ().Replace ('/', '\\')))
				return res;

			if (!Directory.Exists (basePath))
				return res;

			if (path == "**") {
				// if this is the last component of the path, there isn't any file specifier, so there is no possible match
				if (filePath.Length == 1)
					return res;

				// If baseRecursiveDir has already been set, don't overwrite it.
				if (baseRecursiveDir.IsNullOrEmpty)
					baseRecursiveDir = basePath;

				return ExpandWildcardFilePath (project, basePath, baseRecursiveDir, true, filePath.Slice (1), func, directoryExcludeRegex);
			}

			if (filePath.Length == 1) {
				// Last path component. It has to be a file specifier.
				string baseDir = basePath.ToRelative (project.BaseDirectory).ToString ().Replace ('/', '\\');
				if (baseDir == ".")
					baseDir = "";
				else if (!baseDir.EndsWith ("\\", StringComparison.Ordinal))
					baseDir += '\\';
				var recursiveDir = baseRecursiveDir.IsNullOrEmpty ? FilePath.Null : basePath.ToRelative (baseRecursiveDir);
				res = res.Concat (Directory.EnumerateFiles (basePath, path).Select (f => func (f, baseDir + Path.GetFileName (f), recursiveDir)));
			} else {
				// Directory specifier
				// Look for matching directories.
				// The search here is non-recursive, not matter what the 'recursive' parameter says, since we are trying to match a subpath.
				// The recursive search is done below.

				if (path.IndexOfAny (wildcards) != -1) {
					foreach (var dir in Directory.EnumerateDirectories (basePath, path))
						res = res.Concat (ExpandWildcardFilePath (project, dir, baseRecursiveDir, false, filePath.Slice (1), func, directoryExcludeRegex));
				} else
					res = res.Concat (ExpandWildcardFilePath (project, basePath.Combine (path), baseRecursiveDir, false, filePath.Slice (1), func, directoryExcludeRegex));
			}

			if (recursive) {
				// Recursive search. Try to match the remaining subpath in all subdirectories.
				foreach (var dir in Directory.EnumerateDirectories (basePath))
					res = res.Concat (ExpandWildcardFilePath (project, dir, baseRecursiveDir, true, filePath, func, directoryExcludeRegex));
			}

			return res;
		}

		static string ExcludeToRegex (string exclude, bool excludeDirectoriesOnly = false)
		{
			exclude = exclude.Replace ('/', '\\').Replace (@"\\", @"\");
			var sb = StringBuilderCache.Allocate ();
			foreach (var ep in exclude.Split (new char [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
				var ex = ep.AsSpan ().Trim ();
				if (excludeDirectoriesOnly) {
					if (ex.EndsWith (@"\**".AsSpan (), StringComparison.OrdinalIgnoreCase))
						ex = ex.Slice (0, ex.Length - 3);
					else
						continue;
				}
                if (sb.Length > 0)
					sb.Append ('|');
				sb.Append ('^');
                for (int n = 0; n < ex.Length; n++) {
					var c = ex [n];
					if (c == '*') {
						if (n < ex.Length - 1 && ex [n + 1] == '*') {
							if (n < ex.Length - 2 && ex [n + 2] == '\\') {
								// zero or more subdirectories
								sb.Append ("(.*\\\\)?");
								n += 2;
							} else {
								sb.Append (".*");
								n++;
							}
						}
						else
							sb.Append ("[^\\\\]*");
					} else if (regexEscapeChars.Contains (c)) {
						sb.Append ('\\').Append (c);
					} else
						sb.Append (c);
				}
				sb.Append ('$');
			}
			return Core.StringBuilderCache.ReturnAndFree (sb);
        }

		static char [] regexEscapeChars = { '\\', '^', '$', '{', '}', '[', ']', '(', ')', '.', '*', '+', '?', '|', '<', '>', '-', '&' };

		static bool IsIncludeTransform (string include)
		{
			return include.Length > 3 && include [0] == '@' && include [1] == '(' && include [include.Length - 1] == ')';
		}

		MSBuildItemEvaluated CreateEvaluatedItem (MSBuildEvaluationContext context, ProjectInfo pinfo, MSBuildProject project, MSBuildItem sourceItem, string include, string evaluatedFile = null, string recursiveDir = null)
		{
			include = StringInternPool.AddShared (include);

			var it = new MSBuildItemEvaluated (project, sourceItem.Name, sourceItem.Include, include);
			var md = new Dictionary<string,IMSBuildPropertyEvaluated> ();
			// Only evaluate properties for non-transforms.
			if (!IsIncludeTransform (include)) {
				try {
					context.SetItemContext (include, evaluatedFile, recursiveDir);
					foreach (var c in sourceItem.Metadata.GetProperties ()) {
						if (string.IsNullOrEmpty (c.Condition) || SafeParseAndEvaluate (pinfo, context, c.Condition, true))
							md [c.Name] = new MSBuildPropertyEvaluated (project, c.Name, c.Value, context.EvaluateString (c.Value)) { Condition = c.Condition };
					}
				} finally {
					context.ClearItemContext ();
				}
			}
			((MSBuildPropertyGroupEvaluated)it.Metadata).SetProperties (md);
			it.AddSourceItem (sourceItem);
			it.Condition = sourceItem.Condition;
			return it;
		}

		static char[] wildcards = { '*', '%' };

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildProperty prop)
		{
			if (string.IsNullOrEmpty (prop.Condition) || SafeParseAndEvaluate (project, context, prop.Condition, true)) {
				bool needsItemEvaluation;
				var val = context.Evaluate (prop.UnevaluatedValue, out needsItemEvaluation);
				if (needsItemEvaluation)
					context.SetPropertyNeedsTransformEvaluation (prop.Name);
				StoreProperty (project, prop.Name, prop.UnevaluatedValue, val);
				context.SetPropertyValue (prop.Name, val);
			}
		}

		IReadOnlyList<ProjectInfo> GetImportedProjects (ProjectInfo project, MSBuildImport import)
		{
			List<ProjectInfo> prefProjects;
			if (project.ImportedProjects.TryGetValue (import, out prefProjects))
				return prefProjects;
			return Array.Empty<ProjectInfo> ();
		}

		void AddImportedProject (ProjectInfo project, MSBuildImport import, ProjectInfo imported)
		{
			List<ProjectInfo> prefProjects;
			if (!project.ImportedProjects.TryGetValue (import, out prefProjects))
				project.ImportedProjects [import] = prefProjects = new List<ProjectInfo> ();
			prefProjects.Add (imported);
        }

		void DisposeImportedProjects (ProjectInfo pi)
		{
			foreach (var imported in pi.ImportedProjects.Values.SelectMany (i => i)) {
				DisposeImportedProjects (imported);
				DisposeProjectInstance (imported);
			}
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildImport import, bool evalItems)
		{
			if (evalItems) {
				// Properties have already been evaluated
				// Don't evaluate properties, only items and other elements
				var importedProjects = GetImportedProjects (project, import);
				for (int i = 0; i < importedProjects.Count; ++i) {
					var p = importedProjects [i];
					
					EvaluateProject (p, new MSBuildEvaluationContext (context), true);

					foreach (var it in p.EvaluatedItems) {
						it.IsImported = true;
						project.EvaluatedItems.Add (it);
					}
					foreach (var it in p.EvaluatedItemsIgnoringCondition) {
						it.IsImported = true;
						project.EvaluatedItemsIgnoringCondition.Add (it);
					}
					foreach (var it in p.EvaluatedItemDefinitions) {
						project.EvaluatedItemDefinitions.Add (it);
					}
					foreach (var t in p.Targets) {
						t.IsImported = true;
						project.Targets.Add (t);
					}
					foreach (var t in p.TargetsIgnoringCondition) {
						t.IsImported = true;
						project.TargetsIgnoringCondition.Add (t);
					}
					project.ConditionedProperties.Append (p.ConditionedProperties);
					project.GlobIncludes.AddRange (p.GlobIncludes);
				}
				return;
            }


			// Try importing the files using the import as is

			bool keepSearching;

			// If the import is an SDK import, this will contain the SDKs path used to resolve the import.
			string resolvedSdksPath;

			var files = GetImportFiles (project, context, import, null, null, out resolvedSdksPath, out keepSearching);
			if (files != null) {
				foreach (var f in files)
					ImportFile (project, context, import, f, resolvedSdksPath);
			}

			// We may need to keep searching if the import was not found, or if the import had a wildcard.
			// In that case, look in fallback search paths

			if (keepSearching) {
				// Short-circuit if we don't have an import that is done via a property.
				int propertyStart = import.Project.IndexOf ("$(", StringComparison.Ordinal);
				if (propertyStart == -1)
					return;
				
				var importSearchPaths = context.GetProjectImportSearchPaths ();
				for (int i = 0; i < importSearchPaths.Count; ++i) {
					var prop = importSearchPaths [i];

					// Start searching from where the property was found.
					if (import.Project.IndexOf (prop.MSBuildProperty, propertyStart, StringComparison.OrdinalIgnoreCase) == -1)
						continue;

					files = GetImportFiles (project, context, import, prop.Property, prop.Path, out resolvedSdksPath, out keepSearching);
					if (files != null) {
						foreach (var f in files)
							ImportFile (project, context, import, f, resolvedSdksPath);
					}
					if (!keepSearching)
						break;
				}
			}
		}

		string[] GetImportFiles (ProjectInfo project, MSBuildEvaluationContext context, MSBuildImport import, string pathProperty, string pathPropertyValue, out string resolvedSdksPath, out bool keepSearching)
		{
			// This methods looks for targets in location specified by the import, and replacing pathProperty by a specific value.

			if (pathPropertyValue != null) {
				var tempCtx = new MSBuildEvaluationContext (context);
				var mep = MSBuildProjectService.ToMSBuildPath (null, pathPropertyValue);
				tempCtx.SetContextualPropertyValue (pathProperty, mep);
				context = tempCtx;
			}

			resolvedSdksPath = null;
			var projectPath = context.EvaluateString (import.Project);
			project.Imports [import] = projectPath;

			string basePath;
			if (!string.IsNullOrEmpty (import.Sdk) && SdkReference.TryParse (import.Sdk, out var sdkRef)) {
				basePath = SdkResolution.GetResolver (project.GetRootMSBuildProject ().TargetRuntime).GetSdkPath (sdkRef, CustomLoggingService.Instance, null, project.Project.FileName, project.Project.SolutionDirectory);
				if (basePath == null) {
					keepSearching = true;
					return null;
				} else
					// We return here the value of $(MSBuildSDKsPath) where this SDK is located
					resolvedSdksPath = ((FilePath)basePath).ParentDirectory.ParentDirectory;
			} else
				basePath = project.Project.BaseDirectory;

			if (!string.IsNullOrEmpty (import.Condition) && !SafeParseAndEvaluate (project, context, import.Condition, true, basePath)) {
				// Condition evaluates to false. Keep searching because maybe another value for the path property makes
				// the condition evaluate to true.
				keepSearching = true;
				return null;
			}

			string path = MSBuildProjectService.FromMSBuildPath (basePath, projectPath);

			var fileName = Path.GetFileName (path);

			if (fileName.IndexOfAny (new [] { '*', '?' }) == -1) {
				// Not a wildcard. Keep searching if the file doesn't exist.
				var result = File.Exists (path) ? new [] { path } : null;
				keepSearching = result == null;
				return result;
			}
			else {
				// Wildcard import. Always keep searching since we want to import all files that match from all search paths.
				keepSearching = true;
				path = Path.GetDirectoryName (path);
				if (!Directory.Exists (path))
					return null;
				var files = Directory.GetFiles (path, fileName);
				Array.Sort (files);
				return files;
			}
		}

		void ImportFile (ProjectInfo project, MSBuildEvaluationContext context, MSBuildImport import, string file, string resolvedSdksPath)
		{
			if (!File.Exists (file))
				return;

			context.AddImport (file);

			var pref = LoadProject (context, file);
			project.ReferencedProjects.Add (pref);

			var prefProject = new ProjectInfo { Project = pref, Parent = project };
			AddImportedProject (project, import, prefProject);

			var refCtx = new MSBuildEvaluationContext (context);

			// If the imported file belongs to an SDK, set the MSBuildSDKsPath property since some
			// sdk files use that to reference other targets from the same sdk.
			if (resolvedSdksPath != null)
				refCtx.SetContextualPropertyValue ("MSBuildSDKsPath", resolvedSdksPath);

			EvaluateProject (prefProject, refCtx, false);

			foreach (var p in prefProject.Properties) {
				p.Value.IsImported = true;

				// If the importer project already has a value for this property, flag it as defined multiple times
				if (project.Properties.ContainsKey (p.Key))
					p.Value.DefinedMultipleTimes = true;
				
				project.Properties [p.Key] = p.Value;
			}

			context.RemoveImport (file);
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildChoose choose, bool evalItems)
		{
			foreach (var op in choose.GetOptions ()) {
				if (op.IsOtherwise || SafeParseAndEvaluate (project, context, op.Condition, true)) {
					EvaluateObjects (project, context, op.GetAllObjects (), evalItems);
					break;
				}
			}
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildTarget target)
		{
			bool condIsTrue = SafeParseAndEvaluate (project, context, target.Condition);
			var newTarget = new MSBuildTarget (target.Name, target.Tasks);
			newTarget.AfterTargets = context.EvaluateString (target.AfterTargets);
			newTarget.Inputs = context.EvaluateString (target.Inputs);
			newTarget.Outputs = context.EvaluateString (target.Outputs);
			newTarget.BeforeTargets = context.EvaluateString (target.BeforeTargets);
			newTarget.DependsOnTargets = context.EvaluateString (target.DependsOnTargets);
			newTarget.Returns = context.EvaluateString (target.Returns);
			newTarget.KeepDuplicateOutputs = context.EvaluateString (target.KeepDuplicateOutputs);
			project.TargetsIgnoringCondition.Add (newTarget);
			if (condIsTrue)
				project.Targets.Add (newTarget);
		}

		void Evaluate (ProjectInfo project, MSBuildEvaluationContext context, MSBuildItemDefinitionGroup items)
		{
			bool conditionIsTrue = true;

			if (!string.IsNullOrEmpty (items.Condition))
				conditionIsTrue = SafeParseAndEvaluate (project, context, items.Condition);

			foreach (var item in items.Items) {
				var trueCond = conditionIsTrue && (string.IsNullOrEmpty (item.Condition) || SafeParseAndEvaluate (project, context, item.Condition));
				if (trueCond) {
					var it = CreateEvaluatedItem (context, project, project.Project, item, string.Empty);
					project.EvaluatedItemDefinitions.Add (it);
				}
			}
		}

		ImmutableDictionary<string, ConditionExpression> conditionCache = ImmutableDictionary<string, ConditionExpression>.Empty;
		bool SafeParseAndEvaluate (ProjectInfo project, MSBuildEvaluationContext context, string condition, bool collectConditionedProperties = false, string customEvalBasePath = null)
		{
			try {
				if (String.IsNullOrEmpty (condition))
					return true;

				context.CustomFullDirectoryName = customEvalBasePath;

				try {
					ConditionExpression ce = ImmutableInterlocked.GetOrAdd (ref conditionCache, condition, key => ConditionParser.ParseCondition (key));

					if (collectConditionedProperties)
						ce.CollectConditionProperties (project.ConditionedProperties);

					if (!ce.TryEvaluateToBool (context, out bool value))
						throw new InvalidProjectFileException (String.Format ("Can not evaluate \"{0}\" to bool.", condition));

					return value;
				} catch (ExpressionParseException epe) {
					throw new InvalidProjectFileException (
						String.Format ("Unable to parse condition \"{0}\" : {1}", condition, epe.Message),
						epe);
				} catch (ExpressionEvaluationException epe) {
					throw new InvalidProjectFileException (
						String.Format ("Unable to evaluate condition \"{0}\" : {1}", condition, epe.Message),
						epe);
				}
			}
			catch {
				// The condition is likely to be invalid
				return false;
			}
			finally {
				context.CustomFullDirectoryName = null;
			}
		}

		void StoreProperty (ProjectInfo project, string name, string value, string finalValue)
		{
			PropertyInfo pi;
			if (project.Properties.TryGetValue (name, out pi)) {
				pi.Value = value;
				pi.FinalValue = finalValue;
				pi.DefinedMultipleTimes = true;
			} else
				project.Properties [name] = new PropertyInfo { Name = name, Value = value, FinalValue = finalValue };
		}

		public override bool GetItemHasMetadata (object item, string name)
		{
			var it = item as MSBuildItem;
			if (it != null)
				return it.Metadata.HasProperty (name);
			return ((IMSBuildItemEvaluated) item).Metadata.HasProperty (name);
		}

		public override string GetItemMetadata (object item, string name)
		{
			var it = item as MSBuildItem;
			if (it != null)
				return it.Metadata.GetValue (name);
			return ((IMSBuildItemEvaluated)item).Metadata.GetValue (name);
		}

		public override string GetEvaluatedItemMetadata (object item, string name)
		{
			IMSBuildItemEvaluated it = (IMSBuildItemEvaluated) item;
			return it.Metadata.GetValue (name);
		}

		public override IEnumerable<string> GetItemMetadataNames (object item)
		{
			var it = item as MSBuildItem;
			if (it != null)
				return it.Metadata.GetProperties ().Select (p => p.Name);
			return ((IMSBuildItemEvaluated)item).Metadata.GetProperties ().Select (p => p.Name);
		}

		public override IEnumerable<object> GetImports (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).Project.Imports;
		}

		public override string GetImportEvaluatedProjectPath (object projectInstance, object import)
		{
			return ((ProjectInfo)projectInstance).Imports [(MSBuildImport)import];
		}

		public override IEnumerable<object> GetEvaluatedItems (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).EvaluatedItems;
		}

		public override IEnumerable<object> GetEvaluatedItemsIgnoringCondition (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).EvaluatedItemsIgnoringCondition;
		}

		public override IEnumerable<object> GetEvaluatedProperties (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).Properties.Values;
		}

		public override void GetItemInfo (object item, out string name, out string include, out string finalItemSpec, out bool imported)
		{
			var it = (MSBuildItem) item;
			name = it.Name;
			include = it.Include;
			finalItemSpec = it.Include;
			imported = it.IsImported;
		}

		public override void GetEvaluatedItemInfo (object item, out string name, out string include, out string finalItemSpec, out bool imported)
		{
			var it = (IMSBuildItemEvaluated) item;
			name = it.Name;
			include = it.Include;
			finalItemSpec = it.Include;
			imported = it.IsImported;
		}

		public override void GetPropertyInfo (object property, out string name, out string value, out string finalValue, out bool definedMultipleTimes)
		{
			var prop = (PropertyInfo)property;
			name = prop.Name;
			value = prop.Value;
			finalValue = prop.FinalValue;
			definedMultipleTimes = prop.DefinedMultipleTimes;
		}

		public override IEnumerable<MSBuildTarget> GetTargets (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).Targets;
		}

		public override IEnumerable<MSBuildTarget> GetTargetsIgnoringCondition (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).TargetsIgnoringCondition;
		}

		public override void SetGlobalProperty (object projectInstance, string property, string value)
		{
			var pi = (ProjectInfo)projectInstance;
			pi.GlobalProperties [property] = value;
		}

		public override void RemoveGlobalProperty (object projectInstance, string property)
		{
			var pi = (ProjectInfo)projectInstance;
			pi.GlobalProperties.Remove (property);
		}

		public override ConditionedPropertyCollection GetConditionedProperties (object projectInstance)
		{
			var pi = (ProjectInfo)projectInstance;
			return pi.ConditionedProperties;
		}

		public override IEnumerable<MSBuildItem> FindGlobItemsIncludingFile (object projectInstance, string include)
		{
			var pi = (ProjectInfo)projectInstance;
			string filePath = MSBuildProjectService.FromMSBuildPath (pi.Project.BaseDirectory, include);
			foreach (var g in pi.GlobIncludes) {
				if (!g.Condition)
					continue;

				if (g.ExcludeRegex != null) {
					if (g.ExcludeRegex.IsMatch (include))
						continue;
				}
				if (g.RemoveRegex != null) {
					if (g.RemoveRegex.IsMatch (include))
						continue;
				}
				if (IsIncludedInGlob (pi.Project.BaseDirectory, filePath, false, g.IncludeSplit))
					yield return g.Item;
			}
		}

		internal override IEnumerable<MSBuildItem> FindUpdateGlobItemsIncludingFile (object projectInstance, string include, MSBuildItem globItem)
		{
			var pi = (ProjectInfo)projectInstance;
			foreach (var g in pi.GlobIncludes.Where (g => g.Condition && g.Item == globItem && g.Updates != null)) {
				foreach (var update in g.Updates) {
					if (update.UpdateRegex.IsMatch (include)) {
						yield return update.Item;
					}
				}
			}
		}

		bool IsIncludedInGlob (FilePath basePath, FilePath file, bool recursive, in ReadOnlySpan<string> filePath)
		{
			if (filePath.Length <= 0)
				return false;

			var path = filePath [0];

			if (path == "..")
				return IsIncludedInGlob (basePath.ParentDirectory, file, recursive, filePath.Slice (1));

			if (path == ".")
				return IsIncludedInGlob (basePath, file, recursive, filePath.Slice (1));

			if (!Directory.Exists (basePath))
				return false;

			if (path == "**") {
				// if this is the last component of the path, there isn't any file specifier, so there is no possible match
				if (filePath.Length <= 1)
					return false;
				return IsIncludedInGlob (basePath, file, true, filePath.Slice (1));
			}

			if (filePath.Length == 1) {
				// Last path component. It has to be a file specifier.
				if (!file.IsChildPathOf (basePath))
					return false;

				foreach (var f in Directory.EnumerateFiles (basePath, path)) {
					if (f == file)
						return true;
				}
			} else {
				// Directory specifier
				// Look for matching directories.
				// The search here is non-recursive, not matter what the 'recursive' parameter says, since we are trying to match a subpath.
				// The recursive search is done below.

				if (path.IndexOfAny (wildcards) != -1) {
					foreach (var dir in Directory.EnumerateDirectories (basePath, path)) {
						if (IsIncludedInGlob (dir, file, false, filePath.Slice (1)))
							return true;
					}
				} else if (IsIncludedInGlob (basePath.Combine (path), file, false, filePath.Slice (1)))
					return true;
			}

			if (recursive) {
				// Recursive search. Try to match the remaining subpath in all subdirectories.
				foreach (var dir in Directory.EnumerateDirectories (basePath))
					if (IsIncludedInGlob (dir, file, true, filePath))
						return true;
			}

			return false;
		}

		internal override IEnumerable<object> GetEvaluatedItemDefinitions (object projectInstance)
		{
			return ((ProjectInfo)projectInstance).EvaluatedItemDefinitions;
		}

		#endregion

		#region Logging


		private void LogBeginEvaluationStage (MSBuildEvaluationContext context, string v)
		{
			if (context.Log != null) {
				context.Log.PushTask (v);
				context.Log.Indent += 2;
			}
		}

		private void LogEndEvaluationStage (MSBuildEvaluationContext context)
		{
			if (context.Log != null) {
				context.Log.PopTask ();
				context.Log.LogMessage ("");
			}
		}

		public void LogInitialEnvironment (MSBuildEvaluationContext context)
		{
			if (context.Log != null && context.Log.Flags.HasFlag (MSBuildLogFlags.Properties)) {
				context.Log.LogMessage ("Environment at start of build:");
				context.Dump ();
				context.Log.LogMessage ("");
			}
		}

		void LogBeginProjectFileLoad (MSBuildEvaluationContext context, FilePath fileName)
		{
			if (context.Log != null)
				context.Log.PushTask ("Load Project: " + fileName);
		}

		void LogEndProjectFileLoad (MSBuildEvaluationContext context)
		{
			if (context.Log != null)
				context.Log.PopTask ();
		}

		void LogBeginEvalProject (MSBuildEvaluationContext context, ProjectInfo pinfo)
		{
			if (context.Log != null) {
				context.Log.PushTask ("Evaluate Project: " + pinfo.Project.FileName);
				if (context.Log.Flags.HasFlag (MSBuildLogFlags.Properties)) {
					context.Log.LogMessage ("");
					context.Log.LogMessage ("Initial Properties:");
					context.Dump ();
					context.Log.LogMessage ("");
				}
			}
		}

		void LogEndEvalProject (MSBuildEvaluationContext context, ProjectInfo pinfo)
		{
			if (context.Log != null)
				context.Log.PopTask ();
		}

		#endregion
	}

	abstract class MSBuildEngineLogger
	{
		class LogTask {
			public string Name;
			public long Timestamp;
		}

		long initialTimestamp;
		Stack<LogTask> timeStack = new Stack<LogTask> ();

		internal int Indent { get; set; }

		public MSBuildLogFlags Flags { get; set; }

		public MSBuildEngineLogger ()
		{
			initialTimestamp = System.Diagnostics.Stopwatch.GetTimestamp ();
		}

		public void PushTask (string name)
		{
			var tt = System.Diagnostics.Stopwatch.GetTimestamp ();
			var elapsed = (tt - initialTimestamp) / (System.Diagnostics.Stopwatch.Frequency / 1000);
			LogMessage (name + " (t:" + elapsed + ")");
			Indent += 2;
			timeStack.Push (new LogTask { Name = name, Timestamp = tt });
		}

		public void PopTask ()
		{
			var t = System.Diagnostics.Stopwatch.GetTimestamp ();
			var task = timeStack.Pop ();
			var elapsed = (t - task.Timestamp) / (System.Diagnostics.Stopwatch.Frequency / 1000);
			Indent -= 2;
			LogMessage ($"Done {task.Name} ({elapsed}ms)");
		}

		public abstract void LogMessage (string s);
	}

	enum MSBuildLogFlags
	{
		Properties = 0b0001,
		Items = 0b0010
	}

	class ConsoleMSBuildEngineLogger: MSBuildEngineLogger
	{
		public override void LogMessage (string s)
		{
			Console.WriteLine (new string (' ', Indent) + s);
		}
	}
}