Merge pull request #900 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / class / Microsoft.Build / Microsoft.Build.Execution / ProjectInstance.cs
1 //
2 // ProjectInstance.cs
3 //
4 // Author:
5 //   Rolf Bjarne Kvinge (rolf@xamarin.com)
6 //   Atsushi Enomoto (atsushi@xamarin.com)
7 //
8 // Copyright (C) 2011,2013 Xamarin Inc.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 //
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Linq;
34
35 using Microsoft.Build.Construction;
36 using Microsoft.Build.Evaluation;
37 using Microsoft.Build.Framework;
38 using Microsoft.Build.Internal.Expressions;
39 using Microsoft.Build.Logging;
40
41 //
42 // It is not always consistent to reuse Project and its evaluation stuff mostly because
43 // both BuildParameters.ctor() and Project.ctor() takes arbitrary ProjectCollection, which are not very likely eqivalent
44 // (as BuildParameters.ctor(), unlike Project.ctor(...), is known to create a new ProjectCollection instance).
45 //
46 // However, that inconsistency could happen even if you only use ProjectInstance and BuildParameters.
47 // They both have constructors that take ProjectCollection and there is no guarantee that the arguments are the same.
48 // BuildManager.Build() does not fail because of inconsistent ProjectCollection instance on .NET.
49 //
50 // Anyhow, I'm not going to instantiate Project within ProjectInstance code for another reason:
51 // ProjectCollection.GetLoadedProject() does not return any Project instnace for corresponding ProjectInstance
52 // (or I should say, ProjectRootElement for both).
53 using Microsoft.Build.Internal;
54 using System.Xml;
55 using Microsoft.Build.Exceptions;
56 using System.IO;
57
58
59 namespace Microsoft.Build.Execution
60 {
61         public class ProjectInstance
62         {
63                 // instance members
64                 
65                 public ProjectInstance (ProjectRootElement xml)
66                         : this (xml, null, null, ProjectCollection.GlobalProjectCollection)
67                 {
68                 }
69
70                 public ProjectInstance (string projectFile)
71                         : this (projectFile, null, null, ProjectCollection.GlobalProjectCollection)
72                 {
73                 }
74
75                 public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
76                                 string toolsVersion)
77                         : this (projectFile, globalProperties, toolsVersion, ProjectCollection.GlobalProjectCollection)
78                 {
79                 }
80
81                 public ProjectInstance (ProjectRootElement xml, IDictionary<string, string> globalProperties,
82                                 string toolsVersion, ProjectCollection projectCollection)
83                 {
84                         projects = projectCollection;
85                         global_properties = globalProperties ?? new Dictionary<string, string> ();
86                         tools_version = !string.IsNullOrEmpty (toolsVersion) ? toolsVersion :
87                                 !string.IsNullOrEmpty (xml.ToolsVersion) ? xml.ToolsVersion :
88                                 projects.DefaultToolsVersion;
89                         InitializeProperties (xml, null);
90                 }
91
92                 public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
93                                 string toolsVersion, ProjectCollection projectCollection)
94                         : this (ProjectRootElement.Create (projectFile), globalProperties, toolsVersion, projectCollection)
95                 {
96                 }
97
98                 ProjectCollection projects;
99                 IDictionary<string, string> global_properties;
100                 
101                 string full_path, directory;
102                 #if NET_4_5
103                 ElementLocation location;
104                 #endif
105                 
106                 Dictionary<string, ProjectItemDefinitionInstance> item_definitions;
107                 List<ResolvedImport> raw_imports; // maybe we don't need this...
108                 List<ProjectItemInstance> all_evaluated_items;
109                 List<ProjectItemInstance> raw_items;
110                 List<ProjectPropertyInstance> properties;
111                 Dictionary<string, ProjectTargetInstance> targets;
112                 string tools_version;
113                 
114                 List<string> GetDefaultTargets (ProjectRootElement xml)
115                 {
116                         var ret = GetDefaultTargets (xml, true, true);
117                         return ret.Any () ? ret : GetDefaultTargets (xml, false, true);
118                 }
119                 
120                 List<string> GetDefaultTargets (ProjectRootElement xml, bool fromAttribute, bool checkImports)
121                 {
122                         if (fromAttribute) {
123                                 var ret = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
124                                 if (checkImports && ret.Count == 0) {
125                                         foreach (var imp in this.raw_imports) {
126                                                 ret = GetDefaultTargets (imp.ImportedProject, true, false);
127                                                 if (ret.Any ())
128                                                         break;
129                                         }
130                                 }
131                                 return ret;
132                         } else {
133                                 if (xml.Targets.Any ())
134                                         return new String [] { xml.Targets.First ().Name }.ToList ();
135                                 if (checkImports) {
136                                         foreach (var imp in this.raw_imports) {
137                                                 var ret = GetDefaultTargets (imp.ImportedProject, false, false);
138                                                 if (ret.Any ())
139                                                         return ret;
140                                         }
141                                 }
142                                 return new List<string> ();
143                         }
144                 }
145
146                 void InitializeProperties (ProjectRootElement xml, ProjectInstance parent)
147                 {
148                         #if NET_4_5
149                         location = xml.Location;
150                         #endif
151                         full_path = xml.FullPath;
152                         directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
153                         InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
154
155                         raw_imports = new List<ResolvedImport> ();
156                         item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
157                         targets = new Dictionary<string, ProjectTargetInstance> ();
158                         raw_items = new List<ProjectItemInstance> ();
159                         
160                         // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
161                         if (parent != null) {
162                                 properties = parent.properties;
163                         } else {
164                                 properties = new List<ProjectPropertyInstance> ();
165                         
166                                 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
167                                         // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
168                                         // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
169                                         if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
170                                                 this.properties.Add (new ProjectPropertyInstance ((string) p.Key, false, (string) p.Value));
171                                 foreach (var p in global_properties)
172                                         this.properties.Add (new ProjectPropertyInstance (p.Key, false, p.Value));
173                                 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
174                                 foreach (var p in projects.GetReservedProperties (tools, this, xml))
175                                         this.properties.Add (p);
176                                 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
177                                         this.properties.Add (p);
178                         }
179
180                         ProcessXml (parent, xml);
181                         
182                         DefaultTargets = GetDefaultTargets (xml);
183                 }
184                 
185                 static readonly char [] item_target_sep = {';'};
186                 
187                 void ProcessXml (ProjectInstance parent, ProjectRootElement xml)
188                 {
189                         TaskDatabase = new BuildTaskDatabase (this, xml);
190                         
191                         // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
192                         // Conditions could incorrectly reference items and lack of this list causes NRE.
193                         all_evaluated_items = new List<ProjectItemInstance> ();
194
195                         // property evaluation happens couple of times.
196                         // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
197                         // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
198                         // properties and they will be expanded.
199                         var elements = EvaluatePropertiesAndImports (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
200                         
201                         // next, evaluate items
202                         EvaluateItems (xml, elements);
203                         
204                         // finally, evaluate targets and tasks
205                         EvaluateTasks (elements);                       
206                 }
207                 
208                 IEnumerable<ProjectElement> EvaluatePropertiesAndImports (IEnumerable<ProjectElement> elements)
209                 {
210                         // First step: evaluate Properties
211                         foreach (var child in elements) {
212                                 yield return child;
213                                 var pge = child as ProjectPropertyGroupElement;
214                                 if (pge != null && EvaluateCondition (pge.Condition))
215                                         foreach (var p in pge.Properties)
216                                                 // do not allow overwriting reserved or well-known properties by user
217                                                 if (!this.properties.Any (_ => (_.IsImmutable) && _.Name.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
218                                                         if (EvaluateCondition (p.Condition))
219                                                                 this.properties.Add (new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value)));
220
221                                 var ige = child as ProjectImportGroupElement;
222                                 if (ige != null && EvaluateCondition (ige.Condition)) {
223                                         foreach (var incc in ige.Imports) {
224                                                 if (EvaluateCondition (incc.Condition))
225                                                         foreach (var e in Import (incc))
226                                                                 yield return e;
227                                         }
228                                 }
229                                 var inc = child as ProjectImportElement;
230                                 if (inc != null && EvaluateCondition (inc.Condition))
231                                         foreach (var e in Import (inc))
232                                                 yield return e;
233                         }
234                 }
235                 
236                 internal IEnumerable<T> GetAllItems<T> (string include, string exclude, Func<string,T> creator, Func<string,ITaskItem> taskItemCreator, Func<string,bool> itemTypeCheck, Action<T,string> assignRecurse)
237                 {
238                         return ProjectCollection.GetAllItems<T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse,
239                                 t => all_evaluated_items.Any (i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck (i.ItemType)));
240                 }
241
242                 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
243                 {
244                         foreach (var child in elements) {
245                                 var ige = child as ProjectItemGroupElement;
246                                 if (ige != null) {
247                                         foreach (var p in ige.Items) {
248                                                 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
249                                                         continue;
250                                                 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
251                                                 foreach (var item in GetAllItems (p.Include, p.Exclude, creator, s => new ProjectTaskItem (p, s), it => string.Equals (it, p.ItemType, StringComparison.OrdinalIgnoreCase), (t, s) => t.RecursiveDir = s)) {
252                                                         raw_items.Add (item);
253                                                         all_evaluated_items.Add (item);
254                                                 }
255                                         }
256                                 }
257                                 var def = child as ProjectItemDefinitionGroupElement;
258                                 if (def != null) {
259                                         foreach (var p in def.ItemDefinitions) {
260                                                 if (EvaluateCondition (p.Condition)) {
261                                                         ProjectItemDefinitionInstance existing;
262                                                         if (!item_definitions.TryGetValue (p.ItemType, out existing))
263                                                                 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
264                                                         existing.AddItems (p);
265                                                 }
266                                         }
267                                 }
268                         }
269                         all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
270                 }
271                 
272                 void EvaluateTasks (IEnumerable<ProjectElement> elements)
273                 {
274                         foreach (var child in elements) {
275                                 var te = child as ProjectTargetElement;
276                                 if (te != null)
277                                         this.targets.Add (te.Name, new ProjectTargetInstance (te));
278                         }
279                 }
280                 
281                 IEnumerable<ProjectElement> Import (ProjectImportElement import)
282                 {
283                         string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
284                         string path = WindowsCompatibilityExtensions.NormalizeFilePath (ExpandString (import.Project));
285                         path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
286                         if (projects.OngoingImports.Contains (path))
287                                 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
288                         projects.OngoingImports.Push (path);
289                         try {
290                                 using (var reader = XmlReader.Create (path)) {
291                                         var root = ProjectRootElement.Create (reader, projects);
292                                         raw_imports.Add (new ResolvedImport (import, root, true));
293                                         return this.EvaluatePropertiesAndImports (root.Children).ToArray ();
294                                 }
295                         } finally {
296                                 projects.OngoingImports.Pop ();
297                         }
298                 }
299
300                 internal IEnumerable<ProjectItemInstance> AllEvaluatedItems {
301                         get { return all_evaluated_items; }
302                 }
303
304                 public List<string> DefaultTargets { get; private set; }
305                 
306                 public string Directory {
307                         get { return directory; }
308                 }
309                 
310                 public string FullPath {
311                         get { return full_path; }
312                 }
313                 
314                 public IDictionary<string, string> GlobalProperties {
315                         get { return global_properties; }
316                 }
317                 
318                 public List<string> InitialTargets { get; private set; }
319                 
320 #if NET_4_5             
321                 public bool IsImmutable {
322                         get { throw new NotImplementedException (); }
323                 }
324 #endif
325                 
326                 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
327                         get { return item_definitions; }
328                 }
329                 
330                 public ICollection<ProjectItemInstance> Items {
331                         get { return all_evaluated_items; }
332                 }
333                 
334                 public ICollection<string> ItemTypes {
335                         get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
336                 }
337
338 #if NET_4_5             
339                 public ElementLocation ProjectFileLocation {
340                         get { return location; }
341                 }
342 #endif
343
344                 public ICollection<ProjectPropertyInstance> Properties {
345                         get { return properties; }
346                 }
347                 
348                 #if NET_4_5
349                 public
350                 #else
351                 internal
352                 #endif
353                 IDictionary<string, ProjectTargetInstance> Targets {
354                         get { return targets; }
355                 }
356                 
357                 public string ToolsVersion {
358                         get { return tools_version; }
359                 }
360
361                 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
362                 {
363                         return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
364                 }
365                 
366                 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
367                 {
368                         var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
369                         raw_items.Add (item);
370                         all_evaluated_items.Add (item);
371                         return item;
372                 }
373
374                 public bool Build ()
375                 {
376                         return Build (new ILogger [0]);
377                 }
378
379                 public bool Build (IEnumerable<ILogger> loggers)
380                 {
381                         return Build (loggers, new ForwardingLoggerRecord [0]);
382                 }
383                 
384                 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
385                 {
386                         return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
387                 }
388
389                 public bool Build (string target, IEnumerable<ILogger> loggers)
390                 {
391                         return Build (target, loggers, new ForwardingLoggerRecord [0]);
392                 }
393
394                 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
395                 {
396                         return Build (targets, loggers, new ForwardingLoggerRecord [0]);
397                 }
398                 
399                 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
400                 {
401                         return Build (new string [] {target}, loggers, remoteLoggers);
402                 }
403                 
404                 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
405                 {
406                         IDictionary<string, TargetResult> outputs;
407                         return Build (targets, loggers, remoteLoggers, out outputs);
408                 }
409
410                 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
411                 {
412                         return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
413                 }
414
415                 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
416                 {
417                         var manager = new BuildManager ();
418                         var parameters = new BuildParameters (projects) {
419                                 ForwardingLoggers = remoteLoggers,
420                                 Loggers = loggers,
421                         };
422                         var requestData = new BuildRequestData (this, targets ?? DefaultTargets.ToArray ());
423                         var result = manager.Build (parameters, requestData);
424                         targetOutputs = result.ResultsByTarget;
425                         return result.OverallResult == BuildResultCode.Success;
426                 }
427                 
428                 public ProjectInstance DeepCopy ()
429                 {
430                         return DeepCopy (false);
431                 }
432                 
433                 public ProjectInstance DeepCopy (bool isImmutable)
434                 {
435                         throw new NotImplementedException ();
436                 }
437                 
438                 public bool EvaluateCondition (string condition)
439                 {
440                         return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this, null).EvaluateAsBoolean (condition);
441                 }
442
443                 public string ExpandString (string unexpandedValue)
444                 {
445                         return ExpandString (unexpandedValue, null);
446                 }
447                 
448                 string ExpandString (string unexpandedValue, string replacementForMissingStuff)
449                 {
450                         return new ExpressionEvaluator (this, replacementForMissingStuff).Evaluate (unexpandedValue);
451                 }
452
453                 public ICollection<ProjectItemInstance> GetItems (string itemType)
454                 {
455                         return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
456                 }
457
458                 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
459                 {
460                         throw new NotImplementedException ();
461                 }
462
463                 public ProjectPropertyInstance GetProperty (string name)
464                 {
465                         return properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
466                 }
467                 
468                 public string GetPropertyValue (string name)
469                 {
470                         var prop = GetProperty (name);
471                         return prop != null ? prop.EvaluatedValue : string.Empty;
472                 }
473                 
474                 public bool RemoveItem (ProjectItemInstance item)
475                 {
476                         // yeah, this raw_items should vanish...
477                         raw_items.Remove (item);
478                         return all_evaluated_items.Remove (item);
479                 }
480
481                 public bool RemoveProperty (string name)
482                 {
483                         var removed = properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
484                         if (removed == null)
485                                 return false;
486                         properties.Remove (removed);
487                         return true;
488                 }
489                 
490                 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
491                 {
492                         var p = new ProjectPropertyInstance (name, false, evaluatedValue);
493                         properties.Add (p);
494                         return p;
495                 }
496                 
497                 public ProjectRootElement ToProjectRootElement ()
498                 {
499                         throw new NotImplementedException ();
500                 }
501                 
502 #if NET_4_5
503                 public void UpdateStateFrom (ProjectInstance projectState)
504                 {
505                         throw new NotImplementedException ();
506                 }
507 #endif
508                 
509                 // static members               
510
511                 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
512                 {
513                         // ?? ItemDefinition does not have Include attribute. What's the point here?
514                         throw new NotImplementedException ();
515                 }
516
517                 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
518                 {
519                         return ProjectCollection.Escape (item.EvaluatedInclude);
520                 }
521
522                 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
523                 {
524                         return ProjectCollection.Escape (metadatum.EvaluatedValue);
525                 }
526                 
527                 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
528                 {
529                         var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
530                         return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
531                 }
532                 
533                 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
534                 {
535                         var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
536                         return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
537                 }
538
539                 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
540                 {
541                         // WTF happens here.
542                         //return ProjectCollection.Escape (property.EvaluatedValue);
543                         return property.EvaluatedValue;
544                 }
545
546                 internal BuildTaskDatabase TaskDatabase { get; private set; }
547                 
548                 internal string GetFullPath (string pathRelativeToProject)
549                 {
550                         if (Path.IsPathRooted (pathRelativeToProject))
551                                 return pathRelativeToProject;
552                         return Path.GetFullPath (Path.Combine (Directory, pathRelativeToProject));
553                 }
554         }
555 }
556