Esempio n. 1
0
        public async Task CheckPEReferencesNotSameAfterReferenceChangedTest()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "TestProject",
                    "TestProject",
                    LanguageNames.CSharp,
                    metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

                var project = ws.AddProject(projectInfo);

                // get original references
                var compilation1 = await project.GetCompilationAsync();

                var references1 = compilation1.ExternalReferences;

                // explicitly change references
                var forkedProject = project.WithMetadataReferences(ImmutableArray.Create <MetadataReference>(
                                                                       PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location),
                                                                       PortableExecutableReference.CreateFromFile(typeof(Workspace).Assembly.Location)));

                // get new compilation
                var compilation2 = await forkedProject.GetCompilationAsync();

                var references2 = compilation2.ExternalReferences;

                Assert.NotEqual(references1, references2);
            }
        }
Esempio n. 2
0
    public void _UnreachableCode()
    {
        var tree = CSharpSyntaxTree.ParseText(@"
            class C
            {
                void M(int x)
                {
                    return;
                    if(x == 0)                                  //-+     Start is unreachable
                        System.//DebugLogger.Instance.WriteLine(""Hello"");    // |
                    L1:                                            //-+    End is unreachable
                }
            }
        ");

        var Mscorlib    = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
                                                   syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
        var model = compilation.GetSemanticModel(tree);

        //Choose first and last statements
        var firstIf = tree.GetRoot().DescendantNodes().OfType <IfStatementSyntax>().Single();
        var label1  = tree.GetRoot().DescendantNodes().OfType <LabeledStatementSyntax>().Single();

        ControlFlowAnalysis result = model.AnalyzeControlFlow(firstIf, label1);
        //DebugLogger.Instance.WriteLine(result.StartPointIsReachable);    //False
        //DebugLogger.Instance.WriteLine(result.EndPointIsReachable);      //False
    }
Esempio n. 3
0
        public async Task CheckPEReferencesSameAfterSolutionChangedTest()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "TestProject",
                    "TestProject",
                    LanguageNames.CSharp,
                    metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

                var project = ws.AddProject(projectInfo);

                // get original references
                var compilation1 = await project.GetCompilationAsync();

                var references1 = compilation1.ExternalReferences;

                // just some arbitary action to create new snpahost that doesnt affect references
                var info     = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var document = ws.AddDocument(info);

                // get new compilation
                var compilation2 = await document.Project.GetCompilationAsync();

                var references2 = compilation2.ExternalReferences;

                Assert.Equal(references1, references2);
            }
        }
Esempio n. 4
0
    public void _BasicControlFlow()
    {
        var tree = CSharpSyntaxTree.ParseText(@"
            class C
            {
                void M()
                {
        
                    for (int i = 0; i < 10; i++)
                    {
                        if (i == 3)
                            continue;
                        if (i == 8)
                            break;
                    }
                }
            }
        ");

        var Mscorlib    = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
                                                   syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
        var model = compilation.GetSemanticModel(tree);

        var firstFor = tree.GetRoot().DescendantNodes().OfType <ForStatementSyntax>().Single();
        ControlFlowAnalysis result = model.AnalyzeControlFlow(firstFor.Statement);

        //DebugLogger.Instance.WriteLine(result.Succeeded);            //True
        //DebugLogger.Instance.WriteLine(result.ExitPoints.Count());    //2 - continue, and break
    }
Esempio n. 5
0
    public void _EntryAndExitPoints()
    {
        var tree = CSharpSyntaxTree.ParseText(@"
        class C
        {
            void M(int x)
            {
                L1: ; // 1
                if (x == 0) goto L1;    //firstIf
                if (x == 1) goto L2;
                if (x == 3) goto L3;
                L3: ;                   //label3
                L2: ; // 2
                if(x == 4) goto L3;
            }
        }
        ");

        var Mscorlib    = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
                                                   syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
        var model = compilation.GetSemanticModel(tree);

        //Choose first and last statements
        var firstIf = tree.GetRoot().DescendantNodes().OfType <IfStatementSyntax>().First();
        var label3  = tree.GetRoot().DescendantNodes().OfType <LabeledStatementSyntax>().Skip(1).Take(1).Single();

        ControlFlowAnalysis result = model.AnalyzeControlFlow(firstIf, label3);
        //DebugLogger.Instance.WriteLine(result.EntryPoints);      //1 - L3: ; //Label 3 is a candidate entry point within these statements
        //DebugLogger.Instance.WriteLine(result.ExitPoints);       //2 - goto L1;,goto L2; //goto L1 and goto L2 and candidate exit points
    }
Esempio n. 6
0
        public static Assembly CompileLambdaInternal(string lambda, IEnumerable <KeyValuePair <string, string> > supportLambdas, Type returnType, string[] references, params Type[] parameterTypes)
        {
            var coercedTypes        = parameterTypes.Concat(new Type[] { returnType }).Select(t => t.Name == "Object" ? "dynamic" : t.Name);
            var supportLambdaString = supportLambdas == null ? "" : DependentLambdas(lambda, supportLambdas);

            var sources = new string[] { $@"
                using System;
                using System.Linq;
                using System.Collections.Generic;

                namespace InMemory {{
                  public static class DynamicClass {{

                     public static Func<dynamic, string, dynamic> _Trace = (i, m) => i;

                     public static dynamic Trace(dynamic i) {{ return _Trace(i, string.Empty); }}
                     public static dynamic Trace(dynamic i, string m) {{ return _Trace(i, m); }}

                    {supportLambdaString}

                     public static Func<{string.Join(",", coercedTypes)}> mapper = {lambda};
                     public static dynamic executeLambda({String.Join(",", parameterTypes.Select((t, i) => $"dynamic item{i}"))}) {{
                        return mapper({String.Join(",", parameterTypes.Select((t, i) => $"item{i}").ToArray())});
                     }}
                  }}
                }}" };

            return(CompileAssembly(sources, references?.Select(r => PortableExecutableReference.CreateFromFile(r))?.ToArray()));
        }
Esempio n. 7
0
    public void _2RetrieveMethodAndInvocationExpressionSyntax()
    {
        var tree = CSharpSyntaxTree.ParseText(@"
            public class MyClass {
                     int Method1() { return 0; }
                     void Method2()
                     {
                        int x = Method1();
                     }
                }
            }"    );

        var Mscorlib    = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
                                                   syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
        var model = compilation.GetSemanticModel(tree);

        //Looking at the first method symbol
        var methodSyntax = tree.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>().First();
        var methodSymbol = model.GetDeclaredSymbol(methodSyntax);

        //DebugLogger.Instance.WriteLine(methodSymbol.ToString());         //MyClass.Method1()
        //DebugLogger.Instance.WriteLine(methodSymbol.ContainingSymbol);   //MyClass
        //DebugLogger.Instance.WriteLine(methodSymbol.IsAbstract);         //false

        //Looking at the first invocation
        var invocationSyntax = tree.GetRoot().DescendantNodes().OfType <InvocationExpressionSyntax>().First();
        var invokedSymbol    = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1

        //DebugLogger.Instance.WriteLine(invokedSymbol.ToString());         //MyClass.Method1()
        //DebugLogger.Instance.WriteLine(invokedSymbol.ContainingSymbol);   //MyClass
        //DebugLogger.Instance.WriteLine(invokedSymbol.IsAbstract);         //false

        //DebugLogger.Instance.WriteLine(invokedSymbol.Equals(methodSymbol)); //true
    }
Esempio n. 8
0
        public RoslynCompilationWorkspace(WorkspaceConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            Configuration = configuration;

            var dependencyResolver       = configuration.DependencyResolver;
            var compilationConfiguration = configuration.CompilationConfiguration;

            workspace = new InteractiveWorkspace();
            sourceReferenceResolver      = new InteractiveSourceReferenceResolver(dependencyResolver);
            metadataReferenceResolver    = new InteractiveMetadataReferenceResolver(dependencyResolver);
            monoScriptCompilationPatcher = new MonoScriptCompilationPatcher(
                assemblyNamePrefixBytes);

            DependencyResolver = dependencyResolver;

            hostObjectType              = compilationConfiguration.GlobalStateType.ResolvedType;
            EvaluationContextId         = compilationConfiguration.EvaluationContextId;
            includePeImagesInResolution = compilationConfiguration.IncludePEImagesInDependencyResolution;

            initialImports             = compilationConfiguration.DefaultImports.ToImmutableArray();
            initialWarningSuppressions = compilationConfiguration.DefaultWarningSuppressions.ToImmutableArray();
            initialDiagnosticOptions   = initialWarningSuppressions.ToImmutableDictionary(
                warningId => warningId,
                warningId => ReportDiagnostic.Suppress);
            initialReferences = dependencyResolver
                                .ResolveDefaultReferences()
                                .Select(r => PortableExecutableReference.CreateFromFile(r.Path))
                                .ToImmutableArray();

            foreach (var implicitReference in byNameImplicitReferences)
            {
                if (implicitReference == null)
                {
                    continue;
                }

                var assembly = DependencyResolver.ResolveWithoutReferences(
                    new AssemblyName(implicitReference));
                if (assembly != null)
                {
                    initialReferences = initialReferences.Add(
                        MetadataReference.CreateFromFile(assembly.Path));
                }
            }

            CompletionService = workspace
                                .Services
                                .GetLanguageServices(LanguageNames.CSharp)
                                .GetService <CompletionService> ();
        }
Esempio n. 9
0
 public override ImmutableArray <PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties)
 {
     if (reference.StartsWith(PaketPrefix))
     {
         // dummy reference
         return(ImmutableArray.Create(PortableExecutableReference.CreateFromFile(typeof(PaketScriptMetadataResolver).GetTypeInfo().Assembly.Location)));
     }
     else
     {
         return(_inner.ResolveReference(reference, baseFilePath, properties));
     }
 }
Esempio n. 10
0
        /// <summary>
        /// 根据路劲
        /// </summary>
        /// <param name="Path"></param>
        public CsharpParser(string Path)
        {
            var context    = Path.GetFileContext();
            var syntaxTree = CSharpSyntaxTree.ParseText(context);

            roots = syntaxTree.GetRoot();
            if (Mscorlib == null)
            {
                Mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
            }
            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { syntaxTree }, references: new[] { Mscorlib });

            semanticModel = compilation.GetSemanticModel(syntaxTree);
        }
Esempio n. 11
0
        public void Symbol()
        {
            var tree = CSharpSyntaxTree.ParseText(
                @"
public class MyClass {
    public int Method1() { return 0; }
    void Method2() { int x = Method1(); }
}
");

            var mscorlib    = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new [] { tree }, references: new [] { mscorlib }
                                                       );
            var model        = compilation.GetSemanticModel(tree);
            var methodSyntax = tree.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>().First();
            var methodSymbol = model.GetDeclaredSymbol(methodSyntax);

            methodSymbol.ToString().Should().Be("MyClass.Method1()");
            methodSymbol.ContainingType.Name.Should().Be("MyClass");
            methodSymbol.IsAbstract.Should().Be(false);
        }
Esempio n. 12
0
        public static Func <dynamic, dynamic> CompileMapExpression(string expression, string method, IEnumerable <KeyValuePair <string, string> > supportLambdas, Func <dynamic, string, dynamic> logger = null, string[] referencesIn = null)
        {
            try {
                if (IsLambda(expression))
                {
                    return(CompileLambda <dynamic, dynamic>(expression, supportLambdas, logger, referencesIn));
                }
                else if (IsTemplate(expression))
                {
                    return(CompileTemplate(expression));
                }
                else if (expression.EndsWith(".cs"))
                {
                    var asm = CSharpUtility.CompileAssembly(new string[] { File.ReadAllText($"{System.AppDomain.CurrentDomain.BaseDirectory}{expression}") },
                                                            referencesIn?.Select(r => PortableExecutableReference.CreateFromFile(r)).ToArray()
                                                            );

                    var path = Regex.Split(expression, "[.]");
                    return(RetrieveDelegate <dynamic, dynamic>(asm, path.First(), path.ElementAt(1), method));
                }
                else if (expression.EndsWith(".dll"))
                {
                    var path = Regex.Split(expression, "[.]");
                    var asm  = Assembly.LoadFrom(expression);
                    return(RetrieveDelegate <dynamic, dynamic>(asm, path.First(), path.ElementAt(1), method));
                }
                else
                {
                    return((i) => expression);
                }
            }
            catch (Exception e) {
                throw new Exception($"Unable to compile expression: '{expression}' {Environment.NewLine} {e.Message}", e);
            }

            throw new Exception($"Invalid expression provided: '{expression}'");
        }
Esempio n. 13
0
 public override ImmutableArray <PortableExecutableReference> ResolveReference(
     string reference, string baseFilePath, MetadataReferenceProperties properties)
 => ImmutableArray.Create(PortableExecutableReference.CreateFromFile(reference, properties));