protected virtual async Task Execute(string input)
        {
            await HandleScriptErrors(async() =>
            {
                if (_scriptState == null)
                {
                    var sourceText = SourceText.From(input);
                    var context    = new ScriptContext(sourceText, CurrentDirectory, Enumerable.Empty <string>(), scriptMode: ScriptMode.REPL);
                    await RunFirstScript(context);
                }
                else
                {
                    if (input.StartsWith("#r ") || input.StartsWith("#load "))
                    {
                        var lineRuntimeDependencies = ScriptCompiler.RuntimeDependencyResolver.GetDependencies(CurrentDirectory, ScriptMode.REPL, input).ToArray();
                        var lineDependencies        = lineRuntimeDependencies.SelectMany(rtd => rtd.Assemblies).Distinct();

                        var scriptMap = lineRuntimeDependencies.ToDictionary(rdt => rdt.Name, rdt => rdt.Scripts);
                        if (scriptMap.Count > 0)
                        {
                            _scriptOptions =
                                _scriptOptions.WithSourceResolver(
                                    new NuGetSourceReferenceResolver(
                                        new SourceFileResolver(ImmutableArray <string> .Empty, CurrentDirectory), scriptMap));
                        }
                        foreach (var runtimeDependency in lineDependencies)
                        {
                            Logger.Verbose("Adding reference to a runtime dependency => " + runtimeDependency);
                            _scriptOptions = _scriptOptions.AddReferences(MetadataReference.CreateFromFile(runtimeDependency.Path));
                        }
                    }
                    _scriptState = await _scriptState.ContinueWithAsync(input, _scriptOptions, ex => true);
                }
            });
        }
        protected virtual async Task Execute(string input, bool debugMode)
        {
            try
            {
                if (_scriptState == null)
                {
                    var sourceText = SourceText.From(input);
                    var context    = new ScriptContext(sourceText, CurrentDirectory, Enumerable.Empty <string>(), debugMode: debugMode);
                    await RunFirstScript(context);
                }
                else
                {
                    var lineRuntimeDependencies =
                        ScriptCompiler.RuntimeDependencyResolver.GetDependenciesFromCode(CurrentDirectory, input).ToArray();
                    var lineDependencies = lineRuntimeDependencies.SelectMany(rtd => rtd.Assemblies).Distinct();

                    var scriptMap = lineRuntimeDependencies.ToDictionary(rdt => rdt.Name, rdt => rdt.Scripts);
                    if (scriptMap.Count > 0)
                    {
                        _scriptOptions =
                            _scriptOptions.WithSourceResolver(
                                new NuGetSourceReferenceResolver(
                                    new SourceFileResolver(ImmutableArray <string> .Empty, CurrentDirectory), scriptMap));
                    }
                    foreach (var runtimeDependency in lineDependencies)
                    {
                        Logger.Verbose("Adding reference to a runtime dependency => " + runtimeDependency);
                        _scriptOptions = _scriptOptions.AddReferences(MetadataReference.CreateFromFile(runtimeDependency.Path));
                    }

                    _scriptState = await _scriptState.ContinueWithAsync(input, _scriptOptions, ex => true);
                }

                if (_scriptState?.Exception != null)
                {
                    Console.WritePrettyError(CSharpObjectFormatter.Instance.FormatException(_scriptState.Exception));
                }

                if (_scriptState?.ReturnValue != null)
                {
                    _globals.Print(_scriptState.ReturnValue);
                }
            }
            catch (Exception e)
            {
                Console.WritePrettyError(CSharpObjectFormatter.Instance.FormatException(e));
            }
        }
        protected virtual async Task Execute(string input, bool debugMode)
        {
            try
            {
                if (_scriptState == null)
                {
                    var sourceText = SourceText.From(input);
                    var context    = new ScriptContext(sourceText, CurrentDirectory, Enumerable.Empty <string>(), debugMode: debugMode);
                    await RunFirstScript(context);
                }
                else
                {
                    var lineDependencies = ScriptCompiler.RuntimeDependencyResolver.GetDependenciesFromCode(CurrentDirectory, input);

                    foreach (var runtimeDependency in lineDependencies)
                    {
                        Logger.Verbose("Adding reference to a runtime dependency => " + runtimeDependency);
                        _scriptOptions = _scriptOptions.AddReferences(MetadataReference.CreateFromFile(runtimeDependency.Path));
                    }

                    _scriptState = await _scriptState.ContinueWithAsync(input, _scriptOptions, ex => true);
                }

                if (_scriptState?.Exception != null)
                {
                    Console.WritePrettyError(CSharpObjectFormatter.Instance.FormatException(_scriptState.Exception));
                }

                if (_scriptState?.ReturnValue != null)
                {
                    _globals.Print(_scriptState.ReturnValue);
                }
            }
            catch (Exception e)
            {
                Console.WritePrettyError(CSharpObjectFormatter.Instance.FormatException(e));
            }
        }
Exemple #4
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeIdentitfer = GetRuntimeIdentitifer();

            _logger.Verbose($"Current runtime is '{runtimeIdentitfer}'.");

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            var runtimeContext = File.Exists(Path.Combine(context.WorkingDirectory, Project.FileName)) ? ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).FirstOrDefault() : null;

            if (runtimeContext == null)
            {
                _logger.Verbose("Unable to find project context for CSX files. Will default to non-context usage.");
                var scriptProjectProvider = ScriptProjectProvider.Create(new LoggerFactory());
                var scriptProjectInfo     = scriptProjectProvider.CreateProject(context.WorkingDirectory, "netcoreapp1.1");
                runtimeContext = ProjectContext.CreateContextForEachTarget(scriptProjectInfo.PathToProjectJson).FirstOrDefault();
            }

            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'.");
            var projectExporter = runtimeContext.CreateExporter(context.Configuration);

            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblyGroups = projectDependency.RuntimeAssemblyGroups;

                foreach (var libraryAsset in runtimeAssemblyGroups.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = libraryAsset.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }

                foreach (var runtimeAssemblyGroup in runtimeAssemblyGroups)
                {
                    if (!string.IsNullOrWhiteSpace(runtimeAssemblyGroup.Runtime) && runtimeAssemblyGroup.Runtime == runtimeIdentitfer)
                    {
                        foreach (var runtimeAsset in runtimeAssemblyGroups.GetRuntimeAssets(GetRuntimeIdentitifer()))
                        {
                            var runtimeAssetPath = runtimeAsset.ResolvedPath;
                            _logger.Verbose($"Discovered runtime asset dependency ('{runtimeIdentitfer}') for '{runtimeAssetPath}'");
                            runtimeDependencies.Add(runtimeAssetPath);
                        }
                    }
                }
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader             = new InteractiveAssemblyLoader();
            var script             = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var orderedDiagnostics = script.GetDiagnostics(SuppressedDiagnosticIds);

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
        public ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeContext = ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).First();

            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'");

            var projectExporter     = runtimeContext.CreateExporter(context.Configuration);
            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblies = projectDependency.RuntimeAssemblyGroups;

                foreach (var runtimeAssembly in runtimeAssemblies.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = runtimeAssembly.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }
            }

            var opts = ScriptOptions.Default.
                       AddImports(DefaultNamespaces).
                       AddReferences(DefaultAssemblies).
                       WithSourceResolver(new RemoteFileResolver(context.WorkingDirectory));

            if (!string.IsNullOrWhiteSpace(context.FilePath))
            {
                opts = opts.WithFilePath(context.FilePath);
            }

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("system.") ||
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("microsoft.codeanalysis") ||
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("mscorlib"));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader      = new InteractiveAssemblyLoader();
            var script      = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var compilation = script.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in diagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    diagnostics);
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
Exemple #6
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var platformIdentifier = RuntimeHelper.GetPlatformIdentifier();

            _logger.Verbose($"Current runtime is '{platformIdentifier}'.");

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            var pathToProjectJson = Path.Combine(context.WorkingDirectory, Project.FileName);

            IList <RuntimeDependency> runtimeDependencies = new List <RuntimeDependency>();

            if (!File.Exists(pathToProjectJson))
            {
                _logger.Verbose("Unable to find project context for CSX files. Will default to non-context usage.");
                var pathToCsProj       = _scriptProjectProvider.CreateProject(context.WorkingDirectory);
                var dependencyResolver = new DependencyResolver(new CommandRunner(_logger), _logger);
                runtimeDependencies = dependencyResolver.GetRuntimeDependencies(pathToCsProj).ToList();
            }
            else
            {
                _logger.Verbose($"Found runtime context for '{pathToProjectJson}'.");
                var dependencyResolver = new LegacyDependencyResolver(_logger);
                runtimeDependencies = dependencyResolver.GetRuntimeDependencies(pathToProjectJson).ToList();
            }

            AssemblyLoadContext.Default.Resolving +=
                (assemblyLoadContext, assemblyName) => MapUnresolvedAssemblyToRuntimeLibrary(runtimeDependencies.ToList(), assemblyLoadContext, assemblyName);


            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep.Path));
            }

            var loader             = new InteractiveAssemblyLoader();
            var script             = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var orderedDiagnostics = script.GetDiagnostics(SuppressedDiagnosticIds);

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeContext    = ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).First();
            var runtimeIdentitfer = GetRuntimeIdentitifer();

            _logger.Verbose($"Current runtime is '{runtimeIdentitfer}'.");
            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'.");

            var projectExporter = runtimeContext.CreateExporter(context.Configuration);

            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblyGroups = projectDependency.RuntimeAssemblyGroups;

                foreach (var libraryAsset in runtimeAssemblyGroups.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = libraryAsset.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }

                foreach (var runtimeAssemblyGroup in runtimeAssemblyGroups)
                {
                    if (!string.IsNullOrWhiteSpace(runtimeAssemblyGroup.Runtime) && runtimeAssemblyGroup.Runtime == runtimeIdentitfer)
                    {
                        foreach (var runtimeAsset in runtimeAssemblyGroups.GetRuntimeAssets(GetRuntimeIdentitifer()))
                        {
                            var runtimeAssetPath = runtimeAsset.ResolvedPath;
                            _logger.Verbose($"Discovered runtime asset dependency ('{runtimeIdentitfer}') for '{runtimeAssetPath}'");
                            runtimeDependencies.Add(runtimeAssetPath);
                        }
                    }
                }
            }

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader      = new InteractiveAssemblyLoader();
            var script      = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var compilation = script.GetCompilation();

            var diagnostics        = compilation.GetDiagnostics();
            var orderedDiagnostics = diagnostics.OrderBy((d1, d2) =>
            {
                var severityDiff = (int)d2.Severity - (int)d1.Severity;
                return(severityDiff != 0 ? severityDiff : d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
            });

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }