Merge pull request #4621 from alexanderkyte/strdup_env
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / Project.cs
1 //
2 // Project.cs: Project class
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 //   Ankit Jain (jankit@novell.com)
7 //
8 // (C) 2005 Marek Sieradzki
9 // Copyright 2011 Novell, Inc (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29
30 using System;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Specialized;
34 using System.IO;
35 using System.Linq;
36 using System.Reflection;
37 using System.Text;
38 using System.Xml;
39 using System.Xml.Schema;
40 using Microsoft.Build.Framework;
41 using Microsoft.Build.Utilities;
42 using Mono.XBuild.Framework;
43 using Mono.XBuild.CommandLine;
44
45 namespace Microsoft.Build.BuildEngine {
46         public class Project {
47         
48                 bool                            buildEnabled;
49                 Dictionary <string, List <string>>      conditionedProperties;
50                 string[]                        defaultTargets;
51                 Encoding                        encoding;
52                 BuildItemGroup                  evaluatedItems;
53                 BuildItemGroup                  evaluatedItemsIgnoringCondition;
54                 Dictionary <string, BuildItemGroup>     evaluatedItemsByName;
55                 Dictionary <string, BuildItemGroup>     evaluatedItemsByNameIgnoringCondition;
56                 BuildPropertyGroup              evaluatedProperties;
57                 string                          firstTargetName;
58                 string                          fullFileName;
59                 BuildPropertyGroup              globalProperties;
60                 GroupingCollection              groupingCollection;
61                 bool                            isDirty;
62                 bool                            isValidated;
63                 BuildItemGroupCollection        itemGroups;
64                 ImportCollection                imports;
65                 List<string>                    initialTargets;
66                 Dictionary <string, BuildItemGroup> last_item_group_containing;
67                 bool                            needToReevaluate;
68                 Engine                          parentEngine;
69                 BuildPropertyGroupCollection    propertyGroups;
70                 string                          schemaFile;
71                 TaskDatabase                    taskDatabase;
72                 TargetCollection                targets;
73                 DateTime                        timeOfLastDirty;
74                 UsingTaskCollection             usingTasks;
75                 XmlDocument                     xmlDocument;
76                 bool                            unloaded;
77                 bool                            initialTargetsBuilt;
78                 bool                            building;
79                 BuildSettings                   current_settings;
80                 Stack<Batch>                    batches;
81
82                 // This is used to keep track of "current" file,
83                 // which is then used to set the reserved properties
84                 // $(MSBuildThisFile*)
85                 Stack<string> this_file_property_stack;
86                 ProjectLoadSettings             project_load_settings;
87
88
89                 static string extensions_path;
90                 static XmlNamespaceManager      manager;
91                 static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
92
93                 public Project ()
94                         : this (Engine.GlobalEngine)
95                 {
96                 }
97
98                 public Project (Engine engine) : this (engine, null)
99                 {
100                 }
101                 
102                 public Project (Engine engine, string toolsVersion)
103                 {
104                         parentEngine  = engine;
105                         ToolsVersion = toolsVersion;
106
107                         buildEnabled = ParentEngine.BuildEnabled;
108                         xmlDocument = new XmlDocument ();
109                         xmlDocument.PreserveWhitespace = false;
110                         xmlDocument.AppendChild (xmlDocument.CreateElement ("Project", XmlNamespace));
111                         xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
112                         
113                         fullFileName = String.Empty;
114                         timeOfLastDirty = DateTime.Now;
115                         current_settings = BuildSettings.None;
116                         project_load_settings = ProjectLoadSettings.None;
117
118                         encoding = null;
119
120                         initialTargets = new List<string> ();
121                         defaultTargets = new string [0];
122                         batches = new Stack<Batch> ();
123                         this_file_property_stack = new Stack<string> ();
124
125                         globalProperties = new BuildPropertyGroup (null, this, null, false);
126                         foreach (BuildProperty bp in parentEngine.GlobalProperties)
127                                 GlobalProperties.AddProperty (bp.Clone (true));
128                         
129                         ProcessXml ();
130
131                 }
132
133                 [MonoTODO ("Not tested")]
134                 public void AddNewImport (string projectFile,
135                                           string condition)
136                 {
137                         if (projectFile == null)
138                                 throw new ArgumentNullException ("projectFile");
139
140                         XmlElement importElement = xmlDocument.CreateElement ("Import", XmlNamespace);
141                         xmlDocument.DocumentElement.AppendChild (importElement);
142                         importElement.SetAttribute ("Project", projectFile);
143                         if (!String.IsNullOrEmpty (condition))
144                                 importElement.SetAttribute ("Condition", condition);
145
146                         AddImport (importElement, null, false);
147                         MarkProjectAsDirty ();
148                         NeedToReevaluate ();
149                 }
150
151                 public BuildItem AddNewItem (string itemName,
152                                              string itemInclude)
153                 {
154                         return AddNewItem (itemName, itemInclude, false);
155                 }
156                 
157                 [MonoTODO ("Adds item not in the same place as MS")]
158                 public BuildItem AddNewItem (string itemName,
159                                              string itemInclude,
160                                              bool treatItemIncludeAsLiteral)
161                 {
162                         BuildItemGroup big;
163
164                         if (itemGroups.Count == 0)
165                                 big = AddNewItemGroup ();
166                         else {
167                                 if (last_item_group_containing.ContainsKey (itemName)) {
168                                         big = last_item_group_containing [itemName];
169                                 } else {
170                                         // FIXME: not tested
171                                         BuildItemGroup [] groups = new BuildItemGroup [itemGroups.Count];
172                                         itemGroups.CopyTo (groups, 0);
173                                         big = groups [0];
174                                 }
175                         }
176
177                         BuildItem item = big.AddNewItem (itemName, itemInclude, treatItemIncludeAsLiteral);
178                                 
179                         MarkProjectAsDirty ();
180                         NeedToReevaluate ();
181
182                         return item;
183                 }
184
185                 [MonoTODO ("Not tested")]
186                 public BuildItemGroup AddNewItemGroup ()
187                 {
188                         XmlElement element = xmlDocument.CreateElement ("ItemGroup", XmlNamespace);
189                         xmlDocument.DocumentElement.AppendChild (element);
190
191                         BuildItemGroup big = new BuildItemGroup (element, this, null, false);
192                         itemGroups.Add (big);
193                         MarkProjectAsDirty ();
194                         NeedToReevaluate ();
195
196                         return big;
197                 }
198
199                 [MonoTODO ("Ignores insertAtEndOfProject")]
200                 public BuildPropertyGroup AddNewPropertyGroup (bool insertAtEndOfProject)
201                 {
202                         XmlElement element = xmlDocument.CreateElement ("PropertyGroup", XmlNamespace);
203                         xmlDocument.DocumentElement.AppendChild (element);
204
205                         BuildPropertyGroup bpg = new BuildPropertyGroup (element, this, null, false);
206                         propertyGroups.Add (bpg);
207                         MarkProjectAsDirty ();
208                         NeedToReevaluate ();
209
210                         return bpg;
211                 }
212                 
213                 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
214                 public void AddNewUsingTaskFromAssemblyFile (string taskName,
215                                                              string assemblyFile)
216                 {
217                         if (taskName == null)
218                                 throw new ArgumentNullException ("taskName");
219                         if (assemblyFile == null)
220                                 throw new ArgumentNullException ("assemblyFile");
221
222                         XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
223                         xmlDocument.DocumentElement.AppendChild (element);
224                         element.SetAttribute ("TaskName", taskName);
225                         element.SetAttribute ("AssemblyFile", assemblyFile);
226
227                         UsingTask ut = new UsingTask (element, this, null);
228                         usingTasks.Add (ut);
229                         MarkProjectAsDirty ();
230                 }
231                 
232                 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
233                 public void AddNewUsingTaskFromAssemblyName (string taskName,
234                                                              string assemblyName)
235                 {
236                         if (taskName == null)
237                                 throw new ArgumentNullException ("taskName");
238                         if (assemblyName == null)
239                                 throw new ArgumentNullException ("assemblyName");
240
241                         XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
242                         xmlDocument.DocumentElement.AppendChild (element);
243                         element.SetAttribute ("TaskName", taskName);
244                         element.SetAttribute ("AssemblyName", assemblyName);
245
246                         UsingTask ut = new UsingTask (element, this, null);
247                         usingTasks.Add (ut);
248                         MarkProjectAsDirty ();
249                 }
250                 
251                 [MonoTODO ("Not tested")]
252                 public bool Build ()
253                 {
254                         return Build (new string [0]);
255                 }
256                 
257                 [MonoTODO ("Not tested")]
258                 public bool Build (string targetName)
259                 {
260                         if (targetName == null)
261                                 return Build ((string[]) null);
262                         else
263                                 return Build (new string [1] { targetName });
264                 }
265                 
266                 [MonoTODO ("Not tested")]
267                 public bool Build (string [] targetNames)
268                 {
269                         return Build (targetNames, null);
270                 }
271                 
272                 [MonoTODO ("Not tested")]
273                 public bool Build (string [] targetNames,
274                                    IDictionary targetOutputs)
275                 {
276                         return Build (targetNames, targetOutputs, BuildSettings.None);
277                 }
278
279                 [MonoTODO ("Not tested")]
280                 public bool Build (string [] targetNames,
281                                    IDictionary targetOutputs,
282                                    BuildSettings buildFlags)
283                 
284                 {
285                         bool result = false;
286                         ParentEngine.StartProjectBuild (this, targetNames);
287
288                         // Invoking this to emit a warning in case of unsupported
289                         // ToolsVersion
290                         GetToolsVersionToUse (true);
291
292                         string current_directory = Environment.CurrentDirectory;
293                         try {
294                                 current_settings = buildFlags;
295                                 if (!String.IsNullOrEmpty (fullFileName))
296                                         Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
297                                 building = true;
298                                 result = BuildInternal (targetNames, targetOutputs, buildFlags);
299                         } catch (InvalidProjectFileException ie) {
300                                 ParentEngine.LogErrorWithFilename (fullFileName, ie.Message);
301                                 ParentEngine.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", fullFileName, ie.ToString ()));
302                         } catch (Exception e) {
303                                 ParentEngine.LogErrorWithFilename (fullFileName, e.Message);
304                                 ParentEngine.LogMessage (MessageImportance.Low, String.Format ("{0}: {1}", fullFileName, e.ToString ()));
305                                 throw;
306                         } finally {
307                                 ParentEngine.EndProjectBuild (this, result);
308                                 current_settings = BuildSettings.None;
309                                 Directory.SetCurrentDirectory (current_directory);
310                                 building = false;
311                         }
312
313                         return result;
314                 }
315
316                 bool BuildInternal (string [] targetNames,
317                                    IDictionary targetOutputs,
318                                    BuildSettings buildFlags)
319                 {
320                         CheckUnloaded ();
321                         if (buildFlags == BuildSettings.None) {
322                                 needToReevaluate = false;
323                                 Reevaluate ();
324                         }
325
326                         ProcessBeforeAndAfterTargets ();
327
328                         if (targetNames == null || targetNames.Length == 0) {
329                                 if (defaultTargets != null && defaultTargets.Length != 0) {
330                                         targetNames = defaultTargets;
331                                 } else if (firstTargetName != null) {
332                                         targetNames = new string [1] { firstTargetName};
333                                 } else {
334                                         if (targets == null || targets.Count == 0) {
335                                                 LogError (fullFileName, "No target found in the project");
336                                                 return false;
337                                         }
338
339                                         return false;
340                                 }
341                         }
342
343                         if (!initialTargetsBuilt) {
344                                 foreach (string target in initialTargets) {
345                                         if (!BuildTarget (target.Trim (), targetOutputs))
346                                                 return false;
347                                 }
348                                 initialTargetsBuilt = true;
349                         }
350
351                         foreach (string target in targetNames) {
352                                 if (target == null)
353                                         throw new ArgumentNullException ("Target name cannot be null");
354
355                                 if (!BuildTarget (target.Trim (), targetOutputs))
356                                         return false;
357                         }
358                                 
359                         return true;
360                 }
361
362                 bool BuildTarget (string target_name, IDictionary targetOutputs)
363                 {
364                         if (target_name == null)
365                                 throw new ArgumentException ("targetNames cannot contain null strings");
366
367                         if (!targets.Exists (target_name)) {
368                                 LogError (fullFileName, "Target named '{0}' not found in the project.", target_name);
369                                 return false;
370                         }
371
372                         string key = GetKeyForTarget (target_name);
373                         if (!targets [target_name].Build (key))
374                                 return false;
375
376                         ITaskItem[] outputs;
377                         if (targetOutputs != null && ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs))
378                                 targetOutputs [target_name] = outputs;
379                         return true;
380                 }
381
382                 internal string GetKeyForTarget (string target_name)
383                 {
384                         return GetKeyForTarget (target_name, true);
385                 }
386
387                 internal string GetKeyForTarget (string target_name, bool include_global_properties)
388                 {
389                         // target name is case insensitive
390                         return fullFileName + ":" + target_name.ToLowerInvariant () +
391                                         (include_global_properties ? (":" + GlobalPropertiesToString (GlobalProperties))
392                                                                    : String.Empty);
393                 }
394
395                 string GlobalPropertiesToString (BuildPropertyGroup bgp)
396                 {
397                         StringBuilder sb = new StringBuilder ();
398                         foreach (BuildProperty bp in bgp)
399                                 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
400                         return sb.ToString ();
401                 }
402
403                 void ProcessBeforeAndAfterTargets ()
404                 {
405                         var beforeTable = Targets.AsIEnumerable ()
406                                                 .SelectMany (target => GetTargetNamesFromString (target.BeforeTargets),
407                                                                 (target, before_target) => new {before_target, name = target.Name})
408                                                 .ToLookup (x => x.before_target, x => x.name)
409                                                 .ToDictionary (x => x.Key, x => x.Distinct ().ToList ());
410
411                         foreach (var pair in beforeTable) {
412                                 if (targets.Exists (pair.Key))
413                                         targets [pair.Key].BeforeThisTargets = pair.Value;
414                                 else
415                                         LogWarning (FullFileName, "Target '{0}', not found in the project", pair.Key);
416                         }
417
418                         var afterTable = Targets.AsIEnumerable ()
419                                                 .SelectMany (target => GetTargetNamesFromString (target.AfterTargets),
420                                                                 (target, after_target) => new {after_target, name = target.Name})
421                                                 .ToLookup (x => x.after_target, x => x.name)
422                                                 .ToDictionary (x => x.Key, x => x.Distinct ().ToList ());
423
424                         foreach (var pair in afterTable) {
425                                 if (targets.Exists (pair.Key))
426                                         targets [pair.Key].AfterThisTargets = pair.Value;
427                                 else
428                                         LogWarning (FullFileName, "Target '{0}', not found in the project", pair.Key);
429                         }
430                 }
431
432                 string[] GetTargetNamesFromString (string targets)
433                 {
434                         Expression expr = new Expression ();
435                         expr.Parse (targets, ParseOptions.AllowItemsNoMetadataAndSplit);
436                         return (string []) expr.ConvertTo (this, typeof (string []));
437                 }
438
439                 [MonoTODO]
440                 public string [] GetConditionedPropertyValues (string propertyName)
441                 {
442                         if (conditionedProperties.ContainsKey (propertyName))
443                                 return conditionedProperties [propertyName].ToArray ();
444                         else
445                                 return new string [0];
446                 }
447
448                 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
449                 {                       
450                         if (needToReevaluate) {
451                                 needToReevaluate = false;
452                                 Reevaluate ();
453                         }
454
455                         if (evaluatedItemsByName.ContainsKey (itemName))
456                                 return evaluatedItemsByName [itemName];
457                         else
458                                 return new BuildItemGroup (this);
459                 }
460
461                 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
462                 {
463                         if (needToReevaluate) {
464                                 needToReevaluate = false;
465                                 Reevaluate ();
466                         }
467
468                         if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
469                                 return evaluatedItemsByNameIgnoringCondition [itemName];
470                         else
471                                 return new BuildItemGroup (this);
472                 }
473
474                 public string GetEvaluatedProperty (string propertyName)
475                 {
476                         if (needToReevaluate) {
477                                 needToReevaluate = false;
478                                 Reevaluate ();
479                         }
480
481                         if (propertyName == null)
482                                 throw new ArgumentNullException ("propertyName");
483
484                         BuildProperty bp = evaluatedProperties [propertyName];
485
486                         return bp == null ? null : (string) bp;
487                 }
488
489                 [MonoTODO ("We should remember that node and not use XPath to get it")]
490                 public string GetProjectExtensions (string id)
491                 {
492                         if (id == null || id == String.Empty)
493                                 return String.Empty;
494
495                         XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
496
497                         if (node == null)
498                                 return String.Empty;
499                         else
500                                 return node.InnerXml;
501                 }
502
503
504                 public void Load (string projectFileName)
505                 {
506                         Load (projectFileName, ProjectLoadSettings.None);
507                 }
508
509                 public void Load (string projectFileName, ProjectLoadSettings projectLoadSettings)
510                 {
511                         project_load_settings = projectLoadSettings;
512                         if (String.IsNullOrEmpty (projectFileName))
513                                 throw new ArgumentNullException ("projectFileName");
514
515                         if (!File.Exists (projectFileName))
516                                 throw new ArgumentException (String.Format ("Project file {0} not found", projectFileName),
517                                                 "projectFileName");
518
519                         this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
520                         PushThisFileProperty (fullFileName);
521
522                         string filename = fullFileName;
523                         if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
524                                 Project tmp_project = ParentEngine.CreateNewProject ();
525                                 tmp_project.FullFileName = filename;
526                                 SolutionParser sln_parser = new SolutionParser ();
527                                 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
528                                                 LogWarning (filename, message);
529                                         });
530                                 filename = fullFileName + ".proj";
531                                 try {
532                                         tmp_project.Save (filename);
533                                         ParentEngine.RemoveLoadedProject (tmp_project);
534                                         DoLoad (new StreamReader (filename));
535                                 } finally {
536                                         if (Environment.GetEnvironmentVariable ("XBUILD_EMIT_SOLUTION") == null)
537                                                 File.Delete (filename);
538                                 }
539                         } else {
540                                 DoLoad (new StreamReader (filename));
541                         }
542                 }
543                 
544                 [MonoTODO ("Not tested")]
545                 public void Load (TextReader textReader)
546                 {
547                         Load (textReader, ProjectLoadSettings.None);
548                 }
549
550                 public void Load (TextReader textReader, ProjectLoadSettings projectLoadSettings)
551                 {
552                         project_load_settings = projectLoadSettings;
553                         if (!string.IsNullOrEmpty (fullFileName))
554                                 PushThisFileProperty (fullFileName);
555                         DoLoad (textReader);
556                 }
557
558                 public void LoadXml (string projectXml)
559                 {
560                         LoadXml (projectXml, ProjectLoadSettings.None);
561                 }
562
563                 public void LoadXml (string projectXml, ProjectLoadSettings projectLoadSettings)
564                 {
565                         project_load_settings = projectLoadSettings;
566                         if (!string.IsNullOrEmpty (fullFileName))
567                                 PushThisFileProperty (fullFileName);
568                         DoLoad (new StringReader (projectXml));
569                         MarkProjectAsDirty ();
570                 }
571
572
573                 public void MarkProjectAsDirty ()
574                 {
575                         isDirty = true;
576                         timeOfLastDirty = DateTime.Now;
577                 }
578
579                 [MonoTODO ("Not tested")]
580                 public void RemoveAllItemGroups ()
581                 {
582                         int length = ItemGroups.Count;
583                         BuildItemGroup [] groups = new BuildItemGroup [length];
584                         ItemGroups.CopyTo (groups, 0);
585
586                         for (int i = 0; i < length; i++)
587                                 RemoveItemGroup (groups [i]);
588
589                         MarkProjectAsDirty ();
590                         NeedToReevaluate ();
591                 }
592
593                 [MonoTODO ("Not tested")]
594                 public void RemoveAllPropertyGroups ()
595                 {
596                         int length = PropertyGroups.Count;
597                         BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
598                         PropertyGroups.CopyTo (groups, 0);
599
600                         for (int i = 0; i < length; i++)
601                                 RemovePropertyGroup (groups [i]);
602
603                         MarkProjectAsDirty ();
604                         NeedToReevaluate ();
605                 }
606
607                 [MonoTODO]
608                 public void RemoveItem (BuildItem itemToRemove)
609                 {
610                         if (itemToRemove == null)
611                                 throw new ArgumentNullException ("itemToRemove");
612
613                         if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
614                                 throw new InvalidOperationException ("The object passed in is not part of the project.");
615
616                         BuildItemGroup big = itemToRemove.ParentItemGroup;
617
618                         if (big.Count == 1) {
619                                 // ParentItemGroup for items from xml and that have parent is the same
620                                 groupingCollection.Remove (big);
621                         } else {
622                                 if (big.ParentProject != this)
623                                         throw new InvalidOperationException ("The object passed in is not part of the project.");
624
625                                 if (itemToRemove.FromXml)
626                                         big.RemoveItem (itemToRemove);
627                                 else
628                                         big.RemoveItem (itemToRemove.ParentItem);
629                         }
630
631                         MarkProjectAsDirty ();
632                         NeedToReevaluate ();
633                 }
634
635                 [MonoTODO ("Not tested")]
636                 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
637                 {
638                         if (itemGroupToRemove == null)
639                                 throw new ArgumentNullException ("itemGroupToRemove");
640
641                         groupingCollection.Remove (itemGroupToRemove);
642                         MarkProjectAsDirty ();
643                 }
644                 
645                 [MonoTODO]
646                 // NOTE: does not modify imported projects
647                 public void RemoveItemGroupsWithMatchingCondition (string matchCondition)
648                 {
649                         throw new NotImplementedException ();
650                 }
651
652                 [MonoTODO]
653                 public void RemoveItemsByName (string itemName)
654                 {
655                         if (itemName == null)
656                                 throw new ArgumentNullException ("itemName");
657
658                         throw new NotImplementedException ();
659                 }
660
661                 [MonoTODO ("Not tested")]
662                 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
663                 {
664                         if (propertyGroupToRemove == null)
665                                 throw new ArgumentNullException ("propertyGroupToRemove");
666
667                         groupingCollection.Remove (propertyGroupToRemove);
668                         MarkProjectAsDirty ();
669                 }
670                 
671                 [MonoTODO]
672                 // NOTE: does not modify imported projects
673                 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
674                 {
675                         throw new NotImplementedException ();
676                 }
677
678                 [MonoTODO]
679                 public void ResetBuildStatus ()
680                 {
681                         // hack to allow built targets to be removed
682                         building = true;
683                         Reevaluate ();
684                         building = false;
685                 }
686
687                 public void Save (string projectFileName)
688                 {
689                         Save (projectFileName, Encoding.Default);
690                         isDirty = false;
691                 }
692
693                 [MonoTODO ("Ignores encoding")]
694                 public void Save (string projectFileName, Encoding encoding)
695                 {
696                         xmlDocument.Save (projectFileName);
697                         isDirty = false;
698                 }
699
700                 public void Save (TextWriter textWriter)
701                 {
702                         xmlDocument.Save (textWriter);
703                         isDirty = false;
704                 }
705
706                 public void SetImportedProperty (string propertyName,
707                                                  string propertyValue,
708                                                  string condition,
709                                                  Project importProject)
710                 {
711                         SetImportedProperty (propertyName, propertyValue, condition, importProject,
712                                 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
713                 }
714
715                 public void SetImportedProperty (string propertyName,
716                                                  string propertyValue,
717                                                  string condition,
718                                                  Project importedProject,
719                                                  PropertyPosition position)
720                 {
721                         SetImportedProperty (propertyName, propertyValue, condition, importedProject,
722                                 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
723                 }
724
725                 [MonoTODO]
726                 public void SetImportedProperty (string propertyName,
727                                                  string propertyValue,
728                                                  string condition,
729                                                  Project importedProject,
730                                                  PropertyPosition position,
731                                                  bool treatPropertyValueAsLiteral)
732                 {
733                         throw new NotImplementedException ();
734                 }
735
736                 public void SetProjectExtensions (string id, string content)
737                 {
738                         if (id == null)
739                                 throw new ArgumentNullException ("id");
740                         if (content == null)
741                                 throw new ArgumentNullException ("content");
742
743                         XmlNode projectExtensions, node;
744
745                         projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
746                         
747                         if (projectExtensions == null) {
748                                 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
749                                 xmlDocument.DocumentElement.AppendChild (projectExtensions);
750
751                                 node = xmlDocument.CreateElement (id, XmlNamespace);
752                                 node.InnerXml = content;
753                                 projectExtensions.AppendChild (node);
754                         } else {
755                                 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
756
757                                 if (node == null) {
758                                         node = xmlDocument.CreateElement (id, XmlNamespace);
759                                         projectExtensions.AppendChild (node);
760                                 }
761                                 
762                                 node.InnerXml = content;
763                                 
764                         }
765
766                         MarkProjectAsDirty ();
767                 }
768                 
769                 public void SetProperty (string propertyName,
770                                          string propertyValue)
771                 {
772                         SetProperty (propertyName, propertyValue, "true",
773                                 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
774                 }
775
776                 public void SetProperty (string propertyName,
777                                          string propertyValue,
778                                          string condition)
779                 {
780                         SetProperty (propertyName, propertyValue, condition,
781                                 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
782                 }
783
784                 public void SetProperty (string propertyName,
785                                          string propertyValue,
786                                          string condition,
787                                          PropertyPosition position)
788                 {
789                         SetProperty (propertyName, propertyValue, condition,
790                                 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
791                 }
792
793                 [MonoTODO]
794                 public void SetProperty (string propertyName,
795                                          string propertyValue,
796                                          string condition,
797                                          PropertyPosition position,
798                                          bool treatPropertyValueAsLiteral)
799                 {
800                         throw new NotImplementedException ();
801                 }
802
803                 internal void Unload ()
804                 {
805                         unloaded = true;
806                 }
807
808                 internal void CheckUnloaded ()
809                 {
810                         if (unloaded)
811                                 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
812                 }
813
814                 internal void NeedToReevaluate ()
815                 {
816                         needToReevaluate = true;
817                 }
818                                 
819                 // Does the actual loading.
820                 void DoLoad (TextReader textReader)
821                 {
822                         try {
823                                 ParentEngine.RemoveLoadedProject (this);
824         
825                                 xmlDocument.Load (textReader);
826
827                                 if (xmlDocument.DocumentElement.Name == "VisualStudioProject")
828                                         throw new InvalidProjectFileException (String.Format (
829                                                         "Project file '{0}' is a VS2003 project, which is not " +
830                                                         "supported by xbuild. You need to convert it to msbuild " +
831                                                         "format to build with xbuild.", fullFileName));
832
833                                 if (SchemaFile != null) {
834                                         xmlDocument.Schemas.Add (XmlSchema.Read (
835                                                                 new StreamReader (SchemaFile), ValidationCallBack));
836                                         xmlDocument.Validate (ValidationCallBack);
837                                 }
838
839                                 if (xmlDocument.DocumentElement.Name != "Project") {
840                                         throw new InvalidProjectFileException (String.Format (
841                                                 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
842                                 }
843         
844                                 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
845                                         throw new InvalidProjectFileException (
846                                                 @"The default XML namespace of the project must be the MSBuild XML namespace." + 
847                                                 " If the project is authored in the MSBuild 2003 format, please add " +
848                                                 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
849                                                 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.  ");
850                                 }
851                                 ProcessXml ();
852                                 ParentEngine.AddLoadedProject (this);
853                         } catch (Exception e) {
854                                 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
855                                                         fullFileName, e.Message), e);
856                         } finally {
857                                 if (textReader != null)
858                                         textReader.Close ();
859                         }
860                 }
861
862                 void Reevaluate ()
863                 {
864                         ProcessXml ();
865                 }
866
867                 void ProcessXml ()
868                 {
869                         groupingCollection = new GroupingCollection (this);
870                         imports = new ImportCollection (groupingCollection);
871                         usingTasks = new UsingTaskCollection (this);
872                         itemGroups = new BuildItemGroupCollection (groupingCollection);
873                         propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
874                         targets = new TargetCollection (this);
875                         last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
876                         
877                         string effective_tools_version = GetToolsVersionToUse (false);
878                         taskDatabase = new TaskDatabase ();
879                         taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (effective_tools_version));
880
881                         initialTargets = new List<string> ();
882                         defaultTargets = new string [0];
883                         PrepareForEvaluate (effective_tools_version);
884                         ProcessElements (xmlDocument.DocumentElement, null);
885                         
886                         isDirty = false;
887                         Evaluate ();
888                 }
889
890                 void ProcessProjectAttributes (XmlAttributeCollection attributes)
891                 {
892                         foreach (XmlAttribute attr in attributes) {
893                                 switch (attr.Name) {
894                                 case "InitialTargets":
895                                         initialTargets.AddRange (attr.Value.Split (
896                                                                         new char [] {';', ' '},
897                                                                         StringSplitOptions.RemoveEmptyEntries));
898                                         break;
899                                 case "DefaultTargets":
900                                         // first non-empty DefaultTargets found is used
901                                         if (defaultTargets == null || defaultTargets.Length == 0)
902                                                 defaultTargets = attr.Value.Split (new char [] {';', ' '},
903                                                         StringSplitOptions.RemoveEmptyEntries);
904                                         EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets",
905                                                                 DefaultTargets, PropertyType.Reserved));
906                                         break;
907                                 }
908                         }
909                 }
910
911                 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
912                 {
913                         ProcessProjectAttributes (rootElement.Attributes);
914                         foreach (XmlNode xn in rootElement.ChildNodes) {
915                                 if (xn is XmlElement) {
916                                         XmlElement xe = (XmlElement) xn;
917                                         switch (xe.Name) {
918                                         case "ProjectExtensions":
919                                                 AddProjectExtensions (xe);
920                                                 break;
921                                         case "Warning":
922                                         case "Message":
923                                         case "Error":
924                                                 AddMessage (xe);
925                                                 break;
926                                         case "Target":
927                                                 AddTarget (xe, ip);
928                                                 break;
929                                         case "UsingTask":
930                                                 AddUsingTask (xe, ip);
931                                                 break;
932                                         case "Import":
933                                                 AddImport (xe, ip, true);
934                                                 break;
935                                         case "ImportGroup":
936                                                 AddImportGroup (xe, ip, true);
937                                                 break;
938                                         case "ItemGroup":
939                                                 AddItemGroup (xe, ip);
940                                                 break;
941                                         case "PropertyGroup":
942                                                 AddPropertyGroup (xe, ip);
943                                                 break;
944                                         case  "Choose":
945                                                 AddChoose (xe, ip);
946                                                 break;
947                                         case "ItemDefinitionGroup":
948                                                 AddItemDefinitionGroup (xe);
949                                                 break;
950                                         default:
951                                                 var pf = ip == null ? null : string.Format (" '{0}'", ip.FullFileName);
952                                                 throw new InvalidProjectFileException (String.Format ("Invalid element '{0}' in project file{1}.", xe.Name, pf));
953                                         }
954                                 }
955                         }
956                 }
957                 
958                 void PrepareForEvaluate (string effective_tools_version)
959                 {
960                         evaluatedItems = new BuildItemGroup (null, this, null, true);
961                         evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
962                         evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.OrdinalIgnoreCase);
963                         evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.OrdinalIgnoreCase);
964                         if (building && current_settings == BuildSettings.None)
965                                 RemoveBuiltTargets ();
966
967                         InitializeProperties (effective_tools_version);
968                 }
969
970                 void Evaluate ()
971                 {
972                         groupingCollection.Evaluate ();
973
974                         //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
975                         foreach (UsingTask usingTask in UsingTasks)
976                                 usingTask.Evaluate ();
977                 }
978
979                 // Removes entries of all earlier built targets for this project
980                 void RemoveBuiltTargets ()
981                 {
982                         ParentEngine.ClearBuiltTargetsForProject (this);
983                 }
984
985                 void InitializeProperties (string effective_tools_version)
986                 {
987                         BuildProperty bp;
988
989                         evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
990                         conditionedProperties = new Dictionary<string, List<string>> ();
991
992                         foreach (BuildProperty gp in GlobalProperties) {
993                                 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
994                                 evaluatedProperties.AddProperty (bp);
995                         }
996                         
997                         foreach (BuildProperty gp in GlobalProperties)
998                                 ParentEngine.GlobalProperties.AddProperty (gp);
999
1000                         // add properties that we dont have from parent engine's
1001                         // global properties
1002                         foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
1003                                 if (evaluatedProperties [gp.Name] == null) {
1004                                         bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
1005                                         evaluatedProperties.AddProperty (bp);
1006                                 }
1007                         }
1008
1009                         foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
1010                                 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
1011                                 evaluatedProperties.AddProperty (bp);
1012                         }
1013
1014                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
1015                                                 PropertyType.Reserved));
1016                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFullPath", fullFileName, PropertyType.Reserved));
1017                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
1018                                                 Path.GetFileNameWithoutExtension (fullFileName),
1019                                                 PropertyType.Reserved));
1020                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectExtension",
1021                                                 Path.GetExtension (fullFileName),
1022                                                 PropertyType.Reserved));
1023
1024                         string toolsPath = parentEngine.Toolsets [effective_tools_version].ToolsPath;
1025                         if (toolsPath == null)
1026                                 throw new Exception (String.Format ("Invalid tools version '{0}', no tools path set for this.", effective_tools_version));
1027                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", toolsPath, PropertyType.Reserved));
1028                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", toolsPath, PropertyType.Reserved));
1029                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsRoot", Path.GetDirectoryName (toolsPath), PropertyType.Reserved));
1030                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsVersion", effective_tools_version, PropertyType.Reserved));
1031                         SetExtensionsPathProperties (DefaultExtensionsPath);
1032                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
1033                         evaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
1034 #if XBUILD_12
1035                         // see http://msdn.microsoft.com/en-us/library/vstudio/hh162058(v=vs.120).aspx
1036                         if (effective_tools_version == "12.0" || effective_tools_version == "14.0") {
1037                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath32", toolsPath, PropertyType.Reserved));
1038
1039                                 var frameworkToolsPath = ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version451);
1040
1041                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildFrameworkToolsPath", frameworkToolsPath, PropertyType.Reserved));
1042                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildFrameworkToolsPath32", frameworkToolsPath, PropertyType.Reserved));
1043                         }
1044 #endif
1045                         // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
1046                         string projectDir;
1047                         if (FullFileName == String.Empty)
1048                                 projectDir = Environment.CurrentDirectory;
1049                         else
1050                                 projectDir = Path.GetDirectoryName (FullFileName);
1051
1052                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
1053
1054                         if (this_file_property_stack.Count > 0)
1055                                 // Just re-inited the properties, but according to the stack,
1056                                 // we should have a MSBuild*This* property set
1057                                 SetMSBuildThisFileProperties (this_file_property_stack.Peek ());
1058                 }
1059
1060                 internal void SetExtensionsPathProperties (string extn_path)
1061                 {
1062                         if (!String.IsNullOrEmpty (extn_path)) {
1063                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", extn_path, PropertyType.Reserved));
1064                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath32", extn_path, PropertyType.Reserved));
1065                                 evaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath64", extn_path, PropertyType.Reserved));
1066                         }
1067                 }
1068
1069                 // precedence:
1070                 // ToolsVersion property
1071                 // ToolsVersion attribute on the project
1072                 // parentEngine's DefaultToolsVersion
1073                 string GetToolsVersionToUse (bool emitWarning)
1074                 {
1075                         if (!String.IsNullOrEmpty (ToolsVersion))
1076                                 return ToolsVersion;
1077
1078 #if XBUILD_14
1079                         return "14.0";
1080 #elif XBUILD_12
1081                         return "12.0";
1082 #else
1083                         if (!HasToolsVersionAttribute)
1084                                 return parentEngine.DefaultToolsVersion;
1085
1086                         if (parentEngine.Toolsets [DefaultToolsVersion] == null) {
1087                                 if (emitWarning)
1088                                         LogWarning (FullFileName, "Project has unknown ToolsVersion '{0}'. Using the default tools version '{1}' instead.",
1089                                                 DefaultToolsVersion, parentEngine.DefaultToolsVersion);
1090                                 return parentEngine.DefaultToolsVersion;
1091                         }
1092
1093                         return DefaultToolsVersion;
1094 #endif
1095                 }
1096                 
1097                 void AddProjectExtensions (XmlElement xmlElement)
1098                 {
1099                 }
1100                 
1101                 void AddMessage (XmlElement xmlElement)
1102                 {
1103                 }
1104                 
1105                 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
1106                 {
1107                         Target target = new Target (xmlElement, this, importedProject);
1108                         targets.AddTarget (target);
1109                         
1110                         if (firstTargetName == null)
1111                                 firstTargetName = target.Name;
1112                 }
1113                 
1114                 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
1115                 {
1116                         UsingTask usingTask;
1117
1118                         usingTask = new UsingTask (xmlElement, this, importedProject);
1119                         UsingTasks.Add (usingTask);
1120                 }
1121
1122                 void AddImport (XmlElement xmlElement, ImportedProject importingProject, bool evaluate_properties)
1123                 {
1124                         // eval all the properties etc till the import
1125                         if (evaluate_properties) {
1126                                 groupingCollection.Evaluate (EvaluationType.Property | EvaluationType.Choose);
1127                         }
1128                         try {
1129                                 PushThisFileProperty (importingProject != null ? importingProject.FullFileName : FullFileName);
1130
1131                                 string project_attribute = xmlElement.GetAttribute ("Project");
1132                                 if (String.IsNullOrEmpty (project_attribute))
1133                                         throw new InvalidProjectFileException ("The required attribute \"Project\" is missing from element <Import>.");
1134
1135                                 Import.ForEachExtensionPathTillFound (xmlElement, this, importingProject,
1136                                         (importPath, from_source_msg) => AddSingleImport (xmlElement, importPath, importingProject, from_source_msg));
1137                         } finally {
1138                                 PopThisFileProperty ();
1139                         }
1140                 }
1141
1142                 void AddImportGroup (XmlElement xmlElement, ImportedProject importedProject, bool evaluate_properties)
1143                 {
1144                         // eval all the properties etc till the import group
1145                         if (evaluate_properties) {
1146                                 groupingCollection.Evaluate (EvaluationType.Property | EvaluationType.Choose);
1147                         }
1148                         string condition_attribute = xmlElement.GetAttribute ("Condition");
1149                         if (!ConditionParser.ParseAndEvaluate (condition_attribute, this))
1150                                 return;
1151                         foreach (XmlNode xn in xmlElement.ChildNodes) {
1152                                 if (xn is XmlElement) {
1153                                         XmlElement xe = (XmlElement) xn;
1154                                         switch (xe.Name) {
1155                                         case "Import":
1156                                                 AddImport (xe, importedProject, evaluate_properties);
1157                                                 break;
1158                                         default:
1159                                                 throw new InvalidProjectFileException(String.Format("Invalid element '{0}' inside ImportGroup in project file '{1}'.", xe.Name, importedProject.FullFileName));
1160                                         }
1161                                 }
1162                         }
1163                 }
1164
1165                 void AddItemDefinitionGroup (XmlElement xmlElement)
1166                 {
1167                         string condition_attribute = xmlElement.GetAttribute ("Condition");
1168                         if (!ConditionParser.ParseAndEvaluate (condition_attribute, this))
1169                                 return;
1170
1171                         foreach (XmlNode xn in xmlElement.ChildNodes) {
1172                                 // TODO: Add all nodes to some internal dictionary?
1173                         }
1174                 }
1175
1176                 bool AddSingleImport (XmlElement xmlElement, string projectPath, ImportedProject importingProject, string from_source_msg)
1177                 {
1178                         Import import = new Import (xmlElement, projectPath, this, importingProject);
1179                         if (!ConditionParser.ParseAndEvaluate (import.Condition, this)) {
1180                                 ParentEngine.LogMessage (MessageImportance.Low,
1181                                                 "Not importing project '{0}' as the condition '{1}' is false",
1182                                                 import.ProjectPath, import.Condition);
1183                                 return false;
1184                         }
1185
1186                         Import existingImport;
1187                         if (Imports.TryGetImport (import, out existingImport)) {
1188                                 if (importingProject == null)
1189                                         LogWarning (fullFileName,
1190                                                         "Cannot import project '{0}' again. It was already imported by " +
1191                                                         "'{1}'. Ignoring.",
1192                                                         projectPath, existingImport.ContainedInProjectFileName);
1193                                 else
1194                                         LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1195                                                 "A circular reference was found involving the import of '{0}'. " +
1196                                                 "It was earlier imported by '{1}'. Only " +
1197                                                 "the first import of this file will be used, ignoring others.",
1198                                                 import.EvaluatedProjectPath, existingImport.ContainedInProjectFileName);
1199
1200                                 return true;
1201                         }
1202
1203                         if (String.Compare (fullFileName, import.EvaluatedProjectPath) == 0) {
1204                                 LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
1205                                                 "The main project file was imported here, which creates a circular " +
1206                                                 "reference. Ignoring this import.");
1207
1208                                 return true;
1209                         }
1210
1211                         if (project_load_settings != ProjectLoadSettings.IgnoreMissingImports &&
1212                             !import.CheckEvaluatedProjectPathExists ())
1213                                 return false;
1214
1215                         Imports.Add (import);
1216                         string importingFile = importingProject != null ? importingProject.FullFileName : FullFileName;
1217                         ParentEngine.LogMessage (MessageImportance.Low,
1218                                         "{0}: Importing project {1} {2}",
1219                                         importingFile, import.EvaluatedProjectPath, from_source_msg);
1220
1221                         import.Evaluate (project_load_settings == ProjectLoadSettings.IgnoreMissingImports);
1222                         return true;
1223                 }
1224
1225                 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
1226                 {
1227                         BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
1228                         ItemGroups.Add (big);
1229                 }
1230                 
1231                 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
1232                 {
1233                         BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
1234                         PropertyGroups.Add (bpg);
1235                 }
1236                 
1237                 void AddChoose (XmlElement xmlElement, ImportedProject importedProject)
1238                 {
1239                         BuildChoose bc = new BuildChoose (xmlElement, this, importedProject);
1240                         groupingCollection.Add (bc);
1241                 }
1242                 
1243                 static void ValidationCallBack (object sender, ValidationEventArgs e)
1244                 {
1245                         Console.WriteLine ("Validation Error: {0}", e.Message);
1246                 }
1247                 
1248                 public bool BuildEnabled {
1249                         get {
1250                                 return buildEnabled;
1251                         }
1252                         set {
1253                                 buildEnabled = value;
1254                         }
1255                 }
1256
1257                 [MonoTODO]
1258                 public Encoding Encoding {
1259                         get { return encoding; }
1260                 }
1261
1262                 public string DefaultTargets {
1263                         get {
1264                                 return String.Join ("; ", defaultTargets);
1265                         }
1266                         set {
1267                                 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
1268                                 if (value != null)
1269                                         defaultTargets = value.Split (new char [] {';', ' '},
1270                                                         StringSplitOptions.RemoveEmptyEntries);
1271                         }
1272                 }
1273
1274                 public BuildItemGroup EvaluatedItems {
1275                         get {
1276                                 if (needToReevaluate) {
1277                                         needToReevaluate = false;
1278                                         Reevaluate ();
1279                                 }
1280                                 return evaluatedItems;
1281                         }
1282                 }
1283
1284                 public BuildItemGroup EvaluatedItemsIgnoringCondition {
1285                         get {
1286                                 if (needToReevaluate) {
1287                                         needToReevaluate = false;
1288                                         Reevaluate ();
1289                                 }
1290                                 return evaluatedItemsIgnoringCondition;
1291                         }
1292                 }
1293                 
1294                 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
1295                         get {
1296                                 // FIXME: do we need to do this here?
1297                                 if (needToReevaluate) {
1298                                         needToReevaluate = false;
1299                                         Reevaluate ();
1300                                 }
1301                                 return evaluatedItemsByName;
1302                         }
1303                 }
1304
1305                 internal IEnumerable EvaluatedItemsByNameAsDictionaryEntries {
1306                         get {
1307                                 if (EvaluatedItemsByName.Count == 0)
1308                                         yield break;
1309
1310                                 foreach (KeyValuePair<string, BuildItemGroup> pair in EvaluatedItemsByName) {
1311                                         foreach (BuildItem bi in pair.Value)
1312                                                 yield return new DictionaryEntry (pair.Key, bi.ConvertToITaskItem (null, ExpressionOptions.ExpandItemRefs));
1313                                 }
1314                         }
1315                 }
1316
1317                 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1318                         get {
1319                                 // FIXME: do we need to do this here?
1320                                 if (needToReevaluate) {
1321                                         needToReevaluate = false;
1322                                         Reevaluate ();
1323                                 }
1324                                 return evaluatedItemsByNameIgnoringCondition;
1325                         }
1326                 }
1327
1328                 // For batching implementation
1329                 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1330                 Dictionary<string, BuildItemGroup> commonItemsByName;
1331
1332                 struct Batch {
1333                         public Dictionary<string, BuildItemGroup> perBatchItemsByName;
1334                         public Dictionary<string, BuildItemGroup> commonItemsByName;
1335
1336                         public Batch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1337                         {
1338                                 this.perBatchItemsByName = perBatchItemsByName;
1339                                 this.commonItemsByName = commonItemsByName;
1340                         }
1341                 }
1342
1343                 Stack<Batch> Batches {
1344                         get { return batches; }
1345                 }
1346
1347                 internal void PushBatch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1348                 {
1349                         batches.Push (new Batch (perBatchItemsByName, commonItemsByName));
1350                         SetBatchedItems (perBatchItemsByName, commonItemsByName);
1351                 }
1352
1353                 internal void PopBatch ()
1354                 {
1355                         batches.Pop ();
1356                         if (batches.Count > 0) {
1357                                 Batch b = batches.Peek ();
1358                                 SetBatchedItems (b.perBatchItemsByName, b.commonItemsByName);
1359                         } else {
1360                                 SetBatchedItems (null, null);
1361                         }
1362                 }
1363
1364                 void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1365                 {
1366                         this.perBatchItemsByName = perBatchItemsByName;
1367                         this.commonItemsByName = commonItemsByName;
1368                 }
1369
1370                 // Honors batching
1371                 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1372                 {
1373                         if (perBatchItemsByName != null && perBatchItemsByName.TryGetValue (itemName, out group))
1374                                 return true;
1375
1376                         if (commonItemsByName != null && commonItemsByName.TryGetValue (itemName, out group))
1377                                 return true;
1378
1379                         group = null;
1380                         return EvaluatedItemsByName.TryGetValue (itemName, out group);
1381                 }
1382
1383                 internal string GetMetadataBatched (string itemName, string metadataName)
1384                 {
1385                         BuildItemGroup group = null;
1386                         if (itemName == null) {
1387                                 //unqualified, all items in a batch(bucket) have the
1388                                 //same metadata values
1389                                 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1390                                 if (group == null)
1391                                         group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1392                         } else {
1393                                 //qualified
1394                                 TryGetEvaluatedItemByNameBatched (itemName, out group);
1395                         }
1396
1397                         if (group != null) {
1398                                 foreach (BuildItem item in group) {
1399                                         if (item.HasMetadata (metadataName))
1400                                                 return item.GetEvaluatedMetadata (metadataName);
1401                                 }
1402                         }
1403                         return String.Empty;
1404                 }
1405
1406                 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1407                 {
1408                         if (perBatchItemsByName == null && commonItemsByName == null)
1409                                 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1410                                         yield return group;
1411
1412                         if (perBatchItemsByName != null)
1413                                 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1414                                         yield return group;
1415
1416                         if (commonItemsByName != null)
1417                                 foreach (BuildItemGroup group in commonItemsByName.Values)
1418                                         yield return group;
1419                 }
1420
1421                 T GetFirst<T> (ICollection<T> list)
1422                 {
1423                         if (list == null)
1424                                 return default (T);
1425
1426                         foreach (T t in list)
1427                                 return t;
1428
1429                         return default (T);
1430                 }
1431
1432                 internal string ThisFileFullPath {
1433                         get { return this_file_property_stack.Peek (); }
1434                 }
1435
1436                 // Used for MSBuild*This* set of properties
1437                 internal void PushThisFileProperty (string full_filename)
1438                 {
1439                         string last_file = this_file_property_stack.Count == 0 ? String.Empty : this_file_property_stack.Peek ();
1440                         this_file_property_stack.Push (full_filename);
1441                         if (last_file != full_filename)
1442                                 // first time, or different from previous one
1443                                 SetMSBuildThisFileProperties (full_filename);
1444                 }
1445
1446                 internal void PopThisFileProperty ()
1447                 {
1448                         string last_file = this_file_property_stack.Pop ();
1449                         if (this_file_property_stack.Count > 0 && last_file != this_file_property_stack.Peek ())
1450                                 SetMSBuildThisFileProperties (this_file_property_stack.Peek ());
1451                 }
1452
1453                 void SetMSBuildThisFileProperties (string full_filename)
1454                 {
1455                         if (String.IsNullOrEmpty (full_filename))
1456                                 return;
1457
1458                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFile", Path.GetFileName (full_filename), PropertyType.Reserved));
1459                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileFullPath", full_filename, PropertyType.Reserved));
1460                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileName", Path.GetFileNameWithoutExtension (full_filename), PropertyType.Reserved));
1461                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileExtension", Path.GetExtension (full_filename), PropertyType.Reserved));
1462
1463                         string project_dir = Path.GetDirectoryName (full_filename) + Path.DirectorySeparatorChar;
1464                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileDirectory", project_dir, PropertyType.Reserved));
1465                         evaluatedProperties.AddProperty (new BuildProperty ("MSBuildThisFileDirectoryNoRoot",
1466                                                 project_dir.Substring (Path.GetPathRoot (project_dir).Length),
1467                                                 PropertyType.Reserved));
1468                 }
1469
1470
1471                 internal void LogWarning (string filename, string message, params object[] messageArgs)
1472                 {
1473                         BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1474                                 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1475                                 null, null);
1476                         ParentEngine.EventSource.FireWarningRaised (this, bwea);
1477                 }
1478
1479                 internal void LogError (string filename, string message,
1480                                      params object[] messageArgs)
1481                 {
1482                         BuildErrorEventArgs beea = new BuildErrorEventArgs (
1483                                 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1484                                 null, null);
1485                         ParentEngine.EventSource.FireErrorRaised (this, beea);
1486                 }
1487
1488                 internal static string DefaultExtensionsPath {
1489                         get {
1490                                 if (extensions_path == null) {
1491                                         // NOTE: code from mcs/tools/gacutil/driver.cs
1492                                         PropertyInfo gac = typeof (System.Environment).GetProperty (
1493                                                         "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1494
1495                                         if (gac != null) {
1496                                                 MethodInfo get_gac = gac.GetGetMethod (true);
1497                                                 string gac_path = (string) get_gac.Invoke (null, null);
1498                                                 extensions_path = Path.GetFullPath (Path.Combine (
1499                                                                         gac_path, Path.Combine ("..", "xbuild")));
1500                                         }
1501                                 }
1502                                 return extensions_path;
1503                         }
1504                 }
1505
1506                 public BuildPropertyGroup EvaluatedProperties {
1507                         get {
1508                                 if (needToReevaluate) {
1509                                         needToReevaluate = false;
1510                                         Reevaluate ();
1511                                 }
1512                                 return evaluatedProperties;
1513                         }
1514                 }
1515
1516                 internal IEnumerable EvaluatedPropertiesAsDictionaryEntries {
1517                         get {
1518                                 foreach (BuildProperty bp in EvaluatedProperties)
1519                                         yield return new DictionaryEntry (bp.Name, bp.Value);
1520                         }
1521                 }
1522
1523                 public string FullFileName {
1524                         get { return fullFileName; }
1525                         set { fullFileName = value; }
1526                 }
1527
1528                 public BuildPropertyGroup GlobalProperties {
1529                         get { return globalProperties; }
1530                         set {
1531                                 if (value == null)
1532                                         throw new ArgumentNullException ("value");
1533                                 
1534                                 if (value.FromXml)
1535                                         throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1536                                 
1537                                 globalProperties = value;
1538                         }
1539                 }
1540
1541                 public bool IsDirty {
1542                         get { return isDirty; }
1543                 }
1544
1545                 public bool IsValidated {
1546                         get { return isValidated; }
1547                         set { isValidated = value; }
1548                 }
1549
1550                 public BuildItemGroupCollection ItemGroups {
1551                         get { return itemGroups; }
1552                 }
1553                 
1554                 public ImportCollection Imports {
1555                         get { return imports; }
1556                 }
1557                 
1558                 public string InitialTargets {
1559                         get {
1560                                 return String.Join ("; ", initialTargets.ToArray ());
1561                         }
1562                         set {
1563                                 initialTargets.Clear ();
1564                                 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1565                                 if (value != null)
1566                                         initialTargets.AddRange (value.Split (
1567                                                                 new char [] {';', ' '}, StringSplitOptions.RemoveEmptyEntries));
1568                         }
1569                 }
1570
1571                 public Engine ParentEngine {
1572                         get { return parentEngine; }
1573                 }
1574
1575                 public BuildPropertyGroupCollection PropertyGroups {
1576                         get { return propertyGroups; }
1577                 }
1578
1579                 public string SchemaFile {
1580                         get { return schemaFile; }
1581                         set { schemaFile = value; }
1582                 }
1583
1584                 public TargetCollection Targets {
1585                         get { return targets; }
1586                 }
1587
1588                 public DateTime TimeOfLastDirty {
1589                         get { return timeOfLastDirty; }
1590                 }
1591                 
1592                 public UsingTaskCollection UsingTasks {
1593                         get { return usingTasks; }
1594                 }
1595
1596                 [MonoTODO]
1597                 public string Xml {
1598                         get { return xmlDocument.InnerXml; }
1599                 }
1600
1601                 // corresponds to the xml attribute
1602                 public string DefaultToolsVersion {
1603                         get {
1604                                 if (xmlDocument != null)
1605                                         return xmlDocument.DocumentElement.GetAttribute ("ToolsVersion");
1606                                 return null;
1607                         }
1608                         set {
1609                                 if (xmlDocument != null)
1610                                         xmlDocument.DocumentElement.SetAttribute ("ToolsVersion", value);
1611                         }
1612                 }
1613
1614                 public bool HasToolsVersionAttribute {
1615                         get {
1616                                 return xmlDocument != null && xmlDocument.DocumentElement.HasAttribute ("ToolsVersion");
1617                         }
1618                 }
1619
1620                 public string ToolsVersion {
1621                         get; internal set;
1622                 }
1623
1624                 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1625                         get { return last_item_group_containing; }
1626                 }
1627                 
1628                 internal ProjectLoadSettings ProjectLoadSettings {
1629                         get { return project_load_settings; }
1630                         set { project_load_settings = value; }
1631                 }
1632
1633                 internal static XmlNamespaceManager XmlNamespaceManager {
1634                         get {
1635                                 if (manager == null) {
1636                                         manager = new XmlNamespaceManager (new NameTable ());
1637                                         manager.AddNamespace ("tns", ns);
1638                                 }
1639                                 
1640                                 return manager;
1641                         }
1642                 }
1643                 
1644                 internal TaskDatabase TaskDatabase {
1645                         get { return taskDatabase; }
1646                 }
1647                 
1648                 internal XmlDocument XmlDocument {
1649                         get { return xmlDocument; }
1650                 }
1651                 
1652                 internal static string XmlNamespace {
1653                         get { return ns; }
1654                 }
1655
1656                 static string OS {
1657                         get {
1658                                 PlatformID pid = Environment.OSVersion.Platform;
1659                                 switch ((int)pid) {
1660                                 case 128:
1661                                 case 4:
1662                                         return "Unix";
1663                                 case 6:
1664                                         return "OSX";
1665                                 default:
1666                                         return "Windows_NT";
1667                                 }
1668                         }
1669                 }
1670
1671         }
1672 }