Example #1
0
        private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, TestEmitters emitOptions = TestEmitters.All, CSharpCompilationOptions compOptions = null)
        {
            SynchronizationContext.SetSynchronizationContext(null);

            var compilation = this.CreateCompilation(source, references: references, compOptions: compOptions);
            return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: emitOptions);
        }
Example #2
0
 private CompilationVerifier CompileAndVerifyRef(
     string source,
     string expectedOutput = null,
     MetadataReference[] additionalRefs = null,
     IEnumerable<ModuleData> dependencies = null,
     Action<ModuleSymbol> sourceSymbolValidator = null,
     Action<PEAssembly> assemblyValidator = null,
     Action<ModuleSymbol> symbolValidator = null,
     SignatureDescription[] expectedSignatures = null,
     CSharpCompilationOptions options = null,
     bool verify = true)
 {
     return CompileAndVerifyExperimental(
         source,
         MessageID.IDS_FeatureRefLocalsReturns,
         expectedOutput,
         additionalRefs,
         dependencies,
         sourceSymbolValidator,
         assemblyValidator,
         symbolValidator,
         expectedSignatures,
         options,
         verify);
 }
        private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory)
        {
            var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ?
                OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary;
            var options = new CSharpCompilationOptions(outputKind);

            string platformValue = compilerOptions.Platform;
            bool allowUnsafe = compilerOptions.AllowUnsafe ?? false;
            bool optimize = compilerOptions.Optimize ?? false;
            bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false;

            Platform platform;
            if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform))
            {
                platform = Platform.AnyCpu;
            }

            options = options
                        .WithAllowUnsafe(allowUnsafe)
                        .WithPlatform(platform)
                        .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
                        .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug);

            return AddSigningOptions(options, compilerOptions, projectDirectory);
        }
Example #4
0
        private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null)
        {
            SynchronizationContext.SetSynchronizationContext(null);

            var compilation = CreateCompilation(source, references: references, options: options);
            return base.CompileAndVerify(compilation, expectedOutput: expectedOutput);
        }
        public void Test1()
        {
            var test = @"
class C
{
    public void M()
    {
    }
}";
            var expected = new DiagnosticResult
            {
                Id = DiagnosticIds.CompilationAnalyzerRuleId,
                Message = string.Format(Resources.CompilationAnalyzerMessageFormat, DiagnosticIds.SymbolAnalyzerRuleId),
                Severity = DiagnosticSeverity.Warning
            };

            var specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Error);

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication,
                specificDiagnosticOptions: new[]{ specificOption });
            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions);

            specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Suppress);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(new[] { specificOption });
            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions, expected: expected);
        }
        public MyScriptCompiler()
        {
            AddReferencedAssemblies(
                this.GetType().Assembly.Location,
                typeof(int).Assembly.Location,
                typeof(System.Xml.XmlEntity).Assembly.Location,
                typeof(System.Collections.Generic.HashSet<>).Assembly.Location,
                typeof(System.Uri).Assembly.Location
                );

            AddImplicitIngameNamespacesFromTypes(
                typeof(System.Object),
                typeof(System.Text.StringBuilder),
                typeof(System.Collections.IEnumerable),
                typeof(System.Collections.Generic.IEnumerable<>)
                );

            AddUnblockableIngameExceptions(typeof(ScriptOutOfRangeException));

            m_debugCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, platform: Platform.X64);
            m_runtimeCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, platform: Platform.X64);
            m_whitelist = new MyScriptWhitelist(this);
            m_ingameWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.Ingame);
            m_modApiWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.ModApi);
            m_conditionalParseOptions = new CSharpParseOptions();
        }
        protected Assembly CompileExtensions(string toolsDirectory, string assemblyFileName, IEnumerable<string> sourceFileNames)
        {
            Console.WriteLine("Compiling extensions...");

            var syntaxTrees = sourceFileNames.Select(File.ReadAllText).Select(code => CSharpSyntaxTree.ParseText(code)).ToList();

            var references = AppDomain.CurrentDomain.GetAssemblies().Select(assembly => MetadataReference.CreateFromFile(assembly.Location)).ToList();

            // todo: add references from scconfig.json
            references.Add(MetadataReference.CreateFromFile(typeof(XDocument).Assembly.Location)); // add System.Xml.Linq assembly

            Directory.CreateDirectory(Path.GetDirectoryName(assemblyFileName) ?? string.Empty);

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(Path.GetFileNameWithoutExtension(assemblyFileName), syntaxTrees, references, options);

            EmitResult result;
            using (var stream = new FileStream(assemblyFileName, FileMode.Create))
            {
                result = compilation.Emit(stream);
            }

            if (result.Success)
            {
                return Assembly.LoadFrom(assemblyFileName);
            }

            var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
            foreach (var diagnostic in failures)
            {
                Console.WriteLine(@"scc.cmd(0,0): {0} {1}: {2}", diagnostic.Severity, diagnostic.Id, diagnostic.GetMessage());
            }

            return null;
        }
 private CSharpSerializableCompilationOptions(SerializationInfo info, StreamingContext context)
 {
     _options = new CSharpCompilationOptions(
         outputKind: (OutputKind)info.GetInt32(OutputKindString),
         moduleName: info.GetString(ModuleNameString),
         mainTypeName: info.GetString(MainTypeNameString),
         scriptClassName: info.GetString(ScriptClassNameString),
         usings: (string[])info.GetValue(UsingsString, typeof(string[])),
         cryptoKeyContainer: info.GetString(CryptoKeyContainerString),
         cryptoKeyFile: info.GetString(CryptoKeyFileString),
         delaySign: (bool?)info.GetValue(DelaySignString, typeof(bool?)),
         optimizationLevel: (OptimizationLevel)info.GetInt32(OptimizeString),
         checkOverflow: info.GetBoolean(CheckOverflowString),
         allowUnsafe: info.GetBoolean(AllowUnsafeString),
         platform: (Platform)info.GetInt32(PlatformString),
         generalDiagnosticOption: (ReportDiagnostic)info.GetInt32(GeneralDiagnosticOptionString),
         warningLevel: info.GetInt32(WarningLevelString),
         specificDiagnosticOptions: ((Dictionary<string, ReportDiagnostic>)info.GetValue(SpecificDiagnosticOptionsString, typeof(Dictionary<string, ReportDiagnostic>))).ToImmutableDictionary(),
         concurrentBuild: info.GetBoolean(ConcurrentBuildString),
         extendedCustomDebugInformation: info.GetBoolean(ExtendedCustomDebugInformationString),
         xmlReferenceResolver: XmlFileResolver.Default,
         sourceReferenceResolver: SourceFileResolver.Default,
         metadataReferenceResolver: new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default),
         assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
         strongNameProvider: new DesktopStrongNameProvider(),
         metadataImportOptions: (MetadataImportOptions)info.GetByte(MetadataImportOptionsString),
         features: ((string[])info.GetValue(FeaturesString, typeof(string[]))).AsImmutable());
 }
        public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
        {
            var options = new CSharpParseOptions(_languageVersion);
            trees = files.Select(x =>
            {
                var text = x.Value;
                var tree = CSharpSyntaxTree.ParseText(text, options: options);
                if (tree.GetDiagnostics().Any())
                    throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
                return tree;
            }).ToArray();

            // adding everything is going to cause issues with dynamic assemblies
            // so we would want to filter them anyway... but we don't need them really
            //var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
            // though that one is not ok either since we want our own reference
            //var refs = Enumerable.Empty<MetadataReference>();
            // so use the bare minimum
            var asms = ReferencedAssemblies;
            var a1 = typeof(Builder).Assembly;
            asms.Add(a1);
            foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
            var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(
                assemblyName,
                /*syntaxTrees:*/ trees,
                /*references:*/ refs,
                compilationOptions);

            return compilation;
        }
        public static Assembly CreateTestAssembly(List<SyntaxTree> syntaxTrees)
        {
            var systemAssemblyLocation = typeof(object).GetTypeInfo().Assembly.Location;
            var systemDirectory = Directory.GetParent(systemAssemblyLocation);

            var assemblyName = Path.GetRandomFileName();
            var metadataReferences = new List<MetadataReference>
            {
                MetadataReference.CreateFromFile(systemAssemblyLocation),
                MetadataReference.CreateFromFile(typeof(CommandModule).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(systemDirectory.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
                MetadataReference.CreateFromFile(systemDirectory.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll")
            };

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, compilationOptions);

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

                if (!result.Success)
                {
                    throw new Exception(string.Join("\n", result.Diagnostics.Select(x => x.GetMessage())));
                }

                assemblyStream.Seek(0, SeekOrigin.Begin);
                return LoadAssembly(assemblyStream);
            }
        }
        /// <summary>
        /// Gets a dispatcher for the provided <paramref name="actors"/>.
        /// </summary>
        /// <param name="actors">
        /// The actors.
        /// </param>
        /// <param name="source">
        /// The generated source code.
        /// </param>
        /// <returns>
        /// A dispatcher for the provided <paramref name="actors"/>.
        /// </returns>
        /// <exception cref="CodeGenerationException">
        /// A code generation error occurred.
        /// </exception>
        public static IEventDispatcher GetDispatcher(IList<ActorDescription> actors, out string source)
        {
            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                    .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
                    .Select(MetadataReference.CreateFromAssembly)
                    .ToArray();

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var syntax = GenerateCompilationUnit(actors).NormalizeWhitespace();
            source = syntax.ToFullString();

            var compilation =
                CSharpCompilation.Create("CodeGen_" + ClassSuffix + DateTime.UtcNow.Ticks.ToString("X") + ".dll")
                    .AddSyntaxTrees(GenerateCompilationUnit(actors).SyntaxTree)
                    .AddReferences(assemblies)
                    .WithOptions(options);

            Assembly compiledAssembly;
            using (var stream = new MemoryStream())
            {
                var compilationResult = compilation.Emit(stream);
                if (!compilationResult.Success)
                {
                    throw new CodeGenerationException(
                        string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString())));
                }

                compiledAssembly = Assembly.Load(stream.GetBuffer());
            }

            var dispatcher = compiledAssembly.GetTypes().Single(typeof(IEventDispatcher).IsAssignableFrom);
            return (IEventDispatcher)Activator.CreateInstance(dispatcher);
        }
 private CSharpSerializableCompilationOptions(SerializationInfo info, StreamingContext context)
 {
     this.options = new CSharpCompilationOptions(
         outputKind: (OutputKind)info.GetInt32(OutputKindString),
         moduleName: info.GetString(ModuleNameString),
         mainTypeName: info.GetString(MainTypeNameString),
         scriptClassName: info.GetString(ScriptClassNameString),
         usings: (string[])info.GetValue(UsingsString, typeof(string[])),
         cryptoKeyContainer: info.GetString(CryptoKeyContainerString),
         cryptoKeyFile: info.GetString(CryptoKeyFileString),
         delaySign: (bool?)info.GetValue(DelaySignString, typeof(bool?)),
         optimizationLevel: (OptimizationLevel)info.GetInt32(OptimizeString),
         checkOverflow: info.GetBoolean(CheckOverflowString),
         allowUnsafe: info.GetBoolean(AllowUnsafeString),
         fileAlignment: info.GetInt32(FileAlignmentString),
         baseAddress: info.GetUInt64(BaseAddressString),
         platform: (Platform)info.GetInt32(PlatformString),
         generalDiagnosticOption: (ReportDiagnostic)info.GetInt32(GeneralDiagnosticOptionString),
         warningLevel: info.GetInt32(WarningLevelString),
         specificDiagnosticOptions: ((Dictionary<string, ReportDiagnostic>)info.GetValue(SpecificDiagnosticOptionsString, typeof(Dictionary<string, ReportDiagnostic>))).ToImmutableDictionary(),
         highEntropyVirtualAddressSpace: info.GetBoolean(HighEntropyVirtualAddressSpaceString),
         subsystemVersion: SubsystemVersion.Create(info.GetInt32(SubsystemVersionMajorString), info.GetInt32(SubsystemVersionMinorString)),
         runtimeMetadataVersion: info.GetString(RuntimeMetadataVersionString),
         concurrentBuild: info.GetBoolean(ConcurrentBuildString),
         xmlReferenceResolver: XmlFileResolver.Default,
         sourceReferenceResolver: SourceFileResolver.Default,
         metadataReferenceResolver: MetadataFileReferenceResolver.Default,
         metadataReferenceProvider: MetadataFileReferenceProvider.Default,
         assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
         strongNameProvider: new DesktopStrongNameProvider(),
         metadataImportOptions: (MetadataImportOptions)info.GetByte(MetadataImportOptionsString),
         features: ((string[])info.GetValue(FeaturesString, typeof(string[]))).AsImmutable());
 }
        internal static AssemblySymbol[] GetSymbolsForReferences(
            CSharpCompilation[] compilations = null,
            byte[][] bytes = null,
            MetadataReference[] mrefs = null,
            CSharpCompilationOptions options = null)
        {
            var refs = new List<MetadataReference>();

            if (compilations != null)
            {
                foreach (var c in compilations)
                {
                    refs.Add(new CSharpCompilationReference(c));
                }
            }

            if (bytes != null)
            {
                foreach (var b in bytes)
                {
                    refs.Add(new MetadataImageReference(b.AsImmutableOrNull()));
                }
            }

            if (mrefs != null)
            {
                refs.AddRange(mrefs);
            }

            var tc1 = CSharpCompilation.Create(assemblyName: "Dummy", options: options ?? TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[0], references: refs);

           return (from @ref in refs select tc1.GetReferencedAssemblySymbol(@ref)).ToArray();
        }
Example #14
0
        /// <summary>
        /// Generates and compiles an assembly for the provided grains.
        /// </summary>
        /// <param name="generatedSyntax">
        /// The generated code.
        /// </param>
        /// <param name="assemblyName">
        /// The name for the generated assembly.
        /// </param>
        /// <returns>
        /// The raw assembly.
        /// </returns>
        /// <exception cref="CodeGenerationException">
        /// An error occurred generating code.
        /// </exception>
        public static byte[] CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName)
        {
            // Add the generated code attribute.
            var code = AddGeneratedCodeAttribute(generatedSyntax);

            // Reference everything which can be referenced.
            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                    .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
                    .Select(asm => MetadataReference.CreateFromFile(asm.Location))
                    .Cast<MetadataReference>()
                    .ToArray();
            var logger = TraceLogger.GetLogger("CodeGenerator");

            // Generate the code.
            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            string source = null;
            if (logger.IsVerbose3)
            {
                source = GenerateSourceCode(code);

                // Compile the code and load the generated assembly.
                if (logger.IsVerbose3)
                {
                    logger.LogWithoutBulkingAndTruncating(
                        Severity.Verbose3,
                        ErrorCode.CodeGenSourceGenerated,
                        "Generating assembly {0} with source:\n{1}",
                        assemblyName,
                        source);
                }
            }
            
            var compilation =
                CSharpCompilation.Create(assemblyName)
                    .AddSyntaxTrees(code.SyntaxTree)
                    .AddReferences(assemblies)
                    .WithOptions(options);
            using (var stream = new MemoryStream())
            {
                var compilationResult = compilation.Emit(stream);
                if (!compilationResult.Success)
                {
                    source = source ?? GenerateSourceCode(code);
                    var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString()));
                    logger.Warn(
                        ErrorCode.CodeGenCompilationFailed,
                        "Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}",
                        assemblyName,
                        errors,
                        source);
                    throw new CodeGenerationException(errors);
                }
                
                logger.Verbose(ErrorCode.CodeGenCompilationSucceeded, "Compilation of assembly {0} succeeded.", assemblyName);
                return stream.ToArray();
            }
        }
 internal static Compilation CreateCompilation(string source, MetadataReference[] references, string assemblyName, CSharpCompilationOptions options = null)
 {
     return CSharpCompilation.Create(
         assemblyName,
         new[] { SyntaxFactory.ParseSyntaxTree(source) },
         references,
         options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
 }
 public static Task<TestWorkspace> CreateWorkspaceFromFilesAsync(
     string[] files,
     CSharpParseOptions[] parseOptions = null,
     CSharpCompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null)
 {
     return CreateWorkspaceFromFilesAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider);
 }
Example #17
0
 private static CSharpCompilation CreateCompilation(string code, SourceReferenceResolver sourceReferenceResolver = null)
 {
     var options = new CSharpCompilationOptions(
         OutputKind.DynamicallyLinkedLibrary,
         sourceReferenceResolver: sourceReferenceResolver ?? TestSourceReferenceResolver.Default);
     var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Interactive);
     return CreateCompilationWithMscorlib(code, options: options, parseOptions: parseOptions);
 }
Example #18
0
        static void Main(string[] args)
        {
            var someCode = @"using System;

                            namespace SampleDemoApplication
                            {
                                public class Program 
                                {
                                    static void Main(){}

                                    public void Print()
                                    {
                                        Console.WriteLine(""Hello"");
                                    }

                                    public int Add()
                                    {
                                        return 1 + 2;
                                    }
                                }
                            }";

            var syntaxTree = CSharpSyntaxTree.ParseText(someCode);

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
            var compilation = CSharpCompilation.Create("SampleApp", options: compilationOptions)
                                               .AddReferences(new MetadataFileReference(typeof(object).Assembly.Location))
                                               .AddSyntaxTrees(syntaxTree);

            using (var peStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(peStream: peStream, pdbStream: pdbStream);

                    if (result.Success)
                    {
                        var assembly = Assembly.Load(peStream.ToArray(), pdbStream.ToArray());
                        var types = assembly.GetTypes();
                        dynamic instance = Activator.CreateInstance(assembly.GetTypes().First());

                        instance.Print();

                        var addResult = instance.Add();
                        Console.WriteLine(addResult);
                    }
                    else
                    {
                        foreach (var diganostic in result.Diagnostics)
                        {
                            Console.WriteLine(diganostic);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
 /// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
 public static TestWorkspace CreateWorkspaceFromFiles(
     string[] files,
     CSharpParseOptions parseOptions = null,
     CSharpCompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null,
     string[] metadataReferences = null)
 {
     return CreateWorkspaceFromFiles(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider, metadataReferences);
 }
 private static CSharpCompilation CreateCompilationRef(
     string text,
     IEnumerable<MetadataReference> references = null,
     CSharpCompilationOptions options = null,
     string assemblyName = "",
     string sourceFileName = "")
 {
     return CreateCompilationWithMscorlib45(text);
 }
Example #21
0
        private static CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null)
        {
            options = options ?? TestOptions.ReleaseExe;

            IEnumerable<MetadataReference> asyncRefs = new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef };
            references = (references != null) ? references.Concat(asyncRefs) : asyncRefs;

            return CreateCompilationWithMscorlib45(source, options: options, references: references);
        }
Example #22
0
 internal static CSharpCompilation CreateCompilationRef(
     string text,
     IEnumerable<MetadataReference> references = null,
     CSharpCompilationOptions options = null,
     string assemblyName = "",
     string sourceFileName = "")
 {
     return CreateExperimentalCompilationWithMscorlib45(text, MessageID.IDS_FeatureRefLocalsReturns, references, options, assemblyName, sourceFileName);
 }
 public static Task<TestWorkspace> CreateWorkspaceFromFileAsync(
     string file,
     CSharpParseOptions parseOptions = null,
     CSharpCompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null,
     string[] metadataReferences = null)
 {
     return CreateWorkspaceFromFilesAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
 }
        public CSharpSerializableCompilationOptions(CSharpCompilationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            this.options = options;
        }
        public static void Generate(ResourceSource[] sourceFiles, Stream outputStream, AssemblyInfoOptions metadata, string assemblyName, string[] references)
        {
            if (sourceFiles == null)
            {
                throw new ArgumentNullException(nameof(sourceFiles));
            }

            if (outputStream == null)
            {
                throw new ArgumentNullException(nameof(outputStream));
            }

            if (!sourceFiles.Any())
            {
                throw new InvalidOperationException("No source files specified");
            }

            var resourceDescriptions = new List<ResourceDescription>();
            foreach (var resourceInputFile in sourceFiles)
            {
                if (resourceInputFile.Resource.Type == ResourceFileType.Resx)
                {
                    resourceDescriptions.Add(new ResourceDescription(
                        resourceInputFile.MetadataName,
                        () => GenerateResources(resourceInputFile.Resource), true));

                }
                else if (resourceInputFile.Resource.Type == ResourceFileType.Resources)
                {
                    resourceDescriptions.Add(new ResourceDescription(resourceInputFile.Resource.File.Name, () => resourceInputFile.Resource.File.OpenRead(), true));
                }
                else
                {
                    throw new InvalidOperationException("Generation of resource assemblies from dll not supported");
                }
            }

            var compilationOptions = new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(assemblyName,
                references: references.Select(reference => MetadataReference.CreateFromFile(reference)),
                options: compilationOptions);

            compilation = compilation.AddSyntaxTrees(new[]
            {
                CSharpSyntaxTree.ParseText(AssemblyInfoFileGenerator.Generate(metadata, Enumerable.Empty<string>()))
            });

            var result = compilation.Emit(outputStream, manifestResources: resourceDescriptions);
            if (!result.Success)
            {
                foreach (var diagnostic in result.Diagnostics)
                {
                    Reporter.Error.WriteLine(diagnostic.ToString());
                }
                throw new InvalidOperationException("Error occured while emiting assembly");
            }
        }
 public static Task<TestWorkspace> CreateWorkspaceFromLinesAsync(
     string[] lines,
     CSharpParseOptions parseOptions = null,
     CSharpCompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null)
 {
     var file = lines.Join(Environment.NewLine);
     return CreateWorkspaceFromFileAsync(file, parseOptions, compilationOptions, exportProvider);
 }
        public Assembly Compile([NotNull] string toolsDirectory, [NotNull] string assemblyFileName, [NotNull] [ItemNotNull] IEnumerable<string> sourceFileNames)
        {
            // check if assembly is newer than all checkers
            if (File.Exists(assemblyFileName))
            {
                var writeTime = File.GetLastWriteTimeUtc(assemblyFileName);
                if (sourceFileNames.All(f => File.GetLastWriteTimeUtc(f) < writeTime))
                {
                    return Assembly.LoadFrom(assemblyFileName);
                }
            }

            var collectionsFileName = Path.Combine(toolsDirectory, "System.Collections.Immutable.dll");
            if (!File.Exists(collectionsFileName))
            {
                Console.WriteLine(Texts.System_Collections_Immutable_dll_is_missing__Extensions_will_not_be_loaded_);
                return null;
            }

            var codeAnalysisFileName = Path.Combine(toolsDirectory, "Microsoft.CodeAnalysis.dll");
            if (!File.Exists(codeAnalysisFileName))
            {
                Console.WriteLine(Texts.Microsoft_CodeAnalysis_dll_is_missing__Extensions_will_not_be_loaded_);
                return null;
            }

            // compile extensions
            Console.WriteLine(Texts.scc_cmd_0_0___information_SCC0000__Compiling_checkers___);

            var syntaxTrees = sourceFileNames.Select(File.ReadAllText).Select(code => CSharpSyntaxTree.ParseText(code)).ToList();
            var references = AppDomain.CurrentDomain.GetAssemblies().Select(assembly => MetadataReference.CreateFromFile(assembly.Location)).ToList();
            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            Directory.CreateDirectory(Path.GetDirectoryName(assemblyFileName) ?? string.Empty);

            var compilation = CSharpCompilation.Create(Path.GetFileNameWithoutExtension(assemblyFileName), syntaxTrees, references, options);

            EmitResult result;
            using (var stream = new FileStream(assemblyFileName, FileMode.Create))
            {
                result = compilation.Emit(stream);
            }

            if (result.Success)
            {
                return Assembly.LoadFrom(assemblyFileName);
            }

            var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
            foreach (var diagnostic in failures)
            {
                Console.WriteLine(@"scc.cmd(0,0): {0} {1}: {2}", diagnostic.Severity, diagnostic.Id, diagnostic.GetMessage());
            }

            return null;
        }
Example #28
0
        private CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions compOptions = null)
        {
            SynchronizationContext.SetSynchronizationContext(null);

            compOptions = compOptions ?? TestOptions.OptimizedExe;

            IEnumerable<MetadataReference> asyncRefs = new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef };
            references = (references != null) ? references.Concat(asyncRefs) : asyncRefs;

            return CreateCompilationWithMscorlib45(source, compOptions: compOptions, references: references);
        }
        public static void TestSequencePoints(string markup, CSharpCompilationOptions compilationOptions, CSharpParseOptions parseOptions = null, string methodName = "")
        {
            int? position;
            TextSpan? expectedSpan;
            string source;
            MarkupTestFile.GetPositionAndSpan(markup, out source, out position, out expectedSpan);
            var pdb = GetPdbXml(source, compilationOptions, methodName, parseOptions);
            bool hasBreakpoint = CheckIfSpanWithinSequencePoints(expectedSpan.GetValueOrDefault(), source, pdb);

            Assert.True(hasBreakpoint);
        }
Example #30
0
     public void PublicSignWithRelativeKeyPath()
     {
         var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
             .WithPublicSign(true).WithCryptoKeyFile("test.snk");
         var comp = CSharpCompilation.Create("test", options: options);
         comp.VerifyDiagnostics(
 // error CS7088: Invalid 'CryptoKeyFile' value: 'test.snk'.
 Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoKeyFile", "test.snk").WithLocation(1, 1),
 // error CS8102: Public signing was specified and requires a public key, but no public key was specified.
 Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1));
     }
Example #31
0
        public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code)
        {
            CodeAnalysis.SyntaxTree  codeTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code);
            CSharpCompilationOptions options  = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                                             optimizationLevel: OptimizationLevel.Release,
                                                                             generalDiagnosticOption: ReportDiagnostic.Error,
                                                                             reportSuppressedDiagnostics: true);

            List <MetadataReference> references = new List <MetadataReference>();


            foreach (string reference in cp.ReferencedAssemblies)
            {
                references.Add(GetReference(reference));
            }

            if (!cp.ReferencedAssemblies.Contains("netstandard"))
            {
                references.Add(GetReference("netstandard"));
            }

            if (!cp.ReferencedAssemblies.Contains("System.Runtime"))
            {
                references.Add(GetReference("System.Runtime"));
            }

            if (!cp.ReferencedAssemblies.Contains("System.ComponentModel.Primitives"))
            {
                references.Add(GetReference("System.ComponentModel.Primitives"));
            }


            Compilation compilation = CSharpCompilation.Create(
                "_" + Guid.NewGuid().ToString("D"), new SyntaxTree[] { codeTree },
                references: references, options: options
                );



            using (MemoryStream ms = new MemoryStream())
            {
                CodeAnalysis.Emit.EmitResult results = compilation.Emit(ms);
                if (results.Success)
                {
                    return(new CompilerResults()
                    {
                        CompiledAssembly = Assembly.Load(ms.ToArray())
                    });
                }
                else
                {
                    CompilerResults result = new CompilerResults();
                    foreach (Diagnostic d in results.Diagnostics)
                    {
                        result.Errors.Add(new CompilerError()
                        {
                            ErrorText   = d.GetMessage(),
                            ErrorNumber = d.Id,
                            Line        = d.Location.GetLineSpan().StartLinePosition.Line,
                            Column      = d.Location.GetLineSpan().StartLinePosition.Character
                        });
                    }
                    return(result);
                }
            }
        }
        /// <inheritdoc/>
        public byte[] Compile(string code, IEnumerable <string> metadataPropertyKeys)
        {
            _ = code ?? throw new ArgumentNullException(nameof(code));

            // Parse the code
            code = Parse(code, metadataPropertyKeys, _executionState);

            // Get the compilation
            CSharpParseOptions       parseOptions       = new CSharpParseOptions();
            SourceText               sourceText         = SourceText.From(code, Encoding.UTF8);
            SyntaxTree               syntaxTree         = CSharpSyntaxTree.ParseText(sourceText, parseOptions, AssemblyName);
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).
                                                          WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic>
            {
                // ensure that specific warnings about assembly references are always suppressed
                // https://github.com/dotnet/roslyn/issues/5501
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress },

                // we don't care about unreachable code
                { "CS0162", ReportDiagnostic.Suppress },
            });

            // For some reason, Roslyn really wants these added by filename
            // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime
            string            assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            CSharpCompilation compilation  = CSharpCompilation.Create(
                AssemblyName,
                new[] { syntaxTree },
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !string.IsNullOrEmpty(x.Location))
                .Select(x => MetadataReference.CreateFromFile(x.Location)), compilationOptions)
                                             .AddReferences(
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")));

            // Emit the assembly
            ILogger logger = _executionState.Services.GetRequiredService <ILogger <ScriptHelper> >();

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

                // Log warnings
                List <string> warningMessages = result.Diagnostics
                                                .Where(x => x.Severity == DiagnosticSeverity.Warning)
                                                .Select(GetCompilationErrorMessage)
                                                .ToList();
                if (warningMessages.Count > 0)
                {
                    logger.LogWarning(
                        "{0} warnings compiling script:{1}{2}",
                        warningMessages.Count,
                        Environment.NewLine,
                        string.Join(Environment.NewLine, warningMessages));
                }

                // Log errors
                List <string> errorMessages = result.Diagnostics
                                              .Where(x => x.Severity == DiagnosticSeverity.Error)
                                              .Select(GetCompilationErrorMessage)
                                              .ToList();
                if (errorMessages.Count > 0)
                {
                    logger.LogError(
                        "{0} errors compiling script:{1}{2}",
                        errorMessages.Count,
                        Environment.NewLine,
                        string.Join(Environment.NewLine, errorMessages));
                }

                // Throw for errors or not success
                if (!result.Success || errorMessages.Count > 0)
                {
                    throw new ScriptCompilationException(errorMessages);
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(ms.ToArray());
            }
        }
Example #33
0
        /// <summary>
        /// Generates and compiles an assembly for the provided syntax.
        /// </summary>
        /// <param name="generatedSyntax">
        /// The generated code.
        /// </param>
        /// <param name="assemblyName">
        /// The name for the generated assembly.
        /// </param>
        /// <param name="emitDebugSymbols">
        /// Whether or not to emit debug symbols for the generated assembly.
        /// </param>
        /// <param name="logger"> logger to use </param>
        /// <returns>
        /// The raw assembly.
        /// </returns>
        /// <exception cref="CodeGenerationException">
        /// An error occurred generating code.
        /// </exception>
        private Assembly CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName, bool emitDebugSymbols)
        {
            // Add the generated code attribute.
            var code = CodeGeneratorCommon.AddGeneratedCodeAttribute(generatedSyntax);

            // Reference everything which can be referenced.
            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
                .Select(asm => MetadataReference.CreateFromFile(asm.Location))
                .Cast <MetadataReference>()
                .ToArray();

            // Generate the code.
            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

#if NETSTANDARD2_0
            // CoreFX bug https://github.com/dotnet/corefx/issues/5540
            // to workaround it, we are calling internal WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)
            // TODO: this API will be public in the future releases of Roslyn.
            // This work is tracked in https://github.com/dotnet/roslyn/issues/5855
            // Once it's public, we should replace the internal reflection API call by the public one.
            var method = typeof(CSharpCompilationOptions).GetMethod("WithTopLevelBinderFlags", BindingFlags.NonPublic | BindingFlags.Instance);
            // we need to pass BinderFlags.IgnoreCorLibraryDuplicatedTypes, but it's an internal class
            // http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Binder/BinderFlags.cs,00f268571bb66b73
            options = (CSharpCompilationOptions)method.Invoke(options, new object[] { 1u << 26 });
#endif

            string source = null;
            if (this.logger.IsEnabled(LogLevel.Debug))
            {
                source = CodeGeneratorCommon.GenerateSourceCode(code);

                // Compile the code and load the generated assembly.
                this.logger.Debug(
                    ErrorCode.CodeGenSourceGenerated,
                    "Generating assembly {0} with source:\n{1}",
                    assemblyName,
                    source);
            }

            var compilation =
                CSharpCompilation.Create(assemblyName)
                .AddSyntaxTrees(code.SyntaxTree)
                .AddReferences(assemblies)
                .WithOptions(options);

            using (var outputStream = new MemoryStream())
            {
                var emitOptions = new EmitOptions()
                                  .WithEmitMetadataOnly(false)
                                  .WithIncludePrivateMembers(true);

                if (emitDebugSymbols)
                {
                    emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
                }

                var compilationResult = compilation.Emit(outputStream, options: emitOptions);
                if (!compilationResult.Success)
                {
                    source = source ?? CodeGeneratorCommon.GenerateSourceCode(code);
                    var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString()));
                    this.logger.Warn(
                        ErrorCode.CodeGenCompilationFailed,
                        "Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}",
                        assemblyName,
                        errors,
                        source);
                    throw new CodeGenerationException(errors);
                }

                this.logger.Debug(
                    ErrorCode.CodeGenCompilationSucceeded,
                    "Compilation of assembly {0} succeeded.",
                    assemblyName);
                return(Assembly.Load(outputStream.ToArray()));
            }
        }
Example #34
0
        internal static Assembly Generate(List <Model> models, string cacheAssemblyInDir)
        {
            if (!Directory.Exists(cacheAssemblyInDir))
            {
                Directory.CreateDirectory(cacheAssemblyInDir);
            }

            // see if the models have changed
            var assemblyFileName = "models.dll";
            var assemblyFile     = Path.Combine(cacheAssemblyInDir, assemblyFileName);
            var modelsJsonFile   = Path.Combine(cacheAssemblyInDir, "models.json");
            var modelsJson       = models.ToJson();

            if (File.Exists(assemblyFile) && File.Exists(modelsJsonFile))
            {
                if (File.ReadAllText(modelsJsonFile).Equals(modelsJson))
                {
                    return(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile));
                }
            }

            var modelCode = modelCodeFormat.Replace("{", "{{").Replace("}", "}}").Replace("{{{{", "{").Replace("}}}}", "}");
            var sb        = new StringBuilder();

            foreach (var model in models)
            {
                sb.AppendLine(string.Format(modelCode,
                                            model.Singular,
                                            model.Plural,
                                            model.Slug.Trim('/'),
                                            string.Join("\n", model.Fields.Map(s => "public " + s.Type + " " + s.Name + " { get; set; }"))));
            }

            var nsCode = codeFormat.Replace("{", "{{").Replace("}", "}}").Replace("{{{{", "{").Replace("}}}}", "}");
            var code   = string.Format(nsCode, sb.ToString(), typeof(CodeGenerator).Namespace);
            var tree   = SyntaxFactory.ParseSyntaxTree(code);

            var requiredAssemblies = new List <string>
            {
                Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").Location,
                typeof(object).GetTypeInfo().Assembly.Location,
                typeof(Attribute).GetTypeInfo().Assembly.Location,
                typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).GetTypeInfo().Assembly.Location,
                typeof(System.Linq.Expressions.Expression).GetTypeInfo().Assembly.Location,
                typeof(ServiceStack.AppHostBase).GetTypeInfo().Assembly.Location,
                typeof(ServiceStack.RouteAttribute).GetTypeInfo().Assembly.Location,
                typeof(ServiceStack.Data.DbConnectionFactory).GetTypeInfo().Assembly.Location,
                typeof(ServiceStack.Configuration.IResolver).GetTypeInfo().Assembly.Location,
                typeof(ServiceStack.OrmLite.OrmLiteConnection).GetTypeInfo().Assembly.Location,
                typeof(CodeGenerator).GetTypeInfo().Assembly.Location,
            };

            var projectReferences = typeof(CodeGenerator).GetTypeInfo().Assembly.GetReferencedAssemblies();

            foreach (var ssr in projectReferences)
            {
                var asm  = AssemblyLoadContext.Default.LoadFromAssemblyName(ssr);
                var asml = asm?.Location;
                if (asml != null && File.Exists(asml))
                {
                    requiredAssemblies.AddIfNotExists(asml);
                }
            }
            var requiredAssemblyReferences = requiredAssemblies.Map(r => MetadataReference.CreateFromFile(r));

            // A single, immutable invocation to the compiler to produce a library
            var options     = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(assemblyFileName)
                              .WithOptions(options)
                              .AddReferences(requiredAssemblyReferences)
                              .AddSyntaxTrees(tree);

            if (File.Exists(assemblyFile))
            {
                File.Delete(assemblyFile);
            }
            var compilationResult = compilation.Emit(assemblyFile);

            if (compilationResult.Success)
            {
                // Cache the models json
                File.WriteAllText(modelsJsonFile, modelsJson);
                // Load the assembly
                return(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile));
            }
            else
            {
                foreach (Diagnostic codeIssue in compilationResult.Diagnostics)
                {
                    string issue = $@"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()},
                        Location: {codeIssue.Location.GetLineSpan()},
                        Severity: {codeIssue.Severity}";
                    Console.WriteLine(issue);
                }
                return(null);
            }

            // OR IN MEMORY
            // compilation = CSharpCompilation.Create(Guid.NewGuid().ToString("N"))
            //     .WithOptions(options)
            //     .AddReferences(requiredAssemblyReferences)
            //     .AddSyntaxTrees(tree);
            // using (var ms = new MemoryStream())
            // {
            //     var compilationResult2 = compilation.Emit(ms);
            //     if (compilationResult2.Success)
            //     {
            //         ms.Position = 0;
            //         return AssemblyLoadContext.Default.LoadFromStream(ms);
            //     }
            //     else
            //     {
            //         foreach (Diagnostic codeIssue in compilationResult2.Diagnostics)
            //         {
            //             string issue = $@"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()},
            //                 Location: {codeIssue.Location.GetLineSpan()},
            //                 Severity: {codeIssue.Severity}";
            //             Console.WriteLine(issue);
            //         }
            //         return null;
            //     }
            // }
        }
Example #35
0
        public static void Compile()
        {
            var testTree = CSharpSyntaxTree.ParseText(@"
using System;
using ExternalLibrary;

namespace test{

    public class Power
    {

        public void power(int number)
        { 
            new ExternalClass().Print(number * number);
        } 

    }

}");

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            options = options.WithAssemblyIdentityComparer(AssemblyIdentityComparer.Default);

            var references = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").Location),
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ExternalLibrary.dll"))
            };

            if (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is string trustedAssemblies)
            {
                Console.WriteLine(trustedAssemblies);
                references.AddRange(
                    trustedAssemblies.Split(Path.PathSeparator).Select(path =>
                                                                       MetadataReference.CreateFromFile(path))
                    );
            }

            var compilation = CSharpCompilation.Create("DummyAssembly", options: options, references: references)
                              .AddSyntaxTrees(testTree);

            using (var stream = new MemoryStream())
            {
                var compilationResult = compilation.Emit(stream);

                if (!compilationResult.Success)
                {
                    Console.WriteLine(string.Join("\n", compilationResult.Diagnostics.Select(d => d.GetMessage())));
                }
                else
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var assembly = Assembly.Load(stream.ToArray());
                    var type     = assembly.GetType("test.Power");
                    var power    = Activator.CreateInstance(type);
                    type.InvokeMember("power", BindingFlags.Default | BindingFlags.InvokeMethod, null, power, new object[] { 2 });
                }
            }
        }
        protected async Task <Diagnostic[]> GetSortedDiagnosticsFromDocumentsAsync(AnalyzerVerificationContext context, DiagnosticAnalyzer analyzer, Document[] documents, params DiagnosticResult[] expected)
        {
            var projects = new HashSet <Project>();

            foreach (var document in documents)
            {
                projects.Add(document.Project);
            }

            var diagnostics = new List <Diagnostic>();

            foreach (var project in projects)
            {
                var analyzers = ImmutableArray.Create(analyzer)
                                .AddRange(GetRelatedAnalyzers(analyzer));

                var compilation = await project.GetCompilationAsync();

                Assert.NotNull(compilation);

                var optionsProvider = new AnalyzerOptionsProvider(context.Options);
                var options         = new AnalyzerOptions(ImmutableArray <AdditionalText> .Empty, optionsProvider);
                var analyzerOptions = new CompilationWithAnalyzersOptions(options, (e, _, _) => throw e, true, true, true);

                var compilationOptions        = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, reportSuppressedDiagnostics: true);
                var specificDiagnosticOptions = compilationOptions.SpecificDiagnosticOptions;

                // Force all tested diagnostics to be enabled
                foreach (var descriptor in analyzer.SupportedDiagnostics)
                {
                    specificDiagnosticOptions = specificDiagnosticOptions.SetItem(descriptor.Id, ReportDiagnostic.Info);
                }

                var compilationWithAnalyzers = compilation
                                               .WithOptions(compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions))
                                               .WithAnalyzers(analyzers, analyzerOptions);

                var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync();

                var errors = allDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
                foreach (var error in errors)
                {
                    Assert.True(false, $"Line {error.Location.GetLineSpan().StartLinePosition.Line}: {error.GetMessage()}");
                }

                var diags = allDiagnostics
                            .Except(errors)
                            .Where(d => d.Location.IsInSource);             //only keep diagnostics related to a source location

                foreach (var diag in diags)
                {
                    // We should not hit this anymore, but keep in case we change the previous filter
                    if (diag.Location == Location.None || diag.Location.IsInMetadata)
                    {
                        diagnostics.Add(diag);
                    }
                    else
                    {
                        foreach (var document in documents)
                        {
                            var tree = await document.GetSyntaxTreeAsync();

                            if (tree == diag.Location.SourceTree)
                            {
                                diagnostics.Add(diag);
                            }
                        }
                    }
                }
            }

            var results = SortDiagnostics(FilterDiagnostics(diagnostics, context.Filters));

            diagnostics.Clear();
            return(results);
        }
        internal static Task <Compilation> GetCompilationAsync(
            string testFile,
            string caller,
            NullableContextOptions nullableContext,
            bool addCesilReferences = true,
            IEnumerable <string> doNotAddReferences = null
            )
        {
            var trustedAssemblies = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator);
            var systemAssemblies  = trustedAssemblies.Where(p => Path.GetFileName(p).StartsWith("System.")).ToList();

            var references = systemAssemblies.Select(s => MetadataReference.CreateFromFile(s)).ToList();

            var projectName = $"Cesil.Tests.{nameof(SourceGeneratorTestHelper)}";
            var projectId   = ProjectId.CreateNewId(projectName);

            var compilationOptions =
                new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    allowUnsafe: true,
                    nullableContextOptions: nullableContext
                    );

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp9);

            var projectInfo =
                ProjectInfo.Create(
                    projectId,
                    VersionStamp.Create(),
                    projectName,
                    projectName,
                    LanguageNames.CSharp,
                    compilationOptions: compilationOptions,
                    parseOptions: parseOptions
                    );

            var workspace = new AdhocWorkspace();

            var solution =
                workspace
                .CurrentSolution
                .AddProject(projectInfo);

            var x = references.Where(r => r.FilePath.Contains("Serialization")).ToList();

            foreach (var reference in references)
            {
                var path = reference.Display ?? "";
                var ix   = path.LastIndexOf('\\');
                if (ix != -1)
                {
                    path = path.Substring(ix + 1);
                }

                var iy = path.LastIndexOf('.');
                if (iy != -1)
                {
                    path = path.Substring(0, iy);
                }

                if (doNotAddReferences?.Contains(path) ?? false)
                {
                    continue;
                }

                solution = solution.AddMetadataReference(projectId, reference);
            }

            var csFile = $"{caller}.cs";
            var docId  = DocumentId.CreateNewId(projectId, csFile);

            var project = solution.GetProject(projectId);

            project = project.AddDocument(csFile, testFile).Project;

            // find the Cesil folder to include code from
            if (addCesilReferences)
            {
                var cesilRef = GetCesilReference();
                project = project.AddMetadataReference(cesilRef);
            }

            var netstandardRef = GetNetStandard20Reference();

            project = project.AddMetadataReference(netstandardRef);

            return(project.GetCompilationAsync());
        }
        /// <summary>
        /// Each .csx file is to be wrapped in its own project.
        /// This recursive function does a depth first traversal of the .csx files, following #load references
        /// </summary>
        private ProjectInfo CreateCsxProject(string csxPath, IScriptServicesBuilder baseBuilder)
        {
            // Circular #load chains are not allowed
            if (Context.CsxFilesBeingProcessed.Contains(csxPath))
            {
                throw new Exception($"Circular refrences among script files are not allowed: {csxPath} #loads files that end up trying to #load it again.");
            }

            // If we already have a project for this path just use that
            if (Context.CsxFileProjects.ContainsKey(csxPath))
            {
                return(Context.CsxFileProjects[csxPath]);
            }

            // Process the file with ScriptCS first
            Logger.LogInformation($"Processing script {csxPath}...");
            Context.CsxFilesBeingProcessed.Add(csxPath);
            var localScriptServices = baseBuilder.ScriptName(csxPath).Build();
            var processResult       = localScriptServices.FilePreProcessor.ProcessFile(csxPath);

            // CSX file usings
            Context.CsxUsings[csxPath] = processResult.Namespaces.ToList();

            var compilationOptions = new CSharpCompilationOptions(
                outputKind: OutputKind.DynamicallyLinkedLibrary,
                usings: Context.CommonUsings.Union(Context.CsxUsings[csxPath]));

            // #r refernces
            Context.CsxReferences[csxPath] = localScriptServices.MakeMetadataReferences(processResult.References).ToList();

            //#load references recursively
            Context.CsxLoadReferences[csxPath] =
                processResult
                .LoadedScripts
                .Distinct()
                .Except(new[] { csxPath })
                .Select(loadedCsxPath => CreateCsxProject(loadedCsxPath, baseBuilder))
                .ToList();

            // Create the wrapper project and add it to the workspace
            Logger.LogDebug($"Creating project for script {csxPath}.");
            var csxFileName = Path.GetFileName(csxPath);
            var project     = ProjectInfo.Create(
                id: ProjectId.CreateNewId(Guid.NewGuid().ToString()),
                version: VersionStamp.Create(),
                name: csxFileName,
                assemblyName: $"{csxFileName}.dll",
                language: LanguageNames.CSharp,
                compilationOptions: compilationOptions,
                parseOptions: CsxParseOptions,
                metadataReferences: Context.CommonReferences.Union(Context.CsxReferences[csxPath]),
                projectReferences: Context.CsxLoadReferences[csxPath].Select(p => new ProjectReference(p.Id)),
                isSubmission: true,
                hostObjectType: typeof(IScriptHost));

            Workspace.AddProject(project);
            AddFile(csxPath, project.Id);

            //----------LOG ONLY------------
            Logger.LogDebug($"All references by {csxFileName}: \n{string.Join("\n", project.MetadataReferences.Select(r => r.Display))}");
            Logger.LogDebug($"All #load projects by {csxFileName}: \n{string.Join("\n", Context.CsxLoadReferences[csxPath].Select(p => p.Name))}");
            Logger.LogDebug($"All usings in {csxFileName}: \n{string.Join("\n", (project.CompilationOptions as CSharpCompilationOptions)?.Usings ?? new ImmutableArray<string>())}");
            //------------------------------

            // Traversal administration
            Context.CsxFileProjects[csxPath] = project;
            Context.CsxFilesBeingProcessed.Remove(csxPath);

            return(project);
        }
Example #39
0
 public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected)
 {
     options.Errors.Verify(expected);
 }
    /// <summary>
    /// 编译dll
    /// </summary>
    /// <param name="rootpaths"></param>
    /// <param name="output"></param>
    static public bool BuildByRoslyn(string[] dlls, string[] codefiles, string output, bool isdebug = false,bool isUseDefine =false)
    {
        if (Application.platform == RuntimePlatform.OSXEditor)
        {
            for (int i = 0; i < dlls.Length; i++)
            {
                dlls[i] = dlls[i].Replace("\\", "/");
            }

            for (int i = 0; i < codefiles.Length; i++)
            {
                codefiles[i] = codefiles[i].Replace("\\", "/");
            }

            output = output.Replace("\\", "/");
        }

        //添加语法树
        //宏解析
        var                                     Symbols = defineList;
        List<Microsoft.CodeAnalysis.SyntaxTree> codes   = new List<Microsoft.CodeAnalysis.SyntaxTree>();
        CSharpParseOptions opa = null;
        if (isUseDefine)
        {
            opa = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: Symbols);
        }
        else
        {
            opa= new CSharpParseOptions(LanguageVersion.Latest);
        }
        foreach (var cs in codefiles)
        {
            //判断文件是否存在
            if (!File.Exists(cs)) continue;
            //
            var content    = File.ReadAllText(cs);
            var syntaxTree = CSharpSyntaxTree.ParseText(content, opa, cs, Encoding.UTF8);
            codes.Add(syntaxTree);
        }

        //添加dll
        List<MetadataReference> assemblies = new List<MetadataReference>();
        foreach (var dll in dlls)
        {
            var metaref = MetadataReference.CreateFromFile(dll);
            if (metaref != null)
            {
                assemblies.Add(metaref);
            }
        }

        //创建目录
        var dir = Path.GetDirectoryName(output);
        Directory.CreateDirectory(dir);
        //编译参数
        CSharpCompilationOptions option = null;
        if (isdebug)
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Debug, warningLevel: 4,
                                                  allowUnsafe: true);
        }
        else
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Release, warningLevel: 4,
                                                  allowUnsafe: true);
        }

        //创建编译器代理
        var        assemblyname = Path.GetFileNameWithoutExtension(output);
        var        compilation  = CSharpCompilation.Create(assemblyname, codes, assemblies, option);
        EmitResult result       = null;
        if (!isdebug)
        {
            result = compilation.Emit(output);
        }
        else
        {
            var pdbPath = output + ".pdb";
            var emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb,
                                              pdbFilePath: pdbPath);
            using (var dllStream = new MemoryStream())
            using (var pdbStream = new MemoryStream())
            {
                result = compilation.Emit(dllStream, pdbStream, options: emitOptions);

                File.WriteAllBytes(output, dllStream.GetBuffer());
                File.WriteAllBytes(pdbPath, pdbStream.GetBuffer());
            }
        }

        // 编译失败,提示
        if (!result.Success)
        {
            IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                            diagnostic.IsWarningAsError ||
                                                                            diagnostic.Severity ==
                                                                            DiagnosticSeverity.Error);

            foreach (var diagnostic in failures)
            {
                Debug.LogError(diagnostic.ToString());
            }
        }

        return result.Success;
    }
Example #41
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime applicationLifetime)
        {
            //app.UseDeveloperExceptionPage();

            // force instantiation on singletons

            {
                var pmInst = app.ApplicationServices.GetService <PluginLoader>();

                CommonNotificationThread.Instance = app.ApplicationServices.GetService <CommonNotificationThread>();

                BackgroundThreadPluginManager.Instance = app.ApplicationServices.GetService <BackgroundThreadPluginManager>();
                WorkerMonitor.Instance         = app.ApplicationServices.GetService <WorkerMonitor>();
                RealtimeMonitor.Instance       = app.ApplicationServices.GetService <RealtimeMonitor>();
                BackgroundTaskMonitor.Instance = app.ApplicationServices.GetService <BackgroundTaskMonitor>();

                ConnectionStringSecurity.Instance = app.ApplicationServices.GetService <ConnectionStringSecurity>();

                DotNetCoreCounterListener.Instance = app.ApplicationServices.GetService <DotNetCoreCounterListener>();
                DotNetCoreCounterListener.Instance.Start();


                {// More app startup stuff...but have a dependency on the singleton objects above. Can we move this somewhere else?
                    Log.Information("Initialising project object model");
                    // we can only initialise the Project structure once ConnectionStringSecurity exists
                    Settings.SettingsInstance.Instance.ProjectList.ForEach(p => p.AfterDeserializationInit());

                    Log.Information("Initialising plugin loader");
                    PluginLoader.Instance = pmInst;
                    PluginLoader.Instance.InitAsync().GetAwaiter().GetResult();

                    ServerMethodManager.RebuildCacheForAllApps();

                    Log.Information("Starting work spawner.");
                    WorkSpawner.Start();
                }
            }

            applicationLifetime.ApplicationStopped.Register(() =>
            {
                Log.Information("Application stopped");
            });

            applicationLifetime.ApplicationStopping.Register(() =>
            {
                Log.Information("Application is shutting down");
            });


            // app.Use(async (httpContext, next) =>
            // {
            //     //if (httpContext.Request.Path.Value.Contains("api/") && httpContext.Request.Method == "OPTIONS")
            //     if (httpContext.Request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
            //     {
            //         httpContext.Response.Headers.Add("Access-Control-Max-Age", "600");
            //        // return;
            //     }
            //     await next();
            // });

            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024,
            };


            app.UseWebSockets(webSocketOptions);
            app.UseCors("CorsPolicy");


            // SPA (angular) route fallback
            app.Use(async(context, next) =>
            {
                await next();

                if (context.Response.StatusCode == 404 &&
                    !Path.HasExtension(context.Request.Path.Value) &&
                    !(context.Request.Path.Value?.ToLower().StartsWith("/api/") ?? false))
                {
                    context.Request.Path        = "/index.html";
                    context.Response.StatusCode = 200;

                    await next();
                }
            });


            /*****
             *          var mirrorSharpOptions = new MirrorSharpOptions()
             *          {
             *              SelfDebugEnabled = true,
             *              IncludeExceptionDetails = true,
             *              //SetOptionsFromClient = SetOptionsFromClientExtension()
             *              // CSharp = {
             *              //             MetadataReferences = ImmutableList.Create<MetadataReference>(all),
             *              //             CompilationOptions = compilationOptions
             *              //          },
             *              ExceptionLogger = new MirrorSharpExceptionLogger()
             *          }.SetupCSharp(cs =>
             *          {
             *              //cs.MetadataReferences = cs.MetadataReferences.Clear();
             *              //cs.AddMetadataReferencesFromFiles(all);
             *              cs.MetadataReferences = ImmutableList.Create<MetadataReference>(all);
             *              cs.CompilationOptions = compilationOptions;
             *
             *          });
             *
             *
             *          app.UseMirrorSharp(mirrorSharpOptions);
             */
            app.UseDefaultFiles();
            app.UseStaticFiles();

            // TODO: This outputs full request detail into log. Perhaps consider outputting this to a different detailed log
            //app.UseSerilogRequestLogging();
            app.UseSerilogRequestLogging(options =>
            {
                options.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                // Customize the message template
                //HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms
                options.MessageTemplate = "Req/Res: {ReqLen,7} {ResLen,7} {StatusCode} {Elapsed,7:0} ms {RequestMethod,4} {RequestPath}";

                //options.GetLevel = (httpContext, elapsed, ex) => Serilog.Events.LogEventLevel.Warning;


                // Attach additional properties to the request completion event
                options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                {
                    diagnosticContext.Set("ResLen", httpContext.Response.ContentLength ?? 0);
                    diagnosticContext.Set("ReqLen", httpContext.Request.ContentLength ?? 0);
                };
            });

            app.UseRouting();


            MetadataReference[] allMetadataReferences = null;

            try
            {
                allMetadataReferences = CSharpCompilerHelper.GetCommonMetadataReferences();

                var jsDALBasePluginPath = Path.GetFullPath("./plugins/jsdal-plugin.dll");

                if (File.Exists("./plugins/jsdal-plugin.dll"))
                {
                    Array.Resize(ref allMetadataReferences, allMetadataReferences.Length + 1);

                    allMetadataReferences[allMetadataReferences.Length - 1] = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(jsDALBasePluginPath);
                }
                else
                {
                    Log.Error($"Failed to find base plugin assembly at {jsDALBasePluginPath}");
                    SessionLog.Error($"Failed to find base plugin assembly at {jsDALBasePluginPath}");
                }
            }
            catch (Exception mex)
            {
                Log.Error(mex, "Failed to compile collection of metadata references");
            }

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <Hubs.HomeDashboardHub>("/main-stats");
                endpoints.MapHub <Hubs.WorkerDashboardHub>("/worker-hub");
                endpoints.MapHub <Hubs.Performance.RealtimeHub>("/performance-realtime-hub");
                endpoints.MapHub <Hubs.HeartBeat.HeartBeatHub>("/heartbeat");
                endpoints.MapHub <Hubs.BackgroundTaskHub>("/bgtasks-hub");
                endpoints.MapHub <Hubs.BackgroundPluginHub>("/bgplugin-hub");
                endpoints.MapHub <Hubs.ExecHub>("/exec-hub");

                if (allMetadataReferences?.Length > 0)
                {
                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                                          //            generalDiagnosticOption: ReportDiagnostic.Suppress
                                                                          specificDiagnosticOptions: new Dictionary <string, ReportDiagnostic>
                    {
                        { "CS1701", ReportDiagnostic.Suppress },                                     // Binding redirects
                        { "CS1702", ReportDiagnostic.Suppress },
                        { "CS1705", ReportDiagnostic.Suppress }
                    }
                                                                          );

                    var mirrorSharpOptions = new MirrorSharpOptions()
                    {
                        SelfDebugEnabled        = true,
                        IncludeExceptionDetails = true
                                                  //SetOptionsFromClient = SetOptionsFromClientExtension()
                                                  // CSharp = {
                                                  //             MetadataReferences = ImmutableList.Create<MetadataReference>(all),
                                                  //             CompilationOptions = compilationOptions
                                                  //          },
                                                  //   ExceptionLogger = new MirrorSharpExceptionLogger()
                    }.SetupCSharp(cs =>
                    {
                        //cs.MetadataReferences = cs.MetadataReferences.Clear();
                        //cs.AddMetadataReferencesFromFiles(all);
                        cs.MetadataReferences = ImmutableList.Create <MetadataReference>(allMetadataReferences);
                        cs.CompilationOptions = compilationOptions;
                    });

                    endpoints.MapMirrorSharp("/mirrorsharp", mirrorSharpOptions);
                }
                else
                {
                    Log.Warning("Mirrorsharp not started because of errors builiding up metadata references");
                }
            });

            app.UseAuthentication();
            app.UseWebSockets();
            app.UseCookiePolicy();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();

                // unhandled exceptions
                app.UseExceptionHandler(errorApp =>
                {
                    errorApp.Run(async context =>
                    {
                        try
                        {
                            var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();

                            var id = ExceptionLogger.LogException(exceptionHandlerPathFeature.Error, exceptionHandlerPathFeature.Path, "jsdal-server", null);

                            context.Response.StatusCode  = 500;
                            context.Response.ContentType = "text/plain";

                            await context.Response.WriteAsync($"Server error. Ref: {id}");
                            await context.Response.WriteAsync(new string(' ', 512)); // IE padding
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, $"Failed to log unhandled exception because of:\r\n {ex.ToString()}");
                        }
                    });
                });
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public static ClangSharpSourceCompilation Create(
            string sourceDirectory,
            string interopFileName,
            Dictionary <string, string> remaps,
            Dictionary <string, string> typeImports,
            Dictionary <string, string> requiredNamespaces)
        {
            var netstandardPath = FindNetstandardDllPath();

            if (!File.Exists(netstandardPath))
            {
                throw new FileNotFoundException("Failed to find the netstandard DLL.");
            }

            List <MetadataReference> refs = new List <MetadataReference>();

            refs.Add(MetadataReference.CreateFromFile(interopFileName));
            refs.Add(MetadataReference.CreateFromFile(netstandardPath));

            List <SyntaxTree> syntaxTrees = new List <SyntaxTree>();
            var sourceFiles = Directory.GetFiles(sourceDirectory, "*.cs", SearchOption.AllDirectories);

            System.Threading.Tasks.ParallelOptions opt = new System.Threading.Tasks.ParallelOptions()
            {
                MaxDegreeOfParallelism = Environment.ProcessorCount * 2
            };
            System.Threading.Tasks.Parallel.ForEach(sourceFiles, opt, (sourceFile) =>
            {
                if (sourceFile.EndsWith("modified.cs"))
                {
                    return;
                }

                string fileToRead = Path.GetFullPath(sourceFile);
                var tree          = CSharpSyntaxTree.ParseText(File.ReadAllText(fileToRead), null, fileToRead);

                lock (syntaxTrees)
                {
                    syntaxTrees.Add(tree);
                }
            });

            syntaxTrees = NamesToCorrectNamespacesMover.MoveNamesToCorrectNamespaces(syntaxTrees, requiredNamespaces);

            HashSet <string> foundNonEmptyStructs = GetNonEmptyStructs(syntaxTrees);

#if MakeSingleThreaded
            opt.MaxDegreeOfParallelism = 1;
#endif

            List <SyntaxTree> cleanedTrees = new List <SyntaxTree>();
            System.Threading.Tasks.Parallel.ForEach(syntaxTrees, opt, (tree) =>
            {
                string modifiedFile = Path.ChangeExtension(tree.FilePath, ".modified.cs");
                var cleanedTree     = MetadataSyntaxTreeCleaner.CleanSyntaxTree(tree, remaps, requiredNamespaces, foundNonEmptyStructs, modifiedFile);
                File.WriteAllText(modifiedFile, cleanedTree.GetText().ToString());

                lock (cleanedTrees)
                {
                    cleanedTrees.Add(cleanedTree);
                }
            });

            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, allowUnsafe: true);
            var comp =
                CSharpCompilation.Create(
                    //Path.GetFileName(outputFileName),
                    null,
                    cleanedTrees,
                    refs,
                    compilationOptions);

            return(new ClangSharpSourceCompilation(comp, typeImports));
        }
Example #43
0
        static void SingleStatementBodyAnalyzerTest()
        {
            //
            // Construct a syntax tree and a compilation.
            //

            var tree = CSharpSyntaxTree.ParseText(@"
using System;

class Foo
{
    void If(int x)
    {
        if (x > 0)
            Console.WriteLine(x);
        else if (x == 0)
            Console.WriteLine(0);
        else if (x < 0)
            Console.WriteLine(-x);
    }

    void For()
    {
        for (int i = 0; i < 10; i++)
            Console.WriteLine(i);
    }

    void ForEach()
    {
        foreach (var x in new[] { 1, 2, 3 })
            Console.WriteLine(x);
    }

    void While()
    {
        while (true)
            Console.Write('.');
    }
}");

            var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var comp = CSharpCompilation.Create("Demo")
                       .AddSyntaxTrees(tree)
                       .AddReferences(mscorlib)
                       .WithOptions(options);


            //
            // Get diagnostics.
            //

            var diags = AnalyzerDriver.GetDiagnostics(comp, new[] { new SingleStatementBodyAnalyzer() }, null, CancellationToken.None);

            foreach (var diag in diags)
            {
                Console.WriteLine(diag);
            }
        }
Example #44
0
 protected CSharpCompilation CreatePatternCompilation(string source, CSharpCompilationOptions options = null)
 {
     return(CreateCompilation(new[] { source, _iTupleSource }, options: options ?? TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithRecursivePatterns));
 }
Example #45
0
        protected void CreateCompilation(bool persistGeneratedCode, bool optimizeCode, IEnumerable <string> preprocessorSymbols = null)
        {
            var assemblyName      = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var assemblyDirectory = Path.Combine(GeneratedDirectory, assemblyName);

            if (persistGeneratedCode)
            {
                if (Directory.Exists(assemblyDirectory))
                {
                    Directory.Delete(assemblyDirectory);
                }
                Directory.CreateDirectory(assemblyDirectory);
            }


            IEnumerable <MetadataReference> references;


#if DOTNETCORE
            references = NetCoreAssemblyReferences;
#else
            MetadataReference mscorlib  = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
            MetadataReference system    = MetadataReference.CreateFromFile(typeof(Queue <>).GetTypeInfo().Assembly.Location);
            MetadataReference linq      = MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().Assembly.Location);
            MetadataReference contracts = MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.DataContractAttribute).GetTypeInfo().Assembly.Location);
            var thisAssembly            = MetadataReference.CreateFromFile(this.GetType().GetTypeInfo().Assembly.Location);

            MetadataReference unsaferef = MetadataReference.CreateFromFile(typeof(Unsafe).GetTypeInfo().Assembly.Location);
            // The Unsafe assembly depends (at compile time) on System.Runtime.dll
            // Since that assembly does not define any types (just type forwarders), I don't know how to get
            // a reference to it without just looking into the file system.
            var systemRuntimeLocation = $"{System.Environment.GetEnvironmentVariable("windir")}\\Microsoft.NET\\assembly\\GAC_MSIL\\System.Runtime\\v4.0_4.0.0.0__b03f5f7f11d50a3a\\System.Runtime.dll";
            var systemRuntimeRef      = MetadataReference.CreateFromFile(systemRuntimeLocation);

            references = new List <MetadataReference>()
            {
                mscorlib, system, linq, contracts, thisAssembly, unsaferef, systemRuntimeRef,
            };
#endif
            foreach (var r in references)
            {
                this.metadataReferences.Add(r.Display, r);
            }

            CSharpCompilationOptions options = new CSharpCompilationOptions(
                allowUnsafe: true,
                optimizationLevel: (optimizeCode ? OptimizationLevel.Release : OptimizationLevel.Debug),
                outputKind: OutputKind.DynamicallyLinkedLibrary
                );

            var preprocessorSyms = new List <string>()
            {
            };
            if (preprocessorSymbols != null)
            {
                preprocessorSyms.AddRange(preprocessorSymbols);
            }

            this.parseOptions = new CSharpParseOptions().WithPreprocessorSymbols(preprocessorSyms);
            var trees = Sources
                        .Select(s => CSharpSyntaxTree.ParseText(
                                    s.TemplateContents,
                                    path: Path.Combine(assemblyDirectory, s.TemplateName + ".cs"),
                                    encoding: Encoding.GetEncoding(0),
                                    options: parseOptions
                                    ));
            compilation = CSharpCompilation.Create(assemblyName, trees, references, options);
        }
Example #46
0
        /// <summary>
        /// The compiling process is closely related to the rollback process. When the initial compilation fails, the rollback process will be executed.
        /// </summary>
        /// <param name="syntaxTrees">The syntaxtrees to compile</param>
        /// <param name="ms">The memory stream to store the compilation result onto</param>
        /// <param name="devMode"></param>
        public CompilingProcessResult Compile(IEnumerable <SyntaxTree> syntaxTrees, MemoryStream ms, bool devMode)
        {
            var analyzerResult = _input.ProjectInfo.ProjectUnderTestAnalyzerResult;
            var trees          = syntaxTrees.ToList();

            if (_input.ProjectInfo.ProjectUnderTestAnalyzerResult.TargetFramework != Framework.NetClassic)
            {
                // Set assembly and file info for non netclassic frameworks
                AddVersionInfoSyntaxes(trees, analyzerResult);
            }

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                     .WithNullableContextOptions(NullableContextOptions.Enable)
                                     .WithAllowUnsafe(true)
                                     .WithCryptoKeyFile(analyzerResult.SignAssembly ? analyzerResult.AssemblyOriginatorKeyFile : null)
                                     .WithStrongNameProvider(analyzerResult.SignAssembly ? new DesktopStrongNameProvider() : null)
                                     .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                                     .WithConcurrentBuild(true);

            var compilation = CSharpCompilation.Create(analyzerResult.Properties.GetValueOrDefault("TargetName"),
                                                       syntaxTrees: trees,
                                                       options: compilationOptions,
                                                       references: _input.AssemblyReferences);

            RollbackProcessResult rollbackProcessResult;

            // first try compiling
            EmitResult emitResult;
            var        retryCount = 1;

            (rollbackProcessResult, emitResult, retryCount) = TryCompilation(ms, compilation, null, false, devMode, retryCount);

            // If compiling failed and the error has no location, log and throw exception.
            if (!emitResult.Success && emitResult.Diagnostics.Any(diag => diag.Location == Location.None && diag.Severity == DiagnosticSeverity.Error))
            {
                _logger.LogError("Failed to build the mutated assembly due to unrecoverable error: {0}",
                                 emitResult.Diagnostics.First(diag => diag.Location == Location.None && diag.Severity == DiagnosticSeverity.Error));
                throw new StrykerCompilationException("General Build Failure detected.");
            }

            var maxAttempt = 50;

            for (var count = 1; !emitResult.Success && count < maxAttempt; count++)
            {
                // compilation did not succeed. let's compile a couple times more for good measure
                (rollbackProcessResult, emitResult, retryCount) = TryCompilation(ms, rollbackProcessResult?.Compilation ?? compilation, emitResult, retryCount == maxAttempt - 1, devMode, retryCount);
            }

            if (!emitResult.Success)
            {
                // compiling failed
                _logger.LogError("Failed to restore the project to a buildable state. Please report the issue. Stryker can not proceed further");
                foreach (var emitResultDiagnostic in emitResult.Diagnostics)
                {
                    _logger.LogWarning($"{emitResultDiagnostic}");
                }
                throw new StrykerCompilationException("Failed to restore build able state.");
            }
            return(new CompilingProcessResult()
            {
                Success = emitResult.Success,
                RollbackResult = rollbackProcessResult
            });
        }
Example #47
0
        private void recompile()
        {
            if (assemblies == null)
            {
                assemblies = new HashSet <string>();
                foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
                {
                    assemblies.Add(ass.Location);
                }
            }

            assemblies.Add(typeof(JetBrains.Annotations.NotNullAttribute).Assembly.Location);

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            // ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
            var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[]
            {
#if DEBUG
                "DEBUG",
#endif
#if TRACE
                "TRACE",
#endif
#if RELEASE
                "RELEASE",
#endif
            }, languageVersion: LanguageVersion.CSharp7_3);
            var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));

            while (!checkFileReady(lastTouchedFile))
            {
                Thread.Sleep(10);
            }

            Logger.Log($@"Recompiling {Path.GetFileName(checkpointObject.GetType().Name)}...", LoggingTarget.Runtime, LogLevel.Important);

            CompilationStarted?.Invoke();

            // ensure we don't duplicate the dynamic suffix.
            string assemblyNamespace = checkpointObject.GetType().Assembly.GetName().Name.Replace(".Dynamic", "");

            string assemblyVersion  = $"{++currentVersion}.0.*";
            string dynamicNamespace = $"{assemblyNamespace}.Dynamic";

            var compilation = CSharpCompilation.Create(
                dynamicNamespace,
                requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOptions, file))
                // Compile the assembly with a new version so that it replaces the existing one
                .Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions))
                ,
                references,
                options
                );

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

                if (compilationResult.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    CompilationFinished?.Invoke(
                        Assembly.Load(ms.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == checkpointObject.GetType().FullName)
                        );
                }
                else
                {
                    foreach (var diagnostic in compilationResult.Diagnostics)
                    {
                        if (diagnostic.Severity < DiagnosticSeverity.Error)
                        {
                            continue;
                        }

                        CompilationFailed?.Invoke(new Exception(diagnostic.ToString()));
                    }
                }
            }
        }
Example #48
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText("class A{public  int aaa(){return 3;}}");

            var op   = new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary);
            var ref1 = MetadataReference.CreateFromFile("needlib\\mscorlib.dll");
            var comp = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("aaa.dll", new[] { tree },
                                                                              new[] { ref1 }, op);

            var fs     = new System.IO.MemoryStream();
            var fspdb  = new System.IO.MemoryStream();
            var result = comp.Emit(fs, fspdb);

            fs.Seek(0, System.IO.SeekOrigin.Begin);
            fspdb.Seek(0, System.IO.SeekOrigin.Begin);
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL(Debug) console app v" + Assembly.GetEntryAssembly().GetName().Version);
            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            //string filepdb = onlyname + ".pdb";

            ILModule mod = new ILModule();

            //System.IO.Stream fs = null;
            //System.IO.Stream fspdb = null;

            //open file
            //try
            //{
            //    fs = System.IO.File.OpenRead(filename);

            //    if (System.IO.File.Exists(filepdb))
            //    {
            //        fspdb = System.IO.File.OpenRead(filepdb);
            //    }

            //}
            //catch (Exception err)
            //{
            //    log.Log("Open File Error:" + err.ToString());
            //    return;
            //}
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes   = null;
            bool   bSucc   = false;
            string jsonstr = null;
            //convert and build
            NeoModule neoM = null;

            MyJson.JsonNode_Object abijson = null;
            try
            {
                var conv = new ModuleConverter(log);

                NeoModule am = conv.Convert(mod);
                neoM  = am;
                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    abijson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb = new StringBuilder();
                    abijson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }
            if (bSucc)
            {
                _DebugOutput.DebugOutput(neoM, bytes, abijson);
                log.Log("SUCC");
            }
        }
Example #49
0
 private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable <MetadataReference> references = null, CSharpCompilationOptions options = null)
 {
     references = (references != null) ? references.Concat(s_asyncRefs) : s_asyncRefs;
     return(base.CompileAndVerify(source, expectedOutput: expectedOutput, additionalRefs: references, options: options));
 }
Example #50
0
        private Assembly Compile(IBuilderContext builderContext, IEnumerable <SyntaxTree> syntaxTrees, string libraryFile, HashSet <string> fileReferences)
        {
            // Add references
            var metadataReferences = new List <MetadataReference>();

            foreach (var reference in fileReferences.Where(r => !string.IsNullOrEmpty(r)))
            {
                metadataReferences.Add(MetadataReference.CreateFromFile(reference));
            }

            metadataReferences.AddRange(BasicReferenceAssemblies.All);

            // suppress assembly redirect warnings
            // cf. https://github.com/dotnet/roslyn/issues/19640
            var noWarn = new List <KeyValuePair <string, ReportDiagnostic> >
            {
                new KeyValuePair <string, ReportDiagnostic>("CS1701", ReportDiagnostic.Suppress),
                new KeyValuePair <string, ReportDiagnostic>("CS1702", ReportDiagnostic.Suppress),
            };

            // Compile
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: (builderContext == null || builderContext.DebugScripts) ? OptimizationLevel.Debug : OptimizationLevel.Release,
                warningLevel: 4,
                specificDiagnosticOptions: noWarn,
                deterministic: true
                );

            var assemblyName = libraryFile != null?Path.GetFileNameWithoutExtension(libraryFile) : $"Sharpmake_{new Random().Next():X8}" + GetHashCode();

            var    compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, compilationOptions);
            string pdbFilePath = libraryFile != null?Path.ChangeExtension(libraryFile, ".pdb") : null;

            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    EmitResult result = compilation.Emit(
                        dllStream,
                        pdbStream,
                        options: new EmitOptions(
                            debugInformationFormat: DebugInformationFormat.PortablePdb,
                            pdbFilePath: pdbFilePath
                            )
                        );

                    bool throwErrorException = builderContext == null || builderContext.CompileErrorBehavior == BuilderCompileErrorBehavior.ThrowException;
                    LogCompilationResult(result, throwErrorException);

                    if (result.Success)
                    {
                        if (libraryFile != null)
                        {
                            dllStream.Seek(0, SeekOrigin.Begin);
                            using (var fileStream = new FileStream(libraryFile, FileMode.Create))
                                dllStream.CopyTo(fileStream);

                            pdbStream.Seek(0, SeekOrigin.Begin);
                            using (var pdbFileStream = new FileStream(pdbFilePath, FileMode.Create))
                                pdbStream.CopyTo(pdbFileStream);

                            return(Assembly.LoadFrom(libraryFile));
                        }

                        return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer()));
                    }
                }

            return(null);
        }
Example #51
0
        public dynamic GetCodeCompletion(SourceInfo sourceInfo)
        {
            var refs = CompileResources.PortableExecutableCompletionReferences;

            Console.WriteLine($"Refs: {string.Join(", ", refs.Select(x => x.FilePath))}");
            //List<Assembly> assemblies = new List<Assembly>()
            //{
            //    Assembly.Load("Microsoft.CodeAnalysis"),
            //    Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
            //    Assembly.Load("Microsoft.CodeAnalysis.Features"),
            //    Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"),
            //    Assembly.Load("Newtonsoft.Json")
            //};
            //var assembliesList = new List<Assembly>() { Assembly.Load("Newtonsoft.Json") };
            //assemblies.AddRange(assembliesList);
            ////var assembliesList = DownloadNugetPackages.LoadPackages(sourceInfo.Nuget);
            ////foreach (var item in assembliesList)
            ////{
            ////    var fname = item.FullName.Split(',')[0];
            ////    if (assemblies.Where(x => x.FullName.Split(',')[0] == fname).FirstOrDefault() == null)
            ////    {
            ////        var loadAssembly = Assembly.Load(item.FullName.Split(',')[0]);
            ////        assemblies.Add(loadAssembly);
            ////    }
            ////}

            //var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
            //        .Distinct()
            //        .SelectMany(x => x.GetTypes())
            //        .ToArray();

            //var compositionContext = new ContainerConfiguration()
            //    .WithParts(partTypes)
            //    //.WithAssemblies(assemblies)
            //    .CreateContainer();

            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);

            var workspace = new AdhocWorkspace(host);

            var scriptCode = sourceInfo.SourceCode;// "Guid.N";

            var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);

            var usings          = new List <string>();
            var allusingsInCode = sourceInfo.SourceCode.Split(new string[] { "using " }, StringSplitOptions.None);

            foreach (var item in allusingsInCode)
            {
                if (!String.IsNullOrWhiteSpace(item))
                {
                    usings.Add(item.Split(';')[0]);
                }
            }
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings);

            //MetadataReference[] _ref =
            //  DependencyContext.Default.CompileLibraries
            //  .First(cl => cl.Name == "mssqlrestapi")
            //  .ResolveReferencePaths()
            //  .Select(asm => MetadataReference.CreateFromFile(asm))
            //  .ToArray();

            //MetadataReference[] _refs = assembliesList

            //  .Select(asm => MetadataReference.CreateFromFile(asm.Location))
            //  .ToArray();

            //MetadataReference[] newArray = new MetadataReference[_ref.Length + _refs.Length];
            //Array.Copy(_ref, newArray, _ref.Length);
            //Array.Copy(_refs, 0, newArray, _ref.Length, _refs.Length);
            //assembliesList
            //IMethodSymbol methodWithGenericTypeArgsSymbol =    simpleClassToAnalyze.GetMembers("MySimpleMethod").FirstOrDefault()   as IMethodSymbol;
            //var genericMethodSignature = methodWithGenericTypeArgsSymbol.Parameters;

            var scriptProjectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: true)
                                    .WithMetadataReferences(refs)
                                    .WithCompilationOptions(compilationOptions);

            // without .net asseblies
            // .WithMetadataReferences(new[]
            // {
            //  MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
            //  })

            var scriptProject      = workspace.AddProject(scriptProjectInfo);
            var scriptDocumentInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(scriptProject.Id), "Script",
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(TextAndVersion.Create(SourceText.From(scriptCode), VersionStamp.Create())));
            var scriptDocument = workspace.AddDocument(scriptDocumentInfo);

            // cursor position is at the end
            var position = sourceInfo.LineNumberOffsetFromTemplate;// scriptCode.Length - 1;

            var completionService = CompletionService.GetService(scriptDocument);

            var results = completionService.GetCompletionsAsync(scriptDocument, position).Result;

            if (results == null && sourceInfo.LineNumberOffsetFromTemplate < sourceInfo.SourceCode.Length)
            {
                sourceInfo.LineNumberOffsetFromTemplate++;
                GetCodeCompletion(sourceInfo);
            }

            //Method parameters

            List <string> overloads = GetMethodParams(scriptCode, position);

            if (overloads != null && overloads.Count > 0)
            {
                ImmutableArray <CompletionItem> .Builder builder = ImmutableArray.CreateBuilder <CompletionItem>();
                foreach (var item in overloads)
                {
                    string         DisplayText = item;
                    string         insertText  = item.Split('(')[1].Split(')')[0];
                    CompletionItem ci          = CompletionItem.Create(insertText, insertText, insertText);
                    builder.Add(ci);
                }

                if (builder.Count > 0)
                {
                    ImmutableArray <CompletionItem> itemlist = builder.ToImmutable();
                    return(CompletionList.Create(new Microsoft.CodeAnalysis.Text.TextSpan(), itemlist));
                }
            }

            return(results);// JsonConvert.SerializeObject(results);
        }
Example #52
0
 protected CSharpCompilation CreatePatternCompilation(string source, CSharpCompilationOptions options = null)
 {
     return(CreateCompilation(new[] { source, _iTupleSource }, options: options ?? TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators));
 }
Example #53
0
        /// <summary>
        /// Verifies that <paramref name="code"/> produces no diagnostics when analyzed with <paramref name="analyzer"/>.
        /// </summary>
        /// <param name="analyzer">The <see cref="DiagnosticAnalyzer"/> to check <paramref name="code"/> with.</param>
        /// <param name="code">The code to analyze using <paramref name="analyzer"/>. Analyzing the code is expected to produce no errors or warnings.</param>
        /// <param name="compilationOptions">The <see cref="CSharpCompilationOptions"/> to use.</param>
        /// <param name="metadataReferences">The metadata references to use when compiling.</param>
        public static void NoAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, IReadOnlyList <string> code, CSharpCompilationOptions compilationOptions, IEnumerable <MetadataReference> metadataReferences)
        {
            var sln         = CodeFactory.CreateSolution(code, compilationOptions, metadataReferences);
            var diagnostics = Analyze.GetDiagnostics(analyzer, sln);

            NoDiagnostics(diagnostics);
        }
Example #54
0
 private void init()
 {
     __options =
         new CSharpCompilationOptions
             (outputKind: OutputKind.DynamicallyLinkedLibrary);
 }
Example #55
0
        public void Run(string path)
        {
            try
            {
                Assembly tempAsm = null;

                string readText = File.ReadAllText(path);

                var options = new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    reportSuppressedDiagnostics: true,
                    optimizationLevel: OptimizationLevel.Release,
                    generalDiagnosticOption: ReportDiagnostic.Error,
                    allowUnsafe: true);

                MetadataReference[] references = new MetadataReference[] {
                    MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(System.Console).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(ExpressionType).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(RuntimeBinderException).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(System.Runtime.CompilerServices.DynamicAttribute).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location),
                    MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location),
                    MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Reflection")).Location),
                };

                var compilation = CSharpCompilation.Create(
                    Path.GetFileName(path) + Guid.NewGuid().ToString(),
                    references: references,
                    syntaxTrees: new SyntaxTree[] { CSharpSyntaxTree.ParseText(readText) },
                    options: options);

                var stream     = new MemoryStream();
                var emitResult = compilation.Emit(stream);

                if (emitResult.Success)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    tempAsm = AssemblyLoadContext.Default.LoadFromStream(stream);
                }
                else
                {
                    _loggingService.Log();
                    emitResult.Diagnostics.Where(t => t.IsWarningAsError || t.Severity == DiagnosticSeverity.Error)
                    .ToList()
                    .ForEach(x => _loggingService.Log($"{x.Id} {x.Location.GetLineSpan().ToString()}: {x.GetMessage()}{Environment.NewLine}"));

                    throw new Exception($"{Environment.NewLine} Assembly could not be created {Environment.NewLine}");
                }

                // need to check and validate ICommand
                var tempicommand = tempAsm.GetTypes()
                                   .Where(t => t.Name == "ICommand")
                                   .ToList();

                if (tempicommand.Count == 0)
                {
                    throw new Exception("Unable to find ICommand");
                }

                if (tempicommand.Count > 1)
                {
                    throw new Exception("Multiple ICommands Found");
                }

                _assemblyService.Add(tempAsm);
            }
            catch (Exception ex)
            {
                _loggingService.LogException(ex);
            }
        }
        /// <summary>
        /// Compiles an embedded resource into an executable and writes it to disk in the same
        /// directory as the executing assembly.
        /// </summary>
        /// <param name="sourceResourcePath">
        /// The relative resource path, as it must be formatted for a pack URI.
        /// </param>
        /// <param name="absOutputPath">
        /// The absolute path
        /// </param>
        private string CompileExe(string sourceResourcePath, string absOutputPath)
        {
            m_logger.Info("Compiling internal service: {0} to output {1}.", sourceResourcePath, absOutputPath);
            string scriptContents = string.Empty;

            using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceResourcePath))
            {
                using (TextReader tsr = new StreamReader(resourceStream))
                {
                    scriptContents = tsr.ReadToEnd();
                }
            }

            if (scriptContents == null || scriptContents.Length == 0)
            {
                m_logger.Warn("When compiling internal service {0}, failed to load source code.", sourceResourcePath);
                return(string.Empty);
            }

            // The sentinel service is special. It's the only that's going to watch us.
            // So, we need to code our process name into its source before compilation.
            if (sourceResourcePath.IndexOf("Sentinel", StringComparison.OrdinalIgnoreCase) != -1)
            {
                scriptContents = scriptContents.Replace("TARGET_APPLICATION_NAME", Process.GetCurrentProcess().ProcessName);
            }

            HashSet <string> allRefs = new HashSet <string>();

            var dd      = typeof(Enumerable).GetTypeInfo().Assembly.Location;
            var coreDir = Directory.GetParent(dd);

            List <MetadataReference> references = new List <MetadataReference>
            {
                // Here we get the path to the mscorlib and private mscorlib
                // libraries that are required for compilation to succeed.
                //MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location)
            };

            var referencedAssemblies = RecursivelyGetReferencedAssemblies(Assembly.GetEntryAssembly());

            foreach (var referencedAssembly in referencedAssemblies)
            {
                var mref = MetadataReference.CreateFromFile(referencedAssembly.Location);

                if (referencedAssembly.FullName.Contains("System.Runtime.Extension"))
                {
                    // Have to do this to avoid collisions with duplicate type
                    // definitions between private mscorlib and this assembly.
                    // XXX TODO - Needs to be solved in a better way?
                    mref = mref.WithAliases(new List <string>(new[] { "CorPrivate" }));
                }

                if (!allRefs.Contains(mref.Display))
                {
                    references.Add(mref);
                    allRefs.Add(mref.Display);
                }
            }

            // Setup syntax parse options for C#.
            CSharpParseOptions parseOptions = CSharpParseOptions.Default;

            parseOptions = parseOptions.WithLanguageVersion(LanguageVersion.CSharp6);
            parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.None);
            parseOptions = parseOptions.WithKind(SourceCodeKind.Regular);

            // Parse text into syntax tree.
            SyntaxTree jobSyntaxTree = CSharpSyntaxTree.ParseText(scriptContents, parseOptions);

            // Initialize compilation arguments for the build script we're about
            // to compile.
            var op = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            op = op.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
            op = op.WithGeneralDiagnosticOption(ReportDiagnostic.Warn);

            // Initialize the compilation with our options, references and the
            // already parsed syntax tree of the build script.
            CSharpCompilation compilation = CSharpCompilation.Create(
                Path.GetFileNameWithoutExtension(absOutputPath),
                syntaxTrees: new[] { jobSyntaxTree },
                references: references,
                options: op);

            // Compile and emit new assembly into memory.
            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (result.Success)
                {
                    File.WriteAllBytes(absOutputPath, ms.ToArray());
                    m_logger.Info("Generated service assembly {0} for service {1}.", absOutputPath, Path.GetFileNameWithoutExtension(absOutputPath));
                    return(absOutputPath);
                }
                else
                {
                    // Compilation failed.
                    m_logger.Error("Failed to generate service assembly for service {0}.", Path.GetFileNameWithoutExtension(absOutputPath));

                    foreach (var diag in result.Diagnostics)
                    {
                        m_logger.Error(diag.GetMessage());
                    }
                }
            }

            return(string.Empty);
        }