Exemplo n.º 1
0
        private static void MakeLambdaAndClosureMaps(
            ImmutableArray <LambdaDebugInfo> lambdaDebugInfo,
            ImmutableArray <ClosureDebugInfo> closureDebugInfo,
            out IReadOnlyDictionary <int, KeyValuePair <DebugId, int> > lambdaMap,
            out IReadOnlyDictionary <int, DebugId> closureMap)
        {
            var lambdas  = new Dictionary <int, KeyValuePair <DebugId, int> >(lambdaDebugInfo.Length);
            var closures = new Dictionary <int, DebugId>(closureDebugInfo.Length);

            for (int i = 0; i < lambdaDebugInfo.Length; i++)
            {
                var lambdaInfo = lambdaDebugInfo[i];
                lambdas[lambdaInfo.SyntaxOffset] = KeyValuePairUtil.Create(lambdaInfo.LambdaId, lambdaInfo.ClosureOrdinal);
            }

            for (int i = 0; i < closureDebugInfo.Length; i++)
            {
                var closureInfo = closureDebugInfo[i];
                closures[closureInfo.SyntaxOffset] = closureInfo.ClosureId;
            }

            lambdaMap  = lambdas;
            closureMap = closures;
        }
        private static void ReadCSharpNativeImportsInfo(
            ISymUnmanagedReader3 reader,
            EESymbolProvider <TTypeSymbol, TLocalSymbol> symbolProvider,
            int methodToken,
            int methodVersion,
            out ImmutableArray <ImmutableArray <ImportRecord> > importRecordGroups,
            out ImmutableArray <ExternAliasRecord> externAliasRecords)
        {
            ImmutableArray <string> externAliasStrings;

            var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings(
                methodToken,
                KeyValuePairUtil.Create(reader, methodVersion),
                getMethodCustomDebugInfo: (token, arg) => GetCustomDebugInfoBytes(arg.Key, token, arg.Value),
                getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value),
                externAliasStrings: out externAliasStrings);

            Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);

            ArrayBuilder <ImmutableArray <ImportRecord> >?importRecordGroupBuilder = null;
            ArrayBuilder <ExternAliasRecord>?externAliasRecordBuilder = null;

            if (!importStringGroups.IsDefault)
            {
                importRecordGroupBuilder = ArrayBuilder <ImmutableArray <ImportRecord> > .GetInstance(importStringGroups.Length);

                foreach (var importStringGroup in importStringGroups)
                {
                    var groupBuilder = ArrayBuilder <ImportRecord> .GetInstance(importStringGroup.Length);

                    foreach (var importString in importStringGroup)
                    {
                        if (TryCreateImportRecordFromCSharpImportString(symbolProvider, importString, out var record))
                        {
                            groupBuilder.Add(record);
                        }
                        else
                        {
                            Debug.WriteLine($"Failed to parse import string {importString}");
                        }
                    }
                    importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree());
                }

                if (!externAliasStrings.IsDefault)
                {
                    externAliasRecordBuilder = ArrayBuilder <ExternAliasRecord> .GetInstance(externAliasStrings.Length);

                    foreach (var externAliasString in externAliasStrings)
                    {
                        if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out var alias, out var externAlias, out var target, out var kind))
                        {
                            Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'");
                            continue;
                        }

                        Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?");
                        RoslynDebug.Assert(alias != null);       // Name of the extern alias.
                        RoslynDebug.Assert(externAlias == null); // Not used.
                        RoslynDebug.Assert(target != null);      // Name of the target assembly.

                        if (!AssemblyIdentity.TryParseDisplayName(target, out var targetIdentity))
                        {
                            Debug.WriteLine($"Unable to parse target of extern alias '{externAliasString}'");
                            continue;
                        }

                        externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity));
                    }
                }
            }

            importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray <ImmutableArray <ImportRecord> > .Empty;
            externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray <ExternAliasRecord> .Empty;
        }
Exemplo n.º 3
0
        private ImageResource CreateImageResource(int width, int height, double borderSize)
        {
            ImageResource resource2;
            double        x = borderSize / 2.0;

            using (ISurface <ColorBgra> surface = SurfaceAllocator.Bgra.Allocate(width, height, AllocationOptions.ZeroFillNotRequired))
            {
                using (IDrawingContext context = DrawingContext.FromSurface(surface, AlphaMode.Premultiplied, FactorySource.PerThread))
                {
                    RectDouble num4;
                    context.Clear(null);
                    RectDouble num2        = new RectDouble(x, x, width - borderSize, height - borderSize);
                    double     aspectRatio = this.AspectRatio;
                    if (aspectRatio > 1.0)
                    {
                        double num5 = num2.Height / aspectRatio;
                        num4 = new RectDouble(num2.X, num2.Y + ((num2.Height - num5) / 2.0), num2.Width, num5);
                    }
                    else if (aspectRatio < 1.0)
                    {
                        double num6 = num2.Width * aspectRatio;
                        num4 = new RectDouble(num2.X + ((num2.Width - num6) / 2.0), num2.Y, num6, num2.Height);
                    }
                    else
                    {
                        num4 = num2;
                    }
                    IDictionary <string, object> settingValues = (from p in this.RenderSettingPaths select KeyValuePairUtil.Create <string, object>(p, AppSettings.Instance[ConvertToolsPathToToolDefaultsPath(p)].Value)).ToDictionary <string, object>();
                    ShapeRenderParameters        renderParams  = new ShapeRenderParameters(num4.TopLeft, num4.BottomRight, new VectorDouble(1.0, 1.0), settingValues, null);
                    PropertyCollection           properties    = this.CreatePropertyCollection(renderParams);
                    this.OnSetImagePropertyCollectionValues(renderParams, properties);
                    IDictionary <object, object> propertyValues = (from p in properties select KeyValuePairUtil.Create <object, object>(p.GetOriginalNameValue(), p.Value)).ToDictionary <object, object>();
                    ShapeRenderParameters        parameters2    = new ShapeRenderParameters(num4.TopLeft, num4.BottomRight, new VectorDouble(1.0, 1.0), settingValues, propertyValues);
                    ShapeRenderData            data             = this.CreateImageRenderData(parameters2);
                    PaintDotNet.UI.Media.Brush brush            = SolidColorBrushCache.Get((ColorRgba128Float)ColorBgra.FromUInt32(0xff5894c1));
                    if (data.InteriorFill != null)
                    {
                        context.FillGeometry(data.InteriorFill.Geometry, SolidColorBrushCache.Get((ColorRgba128Float)Colors.White), null);
                        LinearGradientBrush brush2 = new LinearGradientBrush {
                            StartPoint = num4.TopLeft,
                            EndPoint   = num4.BottomRight
                        };
                        brush2.GradientStops.Add(new GradientStop((ColorRgba128Float)ColorBgra32.FromUInt32(0xffc0e1f3), 0.0));
                        brush2.GradientStops.Add(new GradientStop((ColorRgba128Float)ColorBgra32.FromUInt32(0xffe0eff8), 1.0));
                        context.FillGeometry(data.InteriorFill.Geometry, brush2, null);
                    }
                    if ((data.InteriorFill != null) && (data.OutlineDraw != null))
                    {
                        RenderLayer layer = RenderLayerCache.Get();
                        using (context.UseLayer(layer, null, data.InteriorFill.Geometry, AntialiasMode.PerPrimitive, null, 1.0, null, LayerOptions.None))
                        {
                            context.DrawGeometry(data.OutlineDraw.Geometry, SolidColorBrushCache.Get((ColorRgba128Float)Colors.White), 3.0);
                        }
                        RenderLayerCache.Return(layer);
                    }
                    if (data.OutlineDraw != null)
                    {
                        context.DrawGeometry(data.OutlineDraw.Geometry, brush, 1.0);
                    }
                    if (data.OutlineFill != null)
                    {
                        context.FillGeometry(data.OutlineFill.Geometry, brush, null);
                    }
                    string imageStringOverlay = this.ImageStringOverlay;
                    if (imageStringOverlay != string.Empty)
                    {
                        double     num7       = (width * 7.0) / 16.0;
                        double     fontSize   = UIUtil.ScaleWidth(num7);
                        TextLayout textLayout = new TextLayout(imageStringOverlay, "Arial", FontWeight.Normal, PaintDotNet.DirectWrite.FontStyle.Normal, FontStretch.Normal, fontSize)
                        {
                            ParagraphAlignment = ParagraphAlignment.Center,
                            TextAlignment      = PaintDotNet.DirectWrite.TextAlignment.Center,
                            MaxWidth           = width - 2,
                            MaxHeight          = height - 2
                        };
                        context.DrawTextLayout(new PointDouble(1.0, 1.0), textLayout, SolidColorBrushCache.Get((ColorRgba128Float)ColorBgra.FromUInt32(0xff5894c1)), DrawTextOptions.None);
                    }
                }
                surface.ConvertFromPremultipliedAlpha();
                using (System.Drawing.Bitmap bitmap = surface.CreateAliasedGdipBitmap())
                {
                    System.Drawing.Bitmap image = new System.Drawing.Bitmap(bitmap);
                    resource2 = ImageResource.FromImage(image);
                }
            }
            return(resource2);
        }
Exemplo n.º 4
0
 private void OnConstructing()
 {
     this.services = new List <KeyValuePair <Type, IObjectRef> >();
     this.services.Add(KeyValuePairUtil.Create <Type, IObjectRef>(typeof(IResourceCache), this));
 }
 private static async Task <ImmutableArray <ITagSpan <InlineDiagnosticsTag> > > GetTagSpansAsync(TestWorkspace workspace)
 {
     workspace.ApplyOptions(new[] { KeyValuePairUtil.Create(new OptionKey2(InlineDiagnosticsOptions.EnableInlineDiagnostics, LanguageNames.CSharp), (object)true) });
     return((await TestDiagnosticTagProducer <InlineDiagnosticsTaggerProvider, InlineDiagnosticsTag> .GetDiagnosticsAndErrorSpans(workspace)).Item2);
 }
Exemplo n.º 6
0
        public ProjectState AddAnalyzerConfigDocuments(ImmutableArray <AnalyzerConfigDocumentState> documents)
        {
            Debug.Assert(!documents.Any(d => this._analyzerConfigDocumentStates.ContainsKey(d.Id)));

            var newAnalyzerConfigDocumentStates = _analyzerConfigDocumentStates.AddRange(documents.Select(d => KeyValuePairUtil.Create(d.Id, d)));

            return(CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates));
        }
        private static DiagnosticAnalyzerInfoCache CreateHostAnalyzerManager(string language, ImmutableArray <DiagnosticAnalyzer> analyzers)
        {
            var map = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePairUtil.Create(language, analyzers)));

            return(CreateHostAnalyzerManager(map));
        }
Exemplo n.º 8
0
        public void ReferenceSearchPaths_LIB()
        {
            var cwd = Temp.CreateDirectory();

            cwd.CreateFile("a.csx").WriteAllText(@"Console.Write(typeof(C).Name);");

            var dir = Temp.CreateDirectory();

            dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1);

            var result = ProcessUtilities.Run(CsiPath, "/r:C.dll a.csx", workingDirectory: cwd.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("LIB", dir.Path) });

            // error CS0006: Metadata file 'C.dll' could not be found
            Assert.True(result.Errors.StartsWith("error CS0006", StringComparison.Ordinal));
            Assert.True(result.ContainsErrors);
        }
Exemplo n.º 9
0
            public bool TryGetDocumentOption(OptionKey option, out object value)
            {
                if (codingConventionsSnapshot != null)
                {
                    var editorConfigPersistence = option.Option.StorageLocations.OfType <IEditorConfigStorageLocation> ().SingleOrDefault();
                    if (editorConfigPersistence != null)
                    {
                        // Temporarly map our old Dictionary<string, object> to a Dictionary<string, string>. This can go away once we either
                        // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take
                        // some interface that lets us pass both the Dictionary<string, string> we get from the new system, and the
                        // Dictionary<string, object> from the old system.
                        //
                        // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser
                        // that the instance doesn't regularly change and thus can be used for further caching
                        var allRawConventions = s_convertedDictionaryCache.GetValue(
                            codingConventionsSnapshot.AllRawConventions,
                            d => ImmutableDictionary.CreateRange(d.Select(c => KeyValuePairUtil.Create(c.Key, c.Value.ToString()))));

                        try {
                            if (editorConfigPersistence.TryGetOption(allRawConventions, option.Option.Type, out value))
                            {
                                return(true);
                            }
                        } catch (Exception ex) {
                            LoggingService.LogError("Error while getting editor config preferences.", ex);
                        }
                    }
                }

                if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize)
                {
                    value = TextPolicy.IndentWidth;
                    return(true);
                }

                if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine)
                {
                    value = TextPolicy.GetEolMarker();
                    return(true);
                }

                if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent)
                {
                    value = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart;
                    return(true);
                }

                if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize)
                {
                    value = TextPolicy.TabWidth;
                    return(true);
                }

                if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs)
                {
                    value = !TextPolicy.TabsToSpaces;
                    return(true);
                }

                var result = Policy.OptionSet.GetOption(option);

                value = result;
                return(true);
            }
Exemplo n.º 10
0
        private void Initialize()
        {
            if ((this.allShapePropertyValuesMap == null) && (this.allShapePropertyValuesArray != null))
            {
                this.allShapePropertyValuesMap = ShapePropertyValuesUtil.ToReadOnlyMap(this.allShapePropertyValuesArray);
            }
            PaintDotNet.UI.Media.DashStyle style = DashStyleUtil.ToMedia(this.PenDashStyle);
            this.outlinePen = new Pen {
                Brush     = SolidColorBrushCache.Get((ColorRgba128Float)Colors.White),
                Thickness = this.PenWidth,
                LineJoin  = PenLineJoin.Miter,
                DashStyle = style
            }.EnsureFrozen <Pen>();
            RectDouble   baseBounds = this.BaseBounds;
            VectorDouble txScale    = this.Transform.GetScale();
            VectorDouble num3       = (VectorDouble)(this.EndPoint - this.StartPoint);
            PointDouble  endPoint   = new PointDouble(this.StartPoint.X + (num3.X * txScale.X), this.StartPoint.Y + (num3.Y * txScale.Y));
            Dictionary <string, object> settingValues = (from gsp in this.Shape.RenderSettingPaths select KeyValuePairUtil.Create <string, object>(gsp, base.GetDrawingSettingValue(gsp))).ToDictionary <string, object>();

            PaintDotNet.Shapes.ShapeRenderParameters renderParams = new PaintDotNet.Shapes.ShapeRenderParameters(this.StartPoint, endPoint, txScale, settingValues, null);
            this.shapePropertySchema = this.Shape.CreatePropertyCollection(renderParams);
            foreach (Property property in this.shapePropertySchema)
            {
                property.ValueChanged += delegate(object s, ValueEventArgs <object> e) {
                    throw new ReadOnlyException();
                };
                property.ReadOnlyChanged += delegate(object s, ValueEventArgs <bool> e) {
                    throw new ReadOnlyException();
                };
            }
            this.shapeRenderParams = new PaintDotNet.Shapes.ShapeRenderParameters(this.StartPoint, endPoint, txScale, settingValues, this.ShapePropertyValues);
            this.shapeRenderData   = LazyResult.New <PaintDotNet.Shapes.ShapeRenderData>(delegate {
                PaintDotNet.Shapes.ShapeRenderData renderData = this.Shape.CreateRenderData(this.shapeRenderParams);
                Matrix3x2Double matrix = Matrix3x2Double.ScalingAt(1.0 / Math.Abs(txScale.X), 1.0 / Math.Abs(txScale.Y), this.StartPoint.X, this.StartPoint.Y);
                return(PaintDotNet.Shapes.ShapeRenderData.Transform(PaintDotNet.Shapes.ShapeRenderData.Transform(renderData, matrix), this.transform));
            }, LazyThreadSafetyMode.ExecutionAndPublication, new SingleUseCriticalSection());
        }
                > GetProjectDiagnosticsToFixAsync(FixAllContext fixAllContext)
            {
                using (
                    Logger.LogBlock(
                        FunctionId.CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics,
                        FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
                        fixAllContext.CancellationToken
                        )
                    )
                {
                    var project = fixAllContext.Project;
                    if (project != null)
                    {
                        switch (fixAllContext.Scope)
                        {
                        case FixAllScope.Project:
                            var diagnostics = await fixAllContext
                                              .GetProjectDiagnosticsAsync(project)
                                              .ConfigureAwait(false);

                            var kvp = SpecializedCollections.SingletonEnumerable(
                                KeyValuePairUtil.Create(project, diagnostics)
                                );
                            return(ImmutableDictionary.CreateRange(kvp));

                        case FixAllScope.Solution:
                            var projectsAndDiagnostics = ImmutableDictionary.CreateBuilder <
                                Project,
                                ImmutableArray <Diagnostic>
                                >();

                            var tasks = project.Solution.Projects
                                        .Select(
                                async p =>
                                new
                            {
                                Project     = p,
                                Diagnostics = await fixAllContext
                                              .GetProjectDiagnosticsAsync(p)
                                              .ConfigureAwait(false)
                            }
                                )
                                        .ToArray();

                            await Task.WhenAll(tasks).ConfigureAwait(false);

                            foreach (var task in tasks)
                            {
                                var projectAndDiagnostics = await task.ConfigureAwait(false);

                                if (projectAndDiagnostics.Diagnostics.Any())
                                {
                                    projectsAndDiagnostics[projectAndDiagnostics.Project] =
                                        projectAndDiagnostics.Diagnostics;
                                }
                            }

                            return(projectsAndDiagnostics.ToImmutable());
                        }
                    }

                    return(ImmutableDictionary <Project, ImmutableArray <Diagnostic> > .Empty);
                }
            }
Exemplo n.º 12
0
            internal virtual async Task <ImmutableDictionary <Document, ImmutableArray <Diagnostic> > > GetDocumentDiagnosticsToFixWorkerAsync(
                FixAllContext fixAllContext)
            {
                var cancellationToken = fixAllContext.CancellationToken;

                using (Logger.LogBlock(
                           FunctionId.CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics,
                           FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
                           cancellationToken))
                {
                    var allDiagnostics = ImmutableArray <Diagnostic> .Empty;
                    var projectsToFix  = ImmutableArray <Project> .Empty;

                    var document = fixAllContext.Document;
                    var project  = fixAllContext.Project;

                    switch (fixAllContext.Scope)
                    {
                    case FixAllScope.Document:
                        if (document != null && !document.IsGeneratedCode(cancellationToken))
                        {
                            var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);

                            var kvp = SpecializedCollections.SingletonEnumerable(KeyValuePairUtil.Create(document, documentDiagnostics));
                            return(ImmutableDictionary.CreateRange(kvp));
                        }

                        break;

                    case FixAllScope.Project:
                        projectsToFix  = ImmutableArray.Create(project);
                        allDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false);

                        break;

                    case FixAllScope.Solution:
                        projectsToFix = project.Solution.Projects
                                        .Where(p => p.Language == project.Language)
                                        .ToImmutableArray();

                        var progressTracker = fixAllContext.ProgressTracker;
                        progressTracker.AddItems(projectsToFix.Length);

                        var diagnostics = new ConcurrentBag <Diagnostic>();
                        var tasks       = new Task[projectsToFix.Length];
                        for (int i = 0; i < projectsToFix.Length; i++)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            var projectToFix = projectsToFix[i];
                            tasks[i] = Task.Run(async() =>
                            {
                                var projectDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(projectToFix).ConfigureAwait(false);
                                foreach (var diagnostic in projectDiagnostics)
                                {
                                    cancellationToken.ThrowIfCancellationRequested();
                                    diagnostics.Add(diagnostic);
                                }

                                progressTracker.ItemCompleted();
                            }, cancellationToken);
                        }

                        await Task.WhenAll(tasks).ConfigureAwait(false);

                        allDiagnostics = allDiagnostics.AddRange(diagnostics);
                        break;
                    }

                    if (allDiagnostics.IsEmpty)
                    {
                        return(ImmutableDictionary <Document, ImmutableArray <Diagnostic> > .Empty);
                    }

                    return(await GetDocumentDiagnosticsToFixAsync(
                               allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false));
                }
            }
Exemplo n.º 13
0
        public void FileThatCannotBeDecoded()
        {
            var code     = "#load \"b.csx\"";
            var resolver = TestSourceReferenceResolver.Create(
                KeyValuePairUtil.Create <string, object>(
                    "a.csx",
                    new byte[] { 0xd8, 0x00, 0x00, 0x00 }
                    ),
                KeyValuePairUtil.Create <string, object>("b.csx", "#load \"a.csx\"")
                );
            var options     = TestOptions.DebugDll.WithSourceReferenceResolver(resolver);
            var compilation = CreateCompilationWithMscorlib45(
                code,
                sourceFileName: "external1.csx",
                options: options,
                parseOptions: TestOptions.Script
                );
            var external1 = compilation.SyntaxTrees.Last();
            var external2 = Parse(code, "external2.csx", TestOptions.Script);

            compilation = compilation.AddSyntaxTrees(external2);

            Assert.Equal(3, compilation.SyntaxTrees.Length);
            compilation
            .GetParseDiagnostics()
            .Verify(
                // (1,7): error CS2015: 'a.csx' is a binary file instead of a text file
                // #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(1, 7)
                );

            var external3 = Parse(
                @"
                #load ""b.csx""
                #load ""a.csx""",
                filename: "external3.csx",
                options: TestOptions.Script
                );

            compilation = compilation.ReplaceSyntaxTree(external1, external3);

            Assert.Equal(3, compilation.SyntaxTrees.Length);
            compilation
            .GetParseDiagnostics()
            .Verify(
                // external3.csx(3,23): error CS2015: 'a.csx' is a binary file instead of a text file
                //                 #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(3, 23),
                // b.csx(1,7): error CS2015: 'a.csx' is a binary file instead of a text file
                // #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(1, 7)
                );

            var external4 = Parse("#load \"a.csx\"", "external4.csx", TestOptions.Script);

            compilation = compilation.ReplaceSyntaxTree(external3, external4);

            Assert.Equal(3, compilation.SyntaxTrees.Length);
            compilation
            .GetParseDiagnostics()
            .Verify(
                // external4.csx(1,7): error CS2015: 'a.csx' is a binary file instead of a text file
                // #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(1, 7),
                // b.csx(1,7): error CS2015: 'a.csx' is a binary file instead of a text file
                // #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(1, 7)
                );

            compilation = compilation.RemoveSyntaxTrees(external2);

            Assert.Equal(external4, compilation.SyntaxTrees.Single());
            compilation
            .GetParseDiagnostics()
            .Verify(
                // external4.csx(1,7): error CS2015: 'a.csx' is a binary file instead of a text file
                // #load "a.csx"
                Diagnostic(ErrorCode.ERR_BinaryFile, @"""a.csx""")
                .WithArguments("a.csx")
                .WithLocation(1, 7)
                );
        }
Exemplo n.º 14
0
        private static void ReadVisualBasicImportsDebugInfo(
            ISymUnmanagedReader reader,
            int methodToken,
            int methodVersion,
            out ImmutableArray <ImmutableArray <ImportRecord> > importRecordGroups,
            out string defaultNamespaceName)
        {
            importRecordGroups = ImmutableArray <ImmutableArray <ImportRecord> > .Empty;

            var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(
                methodToken,
                KeyValuePairUtil.Create(reader, methodVersion),
                (token, arg) => GetImportStrings(arg.Key, token, arg.Value));

            if (importStrings.IsDefault)
            {
                defaultNamespaceName = "";
                return;
            }

            defaultNamespaceName = null;
            var projectLevelImportRecords = ArrayBuilder <ImportRecord> .GetInstance();

            var fileLevelImportRecords = ArrayBuilder <ImportRecord> .GetInstance();

            foreach (string importString in importStrings)
            {
                Debug.Assert(importString != null);

                if (importString.Length > 0 && importString[0] == '*')
                {
                    string            alias  = null;
                    string            target = null;
                    ImportTargetKind  kind   = 0;
                    VBImportScopeKind scope  = 0;

                    if (!CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out target, out kind, out scope))
                    {
                        Debug.WriteLine($"Unable to parse import string '{importString}'");
                        continue;
                    }
                    else if (kind == ImportTargetKind.Defunct)
                    {
                        continue;
                    }

                    Debug.Assert(alias == null); // The default namespace is never aliased.
                    Debug.Assert(target != null);
                    Debug.Assert(kind == ImportTargetKind.DefaultNamespace);

                    // We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal
                    // implicitly uses the last one if there are multiple.
                    Debug.Assert(defaultNamespaceName == null);

                    defaultNamespaceName = target;
                }
                else
                {
                    ImportRecord      importRecord;
                    VBImportScopeKind scope = 0;

                    if (TryCreateImportRecordFromVisualBasicImportString(importString, out importRecord, out scope))
                    {
                        if (scope == VBImportScopeKind.Project)
                        {
                            projectLevelImportRecords.Add(importRecord);
                        }
                        else
                        {
                            Debug.Assert(scope == VBImportScopeKind.File || scope == VBImportScopeKind.Unspecified);
                            fileLevelImportRecords.Add(importRecord);
                        }
                    }
                    else
                    {
                        Debug.WriteLine($"Failed to parse import string {importString}");
                    }
                }
            }

            importRecordGroups = ImmutableArray.Create(
                fileLevelImportRecords.ToImmutableAndFree(),
                projectLevelImportRecords.ToImmutableAndFree());

            defaultNamespaceName = defaultNamespaceName ?? "";
        }
Exemplo n.º 15
0
        public void KnownMatches()
        {
            TestNode x1, x2;

            var oldRoot = new TestNode(0, 1,
                                       x1 = new TestNode(1, 1));

            var newRoot = new TestNode(0, 1,
                                       x2 = new TestNode(1, 2));

            var m = TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot,
                                                           new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, x2) });

            Assert.True(m.TryGetNewNode(x1, out var n));
            Assert.Equal(n, x2);

            Assert.Throws <ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x1) }));

            Assert.Throws <ArgumentException>(() => TestTreeComparer.Instance.ComputeMatch(oldRoot, newRoot, new[] { KeyValuePairUtil.Create(x1, x2), KeyValuePairUtil.Create(x1, new TestNode(0, 0)) }));
        }
Exemplo n.º 16
0
 private void PersistToDisk(object theObject)
 {
     using (this.persistedToDiskRegion.UseEnterScope())
     {
         try
         {
             object persistBackgroundSync = PersistedObject <T> .persistBackgroundSync;
             lock (persistBackgroundSync)
             {
                 using (FileStream stream = new FileStream(this.tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read))
                 {
                     BinaryFormatter formatter             = new BinaryFormatter();
                     KeyValuePair <object, object>[] items = new KeyValuePair <object, object>[] { KeyValuePairUtil.Create <object, object>(MemoryBlock.UseCompressionBooleanDeferredFormatterKey, true) };
                     DeferredFormatter additional          = new DeferredFormatter(null, ArrayUtil.Infer <KeyValuePair <object, object> >(items));
                     StreamingContext  context             = new StreamingContext(formatter.Context.State, additional);
                     formatter.Context = context;
                     formatter.Serialize(stream, theObject);
                     additional.FinishSerialization(stream);
                     stream.Flush();
                 }
             }
         }
         finally
         {
             this.theObjectSaved.Set();
             this.theObjectSaved = null;
         }
         GC.KeepAlive(theObject);
     }
 }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray <byte> cryptoPublicKey,
            out bool?delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out MetadataImportOptions metadataImportOptions,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName   = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName   = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow     = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile      = reader.ReadString();

            cryptoPublicKey = reader.ReadArray <byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List <KeyValuePair <string, ReportDiagnostic> >(count);

                for (var i = 0; i < count; i++)
                {
                    var key   = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePairUtil.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable <KeyValuePair <string, ReportDiagnostic> >();

            concurrentBuild = reader.ReadBoolean();
            deterministic   = reader.ReadBoolean();
            publicSign      = reader.ReadBoolean();

            metadataImportOptions = (MetadataImportOptions)reader.ReadByte();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver      = XmlFileResolver.Default;
            sourceReferenceResolver   = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer  = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider        = new DesktopStrongNameProvider();
        }
Exemplo n.º 18
0
        private static FixAllState GetFixAllState(
            FixAllProvider fixAllProvider,
            IEnumerable <Diagnostic> diagnostics,
            CodeFixProvider fixer,
            TestDiagnosticAnalyzerDriver testDriver,
            Document document,
            FixAllScope scope,
            string equivalenceKey)
        {
            Assert.NotEmpty(diagnostics);

            if (scope == FixAllScope.Custom)
            {
                // Bulk fixing diagnostics in selected scope.
                var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePairUtil.Create(document, diagnostics.ToImmutableArray())));
                return(FixAllState.Create(fixAllProvider, diagnosticsToFix, fixer, equivalenceKey));
            }

            var diagnostic               = diagnostics.First();
            var diagnosticIds            = ImmutableHashSet.Create(diagnostic.Id);
            var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(testDriver, diagnosticIds);

            return(diagnostic.Location.IsInSource
                ? new FixAllState(fixAllProvider, document, fixer, scope, equivalenceKey, diagnosticIds, fixAllDiagnosticProvider)
                : new FixAllState(fixAllProvider, document.Project, fixer, scope, equivalenceKey, diagnosticIds, fixAllDiagnosticProvider));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Calculates information about types and namespaces immediately contained within a namespace.
        /// </summary>
        /// <param name="isGlobalNamespace">
        /// Is current namespace a global namespace?
        /// </param>
        /// <param name="namespaceNameLength">
        /// Length of the fully-qualified name of this namespace.
        /// </param>
        /// <param name="typesByNS">
        /// The sequence of groups of TypeDef row ids for types contained within the namespace,
        /// recursively including those from nested namespaces. The row ids must be grouped by the
        /// fully-qualified namespace name in case-sensitive manner.
        /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of
        /// this namespace. There could be multiple groups for each fully-qualified namespace name.
        ///
        /// The groups must be sorted by the keys in a manner consistent with comparer passed in as
        /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any,
        /// must be in several IGrouping at the very beginning of the sequence.
        /// </param>
        /// <param name="nameComparer">
        /// Equality comparer to compare namespace names.
        /// </param>
        /// <param name="types">
        /// Output parameter, never null:
        /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace.
        /// </param>
        /// <param name="namespaces">
        /// Output parameter, never null:
        /// A sequence with information about namespaces immediately contained within this namespace.
        /// For each pair:
        ///   Key - contains simple name of a child namespace.
        ///   Value - contains a sequence similar to the one passed to this function, but
        ///           calculated for the child namespace.
        /// </param>
        /// <remarks></remarks>
        public static void GetInfoForImmediateNamespaceMembers(
            bool isGlobalNamespace,
            int namespaceNameLength,
            IEnumerable <IGrouping <string, TypeDefinitionHandle> > typesByNS,
            StringComparer nameComparer,
            out IEnumerable <IGrouping <string, TypeDefinitionHandle> > types,
            out IEnumerable <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > > namespaces)
        {
            Debug.Assert(typesByNS != null);
            Debug.Assert(namespaceNameLength >= 0);
            Debug.Assert(!isGlobalNamespace || namespaceNameLength == 0);

            // A list of groups of TypeDef row ids for types immediately contained within this namespace.
            var nestedTypes = new List <IGrouping <string, TypeDefinitionHandle> >();

            // A list accumulating information about namespaces immediately contained within this namespace.
            // For each pair:
            //   Key - contains simple name of a child namespace.
            //   Value – contains a sequence similar to the one passed to this function, but
            //           calculated for the child namespace.
            var  nestedNamespaces = new List <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > >();
            bool possiblyHavePairsWithDuplicateKey = false;

            var enumerator = typesByNS.GetEnumerator();

            using (enumerator)
            {
                if (enumerator.MoveNext())
                {
                    var pair = enumerator.Current;

                    // Simple name of the last encountered child namespace.
                    string lastChildNamespaceName = null;

                    // A list accumulating information about types within the last encountered child namespace.
                    // The list is similar to the sequence passed to this function.
                    List <IGrouping <string, TypeDefinitionHandle> > typesInLastChildNamespace = null;

                    // if there are any types in this namespace,
                    // they will be in the first several groups if their key length
                    // is equal to namespaceNameLength.
                    while (pair.Key.Length == namespaceNameLength)
                    {
                        nestedTypes.Add(pair);

                        if (!enumerator.MoveNext())
                        {
                            goto DoneWithSequence;
                        }

                        pair = enumerator.Current;
                    }

                    // Account for the dot following THIS namespace name.
                    if (!isGlobalNamespace)
                    {
                        namespaceNameLength++;
                    }

                    do
                    {
                        pair = enumerator.Current;

                        string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key);

                        int cmp = nameComparer.Compare(lastChildNamespaceName, childNamespaceName);
                        if (cmp == 0)
                        {
                            // We are still processing the same child namespace
                            typesInLastChildNamespace.Add(pair);
                        }
                        else
                        {
                            // This is a new child namespace
                            if (cmp > 0)
                            {
                                // The sort order is violated for child namespace names. Obfuscation is the likely reason for this.
                                Debug.Assert((object)lastChildNamespaceName != null);
                                possiblyHavePairsWithDuplicateKey = true;
                            }

                            // Preserve information about previous child namespace.
                            if (typesInLastChildNamespace != null)
                            {
                                Debug.Assert(typesInLastChildNamespace.Count != 0);
                                nestedNamespaces.Add(
                                    new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >(
                                        lastChildNamespaceName, typesInLastChildNamespace));
                            }

                            typesInLastChildNamespace = new List <IGrouping <string, TypeDefinitionHandle> >();
                            lastChildNamespaceName    = childNamespaceName;
                            Debug.Assert((object)lastChildNamespaceName != null);

                            typesInLastChildNamespace.Add(pair);
                        }
                    }while (enumerator.MoveNext());

                    // Preserve information about last child namespace.
                    if (typesInLastChildNamespace != null)
                    {
                        Debug.Assert(typesInLastChildNamespace.Count != 0);
                        nestedNamespaces.Add(
                            new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >(
                                lastChildNamespaceName, typesInLastChildNamespace));
                    }

DoneWithSequence:
/*empty statement*/
                    ;
                }
            } // using

            types = nestedTypes;

            // Merge pairs with the same key
            if (possiblyHavePairsWithDuplicateKey)
            {
                var names = new Dictionary <string, int>(nestedNamespaces.Count, nameComparer);

                for (int i = nestedNamespaces.Count - 1; i >= 0; i--)
                {
                    names[nestedNamespaces[i].Key] = i;
                }

                if (names.Count != nestedNamespaces.Count) // nothing to merge otherwise
                {
                    for (int i = 1; i < nestedNamespaces.Count; i++)
                    {
                        var pair     = nestedNamespaces[i];
                        int keyIndex = names[pair.Key];
                        if (keyIndex != i)
                        {
                            Debug.Assert(keyIndex < i);
                            var primaryPair = nestedNamespaces[keyIndex];
                            nestedNamespaces[keyIndex] = KeyValuePairUtil.Create(primaryPair.Key, primaryPair.Value.Concat(pair.Value));
                            nestedNamespaces[i]        = default(KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >);
                        }
                    }

                    int removed = nestedNamespaces.RemoveAll(pair => (object)pair.Key == null);
                    Debug.Assert(removed > 0);
                }
            }

            namespaces = nestedNamespaces;

            Debug.Assert(types != null);
            Debug.Assert(namespaces != null);
        }
Exemplo n.º 20
0
        public void TryApplyWorksSpecificChangeIsAllowedForParseOption()
        {
            // If we don't support the main change kind, then the other method should be called
            using var workspace = new CustomizedCanApplyWorkspace(
                      allowedKinds: new ApplyChangesKind[] { },
                      canApplyParseOptions: (_, newParseOptions) => newParseOptions.Features["Feature"] == "ExpectedValue");

            var project = workspace.CurrentSolution.Projects.Single();

            Assert.True(
                workspace.TryApplyChanges(
                    project.WithParseOptions(project.ParseOptions !.WithFeatures(new[] { KeyValuePairUtil.Create("Feature", "ExpectedValue") })).Solution));
        }
Exemplo n.º 21
0
        public ProjectState AddAdditionalDocuments(ImmutableArray <TextDocumentState> documents)
        {
            Debug.Assert(!documents.Any(d => this.AdditionalDocumentStates.ContainsKey(d.Id)));

            return(this.With(
                       projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
                       additionalDocumentIds: _additionalDocumentIds.AddRange(documents.Select(d => d.Id)),
                       additionalDocumentStates: _additionalDocumentStates.AddRange(documents.Select(d => KeyValuePairUtil.Create(d.Id, d)))));
        }
Exemplo n.º 22
0
        public void TryApplyWorksThrowsIfChangeIsDisallowedForParseOption()
        {
            // If we don't support the main change kind, then the other method should be called
            using var workspace = new CustomizedCanApplyWorkspace(
                      allowedKinds: new ApplyChangesKind[] { },
                      canApplyParseOptions: (_, newParseOptions) => newParseOptions.Features["Feature"] == "ExpectedValue");

            var project = workspace.CurrentSolution.Projects.Single();

            var exception = Assert.Throws <NotSupportedException>(
                () => workspace.TryApplyChanges(
                    project.WithParseOptions(project.ParseOptions !.WithFeatures(new[] { KeyValuePairUtil.Create("Feature", "WrongThing") })).Solution));

            Assert.Equal(WorkspacesResources.Changing_parse_options_is_not_supported, exception.Message);
        }
Exemplo n.º 23
0
        public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices)
        {
            Contract.ThrowIfNull(projectInfo);
            Contract.ThrowIfNull(languageServices);
            Contract.ThrowIfNull(solutionServices);

            _languageServices = languageServices;
            _solutionServices = solutionServices;

            var projectInfoFixed = FixProjectInfo(projectInfo);

            // We need to compute our AnalyerConfigDocumentStates first, since we use those to produce our DocumentStates
            _analyzerConfigDocumentStates = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
                                                                                  projectInfoFixed.AnalyzerConfigDocuments.Select(d =>
                                                                                                                                  KeyValuePairUtil.Create(d.Id, new AnalyzerConfigDocumentState(d, solutionServices))));
            _lazyAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(_analyzerConfigDocumentStates.Values);

            _documentIds           = projectInfoFixed.Documents.Select(d => d.Id).ToImmutableList();
            _additionalDocumentIds = projectInfoFixed.AdditionalDocuments.Select(d => d.Id).ToImmutableList();

            var parseOptions = projectInfoFixed.ParseOptions;
            var docStates    = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
                                                                     projectInfoFixed.Documents.Select(d =>
                                                                                                       new KeyValuePair <DocumentId, DocumentState>(d.Id,
                                                                                                                                                    CreateDocument(d, parseOptions))));

            _documentStates = docStates;

            var additionalDocStates = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
                                                                            projectInfoFixed.AdditionalDocuments.Select(d =>
                                                                                                                        new KeyValuePair <DocumentId, TextDocumentState>(d.Id, new TextDocumentState(d, solutionServices))));

            _additionalDocumentStates  = additionalDocStates;
            _lazyLatestDocumentVersion = new AsyncLazy <VersionStamp>(c => ComputeLatestDocumentVersionAsync(docStates, additionalDocStates, c), cacheResult: true);
            _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy <VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(docStates, additionalDocStates, c), cacheResult: true);

            // ownership of information on document has moved to project state. clear out documentInfo the state is
            // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after
            // the info has changed by DocumentState.
            // we hold onto the info so that we don't need to duplicate all information info already has in the state
            _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed);

            _lazyChecksums = new AsyncLazy <ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true);
        }
Exemplo n.º 24
0
        private static void ReadVisualBasicImportsDebugInfo(
            ISymUnmanagedReader reader,
            int methodToken,
            int methodVersion,
            out ImmutableArray <ImmutableArray <ImportRecord> > importRecordGroups,
            out string defaultNamespaceName
            )
        {
            importRecordGroups = ImmutableArray <ImmutableArray <ImportRecord> > .Empty;

            var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(
                methodToken,
                KeyValuePairUtil.Create(reader, methodVersion),
                (token, arg) => GetImportStrings(arg.Key, token, arg.Value)
                );

            if (importStrings.IsDefault)
            {
                defaultNamespaceName = "";
                return;
            }

            string?lazyDefaultNamespaceName  = null;
            var    projectLevelImportRecords = ArrayBuilder <ImportRecord> .GetInstance();

            var fileLevelImportRecords = ArrayBuilder <ImportRecord> .GetInstance();

            foreach (var importString in importStrings)
            {
                RoslynDebug.AssertNotNull(importString);

                if (importString.Length > 0 && importString[0] == '*')
                {
                    string?alias  = null;
                    string?target = null;

                    if (
                        !CustomDebugInfoReader.TryParseVisualBasicImportString(
                            importString,
                            out alias,
                            out target,
                            out var kind,
                            out var scope
                            )
                        )
                    {
                        Debug.WriteLine($"Unable to parse import string '{importString}'");
                        continue;
                    }
                    else if (kind == ImportTargetKind.Defunct)
                    {
                        continue;
                    }

                    Debug.Assert(alias == null); // The default namespace is never aliased.
                    Debug.Assert(target != null);
                    Debug.Assert(kind == ImportTargetKind.DefaultNamespace);

                    // We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal
                    // implicitly uses the last one if there are multiple.
                    Debug.Assert(lazyDefaultNamespaceName == null);

                    lazyDefaultNamespaceName = target;
                }