/// <summary>
 /// Compile C# expression and emit assembly with evaluation method.
 /// </summary>
 /// <returns>
 /// Result containing generated assembly, type and method names, and any format specifiers.
 /// </returns>
 internal CompileResult CompileExpression(
     InspectionContext inspectionContext,
     string expr,
     DkmEvaluationFlags compilationFlags,
     DiagnosticFormatter formatter,
     out ResultProperties resultProperties,
     out string error,
     out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
     CultureInfo preferredUICulture,
     CompilationTestData testData)
 {
     var diagnostics = DiagnosticBag.GetInstance();
     var result = this.CompileExpression(inspectionContext, expr, compilationFlags, diagnostics, out resultProperties, testData);
     if (diagnostics.HasAnyErrors())
     {
         bool useReferencedModulesOnly;
         error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out useReferencedModulesOnly, out missingAssemblyIdentities);
     }
     else
     {
         error = null;
         missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
     }
     diagnostics.Free();
     return result;
 }
        internal string GetErrorMessageAndMissingAssemblyIdentities(DiagnosticBag diagnostics, DiagnosticFormatter formatter, CultureInfo preferredUICulture, AssemblyIdentity linqLibrary, out bool useReferencedModulesOnly, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
        {
            var errors = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error);
            foreach (var error in errors)
            {
                missingAssemblyIdentities = this.GetMissingAssemblyIdentities(error, linqLibrary);
                if (!missingAssemblyIdentities.IsDefault)
                {
                    break;
                }
            }

            if (missingAssemblyIdentities.IsDefault)
            {
                missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
            }

            useReferencedModulesOnly = errors.All(HasDuplicateTypesOrAssemblies);

            var firstError = errors.FirstOrDefault();
            Debug.Assert(firstError != null);

            var simpleMessage = firstError as SimpleMessageDiagnostic;
            return (simpleMessage != null) ?
                simpleMessage.GetMessage() :
                formatter.Format(firstError, preferredUICulture ?? CultureInfo.CurrentUICulture);
        }
 internal static CompileResult CompileAssignment(
     this EvaluationContextBase context,
     string target,
     string expr,
     out string error,
     CompilationTestData testData = null,
     DiagnosticFormatter formatter = null)
 {
     ResultProperties resultProperties;
     ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
     var result = context.CompileAssignment(
         DefaultInspectionContext.Instance,
         target,
         expr,
         formatter ?? DiagnosticFormatter.Instance,
         out resultProperties,
         out error,
         out missingAssemblyIdentities,
         EnsureEnglishUICulture.PreferredOrNull,
         testData);
     Assert.Empty(missingAssemblyIdentities);
     // This is a crude way to test the language, but it's convenient to share this test helper.
     var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0;
     var expectedFlags = error != null
         ? DkmClrCompilationResultFlags.None
         : isCSharp
             ? DkmClrCompilationResultFlags.PotentialSideEffect
             : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult;
     Assert.Equal(expectedFlags, resultProperties.Flags);
     Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category);
     Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
     Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
     Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
     return result;
 }
 internal abstract CompileResult CompileAssignment(
     InspectionContext inspectionContext,
     string target,
     string expr,
     DiagnosticFormatter formatter,
     out ResultProperties resultProperties,
     out string error,
     out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
     CultureInfo preferredUICulture,
     CompilationTestData testData);
 internal static CompileResult CompileExpression(
     this EvaluationContextBase context,
     string expr,
     out string error,
     CompilationTestData testData = null,
     DiagnosticFormatter formatter = null)
 {
     ResultProperties resultProperties;
     return CompileExpression(context, expr, out resultProperties, out error, testData, formatter);
 }
 internal static CompileResult CompileExpression(
     this EvaluationContextBase context,
     string expr,
     out ResultProperties resultProperties,
     out string error,
     CompilationTestData testData = null,
     DiagnosticFormatter formatter = null)
 {
     ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
     var result = context.CompileExpression(
         DefaultInspectionContext.Instance,
         expr,
         DkmEvaluationFlags.TreatAsExpression,
         formatter ?? DiagnosticFormatter.Instance,
         out resultProperties,
         out error,
         out missingAssemblyIdentities,
         EnsureEnglishUICulture.PreferredOrNull,
         testData);
     Assert.Empty(missingAssemblyIdentities);
     return result;
 }
Exemple #7
0
        private static void ThrowIfAnyCompilationErrors(
            DiagnosticBag diagnostics,
            DiagnosticFormatter formatter
            )
        {
            if (diagnostics.IsEmptyWithoutResolution)
            {
                return;
            }
            var filtered = diagnostics
                           .AsEnumerable()
                           .Where(d => d.Severity == DiagnosticSeverity.Error)
                           .AsImmutable();

            if (filtered.IsEmpty)
            {
                return;
            }
            throw new CompilationErrorException(
                      formatter.Format(filtered[0], CultureInfo.CurrentCulture),
                      filtered
                      );
        }
Exemple #8
0
        internal static CompileResult CompileExpression(
            this EvaluationContextBase context,
            string expr,
            out ResultProperties resultProperties,
            out string error,
            CompilationTestData testData  = null,
            DiagnosticFormatter formatter = null)
        {
            ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
            var result = context.CompileExpression(
                expr,
                DkmEvaluationFlags.TreatAsExpression,
                ImmutableArray <Alias> .Empty,
                formatter ?? DiagnosticFormatter.Instance,
                out resultProperties,
                out error,
                out missingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData);

            Assert.Empty(missingAssemblyIdentities);
            return(result);
        }
        internal static CompileResult CompileAssignment(
            this EvaluationContextBase context,
            string target,
            string expr,
            out string error,
            CompilationTestData testData  = null,
            DiagnosticFormatter formatter = null)
        {
            ResultProperties resultProperties;
            ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
            var result = context.CompileAssignment(
                target,
                expr,
                ImmutableArray <Alias> .Empty,
                formatter ?? DebuggerDiagnosticFormatter.Instance,
                out resultProperties,
                out error,
                out missingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData);

            Assert.Empty(missingAssemblyIdentities);
            // This is a crude way to test the language, but it's convenient to share this test helper.
            var isCSharp      = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0;
            var expectedFlags = error != null
                ? DkmClrCompilationResultFlags.None
                : isCSharp
                    ? DkmClrCompilationResultFlags.PotentialSideEffect
                    : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult;

            Assert.Equal(expectedFlags, resultProperties.Flags);
            Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category);
            Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
            Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
            Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
            return(result);
        }
        public static CompilationResult GetAssemblyFromCompilation(
            ICodeGenAssemblyLoadContext loader,
            Microsoft.CodeAnalysis.Compilation compilation)
        {
            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms, pdbStream: null);

                if (!result.Success)
                {
                    var formatter     = new DiagnosticFormatter();
                    var errorMessages = result.Diagnostics
                                        .Where(IsError)
                                        .Select(d => formatter.Format(d));

                    return(CompilationResult.FromErrorMessages(errorMessages));
                }

                ms.Seek(0, SeekOrigin.Begin);

                try
                {
                    return(CompilationResult.FromAssembly(loader.LoadStream(ms, symbols: null)));
                }
                catch (Exception ex)
                {
                    var v = ex;
                    while (v.InnerException != null)
                    {
                        v = v.InnerException;
                    }

                    return(CompilationResult.FromErrorMessages(ex.GetAllErrorMessages()));
                }
            }
        }
        public CompilationResult Compile(string content)
        {
            var syntaxTrees     = new[] { CSharpSyntaxTree.ParseText(content) };
            var targetFramework = _environment.TargetFramework;

            var references = GetApplicationReferences();

            var assemblyName = Path.GetRandomFileName();

            var compilation = CSharpCompilation.Create(assemblyName,
                                                       options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                                                       syntaxTrees: syntaxTrees,
                                                       references: references);

            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    EmitResult result;

                    if (PlatformHelper.IsMono)
                    {
                        result = compilation.Emit(ms, pdbStream: null);
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();

                        var messages = result.Diagnostics
                                       .Where(IsError)
                                       .Select(d => GetCompilationMessage(formatter, d))
                                       .ToList();

                        return(CompilationResult.Failed(content, messages));
                    }

                    Assembly assembly;
                    ms.Seek(0, SeekOrigin.Begin);

                    if (PlatformHelper.IsMono)
                    {
                        assembly = _loader.LoadStream(ms, pdbStream: null);
                    }
                    else
                    {
                        pdb.Seek(0, SeekOrigin.Begin);
                        assembly = _loader.LoadStream(ms, pdb);
                    }

                    var type = assembly.GetExportedTypes()
                               .First();

                    return(CompilationResult.Successful(string.Empty, type));
                }
            }
        }
        /// <inheritdoc />
        public CompilationResult Compile(IFileInfo fileInfo, string compilationContent)
        {
            var syntaxTrees = new[] { SyntaxTreeGenerator.Generate(compilationContent, fileInfo.PhysicalPath) };

            var references = _applicationReferences.Value;

            var assemblyName = Path.GetRandomFileName();

            var compilation = CSharpCompilation.Create(assemblyName,
                                                       options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                                                       syntaxTrees: syntaxTrees,
                                                       references: references);

            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    EmitResult result;

                    if (_supportsPdbGeneration.Value)
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }
                    else
                    {
                        result = compilation.Emit(ms);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();

                        var messages = result.Diagnostics
                                       .Where(IsError)
                                       .Select(d => GetCompilationMessage(formatter, d))
                                       .ToList();

                        return(CompilationResult.Failed(fileInfo, compilationContent, messages));
                    }

                    Assembly assembly;
                    ms.Seek(0, SeekOrigin.Begin);

                    if (_supportsPdbGeneration.Value)
                    {
                        pdb.Seek(0, SeekOrigin.Begin);
                        assembly = _loader.LoadStream(ms, pdb);
                    }
                    else
                    {
                        assembly = _loader.LoadStream(ms, assemblySymbols: null);
                    }

                    var type = assembly.GetExportedTypes()
                               .First(t => t.Name.
                                      StartsWith(_classPrefix, StringComparison.Ordinal));

                    return(UncachedCompilationResult.Successful(type));
                }
            }
        }
Exemple #13
0
        public async Task <ImmutableArray <SpellingFixResult> > FixProjectAsync(
            Project project,
            CancellationToken cancellationToken = default)
        {
            project = CurrentSolution.GetProject(project.Id);

            ISpellingService service = MefWorkspaceServices.Default.GetService <ISpellingService>(project.Language);

            if (service == null)
            {
                return(ImmutableArray <SpellingFixResult> .Empty);
            }

            ImmutableArray <Diagnostic> previousDiagnostics         = ImmutableArray <Diagnostic> .Empty;
            ImmutableArray <Diagnostic> previousPreviousDiagnostics = ImmutableArray <Diagnostic> .Empty;

            ImmutableArray <SpellingFixResult> .Builder results = ImmutableArray.CreateBuilder <SpellingFixResult>();

            bool nonSymbolsFixed = (Options.ScopeFilter & (SpellingScopeFilter.NonSymbol)) == 0;

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var compilationWithAnalyzersOptions = new CompilationWithAnalyzersOptions(
                    options: default(AnalyzerOptions),
                    onAnalyzerException: default(Action <Exception, DiagnosticAnalyzer, Diagnostic>),
                    concurrentAnalysis: true,
                    logAnalyzerExecutionTime: false,
                    reportSuppressedDiagnostics: false);

                Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                DiagnosticAnalyzer analyzer = service.CreateAnalyzer(SpellingData, Options);

                var compilationWithAnalyzers = new CompilationWithAnalyzers(
                    compilation,
                    ImmutableArray.Create(analyzer),
                    compilationWithAnalyzersOptions);

                ImmutableArray <Diagnostic> diagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken).ConfigureAwait(false);

#if DEBUG
                foreach (IGrouping <Diagnostic, Diagnostic> grouping in diagnostics
                         .GroupBy(f => f, DiagnosticDeepEqualityComparer.Instance))
                {
                    using (IEnumerator <Diagnostic> en = grouping.GetEnumerator())
                    {
                        if (en.MoveNext() &&
                            en.MoveNext())
                        {
                            Debug.Fail(DiagnosticFormatter.FormatDiagnostic(en.Current));
                        }
                    }
                }
#endif
                int length = diagnostics.Length;

                if (length == 0)
                {
                    break;
                }

                if (length == previousDiagnostics.Length &&
                    !diagnostics.Except(previousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any())
                {
                    break;
                }

                if (length == previousPreviousDiagnostics.Length &&
                    !diagnostics.Except(previousPreviousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any())
                {
                    LogHelpers.WriteInfiniteLoopSummary(diagnostics, previousDiagnostics, project, FormatProvider);
                    break;
                }

                var spellingDiagnostics = new List <SpellingDiagnostic>();

                foreach (Diagnostic diagnostic in diagnostics)
                {
                    Debug.Assert(diagnostic.Id == CommonDiagnosticIdentifiers.PossibleMisspellingOrTypo, diagnostic.Id);

                    if (diagnostic.Id != CommonDiagnosticIdentifiers.PossibleMisspellingOrTypo)
                    {
                        if (diagnostic.IsAnalyzerExceptionDiagnostic())
                        {
                            LogHelpers.WriteDiagnostic(diagnostic, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: FormatProvider, indentation: "  ", verbosity: Verbosity.Detailed);
                        }

                        continue;
                    }

                    SpellingDiagnostic spellingDiagnostic = service.CreateSpellingDiagnostic(diagnostic);

                    spellingDiagnostics.Add(spellingDiagnostic);
                }

                if (!nonSymbolsFixed)
                {
                    List <SpellingFixResult> commentResults = await FixCommentsAsync(project, spellingDiagnostics, cancellationToken).ConfigureAwait(false);

                    results.AddRange(commentResults);
                    nonSymbolsFixed = true;
                }

                if ((Options.ScopeFilter & SpellingScopeFilter.Symbol) == 0)
                {
                    break;
                }

                (List <SpellingFixResult> symbolResults, bool allIgnored) = await FixSymbolsAsync(
                    project,
                    spellingDiagnostics,
                    service.SyntaxFacts,
                    cancellationToken)
                                                                            .ConfigureAwait(false);

                results.AddRange(symbolResults);

                if (allIgnored)
                {
                    break;
                }

                if (Options.DryRun)
                {
                    break;
                }

                project = CurrentSolution.GetProject(project.Id);

                previousPreviousDiagnostics = previousDiagnostics;
                previousDiagnostics         = diagnostics;
            }

            return(results.ToImmutableArray());
        }
Exemple #14
0
        internal override CompileResult CompileAssignment(
            InspectionContext inspectionContext,
            string target,
            string expr,
            DiagnosticFormatter formatter,
            out ResultProperties resultProperties,
            out string error,
            out ImmutableArray <AssemblyIdentity> missingAssemblyIdentities,
            System.Globalization.CultureInfo preferredUICulture,
            Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
        {
            var diagnostics = DiagnosticBag.GetInstance();

            try
            {
                var assignment = target.ParseAssignment(expr, diagnostics);
                if (assignment == null)
                {
                    error            = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                    resultProperties = default(ResultProperties);
                    return(default(CompileResult));
                }

                var context = this.CreateCompilationContext(assignment);
                ResultProperties properties;
                var moduleBuilder = context.CompileAssignment(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties);
                if (moduleBuilder == null)
                {
                    error            = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                    resultProperties = default(ResultProperties);
                    return(default(CompileResult));
                }

                using (var stream = new MemoryStream())
                {
                    Cci.PeWriter.WritePeToStream(
                        new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
                        context.MessageProvider,
                        stream,
                        nativePdbWriterOpt: null,
                        allowMissingMethodBodies: false,
                        deterministic: false,
                        cancellationToken: default(CancellationToken));

                    if (diagnostics.HasAnyErrors())
                    {
                        error            = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                        resultProperties = default(ResultProperties);
                        return(default(CompileResult));
                    }

                    resultProperties          = properties;
                    error                     = null;
                    missingAssemblyIdentities = ImmutableArray <AssemblyIdentity> .Empty;
                    return(new CompileResult(
                               stream.ToArray(),
                               typeName: TypeName,
                               methodName: MethodName,
                               formatSpecifiers: null));
                }
            }
            finally
            {
                diagnostics.Free();
            }
        }
Exemple #15
0
        /// <inheritdoc />
        public CompilationResult Compile(IFileInfo fileInfo, string compilationContent)
        {
            var sourceText  = SourceText.From(compilationContent, Encoding.UTF8);
            var syntaxTrees = new[] { CSharpSyntaxTree.ParseText(sourceText, path: fileInfo.PhysicalPath) };

            var references = _applicationReferences.Value;

            var assemblyName = Path.GetRandomFileName();

            var compilation = CSharpCompilation.Create(assemblyName,
                                                       options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                                                       syntaxTrees: syntaxTrees,
                                                       references: references);

            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    EmitResult result;

                    if (PlatformHelper.IsMono)
                    {
                        result = compilation.Emit(ms, pdbStream: null);
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();

                        var messages = result.Diagnostics
                                       .Where(IsError)
                                       .Select(d => GetCompilationMessage(formatter, d))
                                       .ToList();

                        return(CompilationResult.Failed(fileInfo, compilationContent, messages));
                    }

                    Assembly assembly;
                    ms.Seek(0, SeekOrigin.Begin);

                    if (PlatformHelper.IsMono)
                    {
                        assembly = _loader.LoadStream(ms, pdbStream: null);
                    }
                    else
                    {
                        pdb.Seek(0, SeekOrigin.Begin);
                        assembly = _loader.LoadStream(ms, pdb);
                    }

                    var type = assembly.GetExportedTypes()
                               .First();

                    return(UncachedCompilationResult.Successful(type, compilationContent));
                }
            }
        }
        internal string GetErrorMessageAndMissingAssemblyIdentities(DiagnosticBag diagnostics, DiagnosticFormatter formatter, CultureInfo preferredUICulture, out ImmutableArray <AssemblyIdentity> missingAssemblyIdentities)
        {
            Diagnostic firstError = GetErrorAndMissingAssemblyIdentities(diagnostics, out missingAssemblyIdentities);

            Debug.Assert(firstError != null);
            return(formatter.Format(firstError, preferredUICulture ?? CultureInfo.CurrentUICulture));
        }
 internal string GetErrorMessageAndMissingAssemblyIdentities(DiagnosticBag diagnostics, DiagnosticFormatter formatter, CultureInfo preferredUICulture, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
 {
     Diagnostic firstError = GetErrorAndMissingAssemblyIdentities(diagnostics, out missingAssemblyIdentities);
     Debug.Assert(firstError != null);
     return formatter.Format(firstError, preferredUICulture ?? Thread.CurrentThread.CurrentUICulture);
 }
Exemple #18
0
        internal static TResult CompileWithRetry <TResult>(
            ImmutableArray <MetadataBlock> metadataBlocks,
            DiagnosticFormatter formatter,
            CreateContextDelegate createContext,
            CompileDelegate <TResult> compile,
            DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
            out string errorMessage)
        {
            TResult compileResult;

            PooledHashSet <AssemblyIdentity> assembliesLoadedInRetryLoop = null;
            bool tryAgain;
            var  linqLibrary = EvaluationContextBase.SystemLinqIdentity;

            do
            {
                errorMessage = null;

                var context     = createContext(metadataBlocks, useReferencedModulesOnly: false);
                var diagnostics = DiagnosticBag.GetInstance();
                compileResult = compile(context, diagnostics);
                tryAgain      = false;
                if (diagnostics.HasAnyErrors())
                {
                    bool useReferencedModulesOnly;
                    ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
                    errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
                        diagnostics,
                        formatter,
                        preferredUICulture: null,
                        linqLibrary: linqLibrary,
                        useReferencedModulesOnly: out useReferencedModulesOnly,
                        missingAssemblyIdentities: out missingAssemblyIdentities);
                    // If there were LINQ-related errors, we'll initially add System.Linq (set above).
                    // If that doesn't work, we'll fall back to System.Core for subsequent retries.
                    linqLibrary = EvaluationContextBase.SystemCoreIdentity;

                    // Can we remove the `useReferencedModulesOnly` attempt if we're only using
                    // modules reachable from the current module? In short, can we avoid retrying?
                    if (useReferencedModulesOnly)
                    {
                        Debug.Assert(missingAssemblyIdentities.IsEmpty);
                        var otherContext     = createContext(metadataBlocks, useReferencedModulesOnly: true);
                        var otherDiagnostics = DiagnosticBag.GetInstance();
                        var otherResult      = compile(otherContext, otherDiagnostics);
                        if (!otherDiagnostics.HasAnyErrors())
                        {
                            errorMessage  = null;
                            compileResult = otherResult;
                        }
                        otherDiagnostics.Free();
                    }
                    else
                    {
                        if (!missingAssemblyIdentities.IsEmpty)
                        {
                            if (assembliesLoadedInRetryLoop == null)
                            {
                                assembliesLoadedInRetryLoop = PooledHashSet <AssemblyIdentity> .GetInstance();
                            }
                            // If any identities failed to add (they were already in the list), then don't retry.
                            if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
                            {
                                tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
                            }
                        }
                    }
                }
                diagnostics.Free();
            } while (tryAgain);
            assembliesLoadedInRetryLoop?.Free();

            return(compileResult);
        }
Exemple #19
0
        internal static TResult CompileWithRetry <TResult>(
            ImmutableArray <MetadataBlock> metadataBlocks,
            DiagnosticFormatter formatter,
            CreateContextDelegate createContext,
            CompileDelegate <TResult> compile,
            DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
            out string errorMessage)
        {
            TResult compileResult;

            PooledHashSet <AssemblyIdentity> assembliesLoadedInRetryLoop = null;
            bool tryAgain;

            do
            {
                errorMessage = null;

                var context     = createContext(metadataBlocks, useReferencedModulesOnly: false);
                var diagnostics = DiagnosticBag.GetInstance();
                compileResult = compile(context, diagnostics);
                tryAgain      = false;
                if (diagnostics.HasAnyErrors())
                {
                    bool useReferencedModulesOnly;
                    ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
                    errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
                        diagnostics,
                        formatter,
                        preferredUICulture: null,
                        useReferencedModulesOnly: out useReferencedModulesOnly,
                        missingAssemblyIdentities: out missingAssemblyIdentities);
                    if (useReferencedModulesOnly)
                    {
                        Debug.Assert(missingAssemblyIdentities.IsEmpty);
                        var otherContext     = createContext(metadataBlocks, useReferencedModulesOnly: true);
                        var otherDiagnostics = DiagnosticBag.GetInstance();
                        var otherResult      = compile(otherContext, otherDiagnostics);
                        if (!otherDiagnostics.HasAnyErrors())
                        {
                            errorMessage  = null;
                            compileResult = otherResult;
                        }
                        otherDiagnostics.Free();
                    }
                    else
                    {
                        if (!missingAssemblyIdentities.IsEmpty)
                        {
                            if (assembliesLoadedInRetryLoop == null)
                            {
                                assembliesLoadedInRetryLoop = PooledHashSet <AssemblyIdentity> .GetInstance();
                            }
                            // If any identities failed to add (they were already in the list), then don't retry.
                            if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
                            {
                                tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
                            }
                        }
                    }
                }
                diagnostics.Free();
            } while (tryAgain);
            assembliesLoadedInRetryLoop?.Free();

            return(compileResult);
        }
Exemple #20
0
        public CompilationResult Compile(string content, MetadataReference[] references)
        {
            var dummyAssemblyName = Path.GetRandomFileName();

            var compilationReferences = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),         // include corlib
                MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location), // this file (that contains the MyTemplate base class)

                // for some reason on .NET core, I need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "System.Runtime.dll")),

                // as found out by @Isantipov, for some other reason on .NET Core for Mac and Linux, we need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "netstandard.dll"))
            };

            if (references != null)
            {
                compilationReferences.AddRange(references);
            }

            SyntaxTree[] syntaxTrees = { CSharpSyntaxTree.ParseText(content) };
            var          compilation = CSharpCompilation.Create(dummyAssemblyName,
                                                                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                                                                syntaxTrees: syntaxTrees,
                                                                references: compilationReferences.ToArray());

            Assembly assembly;

            byte[] assemblyBytes;

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (!result.Success)
                {
                    var formatter     = new DiagnosticFormatter();
                    var errorMessages = result.Diagnostics
                                        .Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error)
                                        .Select(d => formatter.Format(d));

                    throw new Exception($"Errors encountered whilst compiling assembly: {String.Join(Environment.NewLine, errorMessages)}");
                }

                ms.Seek(0, SeekOrigin.Begin);
                assembly = AssemblyLoadContext.Default.LoadFromStream(ms);

                ms.Seek(0, SeekOrigin.Begin);
                assemblyBytes = ms.ToArray();
            }

            var thisAssemblyReference = MetadataReference.CreateFromStream(new MemoryStream(assemblyBytes));

            var compilationResult = new CompilationResult
            {
                Types              = assembly.GetExportedTypes(),
                Assembly           = assembly,
                AssemblyBytes      = assemblyBytes,
                MetadataReferences = compilationReferences.Union(new[] { thisAssemblyReference })
            };

            return(compilationResult);
        }
Exemple #21
0
 private static CompilationMessage GetCompilationMessage(DiagnosticFormatter formatter, Diagnostic diagnostic)
 {
     return(new CompilationMessage(formatter.Format(diagnostic)));
 }
Exemple #22
0
        /// <inheritdoc />
        public CompilationResult Compile([NotNull] IFileInfo fileInfo, [NotNull] string compilationContent)
        {
            // The path passed to SyntaxTreeGenerator.Generate is used by the compiler to generate symbols (pdb) that
            // map to the source file. If a file does not exist on a physical file system, PhysicalPath will be null.
            // This prevents files that exist in a non-physical file system from being debugged.
            var path = fileInfo.PhysicalPath ?? fileInfo.Name;
            var compilationSettings = _compilerOptionsProvider.GetCompilationSettings(_environment);
            var syntaxTree          = SyntaxTreeGenerator.Generate(compilationContent,
                                                                   path,
                                                                   compilationSettings);
            var references = _applicationReferences.Value;

            var assemblyName       = Path.GetRandomFileName();
            var compilationOptions = compilationSettings.CompilationOptions
                                     .WithOutputKind(OutputKind.DynamicallyLinkedLibrary);

            var compilation = CSharpCompilation.Create(assemblyName,
                                                       options: compilationOptions,
                                                       syntaxTrees: new[] { syntaxTree },
                                                       references: references);

            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    EmitResult result;

                    if (_supportsPdbGeneration.Value)
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }
                    else
                    {
                        result = compilation.Emit(ms);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();

                        var messages = result.Diagnostics
                                       .Where(IsError)
                                       .Select(d => GetCompilationMessage(formatter, d))
                                       .ToList();

                        return(CompilationResult.Failed(fileInfo, compilationContent, messages));
                    }

                    Assembly assembly;
                    ms.Seek(0, SeekOrigin.Begin);

                    if (_supportsPdbGeneration.Value)
                    {
                        pdb.Seek(0, SeekOrigin.Begin);
                        assembly = _loader.LoadStream(ms, pdb);
                    }
                    else
                    {
                        assembly = _loader.LoadStream(ms, assemblySymbols: null);
                    }

                    var type = assembly.GetExportedTypes()
                               .First(t => t.Name.StartsWith(_classPrefix, StringComparison.Ordinal));

                    return(UncachedCompilationResult.Successful(type, compilationContent));
                }
            }
        }
        internal override CompileResult CompileAssignment(
            InspectionContext inspectionContext,
            string target,
            string expr,
            DiagnosticFormatter formatter,
            out ResultProperties resultProperties,
            out string error,
            out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
            System.Globalization.CultureInfo preferredUICulture,
            Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
        {
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                var assignment = target.ParseAssignment(expr, diagnostics);
                if (assignment == null)
                {
                    error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                    resultProperties = default(ResultProperties);
                    return default(CompileResult);
                }

                var context = this.CreateCompilationContext(assignment);
                ResultProperties properties;
                var moduleBuilder = context.CompileAssignment(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties);
                if (moduleBuilder == null)
                {
                    error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                    resultProperties = default(ResultProperties);
                    return default(CompileResult);
                }

                using (var stream = new MemoryStream())
                {
                    Cci.PeWriter.WritePeToStream(
                        new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
                        context.MessageProvider,
                        stream,
                        nativePdbWriterOpt: null,
                        allowMissingMethodBodies: false,
                        deterministic: false,
                        cancellationToken: default(CancellationToken));

                    if (diagnostics.HasAnyErrors())
                    {
                        error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities);
                        resultProperties = default(ResultProperties);
                        return default(CompileResult);
                    }

                    resultProperties = properties;
                    error = null;
                    missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
                    return new CompileResult(
                        stream.ToArray(),
                        typeName: TypeName,
                        methodName: MethodName,
                        formatSpecifiers: null);
                }
            }
            finally
            {
                diagnostics.Free();
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            string fileName        = null;
            string outputDirectory = null;
            bool   separateXsdWsdl = false;
            bool   singleFileWsdl  = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith("-"))
                {
                    if (args[i] == "-separateXsdWsdl")
                    {
                        separateXsdWsdl = true;
                    }
                    else if (args[i] == "-singleFileWsdl")
                    {
                        singleFileWsdl = true;
                    }
                    else if (i + 1 < args.Length)
                    {
                        if (args[i] == "-o")
                        {
                            outputDirectory = args[++i];
                        }
                        else
                        {
                            Console.WriteLine("Unknown option: '" + args[i] + "'");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unknown option: '" + args[i] + "'");
                    }
                }
                else
                {
                    fileName = args[i];
                }
            }
            if (fileName == null)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  Soal.exe [options] [input.soal]");
                Console.WriteLine("Options:");
                Console.WriteLine("  -o [dir]: output directory");
                Console.WriteLine("  -separateXsdWsdl: separate XSD and WSDL files into different directories");
                Console.WriteLine("  -singleFileWsdl: include XSD code into the WSDL");
                return;
            }
            if (outputDirectory == null)
            {
                outputDirectory = Directory.GetCurrentDirectory();
            }
            if (!File.Exists(fileName))
            {
                Console.WriteLine("Could not find file: " + fileName);
                return;
            }
            if (singleFileWsdl && separateXsdWsdl)
            {
                Console.WriteLine("Warning: conflicting options '-separateXsdWsdl' and '-singleFileWsdl'. '-singleFileWsdl' will be used.");
            }
            string source;

            using (StreamReader reader = new StreamReader(fileName))
            {
                source = reader.ReadToEnd();
            }
            SoalSyntaxTree         syntaxTree    = SoalSyntaxTree.ParseText(source);
            ModelReference         soalReference = ModelReference.CreateFromModel(SoalInstance.Model);
            BinderFlags            binderFlags   = BinderFlags.IgnoreAccessibility;
            SoalCompilationOptions options       = new SoalCompilationOptions(SoalLanguage.Instance, OutputKind.NetModule, topLevelBinderFlags: binderFlags, concurrentBuild: false);
            SoalCompilation        compilation   = SoalCompilation.Create("SoalTest").AddReferences(soalReference).AddSyntaxTrees(syntaxTree).WithOptions(options);

            compilation.ForceComplete();
            ImmutableModel model = compilation.Model;
            DiagnosticBag  generatorDiagnostics = new DiagnosticBag();

            if (!compilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                SoalGenerator generator = new SoalGenerator(model, compilation.BuildModelObjectToSymbolMap(), outputDirectory, generatorDiagnostics, fileName);
                generator.SeparateXsdWsdl = separateXsdWsdl;
                generator.SingleFileWsdl  = singleFileWsdl;
                generator.Generate();
                SoalPrinter printer = new SoalPrinter(model.Symbols);
                using (StreamWriter writer = new StreamWriter(fileName + "0"))
                {
                    writer.WriteLine(printer.Generate());
                }
            }
            DiagnosticFormatter formatter = new DiagnosticFormatter();

            foreach (var diagnostic in compilation.GetDiagnostics())
            {
                string msg = formatter.Format(diagnostic);
                Console.WriteLine(msg);
            }
            foreach (var diagnostic in generatorDiagnostics.AsEnumerable())
            {
                string msg = formatter.Format(diagnostic);
                Console.WriteLine(msg);
            }
        }
        internal static IEnumerable <string> Convert(IEnumerable <Diagnostic> diagnostics)
        {
            var formatter = new DiagnosticFormatter();

            return(diagnostics.Select(d => formatter.Format(d)).ToList());
        }
Exemple #26
0
 public PhpCompiler(CommandLineParser parser, string responseFile, string[] args, BuildPaths buildPaths, string additionalReferenceDirectories, IAnalyzerAssemblyLoader analyzerLoader)
     : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader)
 {
     _tempDirectory       = buildPaths.TempDirectory;
     _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths);
 }
        internal string GetErrorMessageAndMissingAssemblyIdentities(DiagnosticBag diagnostics, DiagnosticFormatter formatter, CultureInfo preferredUICulture, AssemblyIdentity linqLibrary, out bool useReferencedModulesOnly, out ImmutableArray <AssemblyIdentity> missingAssemblyIdentities)
        {
            var errors = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error);

            foreach (var error in errors)
            {
                missingAssemblyIdentities = this.GetMissingAssemblyIdentities(error, linqLibrary);
                if (!missingAssemblyIdentities.IsDefault)
                {
                    break;
                }
            }

            if (missingAssemblyIdentities.IsDefault)
            {
                missingAssemblyIdentities = ImmutableArray <AssemblyIdentity> .Empty;
            }

            useReferencedModulesOnly = errors.All(HasDuplicateTypesOrAssemblies);

            var firstError = errors.FirstOrDefault();

            Debug.Assert(firstError != null);

            var simpleMessage = firstError as SimpleMessageDiagnostic;

            return((simpleMessage != null) ?
                   simpleMessage.GetMessage() :
                   formatter.Format(firstError, preferredUICulture ?? CultureInfo.CurrentUICulture));
        }
Exemple #28
0
        public async Task SetSource(string value)
        {
            CancellationToken token;

            await _lock.WaitAsync();

            try
            {
                _cancellationTokenSource?.Cancel();
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = new CancellationTokenSource();
                token   = _cancellationTokenSource.Token;
                _source = value;
            }
            finally
            {
                _lock.Release();
            }


            var result = await EditorEngine.CompileAndRun(_source, token);

            token.ThrowIfCancellationRequested();

            await _lock.WaitAsync();

            try
            {
                EmittedCSharp = result.EmittedCSharp;
                Result        = result.RunResult;
                Diagnostics   = result.Diagnostics;
                RuntimeError  = result.RuntimeError;

                await JsRuntime.InvokeVoidAsync("annotate", Diagnostics.EmptyIfDefault().Select(x =>
                {
                    var(startRow, startColumn, endRow, endColumn) = x.Location.TextRange;
                    return(new AceDiagnostic(startRow - 1, startColumn, endRow - 1, endColumn, DiagnosticFormatter.CreateDiagnosticMessage(x)));
                }));
            }
            finally
            {
                _lock.Release();
            }

            token.ThrowIfCancellationRequested();
            StateHasChanged();
        }