Convert blocking operations in HttpWebRequest and SslClientStream to non-blocking...
[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 = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
117                         if (ret.Count == 0 && xml.Targets.Any ())
118                                 ret.Add (xml.Targets.First ().Name);
119                         return ret;
120                 }
121
122                 void InitializeProperties (ProjectRootElement xml, ProjectInstance parent)
123                 {
124                         #if NET_4_5
125                         location = xml.Location;
126                         #endif
127                         full_path = xml.FullPath;
128                         directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
129                         DefaultTargets = GetDefaultTargets (xml);
130                         InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
131
132                         raw_imports = new List<ResolvedImport> ();
133                         item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
134                         targets = new Dictionary<string, ProjectTargetInstance> ();
135                         raw_items = new List<ProjectItemInstance> ();
136                         
137                         // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
138                         if (parent != null) {
139                                 properties = parent.properties;
140                         } else {
141                                 properties = new List<ProjectPropertyInstance> ();
142                         
143                                 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
144                                         // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
145                                         // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
146                                         if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
147                                                 this.properties.Add (new ProjectPropertyInstance ((string) p.Key, false, (string) p.Value));
148                                 foreach (var p in global_properties)
149                                         this.properties.Add (new ProjectPropertyInstance (p.Key, false, p.Value));
150                                 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
151                                 foreach (var p in projects.GetReservedProperties (tools, this, xml))
152                                         this.properties.Add (p);
153                                 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
154                                         this.properties.Add (p);
155                         }
156
157                         ProcessXml (parent, xml);
158                 }
159                 
160                 static readonly char [] item_target_sep = {';'};
161                 
162                 void ProcessXml (ProjectInstance parent, ProjectRootElement xml)
163                 {
164                         TaskDatabase = new BuildTaskDatabase (this, xml);
165                         
166                         // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
167                         // Conditions could incorrectly reference items and lack of this list causes NRE.
168                         all_evaluated_items = new List<ProjectItemInstance> ();
169
170                         // property evaluation happens couple of times.
171                         // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
172                         // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
173                         // properties and they will be expanded.
174                         var elements = EvaluatePropertiesAndImports (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
175                         
176                         // next, evaluate items
177                         EvaluateItems (xml, elements);
178                         
179                         // finally, evaluate targets and tasks
180                         EvaluateTasks (elements);                       
181                 }
182                 
183                 IEnumerable<ProjectElement> EvaluatePropertiesAndImports (IEnumerable<ProjectElement> elements)
184                 {
185                         // First step: evaluate Properties
186                         foreach (var child in elements) {
187                                 yield return child;
188                                 var pge = child as ProjectPropertyGroupElement;
189                                 if (pge != null && EvaluateCondition (pge.Condition))
190                                         foreach (var p in pge.Properties)
191                                                 // do not allow overwriting reserved or well-known properties by user
192                                                 if (!this.properties.Any (_ => (_.IsImmutable) && _.Name.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
193                                                         if (EvaluateCondition (p.Condition))
194                                                                 this.properties.Add (new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value)));
195
196                                 var ige = child as ProjectImportGroupElement;
197                                 if (ige != null && EvaluateCondition (ige.Condition)) {
198                                         foreach (var incc in ige.Imports) {
199                                                 foreach (var e in Import (incc))
200                                                         yield return e;
201                                         }
202                                 }
203                                 var inc = child as ProjectImportElement;
204                                 if (inc != null && EvaluateCondition (inc.Condition))
205                                         foreach (var e in Import (inc))
206                                                 yield return e;
207                         }
208                 }
209                 
210                 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)
211                 {
212                         return ProjectCollection.GetAllItems<T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse,
213                                 t => all_evaluated_items.Any (i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck (i.ItemType)));
214                 }
215
216                 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
217                 {
218                         foreach (var child in elements) {
219                                 var ige = child as ProjectItemGroupElement;
220                                 if (ige != null) {
221                                         foreach (var p in ige.Items) {
222                                                 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
223                                                         continue;
224                                                 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
225                                                 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)) {
226                                                         raw_items.Add (item);
227                                                         all_evaluated_items.Add (item);
228                                                 }
229                                         }
230                                 }
231                                 var def = child as ProjectItemDefinitionGroupElement;
232                                 if (def != null) {
233                                         foreach (var p in def.ItemDefinitions) {
234                                                 if (EvaluateCondition (p.Condition)) {
235                                                         ProjectItemDefinitionInstance existing;
236                                                         if (!item_definitions.TryGetValue (p.ItemType, out existing))
237                                                                 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
238                                                         existing.AddItems (p);
239                                                 }
240                                         }
241                                 }
242                         }
243                         all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
244                 }
245                 
246                 void EvaluateTasks (IEnumerable<ProjectElement> elements)
247                 {
248                         foreach (var child in elements) {
249                                 var te = child as ProjectTargetElement;
250                                 if (te != null)
251                                         this.targets.Add (te.Name, new ProjectTargetInstance (te));
252                         }
253                 }
254                 
255                 IEnumerable<ProjectElement> Import (ProjectImportElement import)
256                 {
257                         string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
258                         string path = WindowsCompatibilityExtensions.NormalizeFilePath (ExpandString (import.Project));
259                         path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
260                         if (projects.OngoingImports.Contains (path))
261                                 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
262                         projects.OngoingImports.Push (path);
263                         try {
264                                 using (var reader = XmlReader.Create (path)) {
265                                         var root = ProjectRootElement.Create (reader, projects);
266                                         if (DefaultTargets.Count == 0)
267                                                 DefaultTargets.AddRange (GetDefaultTargets (root));
268                                         raw_imports.Add (new ResolvedImport (import, root, true));
269                                         return this.EvaluatePropertiesAndImports (root.Children).ToArray ();
270                                 }
271                         } finally {
272                                 projects.OngoingImports.Pop ();
273                         }
274                 }
275
276                 internal IEnumerable<ProjectItemInstance> AllEvaluatedItems {
277                         get { return all_evaluated_items; }
278                 }
279
280                 public List<string> DefaultTargets { get; private set; }
281                 
282                 public string Directory {
283                         get { return directory; }
284                 }
285                 
286                 public string FullPath {
287                         get { return full_path; }
288                 }
289                 
290                 public IDictionary<string, string> GlobalProperties {
291                         get { return global_properties; }
292                 }
293                 
294                 public List<string> InitialTargets { get; private set; }
295                 
296 #if NET_4_5             
297                 public bool IsImmutable {
298                         get { throw new NotImplementedException (); }
299                 }
300 #endif
301                 
302                 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
303                         get { return item_definitions; }
304                 }
305                 
306                 public ICollection<ProjectItemInstance> Items {
307                         get { return all_evaluated_items; }
308                 }
309                 
310                 public ICollection<string> ItemTypes {
311                         get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
312                 }
313
314 #if NET_4_5             
315                 public ElementLocation ProjectFileLocation {
316                         get { return location; }
317                 }
318 #endif
319
320                 public ICollection<ProjectPropertyInstance> Properties {
321                         get { return properties; }
322                 }
323                 
324                 #if NET_4_5
325                 public
326                 #else
327                 internal
328                 #endif
329                 IDictionary<string, ProjectTargetInstance> Targets {
330                         get { return targets; }
331                 }
332                 
333                 public string ToolsVersion {
334                         get { return tools_version; }
335                 }
336
337                 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
338                 {
339                         return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
340                 }
341                 
342                 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
343                 {
344                         var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
345                         raw_items.Add (item);
346                         all_evaluated_items.Add (item);
347                         return item;
348                 }
349
350                 public bool Build ()
351                 {
352                         return Build (new ILogger [0]);
353                 }
354
355                 public bool Build (IEnumerable<ILogger> loggers)
356                 {
357                         return Build (loggers, new ForwardingLoggerRecord [0]);
358                 }
359                 
360                 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
361                 {
362                         return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
363                 }
364
365                 public bool Build (string target, IEnumerable<ILogger> loggers)
366                 {
367                         return Build (target, loggers, new ForwardingLoggerRecord [0]);
368                 }
369
370                 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
371                 {
372                         return Build (targets, loggers, new ForwardingLoggerRecord [0]);
373                 }
374                 
375                 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
376                 {
377                         return Build (new string [] {target}, loggers, remoteLoggers);
378                 }
379                 
380                 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
381                 {
382                         IDictionary<string, TargetResult> outputs;
383                         return Build (targets, loggers, remoteLoggers, out outputs);
384                 }
385
386                 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
387                 {
388                         return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
389                 }
390
391                 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
392                 {
393                         var manager = new BuildManager ();
394                         var parameters = new BuildParameters (projects) {
395                                 ForwardingLoggers = remoteLoggers,
396                                 Loggers = loggers,
397                         };
398                         var requestData = new BuildRequestData (this, targets);
399                         var result = manager.Build (parameters, requestData);
400                         targetOutputs = result.ResultsByTarget;
401                         return result.OverallResult == BuildResultCode.Success;
402                 }
403                 
404                 public ProjectInstance DeepCopy ()
405                 {
406                         return DeepCopy (false);
407                 }
408                 
409                 public ProjectInstance DeepCopy (bool isImmutable)
410                 {
411                         throw new NotImplementedException ();
412                 }
413                 
414                 public bool EvaluateCondition (string condition)
415                 {
416                         return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this, null).EvaluateAsBoolean (condition);
417                 }
418
419                 public string ExpandString (string unexpandedValue)
420                 {
421                         return ExpandString (unexpandedValue, null);
422                 }
423                 
424                 string ExpandString (string unexpandedValue, string replacementForMissingStuff)
425                 {
426                         return new ExpressionEvaluator (this, replacementForMissingStuff).Evaluate (unexpandedValue);
427                 }
428
429                 public ICollection<ProjectItemInstance> GetItems (string itemType)
430                 {
431                         return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
432                 }
433
434                 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
435                 {
436                         throw new NotImplementedException ();
437                 }
438
439                 public ProjectPropertyInstance GetProperty (string name)
440                 {
441                         return properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
442                 }
443                 
444                 public string GetPropertyValue (string name)
445                 {
446                         var prop = GetProperty (name);
447                         return prop != null ? prop.EvaluatedValue : string.Empty;
448                 }
449                 
450                 public bool RemoveItem (ProjectItemInstance item)
451                 {
452                         // yeah, this raw_items should vanish...
453                         raw_items.Remove (item);
454                         return all_evaluated_items.Remove (item);
455                 }
456
457                 public bool RemoveProperty (string name)
458                 {
459                         var removed = properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
460                         if (removed == null)
461                                 return false;
462                         properties.Remove (removed);
463                         return true;
464                 }
465                 
466                 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
467                 {
468                         var p = new ProjectPropertyInstance (name, false, evaluatedValue);
469                         properties.Add (p);
470                         return p;
471                 }
472                 
473                 public ProjectRootElement ToProjectRootElement ()
474                 {
475                         throw new NotImplementedException ();
476                 }
477                 
478 #if NET_4_5
479                 public void UpdateStateFrom (ProjectInstance projectState)
480                 {
481                         throw new NotImplementedException ();
482                 }
483 #endif
484                 
485                 // static members               
486
487                 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
488                 {
489                         // ?? ItemDefinition does not have Include attribute. What's the point here?
490                         throw new NotImplementedException ();
491                 }
492
493                 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
494                 {
495                         return ProjectCollection.Escape (item.EvaluatedInclude);
496                 }
497
498                 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
499                 {
500                         return ProjectCollection.Escape (metadatum.EvaluatedValue);
501                 }
502                 
503                 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
504                 {
505                         var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
506                         return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
507                 }
508                 
509                 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
510                 {
511                         var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
512                         return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
513                 }
514
515                 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
516                 {
517                         // WTF happens here.
518                         //return ProjectCollection.Escape (property.EvaluatedValue);
519                         return property.EvaluatedValue;
520                 }
521
522                 internal BuildTaskDatabase TaskDatabase { get; private set; }
523                 
524                 internal string GetFullPath (string pathRelativeToProject)
525                 {
526                         if (Path.IsPathRooted (pathRelativeToProject))
527                                 return pathRelativeToProject;
528                         return Path.GetFullPath (Path.Combine (Directory, pathRelativeToProject));
529                 }
530         }
531 }
532