private static DiagnosticAnalyzerService CreateDiagnosticAnalyzerService(
     Dictionary<string, DiagnosticAnalyzer[]> analyzerMap, IAsynchronousOperationListener listener)
 {
     return analyzerMap == null || analyzerMap.Count == 0
         ? new MyDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap(), listener: listener)
         : new MyDiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.ToImmutableArray()), listener: listener);
 }
        /// <summary>
        /// Given an analyzer and a collection of documents to apply it to, run the analyzer and gather an array of
        /// diagnostics found. The returned diagnostics are then ordered by location in the source documents.
        /// </summary>
        /// <param name="analyzers">The analyzer to run on the documents.</param>
        /// <param name="documents">The <see cref="Document"/>s that the analyzer will be run on.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>A collection of <see cref="Diagnostic"/>s that surfaced in the source code, sorted by
        /// <see cref="Diagnostic.Location"/>.</returns>
        protected static async Task<ImmutableArray<Diagnostic>> GetSortedDiagnosticsFromDocumentsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Document[] documents, CancellationToken cancellationToken)
        {
            var projects = new HashSet<Project>();
            foreach (var document in documents)
            {
                projects.Add(document.Project);
            }

            var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>();
            foreach (var analyzer in analyzers)
            {
                foreach (var diagnostic in analyzer.SupportedDiagnostics)
                {
                    // make sure the analyzers we are testing are enabled
                    supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default;
                }
            }

            // Report exceptions during the analysis process as errors
            supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error);

            var diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
            foreach (var project in projects)
            {
                // update the project compilation options
                var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions);
                var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions);
                var processedProject = project.WithCompilationOptions(modifiedCompilationOptions);

                var compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, processedProject.AnalyzerOptions, cancellationToken);
                var compilerDiagnostics = compilation.GetDiagnostics(cancellationToken);
                var compilerErrors = compilerDiagnostics.Where(i => i.Severity == DiagnosticSeverity.Error);
                var diags = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false);
                var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(false);
                var failureDiagnostics = allDiagnostics.Where(diagnostic => diagnostic.Id == "AD0001");
                foreach (var diag in diags.Concat(compilerErrors).Concat(failureDiagnostics))
                {
                    if (diag.Location == Location.None || diag.Location.IsInMetadata)
                    {
                        diagnostics.Add(diag);
                    }
                    else
                    {
                        for (int i = 0; i < documents.Length; i++)
                        {
                            var document = documents[i];
                            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                            if (tree == diag.Location.SourceTree)
                            {
                                diagnostics.Add(diag);
                            }
                        }
                    }
                }
            }

            var results = SortDistinctDiagnostics(diagnostics);
            return results.ToImmutableArray();
        }
 public void Setup()
 {
     _dictionary = Enumerable.Range(1, Size).ToDictionary(_ => "test " + _, _ => _);
     _readonlyDictionary = new ReadonlyDictionary<string, int>(_dictionary);
     _concurrentDictionary = new ConcurrentDictionary<string, int>(_dictionary);
     _immutableDictionary = _dictionary.ToImmutableDictionary();
 }
Example #4
0
        public HtmlFile ReadFile(HtmlFile file)
        {
            CommonMarkSettings.Default.OutputDelegate =
                (document, output, settings) =>
                new CustomHtmlFormatter(output, settings, file).WriteDocument(document);

            var doc = CommonMarkConverter.Parse(file.Source);
            var properties = new Dictionary<string, string>();
            foreach(var node in doc.AsEnumerable())
            {
                if(node.Block?.Tag == BlockTag.FencedCode)
                {
                    if(node.Block.StringContent.TakeFromStart(PropertiesString.Length) == PropertiesString)
                    {
                        string kvString = node.Block.StringContent.ToString().Substring(PropertiesString.Length);
                        var propDict = ReadKV(kvString);
                        propDict.ToList().ForEach(x => properties.Add(x.Key, x.Value));
                    }
                }
            }

            StringBuilder sb = new StringBuilder();

            CommonMarkConverter.ProcessStage3(doc, new StringWriter(sb));

            return file.WithContent(sb.ToString()).WithProperties(properties.ToImmutableDictionary());
        }
Example #5
0
        private static ImmutableDictionary<ErrorCode, string> CreateHelpLinks()
        {
            var map = new Dictionary<ErrorCode, string>()
            {
                // { ERROR_CODE,    HELP_LINK }
            };

            return map.ToImmutableDictionary();
        }
Example #6
0
        private static ImmutableDictionary<ErrorCode, string> CreateCategoriesMap()
        {
            var map = new Dictionary<ErrorCode, string>()
            {
                // { ERROR_CODE,    CATEGORY }
            };

            return map.ToImmutableDictionary();
        }
Example #7
0
 public void Build(FileModel model, IHostService host)
 {
     model.File = Path.ChangeExtension(model.File, ".json");
     var toc = (TocViewModel)model.Content;
     HashSet<string> links = new HashSet<string>();
     Dictionary<string, HashSet<string>> tocMap = new Dictionary<string, HashSet<string>>();
     UpdateRelativePathAndAddTocMap(toc, model, links, tocMap, host);
     model.Properties.LinkToFiles = links.ToImmutableArray();
     model.Properties.TocMap = tocMap.ToImmutableDictionary();
     // todo : metadata.
 }
        private static void GetTagSource(TestWorkspace workspace, DiagnosticServiceWaiter diagnosticWaiter, ErrorSquiggleWaiter squiggleWaiter, out Analyzer analyzer, out DiagnosticAnalyzerService analyzerService, out DiagnosticsSquiggleTaggerProvider.TagSource taggerSource)
        {
            analyzer = new Analyzer();
            var analyzerMap = new Dictionary<string, ImmutableArray<DiagnosticAnalyzer>>() { { LanguageNames.CSharp, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer) } };
            analyzerService = new DiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary());

            var diagnosticListeners = SpecializedCollections.SingletonEnumerable(new Lazy<IAsynchronousOperationListener, FeatureMetadata>(
                    () => diagnosticWaiter, new FeatureMetadata(new Dictionary<string, object>() { { "FeatureName", FeatureAttribute.DiagnosticService } })));

            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable<IDiagnosticUpdateSource>(analyzerService), diagnosticListeners);

            var document = workspace.Documents.First();
            var buffer = document.GetTextBuffer();

            var foregroundService = new TestForegroundNotificationService();
            var optionsService = workspace.Services.GetService<IOptionService>();
            taggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter);
        }
        /// <summary>
        /// The settings provider used to bridge Service Fabric configuration information and DotNetty
        /// </summary>
        /// <param name="traceId">The unique identifier used to correlate debugging and diagnostics messages</param>
        /// <param name="componentName">The component name used for debug and diagnostics messages</param>
        /// <param name="logger">The service fabric logger to be used when writing debug and diagnostics information</param>
        /// <param name="gatewayConfiguration">The gateway configuration used to get current configuration information for DotNetty</param>
        /// <param name="iotHubConfiguration">The IotHub Client configuration used to get current configuration information for DotNetty</param>
        /// <param name="mqttConfiguration">The MQTT configuration used to get current configuration information for DotNetty</param>
        public ServiceFabricConfigurationProvider(Guid traceId, string componentName, IServiceLogger logger, GatewayConfiguration gatewayConfiguration, IoTHubConfiguration iotHubConfiguration, MqttServiceConfiguration mqttConfiguration)
        {
            this.componentName = componentName;
            this.logger = logger;

            this.logger.Verbose(traceId, this.componentName, "Initializing configuration provider.");

            var baseProperties = new Dictionary<string, string>();

            foreach (PropertyInfo element in typeof(GatewayConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!element.PropertyType.IsArray)
                {
                    object value = element.GetValue(gatewayConfiguration, null);
                    baseProperties.Add(element.Name, element.PropertyType == typeof(string) ? value as string : value.ToString());
                }
            }

            foreach (PropertyInfo element in typeof(MqttServiceConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!element.PropertyType.IsArray)
                {
                    object value = element.GetValue(mqttConfiguration, null);
                    baseProperties.Add(element.Name, element.PropertyType == typeof(string) ? value as string : value.ToString());
                }
            }

            foreach (PropertyInfo element in typeof(IoTHubConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!element.PropertyType.IsArray)
                {
                    object value = element.GetValue(iotHubConfiguration, null);
                    baseProperties.Add($"IotHubClient.{element.Name}", value?.ToString());
                }
            }



            this.configurationValues = baseProperties.ToImmutableDictionary();
            this.logger.Informational(traceId, this.componentName, "Initializing configuration provider complete.");
        }
Example #10
0
        public static void IndexSolutions(IEnumerable<string> solutionFilePaths, Dictionary<string, string> properties)
        {
            var assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var path in solutionFilePaths)
            {
                using (Disposable.Timing("Reading assembly names from " + path))
                {
                    foreach (var assemblyName in AssemblyNameExtractor.GetAssemblyNames(path))
                    {
                        assemblyNames.Add(assemblyName);
                    }
                }
            }

            var federation = new Federation();
            foreach (var path in solutionFilePaths)
            {
                using (Disposable.Timing("Generating " + path))
                {
                    using (var solutionGenerator = new SolutionGenerator(
                        path,
                        Paths.SolutionDestinationFolder,
                        properties: properties.ToImmutableDictionary(),
                        federation: federation))
                    {
                        solutionGenerator.GlobalAssemblyList = assemblyNames;
                        solutionGenerator.Generate(solutionExplorerRoot: mergedSolutionExplorerRoot);

                        if (Configuration.ProcessReferencies)
                            Extend.ExtendGenerator.TopReferencedAssemblies(solutionGenerator, federation, mergedSolutionExplorerRoot);
                    }
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
Example #11
0
        private static void IndexSolutions(IEnumerable<string> solutionFilePaths, Dictionary<string, string> properties, Federation federation, Dictionary<string, string> serverPathMappings)
        {
            var assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var path in solutionFilePaths)
            {
                using (Disposable.Timing("Reading assembly names from " + path))
                {
                    foreach (var assemblyName in AssemblyNameExtractor.GetAssemblyNames(path))
                    {
                        assemblyNames.Add(assemblyName);
                    }
                }
            }

            foreach (var path in solutionFilePaths)
            {
                using (Disposable.Timing("Generating " + path))
                {
                    using (var solutionGenerator = new SolutionGenerator(
                        path,
                        Paths.SolutionDestinationFolder,
                        properties: properties.ToImmutableDictionary(),
                        federation: federation,
                        serverPathMappings: serverPathMappings))
                    {
                        solutionGenerator.GlobalAssemblyList = assemblyNames;
                        solutionGenerator.Generate(solutionExplorerRoot: mergedSolutionExplorerRoot);
                    }
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
        private static void HandleAsteriskToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            bool allowAtLineStart;
            bool allowAtLineEnd;
            bool allowPrecedingSpace;
            bool allowTrailingSpace;
            switch (token.Parent.Kind())
            {
            case SyntaxKind.PointerType:
                allowAtLineStart = false;
                allowAtLineEnd = true;
                allowPrecedingSpace = false;
                var nextToken = token.GetNextToken();
                switch (nextToken.Kind())
                {
                case SyntaxKind.OpenBracketToken:
                case SyntaxKind.OpenParenToken:
                    allowTrailingSpace = false;
                    break;
                default:
                    allowTrailingSpace = true;
                    break;
                }

                break;

            case SyntaxKind.PointerIndirectionExpression:
                allowAtLineStart = true;
                allowAtLineEnd = false;
                allowTrailingSpace = false;
                var prevToken = token.GetPreviousToken();
                switch (prevToken.Kind())
                {
                case SyntaxKind.OpenBracketToken:
                case SyntaxKind.OpenParenToken:
                case SyntaxKind.CloseParenToken:
                    allowPrecedingSpace = false;
                    break;
                default:
                    allowPrecedingSpace = true;
                    break;
                }

                break;

            default:
                return;
            }

            bool firstInLine = token.IsFirstInLine();
            bool precededBySpace = firstInLine || token.IsPrecededByWhitespace();
            bool followedBySpace = token.IsFollowedByWhitespace();
            bool lastInLine = token.IsLastInLine();

            if (!allowAtLineStart && firstInLine)
            {
                // Dereference symbol '*' must {not appear at the beginning of a line}.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not appear at the beginning of a line"));
            }
            else if (!allowPrecedingSpace && precededBySpace)
            {
                // Dereference symbol '*' must {not be preceded by a space}.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not be preceded by a space"));
            }

            if (!allowAtLineEnd && lastInLine)
            {
                // Dereference symbol '*' must {not appear at the end of a line}.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not appear at the end of a line"));
            }
            else if (!allowTrailingSpace && followedBySpace)
            {
                // Dereference symbol '*' must {not be followed by a space}.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not be followed by a space"));
            }

            if (!followedBySpace && allowTrailingSpace)
            {
                // Dereference symbol '*' must {be followed by a space}.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "be followed by a space"));
            }
        }
        private static void HandleCloseBraceToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace();

            if (token.Parent is InterpolationSyntax)
            {
                if (precededBySpace)
                {
                    // Closing curly bracket must{ not} be {preceded} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded"));
                }

                return;
            }

            bool followedBySpace = token.IsFollowedByWhitespace();
            bool lastInLine = token.IsLastInLine();
            bool precedesSpecialCharacter;

            if (!followedBySpace && !lastInLine)
            {
                SyntaxToken nextToken = token.GetNextToken();
                precedesSpecialCharacter =
                    nextToken.IsKind(SyntaxKind.CloseParenToken)
                    || nextToken.IsKind(SyntaxKind.CommaToken)
                    || nextToken.IsKind(SyntaxKind.SemicolonToken)
                    || nextToken.IsKind(SyntaxKind.DotToken)
                    || (nextToken.IsKind(SyntaxKind.QuestionToken) && nextToken.GetNextToken(includeZeroWidth: true).IsKind(SyntaxKind.DotToken))
                    || nextToken.IsKind(SyntaxKind.CloseBracketToken);
            }
            else
            {
                precedesSpecialCharacter = false;
            }

            if (!precededBySpace)
            {
                // Closing curly bracket must{} be {preceded} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "preceded"));
            }

            if (!lastInLine && !precedesSpecialCharacter && !followedBySpace)
            {
                // Closing curly bracket must{} be {followed} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed"));
            }
        }
        private static void HandleCloseParenToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace();
            bool followedBySpace = token.IsFollowedByWhitespace();
            bool lastInLine = token.IsLastInLine();
            bool precedesStickyCharacter;
            bool allowEndOfLine = false;

            bool suppressFollowingSpaceError = false;

            SyntaxToken nextToken = token.GetNextToken();
            switch (nextToken.Kind())
            {
            case SyntaxKind.OpenParenToken:
            case SyntaxKind.CloseParenToken:
            case SyntaxKind.OpenBracketToken:
            case SyntaxKind.CloseBracketToken:
            case SyntaxKind.SemicolonToken:
            case SyntaxKind.CommaToken:
                precedesStickyCharacter = true;
                break;

            case SyntaxKind.QuestionToken:
                if (nextToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression))
                {
                    // allow a space for this case, but only if the ')' character is the last on the line
                    allowEndOfLine = true;
                    precedesStickyCharacter = true;
                }
                else
                {
                    precedesStickyCharacter = false;
                }

                break;

            case SyntaxKind.PlusToken:
                precedesStickyCharacter = nextToken.Parent.IsKind(SyntaxKind.UnaryPlusExpression);

                // this will be reported as SA1022
                suppressFollowingSpaceError = true;
                break;

            case SyntaxKind.MinusToken:
                precedesStickyCharacter = nextToken.Parent.IsKind(SyntaxKind.UnaryMinusExpression);

                // this will be reported as SA1021
                suppressFollowingSpaceError = true;
                break;

            case SyntaxKind.DotToken:
                // allow a space for this case, but only if the ')' character is the last on the line
                allowEndOfLine = true;
                precedesStickyCharacter = true;
                break;

            case SyntaxKind.ColonToken:
                bool requireSpace =
                    nextToken.Parent.IsKind(SyntaxKind.ConditionalExpression)
                    || nextToken.Parent.IsKind(SyntaxKind.BaseConstructorInitializer)
                    || nextToken.Parent.IsKind(SyntaxKind.ThisConstructorInitializer);
                precedesStickyCharacter = !requireSpace;
                break;

            case SyntaxKind.PlusPlusToken:
            case SyntaxKind.MinusMinusToken:
                precedesStickyCharacter = true;
                suppressFollowingSpaceError = false;
                break;

            case SyntaxKind.CloseBraceToken:
                precedesStickyCharacter = nextToken.Parent is InterpolationSyntax;
                break;

            default:
                precedesStickyCharacter = false;
                break;
            }

            switch (token.Parent.Kind())
            {
            case SyntaxKind.CastExpression:
                precedesStickyCharacter = true;
                break;

            default:
                break;
            }

            if (precededBySpace)
            {
                // Closing parenthesis must{ not} be {preceded} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded"));
            }

            if (!suppressFollowingSpaceError)
            {
                if (!precedesStickyCharacter && !followedBySpace && !lastInLine)
                {
                    // Closing parenthesis must{} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed"));
                }
                else if (precedesStickyCharacter && followedBySpace && (!lastInLine || !allowEndOfLine))
                {
                    // Closing parenthesis must{ not} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed"));
                }
            }
        }
        private static void CheckIfLocationOfPreviousTokenAndOpenTokenAreTheSame(SyntaxNodeAnalysisContext context, SyntaxToken openToken, bool preserveLayout)
        {
            var previousToken = openToken.GetPreviousToken();
            if (previousToken.IsMissing)
            {
                return;
            }

            var prevTokenLine = previousToken.GetLineSpan();
            var openParenLine = openToken.GetLineSpan();
            if (prevTokenLine.IsValid &&
                openParenLine.IsValid &&
                openParenLine.StartLinePosition.Line != prevTokenLine.StartLinePosition.Line)
            {
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove,
                    [OpenCloseSpacingCodeFixProvider.LayoutKey] = preserveLayout ? OpenCloseSpacingCodeFixProvider.LayoutPreserve : OpenCloseSpacingCodeFixProvider.LayoutPack
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, openToken.GetLocation(), properties.ToImmutableDictionary()));
            }
        }
        private static void HandleOpenBraceToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            bool followedBySpace = token.IsFollowedByWhitespace();

            if (token.Parent is InterpolationSyntax)
            {
                if (followedBySpace)
                {
                    // Opening curly bracket must{} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed"));
                }

                return;
            }

            bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace();

            if (!precededBySpace)
            {
                // Opening curly bracket must{} be {preceded} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "preceded"));
            }

            if (!token.IsLastInLine() && !followedBySpace)
            {
                // Opening curly bracket must{} be {followed} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed"));
            }
        }
Example #17
0
 private ImmutableDictionary<string, FileAndType> GetAllSourceFiles(IEnumerable<FileAndType> allSourceFiles)
 {
     var dict = new Dictionary<string, FileAndType>(TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer);
     foreach (var item in allSourceFiles)
     {
         var path = (string)((TypeForwardedToRelativePath)item.File).GetPathFromWorkingFolder();
         FileAndType ft;
         if (dict.TryGetValue(path, out ft))
         {
             if (TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer.Equals(ft.BaseDir, item.BaseDir) &&
                 TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer.Equals(ft.File, item.File))
             {
                 if (ft.Type >= item.Type)
                 {
                     Logger.LogWarning($"Ignored duplicate file {Path.Combine(item.BaseDir, item.File)}.");
                     continue;
                 }
                 else
                 {
                     Logger.LogWarning($"Ignored duplicate file {Path.Combine(ft.BaseDir, ft.File)}.");
                 }
             }
             else
             {
                 if (ft.Type >= item.Type)
                 {
                     Logger.LogWarning($"Ignored conflict file {Path.Combine(item.BaseDir, item.File)} for {path} by {Path.Combine(ft.BaseDir, ft.File)}.");
                     continue;
                 }
                 else
                 {
                     Logger.LogWarning($"Ignored conflict file {Path.Combine(ft.BaseDir, ft.File)} for {path} by {Path.Combine(item.BaseDir, item.File)}.");
                 }
             }
         }
         dict[path] = item;
     }
     return dict.ToImmutableDictionary(TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer);
 }
Example #18
0
        private static ImmutableDictionary<FixAllProvider, ImmutableHashSet<string>> GetAllFixAllProviders(IEnumerable<CodeFixProvider> providers)
        {
            Dictionary<FixAllProvider, ImmutableHashSet<string>> fixAllProviders = new Dictionary<FixAllProvider, ImmutableHashSet<string>>();

            foreach (var provider in providers)
            {
                var fixAllProvider = provider.GetFixAllProvider();
                var supportedDiagnosticIds = fixAllProvider.GetSupportedFixAllDiagnosticIds(provider);
                foreach (var id in supportedDiagnosticIds)
                {
                    fixAllProviders.AddToInnerSet(fixAllProvider, id);
                }
            }

            return fixAllProviders.ToImmutableDictionary();
        }
        private static void HandleIncrementDecrementToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            switch (token.Parent.Kind())
            {
            case SyntaxKind.PreIncrementExpression:
            case SyntaxKind.PreDecrementExpression:
                if (token.HasTrailingTrivia)
                {
                    string symbolName;
                    if (token.IsKind(SyntaxKind.MinusMinusToken))
                    {
                        symbolName = "Decrement";
                    }
                    else
                    {
                        symbolName = "Increment";
                    }

                    // {Increment|Decrement} symbol '{++|--}' must not be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove,
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), symbolName, token.Text, "followed"));
                }

                break;

            case SyntaxKind.PostIncrementExpression:
            case SyntaxKind.PostDecrementExpression:
                SyntaxToken previousToken = token.GetPreviousToken();
                if (!previousToken.IsMissing && previousToken.HasTrailingTrivia)
                {
                    string symbolName;
                    if (token.IsKind(SyntaxKind.MinusMinusToken))
                    {
                        symbolName = "Decrement";
                    }
                    else
                    {
                        symbolName = "Increment";
                    }

                    // {Increment|Decrement} symbol '{++|--}' must not be {preceded} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove,
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), symbolName, token.Text, "preceded"));
                }

                break;

            default:
                return;
            }
        }
Example #20
0
            internal void CreateSourceAssemblyForCompilation(PhpCompilation compilation)
            {
                if (compilation._lazyAssemblySymbol != null)
                    return;

                // TODO: lock

                Debug.Assert(_lazyExplicitReferences.IsDefault);
                Debug.Assert(_lazyCorLibrary == null);
                Debug.Assert(_lazyPhpCorLibrary == null);

                //
                var externalRefs = CorLibReferences.SelectMany(reference => compilation.Options.MetadataReferenceResolver.ResolveReference(reference, null, new MetadataReferenceProperties()))
                    .Concat(compilation.ExternalReferences).AsImmutable();
                var assemblies = new List<AssemblySymbol>(externalRefs.Length);

                var referencesMap = new Dictionary<MetadataReference, IAssemblySymbol>();
                var metadataMap = new Dictionary<IAssemblySymbol, MetadataReference>();
                var assembliesMap = new Dictionary<AssemblyIdentity, PEAssemblySymbol>();

                var refmodules = new List<PEModuleSymbol>();
                
                foreach (PortableExecutableReference pe in externalRefs)
                {
                    var symbol = PEAssemblySymbol.Create(pe);
                    if (symbol != null)
                    {
                        assemblies.Add(symbol);
                        referencesMap[pe] = symbol;
                        metadataMap[symbol] = pe;

                        if (_lazyCorLibrary == null && symbol.IsCorLibrary)
                            _lazyCorLibrary = symbol;

                        if (_lazyPhpCorLibrary == null && symbol.IsPchpCorLibrary)
                            _lazyPhpCorLibrary = symbol;

                        // cache bound assembly symbol
                        _assembliesMap.Add(symbol.Identity, symbol);

                        // list of modules to initialize later
                        refmodules.AddRange(symbol.Modules.Cast<PEModuleSymbol>());
                    }
                    else
                    {
                        throw new Exception($"symbol '{pe.FilePath}' could not be created!");
                    }
                }

                //
                _lazyExplicitReferences = externalRefs;
                _lazyImplicitReferences = ImmutableArray<MetadataReference>.Empty;
                _metadataMap = metadataMap.ToImmutableDictionary();
                _referencesMap = referencesMap.ToImmutableDictionary();

                //
                var assembly = new SourceAssemblySymbol(compilation, compilation.Options.ModuleName, compilation.Options.ModuleName);
                assembly.SetCorLibrary(_lazyCorLibrary);
                compilation._lazyAssemblySymbol = assembly;

                assembly.SourceModule.SetReferences(new ModuleReferences<AssemblySymbol>(
                    assemblies.Select(x => x.Identity).AsImmutable(),
                    assemblies.AsImmutable(),
                    ImmutableArray<UnifiedAssembly<AssemblySymbol>>.Empty), assembly);

                assemblies.ForEach(ass => ass.SetCorLibrary(_lazyCorLibrary));

                // recursively initialize references of referenced modules
                SetReferencesOfReferencedModules(compilation.Options.MetadataReferenceResolver, refmodules);

                // set cor types for this compilation
                if (_lazyPhpCorLibrary == null) throw new DllNotFoundException("Peachpie.Runtime not found");
                if (_lazyCorLibrary == null) throw new DllNotFoundException("A corlib not found");
                compilation.CoreTypes.Update(_lazyPhpCorLibrary);
                compilation.CoreTypes.Update(_lazyCorLibrary);
            }
        private static void CheckIfCommasAreAtTheSameLineAsThePreviousParameter(SyntaxNodeAnalysisContext context, SyntaxNodeOrTokenList nodeOrTokenList)
        {
            SyntaxNode previousNode = null;

            // If index is even we expecting parameter syntax node, otherwise we expecting comma token.
            for (int index = 0, count = nodeOrTokenList.Count; index < count; ++index)
            {
                SyntaxNodeOrToken nodeOrToken = nodeOrTokenList[index];
                if (index % 2 == 0)
                {
                    // We expecting node here
                    if (nodeOrToken.IsToken)
                    {
                        return;
                    }

                    previousNode = nodeOrToken.AsNode();
                }
                else
                {
                    // We expecting token here
                    if (nodeOrToken.IsNode)
                    {
                        return;
                    }

                    if (previousNode.GetEndLine() < nodeOrToken.GetLineSpan().StartLinePosition.Line)
                    {
                        var properties = new Dictionary<string, string>
                        {
                            [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                            [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove,
                            [OpenCloseSpacingCodeFixProvider.LayoutKey] = OpenCloseSpacingCodeFixProvider.LayoutPreserve
                        };
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, nodeOrToken.GetLocation(), properties.ToImmutableDictionary()));
                    }
                }
            }
        }
Example #22
0
        private ImmutableDictionary<string, ImmutableList<LinkSourceInfo>> GetFileLinkSource(FileAndType ft, HtmlDocument doc)
        {
            var fileLinkSources = new Dictionary<string, List<LinkSourceInfo>>();
            foreach (var pair in (from n in doc.DocumentNode.Descendants()
                                  where !string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase)
                                  from attr in n.Attributes
                                  where string.Equals(attr.Name, "src", StringComparison.OrdinalIgnoreCase) ||
                                        string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase)
                                  where !string.IsNullOrWhiteSpace(attr.Value)
                                  select new { Node = n, Attr = attr }).ToList())
            {
                string anchor = null;
                var link = pair.Attr;
                string linkFile = link.Value;
                var index = linkFile.IndexOfAny(UriFragmentOrQueryString);
                if (index != -1)
                {
                    anchor = linkFile.Substring(index);
                    linkFile = linkFile.Remove(index);
                }
                if (TypeForwardedToRelativePath.IsRelativePath(linkFile))
                {
                    var path = (TypeForwardedToRelativePath)ft.File + (TypeForwardedToRelativePath)linkFile;
                    string file = path.GetPathFromWorkingFolder().UrlDecode();
                    if (SourceFiles.ContainsKey(file))
                    {
                        link.Value = file;
                        if (!string.IsNullOrEmpty(anchor) &&
                            string.Equals(link.Name, "href", StringComparison.OrdinalIgnoreCase))
                        {
                            pair.Node.SetAttributeValue("anchor", anchor);
                        }
                    }

                    List<LinkSourceInfo> sources;
                    if (!fileLinkSources.TryGetValue(file, out sources))
                    {
                        sources = new List<LinkSourceInfo>();
                        fileLinkSources[file] = sources;
                    }
                    sources.Add(new LinkSourceInfo
                    {
                        Target = file,
                        Anchor = anchor,
                        SourceFile = pair.Node.GetAttributeValue("sourceFile", null),
                        LineNumber = pair.Node.GetAttributeValue("sourceStartLineNumber", 0),
                    });
                }
            }
            return fileLinkSources.ToImmutableDictionary(x => x.Key, x => x.Value.ToImmutableList());
        }
        public AuthorizationManager(IAuthorizationConfiguration authorizationConfiguration) {
            defaultAuthorizer = authorizationConfiguration.DefaultAuthorizer;
            if (defaultAuthorizer == null) {
                throw new InitialisationException("Default Authorizer cannot be null");
            }

            var isVisibleDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() {
                {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsVisible"))}
            };

            var isEditableDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() {
                {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsEditable"))}
            };

            if (authorizationConfiguration.NamespaceAuthorizers.Any()) {
                namespaceAuthorizers = authorizationConfiguration.NamespaceAuthorizers.OrderByDescending(x => x.Key.Length).ToImmutableDictionary();
            }
            if (authorizationConfiguration.TypeAuthorizers.Any()) {
                if (authorizationConfiguration.TypeAuthorizers.Values.Any(t => typeof(ITypeAuthorizer<object>).IsAssignableFrom(t))) {
                    throw new InitialisationException("Only Default Authorizer can be ITypeAuthorizer<object>");
                }

                typeAuthorizers = authorizationConfiguration.TypeAuthorizers.ToImmutableDictionary();
                isVisibleDelegates = isVisibleDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsVisible")))).ToImmutableDictionary();
                isEditableDelegates = isEditableDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsEditable")))).ToImmutableDictionary();
            } else { // default authorizer must be the only TypeAuthorizer
                isVisibleDelegates = isVisibleDict.ToImmutableDictionary();
                isEditableDelegates = isEditableDict.ToImmutableDictionary();
            }
        }
        internal static async Task<ImmutableArray<CodeFixEquivalenceGroup>> CreateAsync(CodeFixProvider codeFixProvider, ImmutableDictionary<ProjectId, ImmutableArray<Diagnostic>> allDiagnostics, Solution solution, CancellationToken cancellationToken)
        {
            var fixAllProvider = codeFixProvider.GetFixAllProvider();
            if (fixAllProvider == null)
            {
                return ImmutableArray.Create<CodeFixEquivalenceGroup>();
            }

            Dictionary<ProjectId, Dictionary<string, List<Diagnostic>>> relevantDocumentDiagnostics =
                new Dictionary<ProjectId, Dictionary<string, List<Diagnostic>>>();
            Dictionary<ProjectId, List<Diagnostic>> relevantProjectDiagnostics =
                new Dictionary<ProjectId, List<Diagnostic>>();

            foreach (var projectDiagnostics in allDiagnostics)
            {
                foreach (var diagnostic in projectDiagnostics.Value)
                {
                    if (!codeFixProvider.FixableDiagnosticIds.Contains(diagnostic.Id))
                    {
                        continue;
                    }

                    if (diagnostic.Location.IsInSource)
                    {
                        string sourcePath = diagnostic.Location.GetLineSpan().Path;

                        Dictionary<string, List<Diagnostic>> projectDocumentDiagnostics;
                        if (!relevantDocumentDiagnostics.TryGetValue(projectDiagnostics.Key, out projectDocumentDiagnostics))
                        {
                            projectDocumentDiagnostics = new Dictionary<string, List<Diagnostic>>();
                            relevantDocumentDiagnostics.Add(projectDiagnostics.Key, projectDocumentDiagnostics);
                        }

                        List<Diagnostic> diagnosticsInFile;
                        if (!projectDocumentDiagnostics.TryGetValue(sourcePath, out diagnosticsInFile))
                        {
                            diagnosticsInFile = new List<Diagnostic>();
                            projectDocumentDiagnostics.Add(sourcePath, diagnosticsInFile);
                        }

                        diagnosticsInFile.Add(diagnostic);
                    }
                    else
                    {
                        List<Diagnostic> diagnosticsInProject;
                        if (!relevantProjectDiagnostics.TryGetValue(projectDiagnostics.Key, out diagnosticsInProject))
                        {
                            diagnosticsInProject = new List<Diagnostic>();
                            relevantProjectDiagnostics.Add(projectDiagnostics.Key, diagnosticsInProject);
                        }

                        diagnosticsInProject.Add(diagnostic);
                    }
                }
            }

            ImmutableDictionary<ProjectId, ImmutableDictionary<string, ImmutableArray<Diagnostic>>> documentDiagnosticsToFix =
                relevantDocumentDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableDictionary(j => j.Key, j => j.Value.ToImmutableArray(), StringComparer.OrdinalIgnoreCase));
            ImmutableDictionary<ProjectId, ImmutableArray<Diagnostic>> projectDiagnosticsToFix =
                relevantProjectDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableArray());

            HashSet<string> equivalenceKeys = new HashSet<string>();
            foreach (var diagnostic in relevantDocumentDiagnostics.Values.SelectMany(i => i.Values).SelectMany(i => i).Concat(relevantProjectDiagnostics.Values.SelectMany(i => i)))
            {
                foreach (var codeAction in await GetFixesAsync(solution, codeFixProvider, diagnostic, cancellationToken).ConfigureAwait(false))
                {
                    equivalenceKeys.Add(codeAction.EquivalenceKey);
                }
            }

            List<CodeFixEquivalenceGroup> groups = new List<CodeFixEquivalenceGroup>();
            foreach (var equivalenceKey in equivalenceKeys)
            {
                groups.Add(new CodeFixEquivalenceGroup(equivalenceKey, solution, fixAllProvider, codeFixProvider, documentDiagnosticsToFix, projectDiagnosticsToFix));
            }

            return groups.ToImmutableArray();
        }
        private static void HandleGreaterThanToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            switch (token.Parent.Kind())
            {
            case SyntaxKind.TypeArgumentList:
            case SyntaxKind.TypeParameterList:
                break;

            default:
                // not a generic bracket
                return;
            }

            bool firstInLine = token.IsFirstInLine();
            bool lastInLine = token.IsLastInLine();
            bool precededBySpace = firstInLine || token.IsPrecededByWhitespace();
            bool followedBySpace = token.IsFollowedByWhitespace();
            bool allowTrailingNoSpace;
            bool allowTrailingSpace;

            if (!lastInLine)
            {
                SyntaxToken nextToken = token.GetNextToken();
                switch (nextToken.Kind())
                {
                case SyntaxKind.OpenParenToken:
                // DotToken isn't listed above, but it's required for reasonable member access formatting
                case SyntaxKind.DotToken:
                // CommaToken isn't listed above, but it's required for reasonable nested generic type arguments formatting
                case SyntaxKind.CommaToken:
                // OpenBracketToken isn't listed above, but it's required for reasonable array type formatting
                case SyntaxKind.OpenBracketToken:
                // SemicolonToken isn't listed above, but it's required for reasonable using alias declaration formatting
                case SyntaxKind.SemicolonToken:
                    allowTrailingNoSpace = true;
                    allowTrailingSpace = false;
                    break;

                case SyntaxKind.CloseParenToken:
                case SyntaxKind.GreaterThanToken:
                    allowTrailingNoSpace = true;
                    allowTrailingSpace = true;
                    break;

                case SyntaxKind.QuestionToken:
                    allowTrailingNoSpace = nextToken.Parent.IsKind(SyntaxKind.NullableType);
                    allowTrailingSpace = true;
                    break;

                default:
                    allowTrailingNoSpace = false;
                    allowTrailingSpace = true;
                    break;
                }
            }
            else
            {
                allowTrailingNoSpace = true;
                allowTrailingSpace = true;
            }

            if (!firstInLine && precededBySpace)
            {
                // Closing generic bracket must{ not} be {preceded} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded"));
            }

            if (!lastInLine)
            {
                if (!allowTrailingNoSpace && !followedBySpace)
                {
                    // Closing generic bracket must{} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed"));
                }
                else if (!allowTrailingSpace && followedBySpace)
                {
                    // Closing generic bracket must{ not} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed"));
                }
            }
        }
 private static DiagnosticAnalyzerService CreateDiagnosticAnalyzerService(Dictionary<string, DiagnosticAnalyzer[]> analyzerMap)
 {
     return analyzerMap == null || analyzerMap.Count == 0
         ? new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap())
         : new TestDiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.ToImmutableArray()));
 }
Example #27
0
        private static ImmutableDictionary<string, ImmutableList<CodeFixProvider>> GetAllCodeFixers()
        {
            Assembly assembly = typeof(StyleCop.Analyzers.SpacingRules.SA1027CodeFixProvider).Assembly;

            var codeFixProviderType = typeof(CodeFixProvider);

            Dictionary<string, ImmutableList<CodeFixProvider>> providers = new Dictionary<string, ImmutableList<CodeFixProvider>>();

            foreach (var type in assembly.GetTypes())
            {
                if (type.IsSubclassOf(codeFixProviderType) && !type.IsAbstract)
                {
                    var codeFixProvider = (CodeFixProvider)Activator.CreateInstance(type);

                    foreach (var diagnosticId in codeFixProvider.FixableDiagnosticIds)
                    {
                        providers.AddToInnerList(diagnosticId, codeFixProvider);
                    }
                }
            }

            return providers.ToImmutableDictionary();
        }
        private static void HandleCloseBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            // attribute brackets are handled separately
            if (token.Parent.IsKind(SyntaxKind.AttributeList))
            {
                return;
            }

            bool firstInLine = token.IsFirstInLine();
            bool precededBySpace = firstInLine || token.IsPrecededByWhitespace();
            bool followedBySpace = token.IsFollowedByWhitespace();
            bool lastInLine = token.IsLastInLine();
            bool precedesSpecialCharacter;

            // Tests for this rule have a lot of exclusions which are supposed to be caught by other rules
            bool suppressFollowingSpaceError = true;

            if (!lastInLine)
            {
                SyntaxToken nextToken = token.GetNextToken();
                switch (nextToken.Kind())
                {
                case SyntaxKind.CloseBracketToken:
                case SyntaxKind.OpenParenToken:
                case SyntaxKind.CommaToken:
                case SyntaxKind.SemicolonToken:
                // TODO: "certain types of operator symbols"
                case SyntaxKind.DotToken:
                case SyntaxKind.OpenBracketToken:
                case SyntaxKind.CloseParenToken:
                    precedesSpecialCharacter = true;
                    break;
                case SyntaxKind.PlusPlusToken:
                case SyntaxKind.MinusMinusToken:
                    precedesSpecialCharacter = true;
                    suppressFollowingSpaceError = false;
                    break;

                case SyntaxKind.GreaterThanToken:
                    precedesSpecialCharacter = nextToken.Parent.IsKind(SyntaxKind.TypeArgumentList);
                    break;

                case SyntaxKind.QuestionToken:
                    precedesSpecialCharacter = nextToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression);
                    break;

                case SyntaxKind.CloseBraceToken:
                    precedesSpecialCharacter = nextToken.Parent is InterpolationSyntax;
                    break;

                default:
                    precedesSpecialCharacter = false;
                    break;
                }
            }
            else
            {
                precedesSpecialCharacter = false;
            }

            if (!firstInLine && precededBySpace)
            {
                // Closing square bracket must{ not} be {preceded} by a space.
                var properties = new Dictionary<string, string>
                {
                    [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding,
                    [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                };
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded"));
            }

            if (!lastInLine)
            {
                if (!precedesSpecialCharacter && !followedBySpace)
                {
                    // Closing square bracket must{} be {followed} by a space.
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed"));
                }
                else if (precedesSpecialCharacter && followedBySpace && !suppressFollowingSpaceError)
                {
                    // Closing square brackets must {not} be {followed} by a space
                    var properties = new Dictionary<string, string>
                    {
                        [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing,
                        [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove
                    };
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed"));
                }
            }
        }
Example #29
0
        /// <summary>
        /// Returns a list of all analyzer diagnostics inside the specific project. This is an asynchronous operation.
        /// </summary>
        /// <param name="analyzers">The list of analyzers that should be used</param>
        /// <param name="project">The project that should be analyzed</param>
        /// <param name="force"><see langword="true"/> to force the analyzers to be enabled; otherwise,
        /// <see langword="false"/> to use the behavior configured for the specified <paramref name="project"/>.</param>
        /// <param name="cancellationToken">The cancellation token that the task will observe.</param>
        /// <returns>A list of diagnostics inside the project</returns>
        private static async Task<ImmutableArray<Diagnostic>> GetProjectAnalyzerDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Project project, bool force, CancellationToken cancellationToken)
        {
            var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>();
            if (force)
            {
                foreach (var analyzer in analyzers)
                {
                    foreach (var diagnostic in analyzer.SupportedDiagnostics)
                    {
                        // make sure the analyzers we are testing are enabled
                        supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default;
                    }
                }
            }

            // Report exceptions during the analysis process as errors
            supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error);

            // update the project compilation options
            var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions);
            var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions);
            var processedProject = project.WithCompilationOptions(modifiedCompilationOptions);

            Compilation compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
            CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, cancellationToken: cancellationToken);

            var diagnostics = await FixAllContextHelper.GetAllDiagnosticsAsync(compilation, compilationWithAnalyzers, analyzers, project.Documents, true, cancellationToken).ConfigureAwait(false);
            return diagnostics;
        }
        private static void InitializeWellKnownSystemNamespaceTable()
        {
            if (s_wellKnownSystemNamespaceTable == null)
            {
                lock (s_lock)
                {
                    if (s_wellKnownSystemNamespaceTable == null)
                    {
                        #region List of Well known System Namespaces
                        var wellKnownSystemNamespaces = new List<string>
                                {
                                    "Microsoft.CSharp",
                                    "Microsoft.SqlServer.Server",
                                    "Microsoft.VisualBasic",
                                    "Microsoft.Win32",
                                    "Microsoft.Win32.SafeHandles",
                                    "System",
                                    "System.CodeDom",
                                    "System.CodeDom.Compiler",
                                    "System.Collections",
                                    "System.Collections.Generic",
                                    "System.Collections.ObjectModel",
                                    "System.Collections.Specialized",
                                    "System.ComponentModel",
                                    "System.ComponentModel.Design",
                                    "System.ComponentModel.Design.Serialization",
                                    "System.Configuration",
                                    "System.Configuration.Assemblies",
                                    "System.Data",
                                    "System.Data.Common",
                                    "System.Data.Odbc",
                                    "System.Data.OleDb",
                                    "System.Data.Sql",
                                    "System.Data.SqlClient",
                                    "System.Data.SqlTypes",
                                    "System.Deployment.Internal",
                                    "System.Diagnostics",
                                    "System.Diagnostics.CodeAnalysis",
                                    "System.Diagnostics.SymbolStore",
                                    "System.Drawing",
                                    "System.Drawing.Design",
                                    "System.Drawing.Drawing2D",
                                    "System.Drawing.Imaging",
                                    "System.Drawing.Printing",
                                    "System.Drawing.Text",
                                    "System.Globalization",
                                    "System.IO",
                                    "System.IO.Compression",
                                    "System.IO.IsolatedStorage",
                                    "System.IO.Ports",
                                    "System.Media",
                                    "System.Net",
                                    "System.Net.Cache",
                                    "System.Net.Configuration",
                                    "System.Net.Mail",
                                    "System.Net.Mime",
                                    "System.Net.NetworkInformation",
                                    "System.Net.Security",
                                    "System.Net.Sockets",
                                    "System.Reflection",
                                    "System.Reflection.Emit",
                                    "System.Resources",
                                    "System.Runtime",
                                    "System.Runtime.CompilerServices",
                                    "System.Runtime.ConstrainedExecution",
                                    "System.Runtime.Hosting",
                                    "System.Runtime.InteropServices",
                                    "System.Runtime.InteropServices.ComTypes",
                                    "System.Runtime.InteropServices.Expando",
                                    "System.Runtime.Remoting",
                                    "System.Runtime.Remoting.Activation",
                                    "System.Runtime.Remoting.Channels",
                                    "System.Runtime.Remoting.Contexts",
                                    "System.Runtime.Remoting.Lifetime",
                                    "System.Runtime.Remoting.Messaging",
                                    "System.Runtime.Remoting.Metadata",
                                    "System.Runtime.Remoting.Metadata.W3cXsd2001",
                                    "System.Runtime.Remoting.Proxies",
                                    "System.Runtime.Remoting.Services",
                                    "System.Runtime.Serialization",
                                    "System.Runtime.Serialization.Formatters",
                                    "System.Runtime.Serialization.Formatters.Binary",
                                    "System.Runtime.Versioning",
                                    "System.Security",
                                    "System.Security.AccessControl",
                                    "System.Security.Authentication",
                                    "System.Security.Cryptography",
                                    "System.Security.Cryptography.X509Certificates",
                                    "System.Security.Permissions",
                                    "System.Security.Policy",
                                    "System.Security.Principal",
                                    "System.Text",
                                    "System.Text.RegularExpressions",
                                    "System.Threading",
                                    "System.Timers",
                                    "System.Web",
                                    "System.Web.Caching",
                                    "System.Web.Compilation",
                                    "System.Web.Configuration",
                                    "System.Web.Configuration.Internal",
                                    "System.Web.Handlers",
                                    "System.Web.Hosting",
                                    "System.Web.Mail",
                                    "System.Web.Management",
                                    "System.Web.Profile",
                                    "System.Web.Security",
                                    "System.Web.SessionState",
                                    "System.Web.UI",
                                    "System.Web.UI.Adapters",
                                    "System.Web.UI.HtmlControls",
                                    "System.Web.UI.WebControls",
                                    "System.Web.UI.WebControls.Adapters",
                                    "System.Web.UI.WebControls.WebParts",
                                    "System.Web.Util",
                                    "System.Windows.Forms",
                                    "System.Windows.Forms.ComponentModel.Com2Interop",
                                    "System.Windows.Forms.Design",
                                    "System.Windows.Forms.Layout",
                                    "System.Windows.Forms.PropertyGridInternal",
                                    "System.Windows.Forms.VisualStyles",
                                    "System.Xml",
                                    "System.Xml.Schema",
                                    "System.Xml.Serialization",
                                    "System.Xml.Serialization.Advanced",
                                    "System.Xml.Serialization.Configuration",
                                    "System.Xml.XPath",
                                    "System.Xml.Xsl"
                                };
                        #endregion

                        var wellKnownSystemNamespaceTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        UpdateNamespaceTable(wellKnownSystemNamespaceTable, wellKnownSystemNamespaces);
                        s_wellKnownSystemNamespaceTable = wellKnownSystemNamespaceTable.ToImmutableDictionary();
                    }
                }
            }
        }