Merge pull request #1079 from esdrubal/webclient_cancel
[mono.git] / mcs / class / Microsoft.Build / Microsoft.Build.Internal / BuildEngine4.cs
1 //
2 // BuildEngine4.cs
3 //
4 // Author:
5 //   Atsushi Enomoto (atsushi@xamarin.com)
6 //
7 // Copyright (C) 2013 Xamarin Inc. (http://www.xamarin.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections;
30 using System.Collections.Generic;
31 using Microsoft.Build.Execution;
32 using Microsoft.Build.Framework;
33 using Microsoft.Build.Evaluation;
34 using System.Linq;
35 using System.IO;
36 using Microsoft.Build.Exceptions;
37 using System.Globalization;
38 using Microsoft.Build.Construction;
39 using Microsoft.Build.Internal.Expressions;
40 using System.Xml;
41
42 namespace Microsoft.Build.Internal
43 {
44         class BuildEngine4
45 #if NET_4_5
46                 : IBuildEngine4
47 #else
48                 : IBuildEngine3
49 #endif
50         {
51                 public BuildEngine4 (BuildSubmission submission)
52                 {
53                         this.submission = submission;
54                         event_source = new Microsoft.Build.BuildEngine.EventSource ();
55                         if (submission.BuildManager.OngoingBuildParameters.Loggers != null)
56                                 foreach (var l in submission.BuildManager.OngoingBuildParameters.Loggers)
57                                         l.Initialize (event_source);
58                 }
59
60                 BuildSubmission submission;
61                 ProjectInstance project;
62                 ProjectTaskInstance current_task;
63                 Microsoft.Build.BuildEngine.EventSource event_source;
64                 
65                 public ProjectCollection Projects {
66                         get { return submission.BuildManager.OngoingBuildParameters.ProjectCollection; }
67                 }
68
69                 // FIXME:
70                 // While we are not faced to implement those features, there are some modern task execution requirements.
71                 //
72                 // This will have to be available for "out of process" nodes (see NodeAffinity).
73                 // NodeAffinity is set per project file at BuildManager.HostServices.
74                 // When NodeAffinity is set to OutOfProc, it should probably launch different build host
75                 // that runs separate build tasks. (.NET has MSBuildTaskHost.exe which I guess is about that.)
76                 //
77                 // Also note that the complete implementation has to support LoadInSeparateAppDomainAttribute
78                 // (which is most likely derived from AppDomainIsolatedBuildTask) that marks a task to run
79                 // in separate AppDomain.
80                 //
81                 public void BuildProject (Func<bool> checkCancel, BuildResult result, ProjectInstance project, IEnumerable<string> targetNames, IDictionary<string,string> globalProperties, IDictionary<string,string> targetOutputs, string toolsVersion)
82                 {
83                         if (toolsVersion == null)
84                                 throw new ArgumentNullException ("toolsVersion");
85                         
86                         var parameters = submission.BuildManager.OngoingBuildParameters;
87                         var toolset = parameters.GetToolset (toolsVersion);
88                         if (toolset == null)
89                                 throw new InvalidOperationException (string.Format ("Toolset version '{0}' was not resolved to valid toolset", toolsVersion));
90                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Using Toolset version {0}.", toolsVersion), null, null, MessageImportance.Low));
91                         var buildTaskFactory = new BuildTaskFactory (BuildTaskDatabase.GetDefaultTaskDatabase (toolset), new BuildTaskDatabase (this, submission.BuildRequest.ProjectInstance));
92                         BuildProject (new InternalBuildArguments () { CheckCancel = checkCancel, Result = result, Project = project, TargetNames = targetNames, GlobalProperties = globalProperties, TargetOutputs = targetOutputs, ToolsVersion = toolsVersion, BuildTaskFactory = buildTaskFactory });
93                 }
94
95                 class InternalBuildArguments
96                 {
97                         public Func<bool> CheckCancel;
98                         public BuildResult Result;
99                         public ProjectInstance Project;
100                         public IEnumerable<string> TargetNames;
101                         public IDictionary<string,string> GlobalProperties;
102                         public IDictionary<string,string> TargetOutputs;
103                         public string ToolsVersion;
104                         public BuildTaskFactory BuildTaskFactory;
105                         
106                         public void AddTargetResult (string targetName, TargetResult targetResult)
107                         {
108                                 if (!Result.HasResultsForTarget (targetName))
109                                         Result.AddResultsForTarget (targetName, targetResult);
110                         }
111                 }
112                 
113                 void BuildProject (InternalBuildArguments args)
114                 {
115                         var request = submission.BuildRequest;
116                         var parameters = submission.BuildManager.OngoingBuildParameters;
117                         this.project = args.Project;
118
119                         string directoryBackup = Directory.GetCurrentDirectory ();
120                         Directory.SetCurrentDirectory (project.Directory);
121                         event_source.FireBuildStarted (this, new BuildStartedEventArgs ("Build Started", null, DateTime.Now));
122                         
123                         try {
124                                 
125                                 var initialGlobalPropertiesFormatted = "Initial Global Properties:\n" + string.Join (Environment.NewLine, project.Properties.OrderBy (p => p.Name).Where (p => p.IsImmutable).Select (p => string.Format ("{0} = {1}", p.Name, p.EvaluatedValue)).ToArray ());
126                                 LogMessageEvent (new BuildMessageEventArgs (initialGlobalPropertiesFormatted, null, null, MessageImportance.Low));
127                                 var initialProjectPropertiesFormatted = "Initial Project Properties:\n" + string.Join (Environment.NewLine, project.Properties.OrderBy (p => p.Name).Where (p => !p.IsImmutable).Select (p => string.Format ("{0} = {1}", p.Name, p.EvaluatedValue)).ToArray ());
128                                 LogMessageEvent (new BuildMessageEventArgs (initialProjectPropertiesFormatted, null, null, MessageImportance.Low));
129                                 var initialItemsFormatted = "Initial Items:\n" + string.Join (Environment.NewLine, project.Items.OrderBy (i => i.ItemType).Select (i => string.Format ("{0} : {1}", i.ItemType, i.EvaluatedInclude)).ToArray ());
130                                 LogMessageEvent (new BuildMessageEventArgs (initialItemsFormatted, null, null, MessageImportance.Low));
131                                 
132                                 // null targets -> success. empty targets -> success(!)
133                                 foreach (var targetName in (request.ProjectInstance.InitialTargets).Where (t => t != null))
134                                         BuildTargetByName (targetName, args);
135                                 if (request.TargetNames == null)
136                                         args.Result.OverallResult = args.CheckCancel () ? BuildResultCode.Failure : args.Result.ResultsByTarget.Any (p => p.Value.ResultCode == TargetResultCode.Failure) ? BuildResultCode.Failure : BuildResultCode.Success;
137                                 else {
138                                         foreach (var targetName in (args.TargetNames ?? request.TargetNames).Where (t => t != null))
139                                                 BuildTargetByName (targetName, args);
140                         
141                                         // FIXME: check .NET behavior, whether cancellation always results in failure.
142                                         args.Result.OverallResult = args.CheckCancel () ? BuildResultCode.Failure : args.Result.ResultsByTarget.Any (p => p.Value.ResultCode == TargetResultCode.Failure) ? BuildResultCode.Failure : BuildResultCode.Success;
143                                 }
144                         } catch (Exception ex) {
145                                 args.Result.OverallResult = BuildResultCode.Failure;
146                                 LogErrorEvent (new BuildErrorEventArgs (null, null, project.FullPath, 0, 0, 0, 0, "Unhandled exception occured during a build", null, null));
147                                 LogMessageEvent (new BuildMessageEventArgs ("Exception details: " + ex, null, null, MessageImportance.Low));
148                                 throw; // BuildSubmission re-catches this.
149                         } finally {
150                                 event_source.FireBuildFinished (this, new BuildFinishedEventArgs ("Build Finished.", null, args.Result.OverallResult == BuildResultCode.Success, DateTime.Now));
151                                 Directory.SetCurrentDirectory (directoryBackup);
152                         }
153                 }
154                 
155                 bool BuildTargetByName (string targetName, InternalBuildArguments args)
156                 {
157                         var request = submission.BuildRequest;
158                         var parameters = submission.BuildManager.OngoingBuildParameters;
159                         ProjectTargetInstance target;
160                         TargetResult dummyResult;
161
162                         if (args.Result.ResultsByTarget.TryGetValue (targetName, out dummyResult) && dummyResult.ResultCode == TargetResultCode.Success) {
163                                 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because it was already built successfully.", targetName), null, null, MessageImportance.Low));
164                                 return true; // do not add result.
165                         }
166                         
167                         var targetResult = new TargetResult ();
168
169                         // null key is allowed and regarded as blind success(!) (as long as it could retrieve target)
170                         if (!request.ProjectInstance.Targets.TryGetValue (targetName, out target))
171                                 // FIXME: from MSBuild.exe it is given MSB4057. Can we assign a number too?
172                                 throw new InvalidOperationException (string.Format ("target '{0}' was not found in project '{1}'", targetName, project.FullPath));
173                         else if (!args.Project.EvaluateCondition (target.Condition)) {
174                                 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because condition '{1}' was not met.", target.Name, target.Condition), null, null, MessageImportance.Low));
175                                 targetResult.Skip ();
176                         } else {
177                                 // process DependsOnTargets first.
178                                 foreach (var dep in project.ExpandString (target.DependsOnTargets).Split (';').Select (s => s.Trim ()).Where (s => !string.IsNullOrEmpty (s))) {
179                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' depends on '{1}'.", target.Name, dep), null, null, MessageImportance.Low));
180                                         if (!BuildTargetByName (dep, args)) {
181                                                 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Quit target '{0}', as dependency target '{1}' has failed.", target.Name, dep), null, null, MessageImportance.Low));
182                                                 return false;
183                                         }
184                                 }
185                                 
186                                 Func<string,ITaskItem> creator = s => new TargetOutputTaskItem () { ItemSpec = s };
187                         
188                                 event_source.FireTargetStarted (this, new TargetStartedEventArgs ("Target Started", null, target.Name, project.FullPath, target.FullPath));
189                                 try {
190                                         // FIXME: examine in which scenario Inputs/Outputs inconsistency results in errors. Now it rather prevents csproj build.
191                                         /*if (!string.IsNullOrEmpty (target.Inputs) != !string.IsNullOrEmpty (target.Outputs)) {
192                                                 targetResult.Failure (new InvalidProjectFileException (target.Location, null, string.Format ("Target {0} has mismatching Inputs and Outputs specification. When one is specified, another one has to be specified too.", targetName), null, null, null));
193                                         } else*/ {
194                                                 bool skip = false;
195                                                 if (!string.IsNullOrEmpty (target.Inputs)) {
196                                                         var inputs = args.Project.GetAllItems (target.Inputs, string.Empty, creator, creator, s => true, (t, s) => {
197                                                         });
198                                                         if (!inputs.Any ()) {
199                                                                 LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because there is no input.", target.Name), null, null, MessageImportance.Low));
200                                                                 skip = true;
201                                                         } else {
202                                                                 var outputs = args.Project.GetAllItems (target.Outputs, string.Empty, creator, creator, s => true, (t, s) => {
203                                                                 });
204                                                                 var needsUpdates = GetOlderOutputsThanInputs (inputs, outputs).FirstOrDefault ();
205                                                                 if (needsUpdates != null)
206                                                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' needs to be built because new output {1} is needed.", target.Name, needsUpdates.ItemSpec), null, null, MessageImportance.Low));
207                                                                 else {
208                                                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Target '{0}' was skipped because all the outputs are newer than all the inputs.", target.Name), null, null, MessageImportance.Low));
209                                                                         skip = true;
210                                                                 }
211                                                         }
212                                                 }
213                                                 if (skip) {
214                                                         targetResult.Skip ();
215                                                 } else {
216                                                         if (DoBuildTarget (target, targetResult, args)) {
217                                                                 var items = args.Project.GetAllItems (target.Outputs, string.Empty, creator, creator, s => true, (t, s) => {
218                                                                 });
219                                                                 targetResult.Success (items);
220                                                         }
221                                                 }
222                                         }
223                                 } finally {
224                                         event_source.FireTargetFinished (this, new TargetFinishedEventArgs ("Target Finished", null, targetName, project.FullPath, target.FullPath, targetResult.ResultCode != TargetResultCode.Failure));
225                                 }
226                         }
227                         args.AddTargetResult (targetName, targetResult);
228                         
229                         return targetResult.ResultCode != TargetResultCode.Failure;
230                 }
231                 
232                 IEnumerable<ITaskItem> GetOlderOutputsThanInputs (IEnumerable<ITaskItem> inputs, IEnumerable<ITaskItem> outputs)
233                 {
234                         return outputs.Where (o => !File.Exists (o.GetMetadata ("FullPath")) || inputs.Any (i => string.CompareOrdinal (i.GetMetadata ("LastModifiedTime"), o.GetMetadata ("LastModifiedTime")) > 0));
235                 }
236
237                 // FIXME: Exception should be caught at caller site.
238                 bool DoBuildTarget (ProjectTargetInstance target, TargetResult targetResult, InternalBuildArguments args)
239                 {
240                         var request = submission.BuildRequest;
241         
242                         // Here we check cancellation (only after TargetStarted event).
243                         if (args.CheckCancel ()) {
244                                 targetResult.Failure (new BuildAbortedException ("Build has canceled"));
245                                 return false;
246                         }
247                         
248                         try {
249                                 foreach (var child in target.Children) {
250                                         // Evaluate additional target properties
251                                         var tp = child as ProjectPropertyGroupTaskInstance;
252                                         if (tp != null) {
253                                                 if (!args.Project.EvaluateCondition (tp.Condition))
254                                                         continue;
255                                                 foreach (var p in tp.Properties) {
256                                                         if (!args.Project.EvaluateCondition (p.Condition))
257                                                                 continue;
258                                                         var value = args.Project.ExpandString (p.Value);
259                                                         project.SetProperty (p.Name, value);
260                                                 }
261                                                 continue;
262                                         }
263
264                                         var ii = child as ProjectItemGroupTaskInstance;
265                                         if (ii != null) {
266                                                 if (!args.Project.EvaluateCondition (ii.Condition))
267                                                         continue;
268                                                 foreach (var item in ii.Items) {
269                                                         if (!args.Project.EvaluateCondition (item.Condition))
270                                                                 continue;
271                                                         project.AddItem (item.ItemType, project.ExpandString (item.Include));
272                                                 }
273                                                 continue;
274                                         }
275                                         
276                                         var task = child as ProjectTaskInstance;
277                                         if (task != null) {
278                                                 current_task = task;
279                                                 if (!args.Project.EvaluateCondition (task.Condition)) {
280                                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Task '{0}' was skipped because condition '{1}' wasn't met.", task.Name, task.Condition), null, null, MessageImportance.Low));
281                                                         continue;
282                                                 }
283                                                 if (!RunBuildTask (target, task, targetResult, args))
284                                                         return false;
285                                                 continue;
286                                         }
287
288                                         var onError = child as ProjectOnErrorInstance;
289                                         if (onError != null)
290                                                 continue; // evaluated under catch clause.
291
292                                         throw new NotSupportedException (string.Format ("Unexpected Target element children \"{0}\"", child.GetType ()));
293                                 }
294                         } catch (Exception ex) {
295                                 // fallback task specified by OnError element
296                                 foreach (var c in target.Children.OfType<ProjectOnErrorInstance> ()) {
297                                         if (!args.Project.EvaluateCondition (c.Condition))
298                                                 continue;
299                                         foreach (var fallbackTarget in project.ExpandString (c.ExecuteTargets).Split (';'))
300                                                 BuildTargetByName (fallbackTarget, args);
301                                 }
302                                 int line = target.Location != null ? target.Location.Line : 0;
303                                 int col = target.Location != null ? target.Location.Column : 0;
304                                 LogErrorEvent (new BuildErrorEventArgs (null, null, target.FullPath, line, col, 0, 0, ex.Message, null, null));
305                                 targetResult.Failure (ex);
306                                 return false;
307                         }
308                         return true;
309                 }
310                 
311                 bool RunBuildTask (ProjectTargetInstance target, ProjectTaskInstance taskInstance, TargetResult targetResult, InternalBuildArguments args)
312                 {
313                         var request = submission.BuildRequest;
314
315                         var host = request.HostServices == null ? null : request.HostServices.GetHostObject (request.ProjectFullPath, target.Name, taskInstance.Name);
316                         
317                         // Create Task instance.
318                         var factoryIdentityParameters = new Dictionary<string,string> ();
319                         #if NET_4_5
320                         factoryIdentityParameters ["MSBuildRuntime"] = taskInstance.MSBuildRuntime;
321                         factoryIdentityParameters ["MSBuildArchitecture"] = taskInstance.MSBuildArchitecture;
322                         #endif
323                         var task = args.BuildTaskFactory.CreateTask (taskInstance.Name, factoryIdentityParameters, this);
324                         if (task == null)
325                                 throw new InvalidOperationException (string.Format ("TaskFactory {0} returned null Task", args.BuildTaskFactory));
326                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Using task {0} from {1}", taskInstance.Name, task.GetType ()), null, null, MessageImportance.Low));
327                         task.HostObject = host;
328                         task.BuildEngine = this;
329                         
330                         // Prepare task parameters.
331                         var evaluator = new ExpressionEvaluator (project);
332                         var evaluatedTaskParams = taskInstance.Parameters.Select (p => new KeyValuePair<string,string> (p.Key, project.ExpandString (evaluator, p.Value)));
333
334                         var requiredProps = task.GetType ().GetProperties ()
335                                 .Where (p => p.CanWrite && p.GetCustomAttributes (typeof (RequiredAttribute), true).Any ());
336                         var missings = requiredProps.Where (p => !evaluatedTaskParams.Any (tp => tp.Key.Equals (p.Name, StringComparison.OrdinalIgnoreCase)));
337                         if (missings.Any ())
338                                 throw new InvalidOperationException (string.Format ("Task {0} of type {1} is used without specifying mandatory property: {2}",
339                                         taskInstance.Name, task.GetType (), string.Join (", ", missings.Select (p => p.Name).ToArray ())));
340                         
341                         foreach (var p in evaluatedTaskParams) {
342                                 switch (p.Key.ToLower ()) {
343                                 case "condition":
344                                 case "continueonerror":
345                                         continue;
346                                 }
347                                 var prop = task.GetType ().GetProperty (p.Key);
348                                 if (prop == null)
349                                         throw new InvalidOperationException (string.Format ("Task {0} does not have property {1}", taskInstance.Name, p.Key));
350                                 if (!prop.CanWrite)
351                                         throw new InvalidOperationException (string.Format ("Task {0} has property {1} but it is read-only.", taskInstance.Name, p.Key));
352                                 if (string.IsNullOrEmpty (p.Value) && !requiredProps.Contains (prop))
353                                         continue;
354                                 try {
355                                         prop.SetValue (task, ConvertTo (p.Value, prop.PropertyType, evaluator), null);
356                                 } catch (Exception ex) {
357                                         throw new InvalidOperationException (string.Format ("Failed to convert '{0}' for property '{1}' of type {2}", p.Value, prop.Name, prop.PropertyType), ex);
358                                 }
359                         }
360                         
361                         // Do execute task.
362                         bool taskSuccess = false;
363                         event_source.FireTaskStarted (this, new TaskStartedEventArgs ("Task Started", null, project.FullPath, taskInstance.FullPath, taskInstance.Name));
364                         try {
365                                 taskSuccess = task.Execute ();
366                         
367                                 if (!taskSuccess) {
368                                         targetResult.Failure (null);
369                                         if (!ContinueOnError) {
370                                                 return false;
371                                         }
372                                 } else {
373                                         // Evaluate task output properties and items.
374                                         foreach (var to in taskInstance.Outputs) {
375                                                 if (!project.EvaluateCondition (to.Condition))
376                                                         continue;
377                                                 var toItem = to as ProjectTaskOutputItemInstance;
378                                                 var toProp = to as ProjectTaskOutputPropertyInstance;
379                                                 string taskParameter = toItem != null ? toItem.TaskParameter : toProp.TaskParameter;
380                                                 var pi = task.GetType ().GetProperty (taskParameter);
381                                                 if (pi == null)
382                                                         throw new InvalidOperationException (string.Format ("Task {0} does not have property {1} specified as TaskParameter", taskInstance.Name, toItem.TaskParameter));
383                                                 if (!pi.CanRead)
384                                                         throw new InvalidOperationException (string.Format ("Task {0} has property {1} specified as TaskParameter, but it is write-only", taskInstance.Name, toItem.TaskParameter));
385                                                 var value = pi.GetValue (task, null);
386                                                 var valueString = ConvertFrom (value);
387                                                 if (toItem != null) {
388                                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Output Item {0} from TaskParameter {1}: {2}", toItem.ItemType, toItem.TaskParameter, valueString), null, null, MessageImportance.Low));
389                                                         Action<ITaskItem> addItem = i => {
390                                                                 var metadata = new ArrayList (i.MetadataNames).ToArray ().Cast<string> ().Select (n => new KeyValuePair<string,string> (n, i.GetMetadata (n)));
391                                                                 args.Project.AddItem (toItem.ItemType, i.ItemSpec, metadata);
392                                                         };
393                                                         var taskItemArray = value as ITaskItem [];
394                                                         if (taskItemArray != null) {
395                                                                 foreach (var ti in taskItemArray)
396                                                                         addItem (ti);
397                                                         } else {
398                                                                 var taskItem = value as ITaskItem;
399                                                                 if (taskItem != null) 
400                                                                         addItem (taskItem);
401                                                                 else
402                                                                         foreach (var item in valueString.Split (';'))
403                                                                                 args.Project.AddItem (toItem.ItemType, item);
404                                                         }
405                                                 } else {
406                                                         LogMessageEvent (new BuildMessageEventArgs (string.Format ("Output Property {0} from TaskParameter {1}: {2}", toProp.PropertyName, toProp.TaskParameter, valueString), null, null, MessageImportance.Low));
407                                                         args.Project.SetProperty (toProp.PropertyName, valueString);
408                                                 }
409                                         }
410                                 }
411                         } finally {
412                                 event_source.FireTaskFinished (this, new TaskFinishedEventArgs ("Task Finished", null, project.FullPath, taskInstance.FullPath, taskInstance.Name, taskSuccess));
413                         }
414                         return true;
415                 }
416
417                 object ConvertTo (string source, Type targetType, ExpressionEvaluator evaluator)
418                 {
419                         if (targetType == typeof (ITaskItem) || targetType.IsSubclassOf (typeof (ITaskItem))) {
420                                 var item = evaluator.EvaluatedTaskItems.FirstOrDefault (i => string.Equals (i.ItemSpec, source.Trim (), StringComparison.OrdinalIgnoreCase));
421                                 var ret = new TargetOutputTaskItem () { ItemSpec = source.Trim () };
422                                 if (item != null)
423                                         foreach (string name in item.MetadataNames)
424                                                 ret.SetMetadata (name, item.GetMetadata (name));
425                                 return ret;
426                         }
427                         if (targetType.IsArray)
428                                 return new ArrayList (source.Split (';').Select (s => s.Trim ()).Where (s => !string.IsNullOrEmpty (s)).Select (s => ConvertTo (s, targetType.GetElementType (), evaluator)).ToArray ())
429                                                 .ToArray (targetType.GetElementType ());
430                         if (targetType == typeof (bool)) {
431                                 switch (source != null ? source.ToLower (CultureInfo.InvariantCulture) : string.Empty) {
432                                 case "true":
433                                 case "yes":
434                                 case "on":
435                                         return true;
436                                 case "false":
437                                 case "no":
438                                 case "off":
439                                 case "":
440                                         return false;
441                                 }
442                         }
443                         return Convert.ChangeType (source == "" ? null : source, targetType);
444                 }
445                 
446                 string ConvertFrom (object source)
447                 {
448                         if (source == null)
449                                 return string.Empty;
450                         if (source is ITaskItem)
451                                 return ((ITaskItem) source).ItemSpec;
452                         if (source.GetType ().IsArray)
453                                 return string.Join (";", ((Array) source).Cast<object> ().Select (o => ConvertFrom (o)).ToArray ());
454                         else
455                                 return (string) Convert.ChangeType (source, typeof (string));
456                 }
457                 
458                 class TargetOutputTaskItem : ITaskItem2
459                 {
460                         Hashtable metadata = new Hashtable ();
461                         
462                         #region ITaskItem2 implementation
463                         public string GetMetadataValueEscaped (string metadataName)
464                         {
465                                 return ProjectCollection.Escape ((string) metadata [metadataName]);
466                         }
467                         public void SetMetadataValueLiteral (string metadataName, string metadataValue)
468                         {
469                                 metadata [metadataName] = ProjectCollection.Unescape (metadataValue);
470                         }
471                         public IDictionary CloneCustomMetadataEscaped ()
472                         {
473                                 var ret = new Hashtable ();
474                                 foreach (DictionaryEntry e in metadata)
475                                         ret [e.Key] = ProjectCollection.Escape ((string) e.Value);
476                                 return ret;
477                         }
478                         public string EvaluatedIncludeEscaped {
479                                 get { return ProjectCollection.Escape (ItemSpec); }
480                                 set { ItemSpec = ProjectCollection.Unescape (value); }
481                         }
482                         #endregion
483                         #region ITaskItem implementation
484                         public IDictionary CloneCustomMetadata ()
485                         {
486                                 return new Hashtable (metadata);
487                         }
488                         public void CopyMetadataTo (ITaskItem destinationItem)
489                         {
490                                 foreach (DictionaryEntry e in metadata)
491                                         destinationItem.SetMetadata ((string) e.Key, (string) e.Value);
492                         }
493                         public string GetMetadata (string metadataName)
494                         {
495                                 var wk = ProjectCollection.GetWellKnownMetadata (metadataName, ItemSpec, Path.GetFullPath, null);
496                                 if (wk != null)
497                                         return wk;
498                                 var ret = (string) metadata [metadataName];
499                                 return ret ?? string.Empty;
500                         }
501                         public void RemoveMetadata (string metadataName)
502                         {
503                                 metadata.Remove (metadataName);
504                         }
505                         public void SetMetadata (string metadataName, string metadataValue)
506                         {
507                                 metadata [metadataName] = metadataValue;
508                         }
509                         public string ItemSpec { get; set; }
510                         public int MetadataCount {
511                                 get { return metadata.Count; }
512                         }
513                         public ICollection MetadataNames {
514                                 get { return metadata.Keys; }
515                         }
516                         #endregion
517
518                         public override string ToString ()
519                         {
520                                 return ItemSpec;
521                         }
522                 }
523                 
524 #if NET_4_5
525                 #region IBuildEngine4 implementation
526                 
527                 // task objects are not in use anyways though...
528                 
529                 class TaskObjectRegistration
530                 {
531                         public TaskObjectRegistration (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
532                         {
533                                 Key = key;
534                                 Object = obj;
535                                 Lifetime = lifetime;
536                                 AllowEarlyCollection = allowEarlyCollection;
537                         }
538                         public object Key { get; private set; }
539                         public object Object { get; private set; }
540                         public RegisteredTaskObjectLifetime Lifetime { get; private set; }
541                         public bool AllowEarlyCollection { get; private set; }
542                 }
543                 
544                 List<TaskObjectRegistration> task_objects = new List<TaskObjectRegistration> ();
545
546                 public object GetRegisteredTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
547                 {
548                         var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
549                         return reg != null ? reg.Object : null;
550                 }
551
552                 public void RegisterTaskObject (object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection)
553                 {
554                         task_objects.Add (new TaskObjectRegistration (key, obj, lifetime, allowEarlyCollection));
555                 }
556
557                 public object UnregisterTaskObject (object key, RegisteredTaskObjectLifetime lifetime)
558                 {
559                         var reg = task_objects.FirstOrDefault (t => t.Key == key && t.Lifetime == lifetime);
560                         if (reg != null)
561                                 task_objects.Remove (reg);
562                         return reg.Object;
563                 }
564                 #endregion
565 #endif
566
567                 #region IBuildEngine3 implementation
568
569                 public BuildEngineResult BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs)
570                 {
571                         throw new NotImplementedException ();
572                 }
573
574                 public void Reacquire ()
575                 {
576                         throw new NotImplementedException ();
577                 }
578
579                 public void Yield ()
580                 {
581                         throw new NotImplementedException ();
582                 }
583
584                 #endregion
585
586                 #region IBuildEngine2 implementation
587
588                 // To NOT reuse this IBuildEngine instance for different build, we create another BuildManager and BuildSubmisson and then run it.
589                 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion)
590                 {
591                         toolsVersion = string.IsNullOrEmpty (toolsVersion) ? project.ToolsVersion : toolsVersion;
592                         var globalPropertiesThatMakeSense = new Dictionary<string,string> ();
593                         foreach (DictionaryEntry p in globalProperties)
594                                 globalPropertiesThatMakeSense [(string) p.Key] = (string) p.Value;
595                         var projectToBuild = new ProjectInstance (ProjectRootElement.Create (XmlReader.Create (projectFileName)), globalPropertiesThatMakeSense, toolsVersion, Projects);
596                         IDictionary<string,TargetResult> outs;
597                         var ret = projectToBuild.Build (targetNames ?? new string [] {"Build"}, Projects.Loggers, out outs);
598                         foreach (var p in outs)
599                                 targetOutputs [p.Key] = p.Value.Items ?? new ITaskItem [0];
600                         return ret;
601                 }
602
603                 public bool BuildProjectFilesInParallel (string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
604                 {
605                         throw new NotImplementedException ();
606                 }
607
608                 public bool IsRunningMultipleNodes {
609                         get {
610                                 throw new NotImplementedException ();
611                         }
612                 }
613                 
614                 ProjectInstance GetProjectInstance (string projectFileName, string toolsVersion)
615                 {
616                         string fullPath = Path.GetFullPath (projectFileName);
617                         if (submission.BuildRequest.ProjectFullPath == fullPath)
618                                 return submission.BuildRequest.ProjectInstance;
619                         // FIXME: could also be filtered by global properties
620                         // http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.getloadedprojects.aspx
621                         var project = Projects.GetLoadedProjects (projectFileName).FirstOrDefault (p => p.ToolsVersion == toolsVersion);
622                         if (project == null)
623                                 throw new InvalidOperationException (string.Format ("Project '{0}' is not loaded", projectFileName));
624                         return submission.BuildManager.GetProjectInstanceForBuild (project);
625                 }
626
627                 #endregion
628
629                 #region IBuildEngine implementation
630
631                 public bool BuildProjectFile (string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
632                 {
633                         return BuildProjectFile (projectFileName, targetNames, globalProperties, targetOutputs, Projects.DefaultToolsVersion);
634                 }
635
636                 public void LogCustomEvent (CustomBuildEventArgs e)
637                 {
638                         event_source.FireCustomEventRaised (this, e);
639                 }
640
641                 public void LogErrorEvent (BuildErrorEventArgs e)
642                 {
643                         event_source.FireErrorRaised (this, e);
644                 }
645
646                 public void LogMessageEvent (BuildMessageEventArgs e)
647                 {
648                         event_source.FireMessageRaised (this, e);
649                 }
650
651                 public void LogWarningEvent (BuildWarningEventArgs e)
652                 {
653                         event_source.FireWarningRaised (this, e);
654                 }
655
656                 public int ColumnNumberOfTaskNode {
657                         get { return current_task.Location != null ? current_task.Location.Column : 0; }
658                 }
659
660                 public bool ContinueOnError {
661                         get { return current_task != null && project.EvaluateCondition (current_task.Condition) && EvaluateContinueOnError (current_task.ContinueOnError); }
662                 }
663                 
664                 bool EvaluateContinueOnError (string value)
665                 {
666                         switch (value) {
667                         case "WarnAndContinue":
668                         case "ErrorAndContinue":
669                                 return true;
670                         case "ErrorAndStop":
671                                 return false;
672                         }
673                         // empty means "stop on error", so don't pass empty string to EvaluateCondition().
674                         return !string.IsNullOrEmpty (value) && project.EvaluateCondition (value);
675                 }
676
677                 public int LineNumberOfTaskNode {
678                         get { return current_task.Location != null ? current_task.Location.Line : 0; }
679                 }
680
681                 public string ProjectFileOfTaskNode {
682                         get { return current_task.FullPath; }
683                 }
684
685                 #endregion
686         }
687 }
688