Vbc.cs 54.4 KB
Newer Older
J
Jared Parsons 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
B
beep boop 已提交
2 3

using System;
4 5 6 7 8 9 10 11
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Globalization;

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks.Hosting;
12
using Microsoft.CodeAnalysis.CompilerServer;
13
using System.Diagnostics;
14

A
Andy Gocke 已提交
15
namespace Microsoft.CodeAnalysis.BuildTasks
16 17 18 19 20 21 22 23 24 25 26
{
    /// <summary>
    /// This class defines the "Vbc" XMake task, which enables building assemblies from VB
    /// source files by invoking the VB compiler. This is the new Roslyn XMake task,
    /// meaning that the code is compiled by using the Roslyn compiler server, rather
    /// than vbc.exe. The two should be functionally identical, but the compiler server
    /// should be significantly faster with larger projects and have a smaller memory
    /// footprint.
    /// </summary>
    public class Vbc : ManagedCompiler
    {
27
        private bool _useHostCompilerIfAvailable;
28 29 30

        // The following 1 fields are used, set and re-set in LogEventsFromTextOutput()
        /// <summary>
C
Charles Stoner 已提交
31
        /// This stores the original lines and error priority together in the order in which they were received.
32
        /// </summary>
33
        private readonly Queue<VBError> _vbErrorLines = new Queue<VBError>();
34 35

        // Used when parsing vbc output to determine the column number of an error
36 37
        private bool _isDoneOutputtingErrorMessage;
        private int _numberOfLinesInErrorMessage;
38 39 40 41 42 43 44 45 46

        #region Properties

        // Please keep these alphabetized.  These are the parameters specific to Vbc.  The
        // ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
        // the base class.

        public string BaseAddress
        {
J
Jared Parsons 已提交
47 48
            set { _store[nameof(BaseAddress)] = value; }
            get { return (string)_store[nameof(BaseAddress)]; }
49 50 51 52
        }

        public string DisabledWarnings
        {
J
Jared Parsons 已提交
53 54
            set { _store[nameof(DisabledWarnings)] = value; }
            get { return (string)_store[nameof(DisabledWarnings)]; }
55 56 57 58
        }

        public string DocumentationFile
        {
J
Jared Parsons 已提交
59 60
            set { _store[nameof(DocumentationFile)] = value; }
            get { return (string)_store[nameof(DocumentationFile)]; }
61 62 63 64
        }

        public string ErrorReport
        {
J
Jared Parsons 已提交
65 66
            set { _store[nameof(ErrorReport)] = value; }
            get { return (string)_store[nameof(ErrorReport)]; }
67 68 69 70
        }

        public bool GenerateDocumentation
        {
J
Jared Parsons 已提交
71 72
            set { _store[nameof(GenerateDocumentation)] = value; }
            get { return _store.GetOrDefault(nameof(GenerateDocumentation), false); }
73 74 75 76
        }

        public ITaskItem[] Imports
        {
J
Jared Parsons 已提交
77 78
            set { _store[nameof(Imports)] = value; }
            get { return (ITaskItem[])_store[nameof(Imports)]; }
79 80 81 82
        }

        public string LangVersion
        {
J
Jared Parsons 已提交
83 84
            set { _store[nameof(LangVersion)] = value; }
            get { return (string)_store[nameof(LangVersion)]; }
85 86 87 88
        }

        public string ModuleAssemblyName
        {
J
Jared Parsons 已提交
89 90
            set { _store[nameof(ModuleAssemblyName)] = value; }
            get { return (string)_store[nameof(ModuleAssemblyName)]; }
91 92 93 94
        }

        public bool NoStandardLib
        {
J
Jared Parsons 已提交
95 96
            set { _store[nameof(NoStandardLib)] = value; }
            get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
97 98 99 100 101 102 103 104 105
        }

        // This is not a documented switch. It prevents the automatic reference to Microsoft.VisualBasic.dll.
        // The VB team believes the only scenario for this is when you are building that assembly itself.
        // We have to support the switch here so that we can build the SDE and VB trees, which need to build this assembly.
        // Although undocumented, it cannot be wrapped with #if BUILDING_DF_LKG because this would prevent dogfood builds
        // within VS, which must use non-LKG msbuild bits.
        public bool NoVBRuntimeReference
        {
J
Jared Parsons 已提交
106 107
            set { _store[nameof(NoVBRuntimeReference)] = value; }
            get { return _store.GetOrDefault(nameof(NoVBRuntimeReference), false); }
108 109 110 111
        }

        public bool NoWarnings
        {
J
Jared Parsons 已提交
112 113
            set { _store[nameof(NoWarnings)] = value; }
            get { return _store.GetOrDefault(nameof(NoWarnings), false); }
114 115 116 117
        }

        public string OptionCompare
        {
J
Jared Parsons 已提交
118 119
            set { _store[nameof(OptionCompare)] = value; }
            get { return (string)_store[nameof(OptionCompare)]; }
120 121 122 123
        }

        public bool OptionExplicit
        {
J
Jared Parsons 已提交
124 125
            set { _store[nameof(OptionExplicit)] = value; }
            get { return _store.GetOrDefault(nameof(OptionExplicit), true); }
126 127 128 129
        }

        public bool OptionStrict
        {
J
Jared Parsons 已提交
130 131
            set { _store[nameof(OptionStrict)] = value; }
            get { return _store.GetOrDefault(nameof(OptionStrict), false); }
132 133 134 135
        }

        public bool OptionInfer
        {
J
Jared Parsons 已提交
136 137
            set { _store[nameof(OptionInfer)] = value; }
            get { return _store.GetOrDefault(nameof(OptionInfer), false); }
138 139 140 141 142
        }

        // Currently only /optionstrict:custom
        public string OptionStrictType
        {
J
Jared Parsons 已提交
143 144
            set { _store[nameof(OptionStrictType)] = value; }
            get { return (string)_store[nameof(OptionStrictType)]; }
145 146 147 148
        }

        public bool RemoveIntegerChecks
        {
J
Jared Parsons 已提交
149 150
            set { _store[nameof(RemoveIntegerChecks)] = value; }
            get { return _store.GetOrDefault(nameof(RemoveIntegerChecks), false); }
151 152 153 154
        }

        public string RootNamespace
        {
J
Jared Parsons 已提交
155 156
            set { _store[nameof(RootNamespace)] = value; }
            get { return (string)_store[nameof(RootNamespace)]; }
157 158 159 160
        }

        public string SdkPath
        {
J
Jared Parsons 已提交
161 162
            set { _store[nameof(SdkPath)] = value; }
            get { return (string)_store[nameof(SdkPath)]; }
163 164 165 166 167 168 169 170 171 172 173
        }

        /// <summary>
        /// Name of the language passed to "/preferreduilang" compiler option.
        /// </summary>
        /// <remarks>
        /// If set to null, "/preferreduilang" option is omitted, and vbc.exe uses its default setting.
        /// Otherwise, the value is passed to "/preferreduilang" as is.
        /// </remarks>
        public string PreferredUILang
        {
J
Jared Parsons 已提交
174 175
            set { _store[nameof(PreferredUILang)] = value; }
            get { return (string)_store[nameof(PreferredUILang)]; }
176 177 178 179
        }

        public string VsSessionGuid
        {
J
Jared Parsons 已提交
180 181
            set { _store[nameof(VsSessionGuid)] = value; }
            get { return (string)_store[nameof(VsSessionGuid)]; }
182 183 184 185
        }

        public bool TargetCompactFramework
        {
J
Jared Parsons 已提交
186 187
            set { _store[nameof(TargetCompactFramework)] = value; }
            get { return _store.GetOrDefault(nameof(TargetCompactFramework), false); }
188 189 190 191
        }

        public bool UseHostCompilerIfAvailable
        {
B
beep boop 已提交
192 193
            set { _useHostCompilerIfAvailable = value; }
            get { return _useHostCompilerIfAvailable; }
194 195 196 197
        }

        public string VBRuntimePath
        {
J
Jared Parsons 已提交
198 199
            set { _store[nameof(VBRuntimePath)] = value; }
            get { return (string)_store[nameof(VBRuntimePath)]; }
200 201 202 203
        }

        public string Verbosity
        {
J
Jared Parsons 已提交
204 205
            set { _store[nameof(Verbosity)] = value; }
            get { return (string)_store[nameof(Verbosity)]; }
206 207 208 209
        }

        public string WarningsAsErrors
        {
J
Jared Parsons 已提交
210 211
            set { _store[nameof(WarningsAsErrors)] = value; }
            get { return (string)_store[nameof(WarningsAsErrors)]; }
212 213 214 215
        }

        public string WarningsNotAsErrors
        {
J
Jared Parsons 已提交
216 217
            set { _store[nameof(WarningsNotAsErrors)] = value; }
            get { return (string)_store[nameof(WarningsNotAsErrors)]; }
218 219 220 221
        }

        public string VBRuntime
        {
J
Jared Parsons 已提交
222 223
            set { _store[nameof(VBRuntime)] = value; }
            get { return (string)_store[nameof(VBRuntime)]; }
224 225 226 227
        }

        public string PdbFile
        {
J
Jared Parsons 已提交
228 229
            set { _store[nameof(PdbFile)] = value; }
            get { return (string)_store[nameof(PdbFile)]; }
230 231 232 233 234
        }
        #endregion

        #region Tool Members

235 236 237
        internal override BuildProtocolConstants.RequestLanguage Language
            => BuildProtocolConstants.RequestLanguage.VisualBasicCompile;

238
        private static readonly string[] s_separator = { "\r\n" };
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

        internal override void LogMessages(string output, MessageImportance messageImportance)
        {
            var lines = output.Split(s_separator, StringSplitOptions.None);
            foreach (string line in lines)
            {
                //Code below will parse the set of four lines that comprise a VB
                //error message into a single object. The four-line format contains
                //a second line that is blank. This must be passed to the code below
                //to satisfy the parser. The parser needs to work with output from
                //old compilers as well. 
                LogEventsFromTextOutput(line, messageImportance);
            }
        }

254 255 256 257 258 259 260
        /// <summary>
        ///  Return the name of the tool to execute.
        /// </summary>
        override protected string ToolName
        {
            get
            {
261
                return "vbc.exe";
262 263 264 265 266 267 268 269 270 271 272 273 274 275
            }
        }

        /// <summary>
        /// Override Execute so that we can moved the PDB file if we need to,
        /// after the compiler is done.
        /// </summary>
        public override bool Execute()
        {
            if (!base.Execute())
            {
                return false;
            }

276
            if (!SkipCompilerExecution)
277
            {
278
                MovePdbFileIfNecessary(OutputAssembly.ItemSpec);
279 280
            }

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            return !Log.HasLoggedErrors;
        }

        /// <summary>
        /// Move the PDB file if the PDB file that was generated by the compiler
        /// is not at the specified path, or if it is newer than the one there.
        /// VBC does not have a switch to specify the PDB path, so we are essentially implementing that for it here.
        /// We need make this possible to avoid colliding with the PDB generated by WinMDExp.
        /// 
        /// If at some future point VBC.exe offers a /pdbfile switch, this function can be removed.
        /// </summary>
        internal void MovePdbFileIfNecessary(string outputAssembly)
        {
            // Get the name of the output assembly because the pdb will be written beside it and will have the same name
            if (String.IsNullOrEmpty(PdbFile) || String.IsNullOrEmpty(outputAssembly))
            {
                return;
            }

            try
            {
                string actualPdb = Path.ChangeExtension(outputAssembly, ".pdb"); // This is the pdb that the compiler generated

                FileInfo actualPdbInfo = new FileInfo(actualPdb);

                string desiredLocation = PdbFile;
                if (!desiredLocation.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase))
                {
                    desiredLocation += ".pdb";
                }

                FileInfo desiredPdbInfo = new FileInfo(desiredLocation);

                // If the compiler generated a pdb..
                if (actualPdbInfo.Exists)
                {
                    // .. and the desired one does not exist or it's older...
                    if (!desiredPdbInfo.Exists || (desiredPdbInfo.Exists && actualPdbInfo.LastWriteTime > desiredPdbInfo.LastWriteTime))
                    {
                        // Delete the existing one if it's already there, as Move would otherwise fail
                        if (desiredPdbInfo.Exists)
                        {
                            Utilities.DeleteNoThrow(desiredPdbInfo.FullName);
                        }

                        // Move the file to where we actually wanted VBC to put it
                        File.Move(actualPdbInfo.FullName, desiredLocation);
                    }
                }
B
beep boop 已提交
330
            }
331 332
            catch (Exception e) when (Utilities.IsIoRelatedException(e))
            {
333
                Log.LogErrorWithCodeFromResources("VBC_RenamePDB", PdbFile, e.Message);
334 335 336 337 338 339
            }
        }

        /// <summary>
        /// Generate the path to the tool
        /// </summary>
J
Jared Parsons 已提交
340
        protected override string GenerateFullPathToTool()
341 342 343 344 345 346 347 348 349
        {
            string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion);

            if (null == pathToTool)
            {
                pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest);

                if (null == pathToTool)
                {
350
                    Log.LogErrorWithCodeFromResources("General_FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest));
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                }
            }

            return pathToTool;
        }

        /// <summary>
        /// vbc.exe only takes the BaseAddress in hexadecimal format.  But we allow the caller
        /// of the task to pass in the BaseAddress in either decimal or hexadecimal format.
        /// Examples of supported hex formats include "0x10000000" or "&amp;H10000000".
        /// </summary>
        internal string GetBaseAddressInHex()
        {
            string originalBaseAddress = this.BaseAddress;

            if (originalBaseAddress != null)
            {
                if (originalBaseAddress.Length > 2)
                {
                    string twoLetterPrefix = originalBaseAddress.Substring(0, 2);

                    if (
                         (0 == String.Compare(twoLetterPrefix, "0x", StringComparison.OrdinalIgnoreCase)) ||
                         (0 == String.Compare(twoLetterPrefix, "&h", StringComparison.OrdinalIgnoreCase))
                       )
                    {
                        // The incoming string is already in hex format ... we just need to
                        // remove the 0x or &H from the beginning.
                        return originalBaseAddress.Substring(2);
                    }
                }

                // The incoming BaseAddress is not in hexadecimal format, so we need to
                // convert it to hex.
                try
                {
                    uint baseAddressDecimal = UInt32.Parse(originalBaseAddress, CultureInfo.InvariantCulture);
                    return baseAddressDecimal.ToString("X", CultureInfo.InvariantCulture);
                }
                catch (FormatException e)
                {
                    throw Utilities.GetLocalizedArgumentException(e,
                        ErrorString.Vbc_ParameterHasInvalidValue, "BaseAddress", originalBaseAddress);
                }
            }

            return null;
        }

        /// <summary>
        /// Looks at all the parameters that have been set, and builds up the string
        /// containing all the command-line switches.
        /// </summary>
        protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
        {
            commandLine.AppendSwitchIfNotNull("/baseaddress:", this.GetBaseAddressInHex());
            commandLine.AppendSwitchIfNotNull("/libpath:", this.AdditionalLibPaths, ",");
            commandLine.AppendSwitchIfNotNull("/imports:", this.Imports, ",");
            // Make sure this /doc+ switch comes *before* the /doc:<file> switch (which is handled in the
            // ManagedCompiler.cs base class).  /doc+ is really just an alias for /doc:<assemblyname>.xml,
            // and the last /doc switch on the command-line wins.  If the user provided a specific doc filename,
            // we want that one to win.
            commandLine.AppendPlusOrMinusSwitch("/doc", this._store, "GenerateDocumentation");
            commandLine.AppendSwitchIfNotNull("/optioncompare:", this.OptionCompare);
            commandLine.AppendPlusOrMinusSwitch("/optionexplicit", this._store, "OptionExplicit");
            // Make sure this /optionstrict+ switch appears *before* the /optionstrict:xxxx switch below

            /* twhitney: In Orcas a change was made for devdiv bug 16889 that set Option Strict-, whenever this.DisabledWarnings was
             * empty.  That was clearly the wrong thing to do and we found it when we had a project with all the warning configuration 
             * entries set to WARNING.  Because this.DisabledWarnings was empty in that case we would end up sending /OptionStrict- 
             * effectively silencing all the warnings that had been selected.
             * 
             * Now what we do is:
             *  If option strict+ is specified, that trumps everything and we just set option strict+ 
             *  Otherwise, just set option strict:custom.
             *  You may wonder why we don't try to set Option Strict-  The reason is that Option Strict- just implies a certain
             *  set of warnings that should be disabled (there's ten of them today)  You get the same effect by sending 
             *  option strict:custom on along with the correct list of disabled warnings.
             *  Rather than make this code know the current set of disabled warnings that comprise Option strict-, we just send
             *  option strict:custom on with the understanding that we'll get the same behavior as option strict- since we are passing
             *  the /nowarn line on that contains all the warnings OptionStrict- would disable anyway. The IDE knows what they are
             *  and puts them in the project file so we are good.  And by not making this code aware of which warnings comprise
             *  Option Strict-, we have one less place we have to keep up to date in terms of what comprises option strict-
             */

            // Decide whether we are Option Strict+ or Option Strict:custom
            object optionStrictSetting = this._store["OptionStrict"];
            bool optionStrict = optionStrictSetting != null ? (bool)optionStrictSetting : false;
            if (optionStrict)
            {
                commandLine.AppendSwitch("/optionstrict+");
            }
            else // OptionStrict+ wasn't specified so use :custom.
            {
                commandLine.AppendSwitch("/optionstrict:custom");
            }

            commandLine.AppendSwitchIfNotNull("/optionstrict:", this.OptionStrictType);
            commandLine.AppendWhenTrue("/nowarn", this._store, "NoWarnings");
            commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ',');
            commandLine.AppendPlusOrMinusSwitch("/optioninfer", this._store, "OptionInfer");
            commandLine.AppendWhenTrue("/nostdlib", this._store, "NoStandardLib");
            commandLine.AppendWhenTrue("/novbruntimeref", this._store, "NoVBRuntimeReference");
            commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport);
            commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference);
            commandLine.AppendPlusOrMinusSwitch("/removeintchecks", this._store, "RemoveIntegerChecks");
            commandLine.AppendSwitchIfNotNull("/rootnamespace:", this.RootNamespace);
            commandLine.AppendSwitchIfNotNull("/sdkpath:", this.SdkPath);
            commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion);
            commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName);
            commandLine.AppendWhenTrue("/netcf", this._store, "TargetCompactFramework");
            commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang);
            commandLine.AppendPlusOrMinusSwitch("/highentropyva", this._store, "HighEntropyVA");

            if (0 == String.Compare(this.VBRuntimePath, this.VBRuntime, StringComparison.OrdinalIgnoreCase))
            {
                commandLine.AppendSwitchIfNotNull("/vbruntime:", this.VBRuntimePath);
            }
            else if (this.VBRuntime != null)
            {
                string vbRuntimeSwitch = this.VBRuntime;
                if (0 == String.Compare(vbRuntimeSwitch, "EMBED", StringComparison.OrdinalIgnoreCase))
                {
                    commandLine.AppendSwitch("/vbruntime*");
                }
                else if (0 == String.Compare(vbRuntimeSwitch, "NONE", StringComparison.OrdinalIgnoreCase))
                {
                    commandLine.AppendSwitch("/vbruntime-");
                }
                else if (0 == String.Compare(vbRuntimeSwitch, "DEFAULT", StringComparison.OrdinalIgnoreCase))
                {
                    commandLine.AppendSwitch("/vbruntime+");
                }
                else
                {
                    commandLine.AppendSwitchIfNotNull("/vbruntime:", vbRuntimeSwitch);
                }
            }


            // Verbosity
            if (
                   (this.Verbosity != null) &&

                   (
                      (0 == String.Compare(this.Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) ||
                      (0 == String.Compare(this.Verbosity, "verbose", StringComparison.OrdinalIgnoreCase))
                   )
                )
            {
                commandLine.AppendSwitchIfNotNull("/", this.Verbosity);
            }

            commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile);
            commandLine.AppendSwitchUnquotedIfNotNull("/define:", Vbc.GetDefineConstantsSwitch(this.DefineConstants));
            AddReferencesToCommandLine(commandLine);
            commandLine.AppendSwitchIfNotNull("/win32resource:", this.Win32Resource);

            // Special case for "Sub Main" (See VSWhidbey 381254)
            if (0 != String.Compare("Sub Main", this.MainEntryPoint, StringComparison.OrdinalIgnoreCase))
            {
                commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint);
            }

            base.AddResponseFileCommands(commandLine);

            // This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
            // Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
            // and then any specific warnings that should be treated as errors should be specified with
            // /warnaserror+:<list> after the /warnaserror- switch.  The order of the switches on the command-line
            // does matter.
            //
            // Note that
            //      /warnaserror+
            // is just shorthand for:
            //      /warnaserror+:<all possible warnings>
            //
            // Similarly,
            //      /warnaserror-
            // is just shorthand for:
            //      /warnaserror-:<all possible warnings>
            commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ',');
            commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ',');

            // If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
            bool designTime = false;
            if (this.HostObject != null)
            {
                var vbHost = this.HostObject as IVbcHostObject;
                designTime = vbHost.IsDesignTime();
            }
            if (!designTime)
            {
                if (!string.IsNullOrWhiteSpace(this.VsSessionGuid))
                {
                    commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid);
                }
            }

            // It's a good idea for the response file to be the very last switch passed, just 
            // from a predictability perspective.  It also solves the problem that a dogfooder
            // ran into, which is described in an email thread attached to bug VSWhidbey 146883.
            // See also bugs 177762 and 118307 for additional bugs related to response file position.
            if (this.ResponseFiles != null)
            {
                foreach (ITaskItem response in this.ResponseFiles)
                {
                    commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
                }
            }
        }

B
beep boop 已提交
563
        private void AddReferencesToCommandLine(CommandLineBuilderExtension commandLine)
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
        {
            if ((this.References == null) || (this.References.Length == 0))
            {
                return;
            }

            var references = new List<ITaskItem>(this.References.Length);
            var links = new List<ITaskItem>(this.References.Length);

            foreach (ITaskItem reference in this.References)
            {
                bool embed = Utilities.TryConvertItemMetadataToBool(reference, "EmbedInteropTypes");

                if (embed)
                {
                    links.Add(reference);
                }
                else
                {
                    references.Add(reference);
                }
            }

            if (links.Count > 0)
            {
                commandLine.AppendSwitchIfNotNull("/link:", links.ToArray(), ",");
            }

            if (references.Count > 0)
            {
                commandLine.AppendSwitchIfNotNull("/reference:", references.ToArray(), ",");
            }
        }

        /// <summary>
        /// Validate parameters, log errors and warnings and return true if
        /// Execute should proceed.
        /// </summary>
J
Jared Parsons 已提交
602
        protected override bool ValidateParameters()
603 604 605 606 607 608 609 610 611 612 613 614 615
        {
            if (!base.ValidateParameters())
            {
                return false;
            }

            // Validate that the "Verbosity" parameter is one of "quiet", "normal", or "verbose".
            if (this.Verbosity != null)
            {
                if ((0 != String.Compare(Verbosity, "normal", StringComparison.OrdinalIgnoreCase)) &&
                    (0 != String.Compare(Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) &&
                    (0 != String.Compare(Verbosity, "verbose", StringComparison.OrdinalIgnoreCase)))
                {
616
                    Log.LogErrorWithCodeFromResources("Vbc_EnumParameterHasInvalidValue", "Verbosity", this.Verbosity, "Quiet, Normal, Verbose");
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// This method intercepts the lines to be logged coming from STDOUT from VBC.
        /// Once we see a standard vb warning or error, then we capture it and grab the next 3
        /// lines so we can transform the string form the form of FileName.vb(line) to FileName.vb(line,column)
        /// which will allow us to report the line and column to the IDE, and thus filter the error
        /// in the duplicate case for multi-targeting, or just squiggle the appropriate token 
        /// instead of the entire line.
        /// </summary>
        /// <param name="singleLine">A single line from the STDOUT of the vbc compiler</param>
        /// <param name="messageImportance">High,Low,Normal</param>
        protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
        {
            // We can return immediately if this was not called by the out of proc compiler
            if (!this.UsedCommandLineTool)
            {
                base.LogEventsFromTextOutput(singleLine, messageImportance);
                return;
            }

            // We can also return immediately if the current string is not a warning or error
            // and we have not seen a warning or error yet. 'Error' and 'Warning' are not localized.
B
beep boop 已提交
645
            if (_vbErrorLines.Count == 0 &&
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
                singleLine.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 &&
                singleLine.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1)
            {
                base.LogEventsFromTextOutput(singleLine, messageImportance);
                return;
            }

            ParseVBErrorOrWarning(singleLine, messageImportance);
        }

        /// <summary>
        /// Given a string, parses it to find out whether it's an error or warning and, if so,
        /// make sure it's validated properly.  
        /// </summary>
        /// <comments>
        /// INTERNAL FOR UNITTESTING ONLY
        /// </comments>
        /// <param name="singleLine">The line to parse</param>
        /// <param name="messageImportance">The MessageImportance to use when reporting the error.</param>
        internal void ParseVBErrorOrWarning(string singleLine, MessageImportance messageImportance)
        {
            // if this string is empty then we haven't seen the first line of an error yet
B
beep boop 已提交
668
            if (_vbErrorLines.Count > 0)
669 670 671
            {
                // vbc separates the error message from the source text with an empty line, so
                // we can check for an empty line to see if vbc finished outputting the error message
B
beep boop 已提交
672
                if (!_isDoneOutputtingErrorMessage && singleLine.Length == 0)
673
                {
B
beep boop 已提交
674 675
                    _isDoneOutputtingErrorMessage = true;
                    _numberOfLinesInErrorMessage = _vbErrorLines.Count;
676 677
                }

B
beep boop 已提交
678
                _vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
679 680 681 682 683 684 685 686

                // We are looking for the line that indicates the column (contains the '~'),
                // which vbc outputs 3 lines below the error message:
                //
                // <error message>
                // <blank line>
                // <line with the source text>
                // <line with the '~'>
B
beep boop 已提交
687 688
                if (_isDoneOutputtingErrorMessage &&
                    _vbErrorLines.Count == _numberOfLinesInErrorMessage + 3)
689 690 691 692 693 694 695 696
                {
                    // Once we have the 4th line (error line + 3), then parse it for the first ~
                    // which will correspond to the column of the token with the error because
                    // VBC respects the users's indentation settings in the file it is compiling
                    // and only outputs SPACE chars to STDOUT.

                    // The +1 is to translate the index into user columns which are 1 based.

B
beep boop 已提交
697
                    VBError originalVBError = _vbErrorLines.Dequeue();
698 699 700 701 702 703
                    string originalVBErrorString = originalVBError.Message;

                    int column = singleLine.IndexOf('~') + 1;
                    int endParenthesisLocation = originalVBErrorString.IndexOf(')');

                    // If for some reason the line does not contain any ~ then something went wrong
C
Charles Stoner 已提交
704
                    // so abort and return the original string.
705 706 707 708
                    if (column < 0 || endParenthesisLocation < 0)
                    {
                        // we need to output all of the original lines we ate.
                        Log.LogMessageFromText(originalVBErrorString, originalVBError.MessageImportance);
B
beep boop 已提交
709
                        foreach (VBError vberror in _vbErrorLines)
710 711 712 713
                        {
                            base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
                        }

B
beep boop 已提交
714
                        _vbErrorLines.Clear();
715 716 717 718 719 720 721 722
                        return;
                    }

                    string newLine = null;
                    newLine = originalVBErrorString.Substring(0, endParenthesisLocation) + "," + column + originalVBErrorString.Substring(endParenthesisLocation);

                    // Output all of the lines of the error, but with the modified first line as well.
                    Log.LogMessageFromText(newLine, originalVBError.MessageImportance);
B
beep boop 已提交
723
                    foreach (VBError vberror in _vbErrorLines)
724 725 726 727
                    {
                        base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
                    }

B
beep boop 已提交
728
                    _vbErrorLines.Clear();
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
                }
            }
            else
            {
                CanonicalError.Parts parts = CanonicalError.Parse(singleLine);
                if (parts == null)
                {
                    base.LogEventsFromTextOutput(singleLine, messageImportance);
                }
                else if ((parts.category == CanonicalError.Parts.Category.Error ||
                     parts.category == CanonicalError.Parts.Category.Warning) &&
                     parts.column == CanonicalError.Parts.numberNotSpecified)
                {
                    if (parts.line != CanonicalError.Parts.numberNotSpecified)
                    {
                        // If we got here, then this is a standard VBC error or warning.
B
beep boop 已提交
745 746 747
                        _vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
                        _isDoneOutputtingErrorMessage = false;
                        _numberOfLinesInErrorMessage = 0;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
                    }
                    else
                    {
                        // Project-level errors don't have line numbers -- just output now. 
                        base.LogEventsFromTextOutput(singleLine, messageImportance);
                    }
                }
            }
        }

        #endregion

        /// <summary>
        /// Many VisualStudio VB projects have values for the DefineConstants property that
        /// contain quotes and spaces.  Normally we don't allow parameters passed into the
B
bkoelman 已提交
763
        /// task to contain quotes, because if we weren't careful, we might accidentally
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
        /// allow a parameter injection attach.  But for "DefineConstants", we have to allow
        /// it.
        /// So this method prepares the string to be passed in on the /define: command-line
        /// switch.  It does that by quoting the entire string, and escaping the embedded
        /// quotes.
        /// </summary>
        internal static string GetDefineConstantsSwitch
            (
            string originalDefineConstants
            )
        {
            if ((originalDefineConstants == null) || (originalDefineConstants.Length == 0))
            {
                return null;
            }

            StringBuilder finalDefineConstants = new StringBuilder(originalDefineConstants);

            // Replace slash-quote with slash-slash-quote.
            finalDefineConstants.Replace("\\\"", "\\\\\"");

            // Replace quote with slash-quote.
            finalDefineConstants.Replace("\"", "\\\"");

            // Surround the whole thing with a pair of double-quotes.
            finalDefineConstants.Insert(0, '"');
            finalDefineConstants.Append('"');

            // Now it's ready to be passed in to the /define: switch.
            return finalDefineConstants.ToString();
        }

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        /// <summary>
        /// This method will initialize the host compiler object with all the switches,
        /// parameters, resources, references, sources, etc.
        ///
        /// It returns true if everything went according to plan.  It returns false if the
        /// host compiler had a problem with one of the parameters that was passed in.
        /// 
        /// This method also sets the "this.HostCompilerSupportsAllParameters" property
        /// accordingly.
        ///
        /// Example:
        ///     If we attempted to pass in Platform="foobar", then this method would
        ///     set HostCompilerSupportsAllParameters=true, but it would throw an 
        ///     exception because the host compiler fully supports
        ///     the Platform parameter, but "foobar" is an illegal value.
        ///
        /// Example:
        ///     If we attempted to pass in NoConfig=false, then this method would set
        ///     HostCompilerSupportsAllParameters=false, because while this is a legal
        ///     thing for csc.exe, the IDE compiler cannot support it.  In this situation
        ///     the return value will also be false.
        /// </summary>
        /// <owner>RGoel</owner>
J
Jared Parsons 已提交
819
        private bool InitializeHostCompiler(IVbcHostObject vbcHostObject)
820 821 822 823 824 825
        {
            this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable;
            string param = "Unknown";

            try
            {
J
Jared Parsons 已提交
826
                param = nameof(vbcHostObject.BeginInitialization);
827 828
                vbcHostObject.BeginInitialization();

J
Jared Parsons 已提交
829 830
                CheckHostObjectSupport(param = nameof(AdditionalLibPaths), vbcHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
                CheckHostObjectSupport(param = nameof(AddModules), vbcHostObject.SetAddModules(AddModules));
831 832 833 834 835

                // For host objects which support them, set the analyzers, ruleset and additional files.
                IAnalyzerHostObject analyzerHostObject = vbcHostObject as IAnalyzerHostObject;
                if (analyzerHostObject != null)
                {
J
Jared Parsons 已提交
836 837 838
                    CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
                    CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
                    CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
839 840
                }

J
Jared Parsons 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
                CheckHostObjectSupport(param = nameof(BaseAddress), vbcHostObject.SetBaseAddress(TargetType, GetBaseAddressInHex()));
                CheckHostObjectSupport(param = nameof(CodePage), vbcHostObject.SetCodePage(CodePage));
                CheckHostObjectSupport(param = nameof(DebugType), vbcHostObject.SetDebugType(EmitDebugInformation, DebugType));
                CheckHostObjectSupport(param = nameof(DefineConstants), vbcHostObject.SetDefineConstants(DefineConstants));
                CheckHostObjectSupport(param = nameof(DelaySign), vbcHostObject.SetDelaySign(DelaySign));
                CheckHostObjectSupport(param = nameof(DocumentationFile), vbcHostObject.SetDocumentationFile(DocumentationFile));
                CheckHostObjectSupport(param = nameof(FileAlignment), vbcHostObject.SetFileAlignment(FileAlignment));
                CheckHostObjectSupport(param = nameof(GenerateDocumentation), vbcHostObject.SetGenerateDocumentation(GenerateDocumentation));
                CheckHostObjectSupport(param = nameof(Imports), vbcHostObject.SetImports(Imports));
                CheckHostObjectSupport(param = nameof(KeyContainer), vbcHostObject.SetKeyContainer(KeyContainer));
                CheckHostObjectSupport(param = nameof(KeyFile), vbcHostObject.SetKeyFile(KeyFile));
                CheckHostObjectSupport(param = nameof(LinkResources), vbcHostObject.SetLinkResources(LinkResources));
                CheckHostObjectSupport(param = nameof(MainEntryPoint), vbcHostObject.SetMainEntryPoint(MainEntryPoint));
                CheckHostObjectSupport(param = nameof(NoConfig), vbcHostObject.SetNoConfig(NoConfig));
                CheckHostObjectSupport(param = nameof(NoStandardLib), vbcHostObject.SetNoStandardLib(NoStandardLib));
                CheckHostObjectSupport(param = nameof(NoWarnings), vbcHostObject.SetNoWarnings(NoWarnings));
                CheckHostObjectSupport(param = nameof(Optimize), vbcHostObject.SetOptimize(Optimize));
                CheckHostObjectSupport(param = nameof(OptionCompare), vbcHostObject.SetOptionCompare(OptionCompare));
                CheckHostObjectSupport(param = nameof(OptionExplicit), vbcHostObject.SetOptionExplicit(OptionExplicit));
                CheckHostObjectSupport(param = nameof(OptionStrict), vbcHostObject.SetOptionStrict(OptionStrict));
                CheckHostObjectSupport(param = nameof(OptionStrictType), vbcHostObject.SetOptionStrictType(OptionStrictType));
                CheckHostObjectSupport(param = nameof(OutputAssembly), vbcHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
863 864 865 866 867

                // For host objects which support them, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
                IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
                if (vbcHostObject5 != null)
                {
J
Jared Parsons 已提交
868 869 870
                    CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), vbcHostObject5.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
                    CheckHostObjectSupport(param = nameof(HighEntropyVA), vbcHostObject5.SetHighEntropyVA(HighEntropyVA));
                    CheckHostObjectSupport(param = nameof(SubsystemVersion), vbcHostObject5.SetSubsystemVersion(SubsystemVersion));
871 872 873
                }
                else
                {
J
Jared Parsons 已提交
874
                    CheckHostObjectSupport(param = nameof(Platform), vbcHostObject.SetPlatform(Platform));
875 876 877 878 879
                }

                IVbcHostObject6 vbcHostObject6 = vbcHostObject as IVbcHostObject6;
                if (vbcHostObject6 != null)
                {
J
Jared Parsons 已提交
880 881
                    CheckHostObjectSupport(param = nameof(ErrorLog), vbcHostObject6.SetErrorLog(ErrorLog));
                    CheckHostObjectSupport(param = nameof(ReportAnalyzer), vbcHostObject6.SetReportAnalyzer(ReportAnalyzer));
882 883
                }

J
Jared Parsons 已提交
884 885 886 887 888 889 890 891 892 893 894 895
                CheckHostObjectSupport(param = nameof(References), vbcHostObject.SetReferences(References));
                CheckHostObjectSupport(param = nameof(RemoveIntegerChecks), vbcHostObject.SetRemoveIntegerChecks(RemoveIntegerChecks));
                CheckHostObjectSupport(param = nameof(Resources), vbcHostObject.SetResources(Resources));
                CheckHostObjectSupport(param = nameof(ResponseFiles), vbcHostObject.SetResponseFiles(ResponseFiles));
                CheckHostObjectSupport(param = nameof(RootNamespace), vbcHostObject.SetRootNamespace(RootNamespace));
                CheckHostObjectSupport(param = nameof(SdkPath), vbcHostObject.SetSdkPath(SdkPath));
                CheckHostObjectSupport(param = nameof(Sources), vbcHostObject.SetSources(Sources));
                CheckHostObjectSupport(param = nameof(TargetCompactFramework), vbcHostObject.SetTargetCompactFramework(TargetCompactFramework));
                CheckHostObjectSupport(param = nameof(TargetType), vbcHostObject.SetTargetType(TargetType));
                CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), vbcHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
                CheckHostObjectSupport(param = nameof(WarningsAsErrors), vbcHostObject.SetWarningsAsErrors(WarningsAsErrors));
                CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), vbcHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
896 897
                // DisabledWarnings needs to come after WarningsAsErrors and WarningsNotAsErrors, because
                // of the way the host object works, and the fact that DisabledWarnings trump Warnings[Not]AsErrors.
J
Jared Parsons 已提交
898 899 900
                CheckHostObjectSupport(param = nameof(DisabledWarnings), vbcHostObject.SetDisabledWarnings(DisabledWarnings));
                CheckHostObjectSupport(param = nameof(Win32Icon), vbcHostObject.SetWin32Icon(Win32Icon));
                CheckHostObjectSupport(param = nameof(Win32Resource), vbcHostObject.SetWin32Resource(Win32Resource));
901 902 903 904 905 906

                // In order to maintain compatibility with previous host compilers, we must
                // light-up for IVbcHostObject2
                if (vbcHostObject is IVbcHostObject2)
                {
                    IVbcHostObject2 vbcHostObject2 = (IVbcHostObject2)vbcHostObject;
J
Jared Parsons 已提交
907 908 909
                    CheckHostObjectSupport(param = nameof(ModuleAssemblyName), vbcHostObject2.SetModuleAssemblyName(ModuleAssemblyName));
                    CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
                    CheckHostObjectSupport(param = nameof(Win32Manifest), vbcHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
910
                    // initialize option Infer
J
Jared Parsons 已提交
911
                    CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
912 913 914 915 916 917 918
                }
                else
                {
                    // If we have been given a property that the host compiler doesn't support
                    // then we need to state that we are falling back to the command line compiler
                    if (!String.IsNullOrEmpty(ModuleAssemblyName))
                    {
J
Jared Parsons 已提交
919
                        CheckHostObjectSupport(param = nameof(ModuleAssemblyName), resultFromHostObjectSetOperation: false);
920 921
                    }

J
Jared Parsons 已提交
922
                    if (_store.ContainsKey(nameof(OptionInfer)))
923
                    {
J
Jared Parsons 已提交
924
                        CheckHostObjectSupport(param = nameof(OptionInfer), resultFromHostObjectSetOperation: false);
925 926 927 928
                    }

                    if (!String.IsNullOrEmpty(Win32Manifest))
                    {
J
Jared Parsons 已提交
929
                        CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
930 931 932 933 934 935 936
                    }
                }

                // Check for support of the LangVersion property
                if (vbcHostObject is IVbcHostObject3)
                {
                    IVbcHostObject3 vbcHostObject3 = (IVbcHostObject3)vbcHostObject;
J
Jared Parsons 已提交
937
                    CheckHostObjectSupport(param = nameof(LangVersion), vbcHostObject3.SetLanguageVersion(LangVersion));
938
                }
J
Jared Parsons 已提交
939
                else if (!String.IsNullOrEmpty(LangVersion) && !UsedCommandLineTool)
940
                {
J
Jared Parsons 已提交
941
                    CheckHostObjectSupport(param = nameof(LangVersion), resultFromHostObjectSetOperation: false);
942 943 944 945 946
                }

                if (vbcHostObject is IVbcHostObject4)
                {
                    IVbcHostObject4 vbcHostObject4 = (IVbcHostObject4)vbcHostObject;
J
Jared Parsons 已提交
947
                    CheckHostObjectSupport(param = nameof(VBRuntime), vbcHostObject4.SetVBRuntime(VBRuntime));
948 949 950 951 952 953
                }
                // Support for NoVBRuntimeReference was added to this task after IVbcHostObject was frozen. That doesn't matter much because the host
                // compiler doesn't support it, and almost nobody uses it anyway. But if someone has set it, we need to hard code falling back to
                // the command line compiler here.
                if (NoVBRuntimeReference)
                {
J
Jared Parsons 已提交
954
                    CheckHostObjectSupport(param = nameof(NoVBRuntimeReference), resultFromHostObjectSetOperation: false);
955 956 957 958 959 960 961 962 963
                }

                // In general, we don't support preferreduilang with the in-proc compiler.  It will always use the same locale as the
                // host process, so in general, we have to fall back to the command line compiler if this option is specified.
                // However, we explicitly allow two values (mostly for parity with C#):
                // Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
                // Explicitly specified name of current locale is also supported, since it is effectively a no-op.
                if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
                {
J
Jared Parsons 已提交
964
                    CheckHostObjectSupport(param = nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
965 966 967 968 969 970 971 972 973 974
                }
            }
            catch (Exception e) when (!Utilities.IsCriticalException(e))
            {
                if (this.HostCompilerSupportsAllParameters)
                {
                    // If the host compiler doesn't support everything we need, we're going to end up 
                    // shelling out to the command-line compiler anyway.  That means the command-line
                    // compiler will log the error.  So here, we only log the error if we would've
                    // tried to use the host compiler.
975
                    Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
                }

                return false;
            }
            finally
            {
                // In the case of the VB host compiler, the EndInitialization method will
                // throw (due to FAILED HRESULT) if there was a bad value for one of the
                // parameters.
                vbcHostObject.EndInitialization();
            }

            return true;
        }

        /// <summary>
        /// This method will get called during Execute() if a host object has been passed into the Vbc
        /// task.  Returns one of the following values to indicate what the next action should be:
        ///     UseHostObjectToExecute          Host compiler exists and was initialized.
        ///     UseAlternateToolToExecute       Host compiler doesn't exist or was not appropriate.
        ///     NoActionReturnSuccess           Host compiler was already up-to-date, and we're done.
        ///     NoActionReturnFailure           Bad parameters were passed into the task.
        /// </summary>
        /// <owner>RGoel</owner>
J
Jared Parsons 已提交
1000
        protected override HostObjectInitializationStatus InitializeHostObject()
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        {
            if (this.HostObject != null)
            {
                // When the host object was passed into the task, it was passed in as a generic
                // "Object" (because ITask interface obviously can't have any Vbc-specific stuff
                // in it, and each task is going to want to communicate with its host in a unique
                // way).  Now we cast it to the specific type that the Vbc task expects.  If the
                // host object does not match this type, the host passed in an invalid host object
                // to Vbc, and we error out.

                // NOTE: For compat reasons this must remain IVbcHostObject
                // we can dynamically test for smarter interfaces later..
                using (RCWForCurrentContext<IVbcHostObject> hostObject = new RCWForCurrentContext<IVbcHostObject>(this.HostObject as IVbcHostObject))
                {
                    IVbcHostObject vbcHostObject = hostObject.RCW;

                    if (vbcHostObject != null)
                    {
                        bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(vbcHostObject);

                        // If we're currently only in design-time (as opposed to build-time),
                        // then we're done.  We've initialized the host compiler as best we
                        // can, and we certainly don't want to actually do the final compile.
                        // So return true, saying we're done and successful.
                        if (vbcHostObject.IsDesignTime())
                        {
                            // If we are design-time then we do not want to continue the build at 
                            // this time.
                            return hostObjectSuccessfullyInitialized ?
                                HostObjectInitializationStatus.NoActionReturnSuccess :
                                HostObjectInitializationStatus.NoActionReturnFailure;
                        }

                        // Roslyn doesn't support using the host object for compilation

                        // Since the host compiler has refused to take on the responsibility for this compilation,
                        // we're about to shell out to the command-line compiler to handle it.  If some of the
                        // references don't exist on disk, we know the command-line compiler will fail, so save
                        // the trouble, and just throw a consistent error ourselves.  This allows us to give
                        // more information than the compiler would, and also make things consistent across
                        // Vbc / Csc / etc.  Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
                        // This suite behaves differently in localized builds than on English builds because 
                        // VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
                        if (!CheckAllReferencesExistOnDisk())
                        {
                            return HostObjectInitializationStatus.NoActionReturnFailure;
                        }

                        // The host compiler doesn't support some of the switches/parameters
                        // being passed to it.  Therefore, we resort to using the command-line compiler
                        // in this case.
                        UsedCommandLineTool = true;
                        return HostObjectInitializationStatus.UseAlternateToolToExecute;
                    }
                    else
                    {
1057
                        Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Vbc", "IVbcHostObject");
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
                    }
                }
            }


            // No appropriate host object was found.
            UsedCommandLineTool = true;
            return HostObjectInitializationStatus.UseAlternateToolToExecute;
        }

        /// <summary>
        /// This method will get called during Execute() if a host object has been passed into the Vbc
        /// task.  Returns true if an appropriate host object was found, it was called to do the compile,
        /// and the compile succeeded.  Otherwise, we return false.
        /// </summary>
        /// <owner>RGoel</owner>
J
Jared Parsons 已提交
1074
        protected override bool CallHostObjectToExecute()
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        {
            Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set.");

            IVbcHostObject vbcHostObject = this.HostObject as IVbcHostObject;
            Debug.Assert(vbcHostObject != null, "Wrong kind of host object passed in!");

            IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
            Debug.Assert(vbcHostObject5 != null, "Wrong kind of host object passed in!");

            // IVbcHostObjectFreeThreaded::Compile is the preferred way to compile the host object
            // because while it is still synchronous it does its waiting on our BG thread 
            // (as opposed to the UI thread for IVbcHostObject::Compile)
            if (vbcHostObject5 != null)
            {
                IVbcHostObjectFreeThreaded freeThreadedHostObject = vbcHostObject5.GetFreeThreadedHostObject();
                return freeThreadedHostObject.Compile();
            }
            else
            {
                // If for some reason we can't get to IVbcHostObject5 we just fall back to the old
                // Compile method. This method unfortunately allows for reentrancy on the UI thread.
                return vbcHostObject.Compile();
            }
        }

1100 1101 1102 1103 1104
        /// <summary>
        /// private class that just holds together name, value pair for the vbErrorLines Queue
        /// </summary>
        private class VBError
        {
1105 1106
            public string Message { get; }
            public MessageImportance MessageImportance { get; }
1107 1108 1109 1110 1111 1112 1113 1114 1115

            public VBError(string message, MessageImportance importance)
            {
                this.Message = message;
                this.MessageImportance = importance;
            }
        }
    }
}