PageRenderTime 13ms CodeModel.GetById 2ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/Compilers/CSharp/Test/Symbol/Compilation/GetUnusedImportDirectivesTests.cs

https://github.com/EkardNT/Roslyn
C# | 362 lines | 307 code | 25 blank | 30 comment | 0 complexity | 1981b9479c23a2e314e321eab489bf9d MD5 | raw file
  1// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
  2
  3using System.Collections.Immutable;
  4using System.Linq;
  5using Microsoft.CodeAnalysis.CSharp.Syntax;
  6using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
  7using Microsoft.CodeAnalysis.Test.Utilities;
  8using Roslyn.Test.Utilities;
  9using Roslyn.Utilities;
 10using Xunit;
 11
 12namespace Microsoft.CodeAnalysis.CSharp.UnitTests
 13{
 14    public class GetUnusedImportDirectivesTests : SemanticModelTestBase
 15    {
 16        [Fact]
 17        public void UnusedUsing1()
 18        {
 19            var text = @"
 20using System;
 21
 22class C
 23{
 24    void Foo()
 25    {
 26    }
 27}";
 28            var tree = Parse(text);
 29            var comp = CreateCompilationWithMscorlib(tree);
 30
 31            comp.VerifyDiagnostics(
 32                // (2,1): info CS8019: Unnecessary using directive.
 33                // using System;
 34                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;"));
 35        }
 36
 37
 38        [WorkItem(865627, "DevDiv")]
 39        [Fact]
 40        public void TestUnusedExtensionMarksImportsAsUsed()
 41        {
 42           string class1Source = @"using System;
 43
 44namespace ClassLibrary1
 45{
 46    public class Class1
 47    {
 48        public void Method1(string arg1)
 49        {
 50            Console.WriteLine(arg1);
 51        }
 52    }
 53} 
 54";
 55            var classLib1 = CreateCompilationWithMscorlib(text: class1Source, references: new[] { SystemRef }, assemblyName: "ClassLibrary1");
 56
 57            string class2Source = @"using System;
 58using ClassLibrary1;
 59
 60namespace ClassLibrary2
 61{
 62    public static class Class2
 63    {
 64        public static void Method1(this Class1 arg0, string arg1)
 65        {
 66            Console.Write(""Erroneous: "" + arg1);
 67        }
 68    }
 69}";
 70            var classLib2 = CreateCompilationWithMscorlib(text: class2Source, assemblyName: "ClassLibrary2", references: new[] { SystemRef, SystemCoreRef, classLib1.ToMetadataReference() });
 71
 72
 73            string consoleApplicationSource = @"using ClassLibrary2;
 74using ClassLibrary1;
 75
 76namespace ConsoleApplication
 77{
 78    class Program
 79    {
 80        static void Main(string[] args)
 81        {
 82            var instance1 = new Class1();
 83            instance1.Method1(""Argument1"");
 84        }
 85    }
 86}";
 87            var tree = Parse(consoleApplicationSource);
 88            var comp = CreateCompilationWithMscorlib(tree, new[] { SystemRef, SystemCoreRef, classLib1.ToMetadataReference(), classLib2.ToMetadataReference() }, assemblyName: "ConsoleApplication");
 89            var model = comp.GetSemanticModel(tree) as CSharpSemanticModel;
 90
 91            var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression;
 92
 93            //This is the crux of the test.
 94            //Without this line, with or without the fix, the model never gets pushed to evaluate extension method candidates
 95            //and therefor never marked ClassLibrary2 as a used import in consoleApplication.
 96            //Without the fix, this call used to result in ClassLibrary2 getting marked as used, after the fix, this call does not
 97            //result in changing ClassLibrary2's used status.
 98            model.GetMemberGroup(syntax);
 99
100            model.GetDiagnostics().Verify(Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using ClassLibrary2;"));
101        }
102
103        [WorkItem(747219, "DevDiv2/DevDiv")]
104        [Fact]
105        public void UnusedUsing747219()
106        {
107            var text = @"
108using System;
109using System.Collections.Generic;
110using System.Linq;
111using System.Threading.Tasks;
112 
113class Program
114{
115    static void Main(string[] args)
116    {
117        Enumerable.Repeat(1, 1);
118    }
119}";
120            var tree = Parse(text);
121            var comp = CreateCompilationWithMscorlib(tree);
122            //all unused because system.core was not included and Eunmerable didn't bind
123            comp.VerifyDiagnostics(
124                // (4,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
125                // using System.Linq;
126                Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Linq").WithArguments("Linq", "System"),
127                // (11,9): error CS0103: The name 'Enumerable' does not exist in the current context
128                //         Enumerable.Repeat(1, 1);
129                Diagnostic(ErrorCode.ERR_NameNotInContext, "Enumerable").WithArguments("Enumerable"),
130                // (4,1): info CS8019: Unnecessary using directive.
131                // using System.Linq;
132                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Linq;"),
133                // (2,1): info CS8019: Unnecessary using directive.
134                // using System;
135                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;"),
136                // (3,1): info CS8019: Unnecessary using directive.
137                // using System.Collections.Generic;
138                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Collections.Generic;"),
139                // (5,1): info CS8019: Unnecessary using directive.
140                // using System.Threading.Tasks;
141                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Threading.Tasks;")
142                );
143
144
145            comp = comp.WithReferences(comp.References.Concat(SystemCoreRef));
146            comp.VerifyDiagnostics(
147                // (2,1): info CS8019: Unnecessary using directive.
148                // using System;
149                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;"),
150                // (3,1): info CS8019: Unnecessary using directive.
151                // using System.Collections.Generic;
152                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Collections.Generic;"),
153                // (5,1): info CS8019: Unnecessary using directive.
154                // using System.Threading.Tasks;
155                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Threading.Tasks;")
156                );
157        }
158
159        [Fact]
160        public void UsedUsing1()
161        {
162            var text = @"
163using System;
164
165class C
166{
167    void Foo()
168    {
169        Console.WriteLine();
170    }
171}";
172            var tree = Parse(text);
173            var comp = CreateCompilationWithMscorlib(tree);
174            comp.VerifyDiagnostics();
175        }
176
177        [Fact]
178        public void SpeculativeBindingDoesNotAffectResult()
179        {
180            var text = @"
181using System;
182
183class C
184{
185    void Foo()
186    {
187        /*here*/
188    }
189}";
190            var tree = Parse(text);
191            var comp = CreateCompilationWithMscorlib(tree);
192            var model = comp.GetSemanticModel(tree);
193
194            var position = text.IndexOf("/*here*/");
195            var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.IdentifierName("Console"), SpeculativeBindingOption.BindAsTypeOrNamespace);
196            Assert.NotNull(info.Symbol);
197            Assert.Equal(SymbolKind.NamedType, info.Symbol.Kind);
198            Assert.Equal("Console", info.Symbol.Name);
199            Assert.Equal(SymbolKind.Namespace, info.Symbol.ContainingSymbol.Kind);
200            Assert.Equal("System", info.Symbol.ContainingSymbol.Name);
201
202            comp.VerifyDiagnostics(
203                // (2,1): info CS8019: Unnecessary using directive.
204                // using System;
205                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;")
206                );
207        }
208
209        [Fact]
210        public void AllAssemblyLevelAttributesMustBeBound()
211        {
212            var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.SymbolsTests.General.snKey).Path;
213
214            var signing = Parse(@"
215using System.Reflection;
216
217[assembly: AssemblyVersion(""1.2.3.4"")]
218[assembly: AssemblyKeyFile(@""" + snkPath + @""")]
219");
220
221            var ivtCompilation = CreateCompilationWithMscorlib(
222                assemblyName: "IVT",
223                compOptions: TestOptions.Dll.WithStrongNameProvider(new DesktopStrongNameProvider()),
224                references: new[] {SystemCoreRef},
225                trees: new[] 
226                {
227                    Parse(@"
228using System.Runtime.CompilerServices;
229
230[assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
231
232namespace NamespaceContainingInternalsOnly
233{
234    internal static class Extensions
235    {
236        internal static void Foo(this int x) {}
237    }
238}
239"),
240                    signing
241                });
242
243            var libCompilation = CreateCompilationWithMscorlib(
244                assemblyName: "Lib",
245                compOptions: TestOptions.Dll.WithStrongNameProvider(new DesktopStrongNameProvider()),
246                references: new[] { ivtCompilation.ToMetadataReference() },
247                trees: new[]
248                {
249                    Parse(@"
250using NamespaceContainingInternalsOnly;
251
252public class C
253{
254    internal static void F(int x)
255    {
256        x.Foo();
257    }
258}
259"),
260                    signing
261                });
262
263            libCompilation.VerifyDiagnostics();
264        }
265
266        [WorkItem(747219, "DevDiv")]
267        [Fact]
268        public void SemanticModelCallDoesNotCountsAsUse()
269        {
270            var source = @"
271using System.Collections;
272using System.Collections.Generic;
273
274class C 
275{
276    void M()
277    {
278        return;
279    }
280}";
281
282            var comp = CreateCompilationWithMscorlib(source);
283            comp.VerifyDiagnostics(
284                // (2,1): info CS8019: Unnecessary using directive.
285                // using System.Collections;
286                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Collections;"),
287                // (3,1): info CS8019: Unnecessary using directive.
288                // using System.Collections.Generic;
289                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Collections.Generic;")
290                );
291        }
292
293        [WorkItem(747219, "DevDiv")]
294        [Fact]
295        public void INF_UnusedUsingDirective()
296        {
297            var source = @"
298using System.Collections;
299using C = System.Console;
300";
301
302            CreateCompilationWithMscorlib(source).VerifyDiagnostics(
303                // (2,1): info CS8019: Unnecessary using directive.
304                // using System.Collections;
305                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Collections;"),
306                // (3,1): info CS8019: Unnecessary using directive.
307                // using C = System.Console;
308                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using C = System.Console;"));
309        }
310
311        [WorkItem(747219, "DevDiv")]
312        [Fact]
313        public void INF_UnusedExternAlias()
314        {
315            var source = @"
316extern alias A;
317";
318            var lib = CreateCompilation("", assemblyName: "lib");
319            var comp = CreateCompilationWithMscorlib(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("A")) });
320
321            comp.VerifyDiagnostics(
322                // (2,1): info CS8020: Unused extern alias.
323                // extern alias A;
324                Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias A;"));
325        }
326
327        [WorkItem(747219, "DevDiv")]
328        [Fact]
329        public void CrefCountsAsUse()
330        {
331            var source = @"
332using System;
333
334/// <see cref='Console'/>
335public class C { }
336";
337
338            // Not binding doc comments.
339            CreateCompilationWithMscorlib(source).VerifyDiagnostics(
340                // (2,1): info CS8019: Unnecessary using directive.
341                // using System;
342                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;"));
343
344            // Binding doc comments.
345            CreateCompilationWithMscorlibAndDocumentationComments(source).VerifyDiagnostics();
346        }
347
348        [WorkItem(770147, "DevDiv")]
349        [Fact]
350        public void InfoAndWarnAsError()
351        {
352            var source = @"
353using System;
354";
355            var comp = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll.WithGeneralDiagnosticOption(ReportDiagnostic.Error));
356            comp.VerifyEmitDiagnostics(
357                // (2,1): info CS8019: Unnecessary using directive.
358                // using System;
359                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;").WithWarningAsError(false));
360        }
361    }
362}