/// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task <EvaluationState> InitializeContextAsync(
                Task <EvaluationState> lastTask,
                RemoteAsyncOperation <RemoteExecutionResult> operation,
                string initializationFileOpt,
                bool isRestarting)
            {
                Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));

                var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);

                try
                {
                    // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(_replServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFileOpt))
                    {
                        Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
                        var parser = _replServiceProvider.CommandLineParser;

                        // The base directory for relative paths is the directory that contains the .rsp file.
                        // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                        var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
                        var args         = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);

                        foreach (var error in args.Errors)
                        {
                            var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
                            var sourceResolver   = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);

                            var metadataReferences = new List <PortableExecutableReference>();
                            foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);

                                var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                }
                            }

                            var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.
                                WithFilePath(scriptPathOpt).
                                WithReferences(metadataReferences).
                                WithImports(CommandLineHelpers.GetImports(args)).
                                WithMetadataResolver(metadataResolver).
                                WithSourceResolver(sourceResolver),
                                args.SourcePaths,
                                args.ReferencePaths,
                                rspDirectory);

                            _globals.ReferencePaths.Clear();
                            _globals.ReferencePaths.AddRange(args.ReferencePaths);

                            _globals.SourcePaths.Clear();
                            _globals.SourcePaths.AddRange(args.SourcePaths);

                            _globals.Args.AddRange(args.ScriptArguments);

                            if (scriptPathOpt != null)
                            {
                                var newScriptState = await ExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false);

                                if (newScriptState != null)
                                {
                                    // remove references and imports from the options, they have been applied and will be inherited from now on:
                                    rspState = rspState.
                                               WithScriptState(newScriptState).
                                               WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
                                }
                            }

                            state = rspState;
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return(state);
            }
Exemplo n.º 2
0
        /// <summary>
        /// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
        /// </summary>
        private void ProcessStarting(bool initialize)
        {
            var textView = GetCurrentWindowOrThrow().TextView;

            var dispatcher = ((FrameworkElement)textView).Dispatcher;

            if (!dispatcher.CheckAccess())
            {
                dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize)));
                return;
            }

            // Freeze all existing classifications and then clear the list of submission buffers we have.
            _submissionBuffers.Remove(_currentSubmissionBuffer); // if present
            foreach (var textBuffer in _submissionBuffers)
            {
                InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer);
            }
            _submissionBuffers.Clear();

            // We always start out empty
            _workspace.ClearSolution();
            _currentSubmissionProjectId  = null;
            _previousSubmissionProjectId = null;

            var metadataService          = _workspace.CurrentSolution.Services.MetadataService;
            var mscorlibRef              = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
            var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, Script.HostAssemblyReferenceProperties);

            _responseFileReferences = ImmutableArray.Create <MetadataReference>(mscorlibRef, interactiveHostObjectRef);
            _responseFileImports    = ImmutableArray <string> .Empty;
            _initialScriptFileOpt   = null;
            ReferenceSearchPaths    = ImmutableArray <string> .Empty;
            SourceSearchPaths       = ImmutableArray <string> .Empty;

            if (initialize && File.Exists(_responseFilePath))
            {
                // The base directory for relative paths is the directory that contains the .rsp file.
                // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                var responseFileDirectory = Path.GetDirectoryName(_responseFilePath);
                var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, responseFileDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);

                if (args.Errors.Length == 0)
                {
                    var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, responseFileDirectory);
                    var sourceResolver   = CreateSourceReferenceResolver(args.SourcePaths, responseFileDirectory);

                    // ignore unresolved references, they will be reported in the interactive window:
                    var responseFileReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference));

                    _initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;

                    ReferenceSearchPaths = args.ReferencePaths;
                    SourceSearchPaths    = args.SourcePaths;

                    _responseFileReferences = _responseFileReferences.AddRange(responseFileReferences);
                    _responseFileImports    = CommandLineHelpers.GetImports(args);
                }
            }

            _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
            _sourceReferenceResolver   = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);

            // create the first submission project in the workspace after reset:
            if (_currentSubmissionBuffer != null)
            {
                AddSubmission(_currentSubmissionBuffer, this.LanguageName);
            }
        }
Exemplo n.º 3
0
            /// <summary>
            /// Loads references, set options and execute files specified in the initialization file.
            /// Also prints logo unless <paramref name="isRestarting"/> is true.
            /// </summary>
            private async Task <EvaluationState> InitializeContextAsync(
                Task <EvaluationState> lastTask,
                TaskCompletionSource <RemoteExecutionResult> completionSource,
                string?initializationFilePath,
                bool isRestarting
                )
            {
                Contract.ThrowIfFalse(
                    initializationFilePath == null ||
                    PathUtilities.IsAbsolute(initializationFilePath)
                    );
                var serviceState = GetServiceState();
                var state        = await ReportUnhandledExceptionIfAnyAsync(lastTask)
                                   .ConfigureAwait(false);

                string?initializationScriptPath = null;
                var    initialImports           = ImmutableArray <string> .Empty;
                var    metadataReferencePaths   = ImmutableArray.CreateBuilder <string>();

                try
                {
                    metadataReferencePaths.Add(typeof(object).Assembly.Location);
                    metadataReferencePaths.Add(typeof(InteractiveScriptGlobals).Assembly.Location);

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(serviceState.ReplServiceProvider.Logo);
                    }

                    if (File.Exists(initializationFilePath))
                    {
                        Console.Out.WriteLine(
                            string.Format(
                                InteractiveHostResources.Loading_context_from_0,
                                Path.GetFileName(initializationFilePath)
                                )
                            );
                        var parser = serviceState.ReplServiceProvider.CommandLineParser;

                        // Add the Framework runtime directory to reference search paths when running on .NET Framework (PlatformAssemblyPaths list is empty).
                        // Otherwise, platform assemblies are looked up in PlatformAssemblyPaths directly.
                        var sdkDirectory = s_currentPlatformInfo.PlatformAssemblyPaths.IsEmpty
                            ? RuntimeEnvironment.GetRuntimeDirectory()
                            : null;

                        var rspDirectory = Path.GetDirectoryName(initializationFilePath);
                        var args         = parser.Parse(
                            new[] { "@" + initializationFilePath },
                            baseDirectory: rspDirectory,
                            sdkDirectory,
                            additionalReferenceDirectories: null
                            );

                        foreach (var error in args.Errors)
                        {
                            var writer =
                                (error.Severity == DiagnosticSeverity.Error)
                                    ? Console.Error
                                    : Console.Out;
                            writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
                        }

                        if (args.Errors.Length == 0)
                        {
                            var referencePaths = args.ReferencePaths;
                            var sourcePaths    = args.SourcePaths;

                            // TODO: Workaround for https://github.com/dotnet/roslyn/issues/45346
                            var referencePathsWithoutRspDir = referencePaths.Remove(rspDirectory);
                            var metadataResolver            = state.MetadataReferenceResolver.WithSearchPaths(
                                referencePathsWithoutRspDir
                                );
                            var rspMetadataResolver = state.MetadataReferenceResolver
                                                      .WithSearchPaths(referencePaths)
                                                      .WithBaseDirectory(rspDirectory);

                            var sourceResolver = CreateSourceReferenceResolver(
                                sourcePaths,
                                rspDirectory
                                );

                            var metadataReferences = new List <PortableExecutableReference>();
                            foreach (var cmdLineReference in args.MetadataReferences)
                            {
                                // interactive command line parser doesn't accept modules or linked assemblies
                                Debug.Assert(
                                    cmdLineReference.Properties.Kind == MetadataImageKind.Assembly &&
                                    !cmdLineReference.Properties.EmbedInteropTypes
                                    );

                                var resolvedReferences = rspMetadataResolver.ResolveReference(
                                    cmdLineReference.Reference,
                                    baseFilePath: null,
                                    properties: MetadataReferenceProperties.Assembly
                                    );
                                if (!resolvedReferences.IsDefaultOrEmpty)
                                {
                                    metadataReferences.AddRange(resolvedReferences);
                                    metadataReferencePaths.AddRange(
                                        resolvedReferences
                                        .Where(r => r.FilePath != null)
                                        .Select(r => r.FilePath !)
                                        );
                                }
                            }

                            initializationScriptPath = args.SourceFiles.IsEmpty
                                ? null
                                : args.SourceFiles[0].Path;
                            initialImports = CommandLineHelpers.GetImports(args);

                            var rspState = new EvaluationState(
                                state.ScriptState,
                                state.ScriptOptions
                                .WithFilePath(initializationScriptPath)
                                .WithReferences(metadataReferences)
                                .WithImports(initialImports)
                                .WithMetadataResolver(metadataResolver)
                                .WithSourceResolver(sourceResolver),
                                args.SourcePaths,
                                rspDirectory
                                );

                            var globals = serviceState.Globals;
                            globals.ReferencePaths.Clear();
                            globals.ReferencePaths.AddRange(referencePathsWithoutRspDir);

                            globals.SourcePaths.Clear();
                            globals.SourcePaths.AddRange(sourcePaths);

                            globals.Args.AddRange(args.ScriptArguments);

                            if (initializationScriptPath != null)
                            {
                                var newScriptState = await TryExecuteFileAsync(
                                    rspState,
                                    initializationScriptPath
                                    )
                                                     .ConfigureAwait(false);

                                if (newScriptState != null)
                                {
                                    // remove references and imports from the options, they have been applied and will be inherited from now on:
                                    rspState = rspState
                                               .WithScriptState(newScriptState)
                                               .WithOptions(
                                        rspState.ScriptOptions.RemoveImportsAndReferences()
                                        );
                                }
                            }

                            state = rspState;
                        }
                    }

                    if (!isRestarting)
                    {
                        Console.Out.WriteLine(
                            InteractiveHostResources.Type_Sharphelp_for_more_information
                            );
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    var initResult = new RemoteInitializationResult(
                        initializationScriptPath,
                        metadataReferencePaths.ToImmutableArray(),
                        initialImports
                        );
                    state = CompleteExecution(state, completionSource, success: true, initResult);
                }

                return(state);
            }
Exemplo n.º 4
0
 public ParamsObject() : this(
         CommandLineHelpers.RemoveAppNameFromArgs(Environment.CommandLine, Environment.CurrentDirectory))
 {
 }
        private static void BuildJobPropertyChanged(object sender, PropertyChangedEventArgs eventArgs, bool isChildBuild)
        {
            string spacingString = isChildBuild ? "   " : string.Empty;
            var    job           = (IBuildQueueJob)sender;

            if (!IsStatusChangedEvent(eventArgs))
            {
                return;
            }

            bool buildFinished = false;

            if (job.State == JobState.Error || job.State == JobState.Failed)
            {
                WriteErrorsFromJob(job);
                buildFinished = true;
            }
            else if (job.State == JobState.Success)
            {
                if (isChildBuild)
                {
                    WriteChildBuildFinishedMessage(job.AssociatedEnvoy.Name.Last);
                }
                buildFinished = true;
            }

            if (buildFinished)
            {
                if (isChildBuild)
                {
                    job.PropertyChanged -= OnChildBuildJobPropertyChanged;
                }
                else
                {
                    job.PropertyChanged -= OnRootBuildJobPropertyChanged;
                }
                return;
            }

            // We've already printed an update for the first build step (starting the build), so we don't want to print it again here.
            if (job.CurrentStepIndex != 0)
            {
                CommandLineInterfaceApplication.WriteLine($"{spacingString}{job.AssociatedEnvoy.Name.Last} -- {job.CurrentActionDisplayName}. -- {CommandLineHelpers.GetFullDateTimeString()}");
            }
        }
Exemplo n.º 6
0
        public void Call(string[] args)
        {
            var paramList = CommandLineHelpers.ParseParameterList(args, Method);

            Method.Invoke(Instance, paramList);
        }