Exemple #1
0
            public void StaticOtherType(Scope scope, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public static class Bar
    {
        public static int Value => 1;
    }

    public class Foo
    {
        public Foo()
        {
            Equals(Bar.Value, 2);
            int j = 3;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var node          = syntaxTree.FindConstructorDeclaration("Foo");

                using (var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None))
                {
                    Assert.AreEqual(expected, string.Join(", ", walker.Literals));
                }
            }
Exemple #2
0
        public void BackingFieldPrivateSetSimple()
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public sealed class Foo
    {
        private int bar;

        public int Bar
        {
            get { return this.bar; }
            private set { this.bar = value; }
        }

        public void Meh()
        {
            var temp = this.bar;
        }
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.FindEqualsValueClause("var temp = this.bar").Value;

            using (var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", assignedValues);
                Assert.AreEqual(string.Empty, actual);
            }
        }
Exemple #3
0
        public void RecursiveGetAndSet(string code, string expected)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public sealed class Foo
    {
        public Foo()
        {
            var temp1 = this.Bar;
            this.Bar = 2;
            var temp2 = this.Bar;
        }

        public int Bar
        {
            get { return this.Bar; }
            set { this.Bar = value; }
        }

        public void Meh()
        {
            var temp3 = this.Bar;
        }
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.FindEqualsValueClause(code).Value;

            using (var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", assignedValues);
                Assert.AreEqual(expected, actual);
            }
        }
        public void AsyncAwait(string code, Search search, string expected)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System;
    using System.Threading.Tasks;

    public class Disposable : IDisposable
    {
        public void Dispose()
        {
        }
    }

    internal class Foo
    {
        internal async Task Bar()
        {
            var value = // Meh();
        }

        internal static async Task<int> RecursiveAsync() => RecursiveAsync();

        internal static async Task<int> RecursiveAsync(int arg) => RecursiveAsync(arg);

        internal static async Task<string> CreateStringAsync()
        {
            await Task.Delay(0);
            return new string(' ', 1);
        }

        internal static async Task<string> ReturnAwaitTaskRunAsync()
        {
            await Task.Delay(0);
            return await Task.Run(() => new string(' ', 1)).ConfigureAwait(false);
        }

        internal static Task<int> CreateAsync(int arg)
        {
            switch (arg)
            {
                case 0:
                    return Task.FromResult(1);
                case 1:
                    return Task.FromResult(arg);
                case 2:
                    return Task.Run(() => 2);
                case 3:
                    return Task.Run(() => arg);
                case 4:
                    return Task.Run(() => { return 3; });
                default:
                    return Task.Run(() => { return arg; });
            }
        }

        internal static async int CreateInt() => 1;

        private static async Task<int> RecursiveAsync1(int value)
        {
            return await RecursiveAsync2(value);
        }
        
        private static async Task<int> RecursiveAsync2(int value)
        {
            return await RecursiveAsync1(value);
        }

        private static async Task<int> RecursiveAsync3(int value)
        {
            return RecursiveAsync4(value);
        }
        
        private static async Task<int> RecursiveAsync4(int value)
        {
            return await RecursiveAsync3(value);
        }
    }
}";

            testCode = testCode.AssertReplace("// Meh()", code);
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.BestMatch <EqualsValueClauseSyntax>(code).Value;

            using (var pooled = ReturnValueWalker.Create(value, search, semanticModel, CancellationToken.None))
            {
                Assert.AreEqual(expected, string.Join(", ", pooled.Item));
            }
        }
Exemple #5
0
            public static void Expression(string code, bool expected)
            {
                var testCode      = @"
namespace N
{
    internal class Foo
    {
        internal Foo(object o)
        {
            var value = PLACEHOLDER;
        }
    }
}".AssertReplace("PLACEHOLDER", code);
                var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                Assert.AreEqual(expected, Disposable.IsPotentiallyAssignableFrom(value, semanticModel, CancellationToken.None));
            }
Exemple #6
0
        // [TestCase("Method()")]
        public static void TryGetWalked(string expression)
        {
            var code          = @"
namespace RoslynSandbox
{
    class C
    {
        public readonly int field = typeof(int);

        public C()
        {
            var local = typeof(int);
            _ = local.ToString();
        }

        public Type CalculatedProperty => typeof(int);

        public Type GetOnlyProperty { get; } = typeof(int);

        public static Type Method() => typeof(int);
    }
}".AssertReplace("local.ToString()", $"{expression}.ToString()");
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = ((MemberAccessExpressionSyntax)syntaxTree.FindInvocation("ToString()").Expression).Expression;
            var context       = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None);

            Assert.AreEqual(true, Type.TryGet(node, context, out var type, out var source));
            Assert.AreEqual("int", type.ToDisplayString());
            Assert.AreEqual("typeof(int)", source.ToString());
        }
        public void Call(string code, Search search, string expected)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System;
    using System.Collections.Generic;

    internal class Foo
    {
        internal Foo()
        {
            var temp = // Meh();
        }

        internal static int StaticCreateIntStatementBody()
        {
            return 1;
        }

        internal static int StaticCreateIntExpressionBody() => 2;

        internal static int IdStatementBody(int arg)
        {
            return arg;
        }

        internal static int IdExpressionBody(int arg) => arg;

        internal static int OptionalIdExpressionBody(int arg = 1) => arg;

        internal static int CallingIdExpressionBody(int arg1) => IdExpressionBody(arg1);

        public static int AssigningToParameter(int arg)
        {
            if (true)
            {
                return arg;
            }
            else
            {
                if (true)
                {
                    arg = 2;
                }
                else
                {
                    arg = 3;
                }

                return arg;
            }

            return 4;
        }

        public static int ConditionalId(int arg)
        {
            if (true)
            {
                return arg;
            }

            return arg;
        }

        public static int ReturnLocal()
        {
            var local = 1;
            return local;
        }

        public static int ReturnLocalAssignedTwice(bool flag)
        {
            var local = 1;
            local = 2;
            if (flag)
            {
                return local;
            }

            local = 5;
            return 3;
        }

        public static int Recursive() => Recursive();

        public static int Recursive(int arg) => Recursive(arg);

        public static bool Recursive(bool flag)
        {
            if (flag)
            {
                return Recursive(!flag);
            }

            return flag;
        }

        public Foo ThisExpressionBody() => this;

        private static int RecursiveWithOptional(int arg, IEnumerable<int> args = null)
        {
            if (arg == null)
            {
                return RecursiveWithOptional(arg, new[] { arg });
            }

            return arg;
        }

        private static int Recursive1(int value)
        {
            return Recursive2(value);
        }

        private static int Recursive2(int value)
        {
            return Recursive1(value);
        }
    }
}";

            testCode = testCode.AssertReplace("// Meh()", code);
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.BestMatch <EqualsValueClauseSyntax>(code).Value;

            using (var pooled = ReturnValueWalker.Create(value, search, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", pooled.Item);
                Assert.AreEqual(expected, actual);
            }
        }
            public static void FieldCtorArgThenIdMethod(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class C
    {
        private readonly int value;

        internal C(int arg)
        {
            var temp1 = this.value;
            this.value = Id(arg);
            var temp2 = this.value;
        }

        internal void M(int arg)
        {
            var temp3 = this.value;
        }

        private static T Id<T>(T genericArg) => genericArg;
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
            public static void FieldInitializedlWithLiteralAndAssignedInCtor(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class C
    {
        private readonly int value = 1;
        private readonly int temp1;

        internal C()
        {
            this.temp1 = this.value;
            var temp1 = this.value;
            var temp2 = this.temp1;
            this.value = 2;
            var temp3 = this.value;
            var temp4 = this.temp1;
        }

        internal void M()
        {
            var temp5 = this.value;
            var temp6 = this.temp1;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
Exemple #10
0
        private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
            {
                // get states by id order to have deterministic checksum
                var documentChecksumsTasks          = DocumentIds.Select(id => DocumentStates[id].GetChecksumAsync(cancellationToken));
                var additionalDocumentChecksumTasks = AdditionalDocumentIds.Select(id => AdditionalDocumentStates[id].GetChecksumAsync(cancellationToken));

                var serializer = new Serializer(_solutionServices.Workspace.Services);

                var infoChecksum = serializer.CreateChecksum(new SerializedProjectInfo(Id, Version, Name, AssemblyName, Language, FilePath, OutputFilePath, IsSubmission), cancellationToken);

                var compilationOptionsChecksum = SupportsCompilation ? serializer.CreateChecksum(CompilationOptions, cancellationToken) : Checksum.Null;
                var parseOptionsChecksum       = SupportsCompilation ? serializer.CreateChecksum(ParseOptions, cancellationToken) : Checksum.Null;

                var projectReferenceChecksums  = new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray());
                var metadataReferenceChecksums = new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray());
                var analyzerReferenceChecksums = new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray());

                var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);

                var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);

                return(new ProjectStateChecksums(
                           infoChecksum,
                           compilationOptionsChecksum,
                           parseOptionsChecksum,
                           new DocumentChecksumCollection(documentChecksums),
                           projectReferenceChecksums,
                           metadataReferenceChecksums,
                           analyzerReferenceChecksums,
                           new TextDocumentChecksumCollection(additionalChecksums)));
            }
        }
            public static void FieldPublicCtorFactory(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class C
    {
        public int value = 1;

        public C(int ctorArg)
        {
            var temp1 = this.value;
            this.value = ctorArg;
            var temp2 = this.value;
        }

        internal static C Create()
        {
            return new C(2);
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
Exemple #12
0
        public void TryFindWhenProperty(Scope scope)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public class C
    {
        public int P { get; }

        public void M()
        {
            var p = this.P.ToString();
        }
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindMethodDeclaration("M");

            using (var walker = IdentifierNameExecutionWalker.Borrow(node, scope, semanticModel, CancellationToken.None))
            {
                CollectionAssert.AreEqual(new[] { "var", "P", "ToString" }, walker.IdentifierNames.Select(x => x.Identifier.ValueText));

                Assert.AreEqual(true, walker.TryFind("P", out var match));
                Assert.AreEqual("P", match.Identifier.ValueText);

                Assert.AreEqual(false, walker.TryFind("missing", out _));
            }
        }
Exemple #13
0
        public void DependencyPropertyRegisterReadOnly(Scope scope, string expected)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    using System.Windows;
    using System.Windows.Controls;

    public class FooControl : Control
    {
        private static readonly DependencyPropertyKey ValuePropertyKey = DependencyProperty.RegisterReadOnly(
            nameof(Value),
            typeof(int),
            typeof(FooControl), 
            new PropertyMetadata(default(int)));

        public static readonly DependencyProperty ValueProperty = ValuePropertyKey.DependencyProperty;

        public int Value
        {
            get => (int) this.GetValue(ValueProperty);
            private set => this.SetValue(ValuePropertyKey, value);
        }
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindExpression("ValuePropertyKey.DependencyProperty");

            using (var walker = IdentifierNameExecutionWalker.Borrow(node, scope, semanticModel, CancellationToken.None))
            {
                Assert.AreEqual(expected, string.Join(", ", walker.IdentifierNames));
            }
        }
Exemple #14
0
        public void StaticInitializers(Scope scope, string expected)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public sealed class Foo
    {
        public static readonly Foo Default = new Foo();
        
        private static readonly string text = ""abc"";
        
        public string Text { get; set; } = text;
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindExpression("new Foo()");

            using (var walker = IdentifierNameExecutionWalker.Borrow(node, scope, semanticModel, CancellationToken.None))
            {
                Assert.AreEqual(expected, string.Join(", ", walker.IdentifierNames));
            }
        }
Exemple #15
0
        public static void TryGetAssemblyLoad(string expression)
        {
            var code          = @"
namespace RoslynSandbox
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    class C
    {
        public readonly int Field;

        public C(C foo)
        {
            var type = Assembly.Load(""mscorlib"").GetType(""System.Int32"");
        }

        public int Property { get; }

        public class Baz<T>
        {
        }

        public class Nested { }
    }
}".AssertReplace("Assembly.Load(\"mscorlib\").GetType(\"System.Int32\")", expression);
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindExpression(expression);
            var context       = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None);

            Assert.AreEqual(false, Type.TryGet(node, context, out _, out _));
        }
            public static void InitializedInChainedWithLiteralGeneric(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class C<T>
    {
        internal C()
        {
            this.Value = 2;
        }

        internal C(string text)
            : this()
        {
            this.Value = 3;
            var temp1 = this.Value;
            this.Value = 4;
        }

        public int Value { get; set; } = 1;

        internal void M()
        {
            var temp2 = this.Value;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
Exemple #17
0
        public static void TryGet(string expression, string expected, string expectedSource)
        {
            var code          = @"
namespace RoslynSandbox
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    class C
    {
        public readonly int Field;

        public C(C foo, int? nullableInt)
        {
            var type = typeof(C);
        }

        public int Property { get; }

        public class Baz<T>
        {
        }

        public class Nested { }
    }
}".AssertReplace("typeof(C)", expression);
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindExpression(expression);
            var context       = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None);

            Assert.AreEqual(true, Type.TryGet(node, context, out var type, out var source));
            Assert.AreEqual(expected, type.ToDisplayString());
            Assert.AreEqual(expectedSource, source.ToString());
        }
            public static void InitializedInExplicitBaseCtorWithLiteral(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class Base
    {
        protected int value = 1;

        public Base()
        {
            this.value = -1;
        }

        public Base(int value)
        {
            this.value = value;
        }
    }

    internal class C : Base
    {
        internal C()
            : base(2)
        {
            this.value = 3;
            var temp1 = this.value;
            this.value = 4;
        }

        internal void M()
        {
            var temp2 = this.value;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
        public void AwaitSyntaxError(Search search, string expected)
        {
            var testCode      = @"
using System.Threading.Tasks;

internal class Foo
{
    internal static async Task Bar()
    {
        var text = await CreateAsync().ConfigureAwait(false);
    }

    internal static async Task<string> CreateAsync()
    {
        await Task.Delay(0);
        return await Task.SyntaxError(() => new string(' ', 1)).ConfigureAwait(false);
    }
}";
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.BestMatch <EqualsValueClauseSyntax>("var text = await CreateAsync()").Value;

            using (var pooled = ReturnValueWalker.Create(value, search, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", pooled.Item);
                Assert.AreEqual(expected, actual);
            }
        }
            public static void AbstractGenericInitializedInBaseCtorSimple()
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    public abstract class Base<T>
    {
        protected Base()
        {
            this.Value = default(T);
        }

        public abstract T Value { get; set; }
    }

    public class C : Base<int>
    {
        public C()
        {
            var temp = this.Value;
        }

        public override int Value { get; set; }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause("var temp = this.Value;").Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual("default(T)", actual);
            }
        public void Lambda(string code, Search search, string expected)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System;

    internal class Foo
    {
        internal Foo()
        {
            Func<int> temp = () => 1;
        }

        internal static int StaticCreateIntStatementBody()
        {
            return 1;
        }
    }
}";

            testCode = testCode.AssertReplace("Func<int> temp = () => 1", code);
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.BestMatch <EqualsValueClauseSyntax>(code).Value;

            using (var pooled = ReturnValueWalker.Create(value, search, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", pooled.Item);
                Assert.AreEqual(expected, actual);
            }
        }
            public static void FieldChainedCtor(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class C
    {
        public int value = 1;

        internal C()
        {
            var temp1 = this.value;
            this.value = 2;
            var temp2 = this.value;
        }

        internal C(string text)
            : this()
        {
            var temp3 = this.value;
            this.value = 3;
            var temp4 = this.value;
            this.value = 4;
            var temp5 = this.value;
        }

        internal void M(int arg)
        {
            var temp6 = this.value;
            this.value = 5;
            var temp7 = this.value;
            this.value = arg;
            var temp8 = this.value;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
        public void Property(string code, Search search, string expected)
        {
            var testCode = @"
namespace RoslynSandbox
{
    internal class Foo
    {
        private readonly int value = 1;

        internal Foo()
        {
            var temp = // Meh();
        }


        public static int StaticRecursiveExpressionBody => StaticRecursiveExpressionBody;

        public static int StaticRecursiveStatementBody
        {
            get
            {
                return StaticRecursiveStatementBody;
            }
        }

        public int RecursiveExpressionBody => this.RecursiveExpressionBody;

        public int RecursiveStatementBody
        {
            get
            {
                return this.RecursiveStatementBody;
            }
        }


        public int CalculatedExpressionBody => 1;

        public int CalculatedStatementBody
        {
            get
            {
                return 1;
            }
        }

        public Foo ThisExpressionBody => this;

        public int CalculatedReturningFieldExpressionBody => this.value;

        public int CalculatedReturningFieldStatementBody
        {
            get
            {
                return this.value;
            }
        }
    }
}";

            testCode = testCode.AssertReplace("// Meh()", code);
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.BestMatch <EqualsValueClauseSyntax>(code).Value;

            using (var pooled = ReturnValueWalker.Create(value, search, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", pooled.Item);
                Assert.AreEqual(expected, actual);
            }
        }
            public static void InitializedInBaseCtorWithDefaultGenericGeneric(string code, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    internal class Base<T>
    {
        protected readonly T value;

        internal Base()
        {
            this.value = default(T);
        }

        internal Base(T value)
        {
            this.value = value;
        }
    }

    internal class C<T> : Base<T>
    {
        internal C()
        {
            var temp1 = this.value;
        }

        internal void M()
        {
            var temp2 = this.value;
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindEqualsValueClause(code).Value;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                var actual = string.Join(", ", assignedValues);

                Assert.AreEqual(expected, actual);
            }
Exemple #25
0
 /// <summary>
 /// Creates a new <see cref="ScriptOptions"/> with the references changed.
 /// </summary>
 /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
 private ScriptOptions WithReferences(ImmutableArray <MetadataReference> references) =>
 MetadataReferences.Equals(references) ? this : new ScriptOptions(this)
 {
     MetadataReferences = CheckImmutableArray(references, nameof(references))
 };
            public static void FieldAssignedInLambdaCtor()
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace N
{
    using System;

    public class C
    {
        private int value;

        public C()
        {
            Console.CancelKeyPress += (o, e) =>
            {
                this.value = 1;
            };
        }
    }
}");
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var value         = syntaxTree.FindAssignmentExpression("this.value = 1").Left;

                using var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None);
                Assert.AreEqual("1", assignedValues.Single().ToString());
            }
Exemple #27
0
        public void BackingFieldPublicSetInitializedAndPropertyAssignedInCtorWeirdSetter(string code, string expected)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public sealed class Foo
    {
        private int bar = 1;

        public Foo()
        {
            var temp1 = this.bar;
            var temp2 = this.Bar;
            this.Bar = 2;
            var temp3 = this.bar;
            var temp4 = this.Bar;
        }

        public int Bar
        {
            get { return this.bar; }
            set
            {
                if (true)
                {
                    this.bar = value;
                }
                else
                {
                    this.bar = value;
                }

                this.bar = value / 2;
                this.bar = 3;
            }
        }

        public void Meh()
        {
            var temp5 = this.bar;
            var temp6 = this.Bar;
        }
    }
}");
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.FindEqualsValueClause(code).Value;

            using (var assignedValues = AssignedValueWalker.Borrow(value, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", assignedValues);
                Assert.AreEqual(expected, actual);
            }
        }
        public void TryMostSpecificWhenAmbiguous(string filterTypes, string signature1, string signature2)
        {
            var code = @"
namespace RoslynSandbox
{
    using System;

    public class C
    {
        public object Get() => typeof(C).GetMethod(nameof(this.M), new[] { typeof(FilterType) });

        public void M(Type1 _) { }

        public void M(Type2 _) { }
    }
}".AssertReplace("new[] { typeof(FilterType) }", filterTypes)
                       .AssertReplace("M(Type1 _)", signature1)
                       .AssertReplace("M(Type2 _)", signature2);

            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var m1            = semanticModel.GetDeclaredSymbol(syntaxTree.FindMethodDeclaration(signature1), CancellationToken.None);
            var m2            = semanticModel.GetDeclaredSymbol(syntaxTree.FindMethodDeclaration(signature2), CancellationToken.None);
            var invocation    = syntaxTree.FindInvocation("GetMethod");
            var context       = new SyntaxNodeAnalysisContext(null, semanticModel, null, null, null, CancellationToken.None);

            Assert.AreEqual(true, Types.TryCreate(invocation, (IMethodSymbol)semanticModel.GetSymbolInfo(invocation).Symbol, context, out var types));
            Assert.AreEqual(false, types.TryMostSpecific(m1, m2, out _));
        }
Exemple #29
0
        public void Recursive()
        {
            var syntaxTree       = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public class Foo
    {
        private Bar bar1;
        private Bar bar2;

        public Bar Bar1
        {
            get
            {
                return this.bar1;
            }

            set
            {
                if (Equals(value, this.bar1))
                {
                    return;
                }

                if (value != null && this.bar2 != null)
                {
                    this.Bar2 = null;
                }

                if (this.bar1 != null)
                {
                    this.bar1.Selected = false;
                }

                this.bar1 = value;
                if (this.bar1 != null)
                {
                    this.bar1.Selected = true;
                }
            }
        }

        public Bar Bar2
        {
            get
            {
                return this.bar2;
            }

            set
            {
                if (Equals(value, this.bar2))
                {
                    return;
                }

                if (value != null && this.bar1 != null)
                {
                    this.Bar1 = null;
                }

                if (this.bar2 != null)
                {
                    this.bar2.Selected = false;
                }

                this.bar2 = value;
                if (this.bar2 != null)
                {
                    this.bar2.Selected = true;
                }
            }
        }
    }

    public class Bar
    {
        public bool Selected { get; set; }
    }
}");
            var compilation      = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel    = compilation.GetSemanticModel(syntaxTree);
            var fieldDeclaration = syntaxTree.FindFieldDeclaration("bar1");
            var field            = semanticModel.GetDeclaredSymbolSafe(fieldDeclaration, CancellationToken.None);

            using (var assignedValues = AssignedValueWalker.Borrow(field, semanticModel, CancellationToken.None))
            {
                var actual = string.Join(", ", assignedValues);
                Assert.AreEqual("null, value", actual);
            }
        }
Exemple #30
0
            public void Binary(string expression, Scope scope, string expected)
            {
                var syntaxTree    = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public class Foo
    {
        public object Value1 => 1;

        public object Value2 => 2;

        public object Bar() => Value1 ?? Value2;
    }
}".AssertReplace("Value1 ?? Value2", expression));
                var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var node          = syntaxTree.FindMethodDeclaration("Bar");

                using (var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None))
                {
                    Assert.AreEqual(expected, string.Join(", ", walker.Literals));
                }
            }