/// <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);
            }
            /// <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.Loading_context_from_0, 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 TryExecuteFileAsync(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.Type_Sharphelp_for_more_information);
                    }
                }
                catch (Exception e)
                {
                    ReportUnhandledException(e);
                }
                finally
                {
                    state = CompleteExecution(state, operation, success: true);
                }

                return state;
            }
Example #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);
            }
            /// <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 /* TODO: pass a valid value*/);

                        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)
                        {
                            // TODO (tomat): other arguments
                            // TODO (tomat): parse options

                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);

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

                            _hostObject.SourcePaths.Clear();

                            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);
                                }
                            }

                            // only search for scripts next to the .rsp file:
                            var sourceSearchPaths = ImmutableArray<string>.Empty;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.AddReferences(metadataReferences),
                                sourceSearchPaths,
                                args.ReferencePaths,
                                rspDirectory);

                            foreach (CommandLineSourceFile file in args.SourceFiles)
                            {
                                // execute all files as scripts (matches csi/vbi semantics)

                                string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
                                if (fullPath != null)
                                {
                                    var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);
                                    if (newScriptState != null)
                                    {
                                        rspState = rspState.WithScriptState(newScriptState);
                                    }
                                }
                            }

                            state = new EvaluationState(
                                rspState.ScriptStateOpt,
                                rspState.ScriptOptions,
                                ImmutableArray<string>.Empty,
                                args.ReferencePaths,
                                state.WorkingDirectory);
                        }
                    }

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

                return state;
            }
            /// <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 /* TODO: pass a valid value*/);

                        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)
                        {
                            // TODO (tomat): other arguments
                            // TODO (tomat): parse options

                            var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);

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

                            _hostObject.SourcePaths.Clear();

                            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);
                                }
                            }

                            // only search for scripts next to the .rsp file:
                            var sourceSearchPaths = ImmutableArray <string> .Empty;

                            var rspState = new EvaluationState(
                                state.ScriptStateOpt,
                                state.ScriptOptions.AddReferences(metadataReferences),
                                sourceSearchPaths,
                                args.ReferencePaths,
                                rspDirectory);

                            foreach (CommandLineSourceFile file in args.SourceFiles)
                            {
                                // execute all files as scripts (matches csi/vbi semantics)

                                string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
                                if (fullPath != null)
                                {
                                    var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);

                                    if (newScriptState != null)
                                    {
                                        rspState = rspState.WithScriptState(newScriptState);
                                    }
                                }
                            }

                            state = new EvaluationState(
                                rspState.ScriptStateOpt,
                                rspState.ScriptOptions,
                                ImmutableArray <string> .Empty,
                                args.ReferencePaths,
                                state.WorkingDirectory);
                        }
                    }

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

                return(state);
            }