Esempio n. 1
0
        public static Assembly Compile(SyntaxTree tree, string dllName)
        {
            var myRefs =
                new[] {
                    "System", "System.Core", "mscorlib", "System.Runtime"
                }.Select(MetadataReference.CreateAssemblyReference);

            var obsRef = new MetadataFileReference(typeof(Observable).Assembly.Location);
            var synRef = new MetadataFileReference(typeof(CommonSyntaxTree).Assembly.Location);
            var comRef = new MetadataFileReference(typeof(CompilationOptions).Assembly.Location);

            myRefs = myRefs.Union(new[] { obsRef, synRef, comRef });

            var compiledCode = Compilation.Create(
                outputName: dllName,
                options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: myRefs);

            using (var stream = new MemoryStream())
            {
                var emitResult = compiledCode.Emit(stream);
                if (!emitResult.Success)
                {
                    var message = string.Join("\r\n", emitResult.Diagnostics);
                    throw new ApplicationException(message);
                }

                return Assembly.Load(stream.GetBuffer());
            }
        }
        public void CS1009FTL_MetadataCantOpenFileModule()
        {
            //CSC /TARGET:library /addmodule:class1.netmodule text.CS
            var text = @"class Test
{
    public static int Main()
    {
        return 1;
    }
}";
            var refFile = Temp.CreateFile();
            var reference = new MetadataFileReference(refFile.Path, MetadataImageKind.Module);

            CreateCompilationWithMscorlib(text, new[] { reference }).VerifyDiagnostics(
                 // error CS0009: Metadata file '...' could not be opened -- Image too small to contain DOS header.
                 Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(refFile.Path, "Image too small to contain DOS header."));
        }
Esempio n. 3
0
        public void CS1009FTL_MetadataCantOpenFileModule()
        {
            //CSC /TARGET:library /addmodule:class1.netmodule text.CS
            var text      = @"class Test
{
    public static int Main()
    {
        return 1;
    }
}";
            var refFile   = Temp.CreateFile();
            var reference = new MetadataFileReference(refFile.Path, MetadataImageKind.Module);

            CreateCompilationWithMscorlib(text, new[] { reference }).VerifyDiagnostics(
                // error CS0009: Metadata file '...' could not be opened -- Image is too small.
                Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(refFile.Path, "Image is too small."));
        }
Esempio n. 4
0
        private static Compilation CreateTestCompilation()
        {
            SyntaxTree programTree  = CSharpSyntaxTree.ParseText(File.ReadAllText(@"..\..\Program.cs"));
            SyntaxTree rewriterTree = CSharpSyntaxTree.ParseText(File.ReadAllText(@"..\..\TypeInferenceRewriter.cs"));

            SyntaxTree[] sourceTrees = { programTree, rewriterTree };

            MetadataReference mscorlib           = new MetadataFileReference(typeof(object).Assembly.Location);
            MetadataReference codeAnalysis       = new MetadataFileReference(typeof(SyntaxTree).Assembly.Location);
            MetadataReference csharpCodeAnalysis = new MetadataFileReference(typeof(CSharpSyntaxTree).Assembly.Location);

            MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis };

            return(CSharpCompilation.Create("SyntaxRewriterTest",
                                            sourceTrees,
                                            references,
                                            new CSharpCompilationOptions(OutputKind.ConsoleApplication)));
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var tree = CSharpSyntaxTree.ParseText("class Foo { void Bar(int x) {} }");

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

            var res = comp.Emit("Demo.dll");

            if (!res.Success)
            {
                foreach (var diagnostic in res.Diagnostics)
                {
                    Console.WriteLine(diagnostic.GetMessage());
                }
            }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            var tree = CSharpSyntaxTree.ParseText(@"
using System;

class Foo
{
    void Bar(int x)
    {
    }
}");

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

            // var res = comp.Emit("Demo.dll");

            // Insert semantic analysis here
        }
Esempio n. 7
0
        private bool TryResolveDependency(PackageReference dependency, LoadContext loadContext, List <string> errors, out MetadataReference resolved)
        {
            resolved = null;

            var childContext = new LoadContext(dependency.Name, loadContext.TargetFramework);

            var loadResult = _dependencyLoader.Load(childContext);

            if (loadResult == null)
            {
                string assemblyLocation;
                if (_globalAssemblyCache.TryResolvePartialName(dependency.Name, out assemblyLocation))
                {
                    resolved = new MetadataFileReference(assemblyLocation);
                    return(true);
                }

                errors.Add(String.Format("Unable to resolve dependency '{0}' for target framework '{1}'.", dependency, loadContext.TargetFramework));
                return(false);
            }

            if (loadResult.Errors != null)
            {
                errors.AddRange(loadResult.Errors);
                return(false);
            }

            CompiledAssembly compiledAssembly;

            if (_compiledAssemblies.TryGetValue(dependency.Name, out compiledAssembly))
            {
                resolved = compiledAssembly.MetadataReference;
                return(true);
            }

            resolved = new MetadataFileReference(loadResult.Assembly.Location);
            return(true);
        }
        public void ExternAliasToSameDll()
        {
            var systemDllPath = typeof(Uri).Assembly.Location;
            var alias1 = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias1"));
            var alias2 = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias2"));

            var text = @"
extern alias Alias1;
extern alias Alias2;

class A { }
";
            var comp = CreateCompilationWithMscorlib(text, references: new MetadataReference[] { alias1, alias2 });
            Assert.Equal(3, comp.References.Count());
            Assert.Equal("Alias2", comp.References.Last().Properties.Aliases.Single());
            comp.VerifyDiagnostics(
                // (2,1): info CS8020: Unused extern alias.
                // extern alias Alias1;
                Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias Alias1;"),
                // (3,1): info CS8020: Unused extern alias.
                // extern alias Alias2;
                Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias Alias2;"));
        }
Esempio n. 9
0
    static void Main(string[] args)
    {
        var code = @"enum E { V } class { static void Main() { string s = ""Value: "" + E.V; } }";
        var doc  = Solution.Create(SolutionId.CreateNewId())
                   .AddCSharpProject("foo", "foo")
                   .AddMetadataReference(MetadataFileReference.CreateAssemblyReference("mscorlib"))
                   .AddDocument("doc.cs", code);
        var stringType = doc.Project.GetCompilation().GetSpecialType(SpecialType.System_String);
        var e          = doc.Project.GetCompilation().GlobalNamespace.GetTypeMembers("E").Single();
        var v          = e.GetMembers("V").Single();
        var refs       = v.FindReferences(doc.Project.Solution);
        var toStrings  = from referencedLocation in refs
                         from r in referencedLocation.Locations
                         let node = GetNode(doc, r.Location)
                                    let convertedType = doc.GetSemanticModel().GetTypeInfo(GetNode(doc, r.Location)).ConvertedType
                                                        where convertedType.Equals(stringType)
                                                        select r.Location;

        foreach (var loc in toStrings)
        {
            Console.WriteLine(loc);
        }
    }
Esempio n. 10
0
        public void ExternAliasToSameDll()
        {
            var systemDllPath = typeof(Uri).Assembly.Location;
            var alias1        = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias1"));
            var alias2        = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias2"));

            var text = @"
extern alias Alias1;
extern alias Alias2;

class A { }
";
            var comp = CreateCompilationWithMscorlib(text, references: new MetadataReference[] { alias1, alias2 });

            Assert.Equal(3, comp.References.Count());
            Assert.Equal("Alias2", comp.References.Last().Properties.Aliases.Single());
            comp.VerifyDiagnostics(
                // (2,1): info CS8020: Unused extern alias.
                // extern alias Alias1;
                Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Alias1;"),
                // (3,1): info CS8020: Unused extern alias.
                // extern alias Alias2;
                Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Alias2;"));
        }
Esempio n. 11
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);
            }
        }
Esempio n. 12
0
        public void CompilationWithReferenceDirectives_Errors()
        {
            using (MetadataCache.LockAndClean())
            {
                var data = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.NetFX.v4_0_30319.System_Data).Path;
                var core = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.NetFX.v4_0_30319.System_Core).Path;
                var system = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.NetFX.v4_0_30319.System).Path;
                var mscorlibRef = new MetadataFileReference(typeof(object).Assembly.Location);

                var trees = new[] {
                    SyntaxFactory.ParseSyntaxTree(@"
#r System
#r ""~!@#$%^&*():\?/""
#r ""non-existing-reference""
", options: TestOptions.Script),
                SyntaxFactory.ParseSyntaxTree(@"
#r ""System.Core""
")
                };

                var compilation = CSharpCompilation.Create("foo",
                    syntaxTrees: trees,
                    references: new[] { mscorlibRef },
                    options: TestOptions.Dll
                        .WithMetadataReferenceResolver(new Resolver(data, core, system))
                        .WithMetadataReferenceProvider(MetadataFileReferenceProvider.Default));

                compilation.VerifyDiagnostics(
                // (3,1): error CS0006: Metadata file '~!@#$%^&*():\?/' could not be found
                Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""~!@#$%^&*():\?/""").WithArguments(@"~!@#$%^&*():\?/"),
                // (4,1): error CS0006: Metadata file 'non-existing-reference' could not be found
                Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""non-existing-reference""").WithArguments("non-existing-reference"),
                // (2,4): error CS7010: Quoted file name expected
                Diagnostic(ErrorCode.ERR_ExpectedPPFile, "System"),
                // (2,1): error CS7011: #r is only allowed in scripts
                Diagnostic(ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts, @"#r ""System.Core"""));
            }
        }
        public void TestFileReferenceLocation()
        {
            var source = @"public class C { }";

            var tree = Parse(source, "file.cs");

            var libFile = Temp.CreateFile(extension: ".dll");
            var libPath = libFile.Path;

            var libComp = CreateCompilationWithMscorlib(tree, assemblyName: "Metadata");
            libComp.Emit(libPath).Diagnostics.Verify();

            var libRef = new MetadataFileReference(libPath, MetadataReferenceProperties.Assembly);
            var comp = CreateCompilationWithMscorlib(tree, new[] { libRef }, assemblyName: "Source");

            var sourceAssembly = comp.SourceAssembly;
            var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef);

            var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
            var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
            var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType);
            Assert.Equal("C [file.cs(1)]", distinguisher.First.ToString());
            Assert.Equal(string.Format("C [{0}]", libPath), distinguisher.Second.ToString());
        }
        public void TestPathLocationsWithoutCompilation()
        {
            var source = @"public class C { }";

            var tree = Parse(source, @"a\..\file.cs");

            var libFile = Temp.CreateFile(extension: ".dll");
            var libPath = libFile.Path;

            var libComp = CreateCompilationWithMscorlib(tree, assemblyName: "Metadata");
            libComp.Emit(libPath).Diagnostics.Verify();

            var libRef = new MetadataFileReference(libPath, MetadataReferenceProperties.Assembly);
            var comp = CreateCompilationWithMscorlib(tree, new[] { libRef }, assemblyName: "Source");

            var sourceAssembly = comp.SourceAssembly;
            var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef);

            var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
            var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C");

            var distinguisher = new SymbolDistinguisher(null, sourceType, referencedType); 
            Assert.Equal(@"C [a\..\file.cs(1)]", distinguisher.First.ToString()); // File path comes out of tree.
            Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString());
        }
Esempio n. 15
0
        private void PopulateMetadataReferences(PackageDescription package, IDictionary<string, IMetadataReference> paths)
        {
            foreach (var assemblyPath in package.Target.CompileTimeAssemblies)
            {
                if (PackageDependencyProvider.IsPlaceholderFile(assemblyPath))
                {
                    continue;
                }

                var name = Path.GetFileNameWithoutExtension(assemblyPath);
                var path = Path.Combine(package.Path, assemblyPath);
                paths[name] = new MetadataFileReference(name, path);
            }
        }
Esempio n. 16
0
        public void CS1704ERR_DuplicateImportSimple()
        {
            using (MetadataCache.LockAndClean())
            {
                var text = @"extern alias A1;
extern alias A2;
";
                var text1 = @"using System;
public class A { }";


                var c1 = CreateCompilationWithMscorlib(text1,
                    compOptions: TestOptions.Dll,
                    assemblyName: "CS1704");

                var dir1 = Temp.CreateDirectory();
                var exe1 = dir1.CreateFile("CS1704.dll");
                var pdb1 = dir1.CreateFile("CS1704.pdb");

                var dir2 = Temp.CreateDirectory();
                var exe2 = dir2.CreateFile("CS1704.dll");
                var pdb2 = dir2.CreateFile("CS1704.pdb");

                using (var output = exe1.Open())
                {
                    using (var outputPdb = pdb1.Open())
                    {
                        c1.Emit(output, null, pdb1.Path, outputPdb, null);
                    }
                }

                using (var output = exe2.Open())
                {
                    using (var outputPdb = pdb2.Open())
                    {
                        c1.Emit(output, null, pdb2.Path, outputPdb, null);
                    }
                }

                var ref1 = new MetadataFileReference(exe1.Path, aliases: ImmutableArray.Create("A1"));
                var ref2 = new MetadataFileReference(exe2.Path, aliases: ImmutableArray.Create("A2"));

                CreateCompilationWithMscorlib(text, new[] { ref1, ref2 }).VerifyDiagnostics(
                    // error CS1704: An assembly with the same simple name 'CS1704' has already been imported. 
                    // Try removing one of the references (e.g. '...\SymbolsTests\netModule\CS1704.dll') or sign them to enable side-by-side.
                    Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("CS1704", exe1.Path),
                    // (1,1): info CS8020: Unused extern alias.
                    // extern alias A1;
                    Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias A1;"),
                    // (2,1): info CS8020: Unused extern alias.
                    // extern alias A2;
                    Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias A2;"));
            }
        }
Esempio n. 17
0
        public void DuplicateAssemblyReferences_EquivalentPath()
        {
            using (MetadataCache.LockAndClean())
            {
                string p1 = Temp.CreateFile().WriteAllBytes(TestResources.SymbolsTests.General.MDTestLib1).Path;
                string p2 = MakeEquivalentPath(p1);
                string p3 = MakeEquivalentPath(p2);

                var r1 = new MetadataFileReference(p1);
                var r2 = new MetadataFileReference(p2);
                SyntaxTree t1, t2, t3;

                var compilation = CSharpCompilation.Create("foo",
                    syntaxTrees: new[] 
                    {
                        t1 = Parse("#r \"" + p2 + "\"", options: TestOptions.Script),
                        t2 = Parse("#r \"" + p3 + "\"", options: TestOptions.Script),
                        t3 = Parse("#r \"Foo\"", options: TestOptions.Script),
                    },
                    references: new MetadataReference[] { MscorlibRef, r1, r2 },
                    options: TestOptions.Dll.
                        WithMetadataReferenceResolver(new MappingReferenceResolver(assemblyNames: new Dictionary<string, string> { { "Foo", p3 } })).
                        WithMetadataReferenceProvider(MetadataFileReferenceProvider.Default)
                );

                // no diagnostics expected, all duplicate references should be ignored as they all refer to the same file:
                compilation.VerifyDiagnostics();

                var refs = compilation.ExternalReferences;
                Assert.Equal(3, refs.Length);
                Assert.Equal(MscorlibRef, refs[0]);
                Assert.Equal(r1, refs[1]);
                Assert.Equal(r2, refs[2]);

                // all #r's are referring to the same assembly that is already listed in external references:
                var dirRefs = compilation.DirectiveReferences;
                Assert.Equal(0, dirRefs.Length);

                var as1 = compilation.GetReferencedAssemblySymbol(r2);
                Assert.Equal("MDTestLib1", as1.Identity.Name);

                // r1 is a dup of r2:
                Assert.Null(compilation.GetReferencedAssemblySymbol(r1));

                var rd1 = t1.GetCompilationUnitRoot().GetReferenceDirectives().Single();
                var rd2 = t2.GetCompilationUnitRoot().GetReferenceDirectives().Single();
                var rd3 = t3.GetCompilationUnitRoot().GetReferenceDirectives().Single();

                var dr1 = compilation.GetDirectiveReference(rd1) as MetadataFileReference;
                var dr2 = compilation.GetDirectiveReference(rd2) as MetadataFileReference;
                var dr3 = compilation.GetDirectiveReference(rd3) as MetadataFileReference;

                Assert.Equal(MetadataImageKind.Assembly, dr1.Properties.Kind);
                Assert.Equal(MetadataImageKind.Assembly, dr2.Properties.Kind);
                Assert.Equal(MetadataImageKind.Assembly, dr3.Properties.Kind);

                Assert.True(dr1.Properties.Aliases.IsDefault);
                Assert.True(dr2.Properties.Aliases.IsDefault);
                Assert.True(dr3.Properties.Aliases.IsDefault);

                Assert.False(dr1.Properties.EmbedInteropTypes);
                Assert.False(dr2.Properties.EmbedInteropTypes);
                Assert.False(dr3.Properties.EmbedInteropTypes);

                // the paths are normalized:
                Assert.Equal(p1, dr1.FullPath);
                Assert.Equal(p1, dr2.FullPath);
                Assert.Equal(p1, dr3.FullPath);
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            //
            // Get the syntax tree.
            //

            var code = @"
using System;

class Foo
{
    void Bar(int x)
    {
        Console.WriteLine(3.14);
        Console.WriteLine(""qux"");
        Console.WriteLine('c');
        Console.WriteLine(null);
        Console.WriteLine(x * 2 + 1);
    }
}
";

            var tree = CSharpSyntaxTree.ParseText(code);
            var root = tree.GetRoot();


            //
            // Get the semantic model from the compilation.
            //

            var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
            var comp     = CSharpCompilation.Create("Demo").AddSyntaxTrees(tree).AddReferences(mscorlib);
            var model    = comp.GetSemanticModel(tree);


            //
            // Traverse the tree.
            //

            var walker = new ConsoleWriteLineWalker();

            walker.Visit(root);


            //
            // Analyze the constant argument (if any).
            //

            foreach (var arg in walker.Arguments)
            {
                var val = model.GetConstantValue(arg);
                if (val.HasValue)
                {
                    Console.WriteLine(arg + " has constant value " + (val.Value ?? "null") + " of type " + (val.Value?.GetType() ?? typeof(object)));
                }
                else
                {
                    Console.WriteLine(arg + " has no constant value");
                }
            }
        }
        public void MetadataReference_Display()
        {
            MetadataReference r;

            r = new MetadataImageReference(AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1));
            Assert.Equal("<in-memory assembly>".NeedsLocalization(), r.Display);

            r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1));
            Assert.Equal("<in-memory module>".NeedsLocalization(), r.Display);

            r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), filePath: @"c:\blah");
            Assert.Equal(@"c:\blah", r.Display);

            r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), display: @"dddd");
            Assert.Equal(@"dddd", r.Display);

            r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), filePath: @"c:\blah", display: @"dddd");
            Assert.Equal(@"dddd", r.Display);

            r = new MetadataFileReference(@"c:\some path");
            Assert.Equal(@"c:\some path", r.Display);

            r = CS.CSharpCompilation.Create("compilation name").ToMetadataReference();
            Assert.Equal(@"compilation name", r.Display);

            r = VisualBasic.VisualBasicCompilation.Create("compilation name").ToMetadataReference();
            Assert.Equal(@"compilation name", r.Display);
        }
Esempio n. 20
0
        public void DuplicateModuleReferences_EquivalentPath()
        {
            using (MetadataCache.LockAndClean())
            {
                var dir = Temp.CreateDirectory();
                string p1 = dir.CreateFile("netModule1.netmodule").WriteAllBytes(TestResources.SymbolsTests.netModule.netModule1).Path;
                string p2 = MakeEquivalentPath(p1);

                var m1 = new MetadataFileReference(p1, MetadataImageKind.Module);
                var m2 = new MetadataFileReference(p2, MetadataImageKind.Module);

                var compilation = CSharpCompilation.Create("foo", options: TestOptions.Dll,
                    references: new MetadataReference[] { m1, m2 });

                compilation.VerifyDiagnostics();

                var mods = compilation.Assembly.Modules.ToArray();
                Assert.Equal(2, mods.Length);

                Assert.Null(compilation.GetReferencedModuleSymbol(m1));
                Assert.NotNull(compilation.GetReferencedModuleSymbol(m2));
            }
        }
Esempio n. 21
0
        private Compilation CreateCompilation(string name, params SyntaxTree[] syntaxTrees)
        {
            var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib");
            var app = new MetadataFileReference(typeof (LexLogFormat).Assembly.Location);

            var compilation = Compilation.Create(
                name,
                syntaxTrees: syntaxTrees,
                references: new[] {mscorlib, app},
                options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimize: true));

            return compilation;
        }
Esempio n. 22
0
        public void DuplicateAssemblyReferences_EquivalentName()
        {
            using (MetadataCache.LockAndClean())
            {
                string p1 = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.NetFX.v4_0_30319.System_Core).Path;
                string p2 = Temp.CreateFile().CopyContentFrom(p1).Path;

                var r1 = new MetadataFileReference(p1);
                var r2 = new MetadataFileReference(p2);

                var compilation = CSharpCompilation.Create("foo", references: new[] { r1, r2 });

                var refs = compilation.Assembly.Modules.Select(module => module.GetReferencedAssemblies()).ToArray();
                Assert.Equal(1, refs.Length);
                Assert.Equal(1, refs[0].Length);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Note that it leaves any calls to contract methods in their original locations,
        /// i.e., it does *not* extract contracts. That is up to the caller of this method.
        /// </summary>
        public static bool FileToUnitAndSourceLocationProvider(IMetadataHost host, string filename,
                                                               List <string> libPaths,
                                                               List <string> referencedAssemblies,
                                                               out IModule module,
                                                               out ISourceLocationProvider /*?*/ sourceLocationProvider)
        {
            var text = File.ReadAllText(filename);
            CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, filename);
            // This ctor isn't implemented yet.
            //var mscorlib = new Roslyn.Compilers.AssemblyObjectReference(typeof(object).Assembly);
            //var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib"); // Roslyn takes care of resolving where it lives.
            var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
            var refs     = new List <MetadataReference>();

            refs.Add(mscorlib);
            foreach (var r in referencedAssemblies)
            {
                refs.Add(new MetadataFileReference(Path.GetFileNameWithoutExtension((r))));
            }

            var baseFileName = Path.GetFileNameWithoutExtension(filename);

            var defaultResolver = FileResolver.Default;
            var ar = new FileResolver(libPaths.Select(lp => Path.GetFullPath(lp)), defaultResolver.KeyFileSearchPaths, defaultResolver.BaseDirectory);
            var c  = CSharpCompilation.Create(
                baseFileName
                , syntaxTrees: new SyntaxTree[] { tree }
                , references: refs
                , fileResolver: ar
                , options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );
            var diags = c.GetDiagnostics();

            if (diags.Count() > 0)
            {
                foreach (var diag in diags)
                {
                    Console.WriteLine(diag.ToString());
                }
                if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError))
                {
                    module = Dummy.Module;
                    sourceLocationProvider = null;
                    return(false);
                }
            }
            //c = c.AddSyntaxTrees(tree); // Use this form to add another syntax tree to the same compilation (getting a new compilation since they're immutable)
            var binding = c.GetSemanticModel(tree);

            diags = binding.GetDiagnostics();
            if (diags.Count() > 0)
            {
                foreach (var d in diags)
                {
                    Console.WriteLine(d.ToString());
                }
                if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError))
                {
                    module = Dummy.Module;
                    sourceLocationProvider = null;
                    return(false);
                }
            }
            ConvertRoslynToCCI(host, tree, binding, out module, out sourceLocationProvider);
            return(true);
        }
Esempio n. 24
0
        private ISemanticModel GetSemanticModelFromSyntaxTree(CommonSyntaxTree syntaxTree, string code, bool includeDocumentation = false)
        {
            _systemXmlFilesDir = GetSystemXmlFilesDir();

            MetadataReference mscorlib = CreateMetadataReference("mscorlib", includeDocumentation);
            var metaDllReferences      = new List <MetadataReference> {
                mscorlib
            };

            if (this.Language == Language.VbNet)
            {
                //Need to add vb or getting error
                //Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined.
                MetadataReference vb = CreateMetadataReference("Microsoft.VisualBasic", includeDocumentation);
                metaDllReferences.Add(vb);
            }


            //Eric: this doesn't seem to work so using mscorlib only for now.

            List <string> gacDlls = GetGacDlls(code);

            foreach (string dllName in gacDlls)
            {
                string dllNameWithoutExtension = dllName.Substring(0, dllName.Length - 4);                 //remove .dll

                MetadataReference metaRef = CreateMetadataReference(dllNameWithoutExtension, includeDocumentation);
                metaDllReferences.Add(metaRef);
            }

            Dictionary <string, string> nugGetXmlFileNameToPath = new Dictionary <string, string>();

            if (includeDocumentation)
            {
                foreach (var nuGetxmlFilePath in NuGetXmlFileReferences)
                {
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(nuGetxmlFilePath);
                    nugGetXmlFileNameToPath[fileNameWithoutExtension] = nuGetxmlFilePath;
                }
            }


            foreach (var path in GetNonGacDlls())
            {
                string fileName = Path.GetFileNameWithoutExtension(path);

                RoslynDocumentationProvider documentationProvider = null;
                if (includeDocumentation && nugGetXmlFileNameToPath.ContainsKey(fileName))
                {
                    documentationProvider = new RoslynDocumentationProvider(nugGetXmlFileNameToPath[fileName]);
                }

                var reference = new MetadataFileReference(path, MetadataReferenceProperties.Assembly, documentationProvider);
                metaDllReferences.Add(reference);
            }



            //http://msdn.microsoft.com/en-us/vstudio/hh500769.aspx#Toc306015688

            CommonCompilation compilation = this.CreateCompilation("Compilation_For_AutoComplete",
                                                                   syntaxTrees: new[] { syntaxTree },
                                                                   matadataReferences: metaDllReferences);

            ISemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);

            return(semanticModel);
        }
		private ISemanticModel GetSemanticModelFromSyntaxTree(CommonSyntaxTree syntaxTree, string code, bool includeDocumentation = false)
		{
			_systemXmlFilesDir = GetSystemXmlFilesDir();

			MetadataReference mscorlib = CreateMetadataReference("mscorlib", includeDocumentation);
			var metaDllReferences = new List<MetadataReference> {mscorlib};

			if (this.Language == Language.VbNet)
			{
				//Need to add vb or getting error
				//Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined.
				MetadataReference vb = CreateMetadataReference("Microsoft.VisualBasic", includeDocumentation);
				metaDllReferences.Add(vb);
			}


			//Eric: this doesn't seem to work so using mscorlib only for now.

			List<string> gacDlls = GetGacDlls(code);
			foreach (string dllName in gacDlls)
			{
				string dllNameWithoutExtension = dllName.Substring(0, dllName.Length - 4); //remove .dll

				MetadataReference metaRef = CreateMetadataReference(dllNameWithoutExtension, includeDocumentation);
				metaDllReferences.Add(metaRef);

			}

			Dictionary <string, string> nugGetXmlFileNameToPath = new Dictionary<string, string>();

			if (includeDocumentation)
				foreach (var nuGetxmlFilePath in NuGetXmlFileReferences)
				{
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(nuGetxmlFilePath);
					nugGetXmlFileNameToPath[fileNameWithoutExtension] = nuGetxmlFilePath;
				}


			foreach (var path in GetNonGacDlls())
			{
				string fileName = Path.GetFileNameWithoutExtension(path);

				RoslynDocumentationProvider documentationProvider = null;
				if (includeDocumentation && nugGetXmlFileNameToPath.ContainsKey(fileName))
					documentationProvider = new RoslynDocumentationProvider(nugGetXmlFileNameToPath[fileName]);

				var reference = new MetadataFileReference(path, MetadataReferenceProperties.Assembly, documentationProvider);
				metaDllReferences.Add(reference);
			}


			
			//http://msdn.microsoft.com/en-us/vstudio/hh500769.aspx#Toc306015688

			CommonCompilation compilation = this.CreateCompilation("Compilation_For_AutoComplete",
			                                                       syntaxTrees: new[] {syntaxTree},
			                                                       matadataReferences: metaDllReferences);

			ISemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);
			return semanticModel;
		}
Esempio n. 26
0
        // Internal Methods 

        internal static Translator PrepareTranslator()
        {
            if (_translator != null)
            {
                return(_translator);
            }
            var csProject = LangPhpTestCsProj;

            using (var comp = new Cs2PhpCompiler {
                VerboseToConsole = true, ThrowExceptions = true
            })
            {
                Console.WriteLine("Try to load " + csProject);

#if DEBUG
                comp.LoadProject(csProject, "DEBUG");
#else
                comp.LoadProject(csProject, "RELEASE");
#endif

                /*
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Compiler\bin\Debug\Lang.Php.Compiler.dll
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Framework\bin\Debug\Lang.Php.Framework.dll
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Test\bin\Debug\Lang.Php.dll
                 */


                Console.WriteLine("Preparing before compilation");
                string[] removeL = "Lang.Php.Compiler,Lang.Php.Framework,Lang.Php".Split(',');

                #region Remove Lang.Php reference

                {
                    foreach (var r in removeL)
                    {
                        // ... will be replaced by reference to dll from compiler base dir
                        // I know - compilation libraries should be loaded into separate application domain
                        var remove =
                            comp.CSharpProject.MetadataReferences.FirstOrDefault(i => i.Display.EndsWith(r + ".dll"));
                        if (remove != null)
                        {
                            comp.RemoveMetadataReferences(remove);
                        }
                    }
                }

                #endregion

                string[] filenames;

                #region We have to remove and add again references - strange

                {
                    // in other cases some referenced libraries are ignored
                    var refToRemove = comp.CSharpProject.MetadataReferences.OfType <MetadataFileReference>().ToList();
                    foreach (var i in refToRemove)
                    {
                        comp.RemoveMetadataReferences(i);
                    }
                    var ref1 = refToRemove.Select(i => i.FilePath).ToList();
                    // foreach (var r in removeL)
                    //     ref1.Add(Path.Combine(Directory.GetCurrentDirectory(), r + ".dll"));
                    ref1.Add(typeof(DirectCallAttribute).Assembly.Location);
                    ref1.Add(typeof(EmitContext).Assembly.Location);
                    ref1.Add(typeof(Extension).Assembly.Location);
                    filenames = ref1.Distinct().ToArray();
                }

                #endregion

                #region Translation assemblies

                {
                    comp.TranslationAssemblies.Add(typeof(Extension).Assembly);
                    comp.TranslationAssemblies.Add(typeof(Translator).Assembly);
                }

                #endregion

                foreach (var fileName in filenames)
                {
                    var g = new MetadataFileReference(fileName, MetadataReferenceProperties.Assembly);
                    comp.AddMetadataReferences(g);
                    Console.WriteLine("  Add reference     {0}", g.Display);
                }

                //                using (var sandbox = new AssemblySandbox())
                //                {
                //                //
                //                Console.WriteLine("Start compile");
                //                var result = comp.CompileCSharpProject(sandbox, comp.DllFileName);
                //                if (!result.Success)
                //                {
                //                    foreach (var i in result.Diagnostics)
                //                        Console.WriteLine(i);
                //                }
                //                Assert.True(result.Success, "Compilation failed");
                //                }
                TranslationInfo translationInfo = comp.ParseCsSource();


                translationInfo.CurrentAssembly = comp.CompiledAssembly;
                var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly);
                var ecBaseDir  = Path.Combine(Directory.GetCurrentDirectory(), assemblyTi.RootPath.Replace("/", "\\"));
                Console.WriteLine("Output root {0}", ecBaseDir);

                var translationState = new TranslationState(translationInfo);
                _translator = new Translator(translationState);

                _translator.Translate(comp.Sandbox);
                return(_translator);
            }
        }
 private CS.CSharpCompilation CreateCSharpCompilation(string sourceText)
 {
     MetadataReference mscorlib = new MetadataFileReference(typeof(int).Assembly.Location);
     var syntaxTree = CS.SyntaxFactory.ParseSyntaxTree(sourceText);
     return (CS.CSharpCompilation)CS.CSharpCompilation.Create("foo.exe").AddReferences(mscorlib).AddSyntaxTrees(syntaxTree);
 }
Esempio n. 28
0
        static void Main2(string[] args)
        {

   var tree = SyntaxTree.ParseText(@"using System;
namespace HelloWorld
{
    public class Program
    {
        public static void Tain(int x)
        {
           
            Console.ReadKey();
        }
    }
}");

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

        var comp = Compilation.Create("MyCompilation", new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
            .AddSyntaxTrees(tree).AddReferences(mscorlib);
        

        var outputFileName = Path.Combine(Path.GetTempPath(), "MyCompilation.lib");
        var ilStream = new FileStream(outputFileName, FileMode.OpenOrCreate);

        var result = comp.Emit(ilStream);
        ilStream.Close();

        using (var host = new PeReader.DefaultHost())
        {
            //Read the Metadata Model from the PE file
            var module = host.LoadUnitFrom(outputFileName) as IModule;
            if (module == null || module == Dummy.Module || module == Dummy.Assembly)
            {
                Console.WriteLine(outputFileName + " is not a PE file containing a CLR module or assembly.");
                return;
            }

        //Construct a Code Model from the Metadata model via decompilation
            Module decompiledModule = Decompiler.GetCodeModelFromMetadataModel(host, module, null);
        //    decompiledModule.UnitNamespaceRoot.GetMembersNamed(host.NameTable.GetNameFor("Tain"), true);
            var type = decompiledModule.AllTypes.Single(t => t.Name.Value == "Program");
            //type.Methods.Single(m=>m.)
            
        }
           
        if (result.Success)
        {
            // Run the compiled program.
            Process.Start(outputFileName);
        }
        else
        {
            foreach (var diag in result.Diagnostics)
            {
                Console.WriteLine(diag.ToString());
            }
        }
    

            /*
     var   sourceText =     @"using System; 
using System.Collections; 
using System.Linq; 
using System.Text; 
  
namespace HelloWorld 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine(""Hello, World!""); 
        } 
    } 
}"; 

            SyntaxTree tree = SyntaxTree.ParseText(sourceText);

            MetadataReference mscorlib = MetadataReference.CreateAssemblyReference(
                                             "mscorlib");


            Compilation compilation = Compilation.Create("HelloWorld", new CompilationOptions(OutputKind.ConsoleApplication))
                            .AddReferences(mscorlib)
                            .AddSyntaxTrees(tree);

         
            //Directory.CreateDirectory(@"C:\Ttemp")
            compilation.Emit(@"C:\VisualMutatorTemp\Test.exe");*/

        }
Esempio n. 29
0
        static void Main2(string[] args)
        {
            var tree = SyntaxTree.ParseText(@"using System;
namespace HelloWorld
{
    public class Program
    {
        public static void Tain(int x)
        {
           
            Console.ReadKey();
        }
    }
}");

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

            var comp = Compilation.Create("MyCompilation", new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                       .AddSyntaxTrees(tree).AddReferences(mscorlib);


            var outputFileName = Path.Combine(Path.GetTempPath(), "MyCompilation.lib");
            var ilStream       = new FileStream(outputFileName, FileMode.OpenOrCreate);

            var result = comp.Emit(ilStream);

            ilStream.Close();

            using (var host = new PeReader.DefaultHost())
            {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(outputFileName) as IModule;
                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    Console.WriteLine(outputFileName + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Construct a Code Model from the Metadata model via decompilation
                Module decompiledModule = Decompiler.GetCodeModelFromMetadataModel(host, module, null);
                //    decompiledModule.UnitNamespaceRoot.GetMembersNamed(host.NameTable.GetNameFor("Tain"), true);
                var type = decompiledModule.AllTypes.Single(t => t.Name.Value == "Program");
                //type.Methods.Single(m=>m.)
            }

            if (result.Success)
            {
                // Run the compiled program.
                Process.Start(outputFileName);
            }
            else
            {
                foreach (var diag in result.Diagnostics)
                {
                    Console.WriteLine(diag.ToString());
                }
            }


            /*
             * var   sourceText =     @"using System;
             * using System.Collections;
             * using System.Linq;
             * using System.Text;
             *
             * namespace HelloWorld
             * {
             * class Program
             * {
             * static void Main(string[] args)
             * {
             * Console.WriteLine(""Hello, World!"");
             * }
             * }
             * }";
             *
             * SyntaxTree tree = SyntaxTree.ParseText(sourceText);
             *
             * MetadataReference mscorlib = MetadataReference.CreateAssemblyReference(
             *                               "mscorlib");
             *
             *
             * Compilation compilation = Compilation.Create("HelloWorld", new CompilationOptions(OutputKind.ConsoleApplication))
             *              .AddReferences(mscorlib)
             *              .AddSyntaxTrees(tree);
             *
             *
             * //Directory.CreateDirectory(@"C:\Ttemp")
             * compilation.Emit(@"C:\VisualMutatorTemp\Test.exe");*/
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            //
            // Get the syntax tree.
            //

            var code = @"
using System;

class Foo
{
    private int y;

    void Bar(int x)
    {
        Console.WriteLine(x);
        Console.WriteLine(y);

        int z = 42;
        Console.WriteLine(z);

        Console.WriteLine(a);
    }
}
";

            var tree = CSharpSyntaxTree.ParseText(code);
            var root = tree.GetRoot();


            //
            // Get the semantic model from the compilation.
            //

            var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
            var comp     = CSharpCompilation.Create("Demo").AddSyntaxTrees(tree).AddReferences(mscorlib);
            var model    = comp.GetSemanticModel(tree);


            //
            // Traverse the tree.
            //

            var walker = new ConsoleWriteLineWalker();

            walker.Visit(root);


            //
            // Bind the arguments.
            //

            foreach (var arg in walker.Arguments)
            {
                var symbol = model.GetSymbolInfo(arg);
                if (symbol.Symbol != null)
                {
                    Console.WriteLine(arg + " is bound to " + symbol.Symbol + " of type " + symbol.Symbol.Kind);
                }
                else
                {
                    Console.WriteLine(arg + " could not be bound");
                }
            }
        }