public static bool TryGetEditorConfigOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption <T> option, out T value)
 {
     return(TryGetEditorConfigOption(analyzerConfigOptions, option, out value));
 }
Esempio n. 2
0
        public IFormattingResult Format(SyntaxNode node, IEnumerable <TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable <AbstractFormattingRule> rules, CancellationToken cancellationToken)
        {
            CheckArguments(node, spans, options, rules);

            // quick exit check
            var spansToFormat = new NormalizedTextSpanCollection(spans.Where(s_notEmpty));

            if (spansToFormat.Count == 0)
            {
                return(CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList <AbstractFormattingResult>()));
            }

            // check what kind of formatting strategy to use
            if (AllowDisjointSpanMerging(spansToFormat, shouldUseFormattingSpanCollapse))
            {
                return(FormatMergedSpan(node, options, rules, spansToFormat, cancellationToken));
            }

            return(FormatIndividually(node, options, rules, spansToFormat, cancellationToken));
        }
        /// <summary>
        /// return AlignTokensOperation for the node provided by the given formatting rules
        /// </summary>
        internal static IEnumerable <AlignTokensOperation> GetAlignTokensOperations(IEnumerable <AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options)
        {
            var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options);

            var list = new List <AlignTokensOperation>();

            chainedFormattingRules.AddAlignTokensOperations(list, node);
            return(list);
        }
        protected override void UpdateOptions(
            AnalyzerConfigOptions editorConfigOptions,
            OptionSet visualStudioOptions
            )
        {
            var qualifySettings = GetQualifyCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(qualifySettings);

            var predefinedTypesSettings = GetPredefinedTypesCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(predefinedTypesSettings);

            var nullCheckingSettings = GetNullCheckingCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(nullCheckingSettings);

            var modifierSettings = GetModifierCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(modifierSettings);

            var codeBlockSettings = GetCodeBlockCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(codeBlockSettings);

            var expressionSettings = GetExpressionCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(expressionSettings);

            var parameterSettings = GetParameterCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(parameterSettings);

            var parenthesesSettings = GetParenthesesCodeStyleOptions(
                editorConfigOptions,
                visualStudioOptions,
                SettingsUpdater
                );

            AddRange(parenthesesSettings);
            // TODO(jmarolf): set as stable
        }
Esempio n. 5
0
        private static void CheckArguments(SyntaxNode node, IEnumerable <TextSpan> spans, AnalyzerConfigOptions options, IEnumerable <AbstractFormattingRule> rules)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            if (spans == null)
            {
                throw new ArgumentNullException(nameof(spans));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (rules == null)
            {
                throw new ArgumentException("rules");
            }
        }
 public override void AddAnchorIndentationOperations(List <AnchorIndentationOperation> list, SyntaxNode node, AnalyzerConfigOptions options, in NextAnchorIndentationOperationAction nextOperation)
Esempio n. 7
0
 public CombinedAnalyzerConfigOptions(AnalyzerConfigOptions workspaceOptions, AnalyzerConfigOptionsResult?result)
 {
     _workspaceOptions = workspaceOptions;
     _result           = result;
 }
Esempio n. 8
0
 public AnalyzerOptionsProvider(AnalyzerConfigOptions options, AnalyzerOptions fallbackOptions)
     : this(options, fallbackOptions.GetIdeOptions())
 {
 }
Esempio n. 9
0
        public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
        {
            // This is a workaround until we have an API for enumeratings AnalyzerConfigOptions. See https://github.com/dotnet/roslyn/issues/41840
            var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var backing      = backingField?.GetValue(analyzerConfigOptions);

            if (backing is IReadOnlyDictionary <string, string> backingDictionary)
            {
                return(editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value));
            }

            value = null;
            return(false);
        }
Esempio n. 10
0
        public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, AnalyzerConfigOptions analyzerConfigOptions)
        {
            // Check if the option is defined explicitly in the editorconfig
            var diagnosticKey = $"{DotnetDiagnosticPrefix}.{descriptor.Id}.{SeveritySuffix}";

            if (analyzerConfigOptions.TryGetValue(diagnosticKey, out var value) &&
                EditorConfigSeverityStrings.TryParse(value, out var severity))
            {
                return(severity);
            }

            // Check if the option is defined as part of a bulk configuration
            // Analyzer bulk configuration does not apply to:
            //  1. Disabled by default diagnostics
            //  2. Compiler diagnostics
            //  3. Non-configurable diagnostics
            if (!descriptor.IsEnabledByDefault ||
                descriptor.CustomTags.Any(tag => tag == WellKnownDiagnosticTags.Compiler || tag == WellKnownDiagnosticTags.NotConfigurable))
            {
                return(ReportDiagnostic.Default);
            }

            // If user has explicitly configured default severity for the diagnostic category, that should be respected.
            // For example, 'dotnet_analyzer_diagnostic.category-security.severity = error'
            var categoryBasedKey = $"{DotnetAnalyzerDiagnosticPrefix}.{CategoryPrefix}-{descriptor.Category}.{SeveritySuffix}";

            if (analyzerConfigOptions.TryGetValue(categoryBasedKey, out value) &&
                EditorConfigSeverityStrings.TryParse(value, out severity))
            {
                return(severity);
            }

            // Otherwise, if user has explicitly configured default severity for all analyzer diagnostics, that should be respected.
            // For example, 'dotnet_analyzer_diagnostic.severity = error'
            if (analyzerConfigOptions.TryGetValue(DotnetAnalyzerDiagnosticSeverityKey, out value) &&
                EditorConfigSeverityStrings.TryParse(value, out severity))
            {
                return(severity);
            }

            // option not defined in editorconfig, assumed to be the default
            return(ReportDiagnostic.Default);
        }
Esempio n. 11
0
 public AnalyzerOptionsProvider(AnalyzerConfigOptions options, IdeAnalyzerOptions fallbackOptions)
 {
     _options         = options;
     _fallbackOptions = fallbackOptions;
 }
Esempio n. 12
0
 public override void AddIndentBlockOperations(List <IndentBlockOperation> list, SyntaxNode node, AnalyzerConfigOptions options, in NextIndentBlockOperationAction nextOperation)
        private IEnumerable <WhitespaceSetting> GetWrappingOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService)
        {
            yield return(WhitespaceSetting.Create(CSharpFormattingOptions2.WrappingPreserveSingleLine, CSharpEditorResources.Leave_block_on_single_line, editorConfigOptions, visualStudioOptions, updaterService, FileName));

            yield return(WhitespaceSetting.Create(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, CSharpEditorResources.Leave_statements_and_member_declarations_on_the_same_line, editorConfigOptions, visualStudioOptions, updaterService, FileName));
        }
 public static bool TryGetEditorConfigOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, Option <T> option, out T value)
 {
     return(TryGetEditorConfigOption(analyzerConfigOptions, (IOption)option, out value));
 }
Esempio n. 15
0
 public static T GetEditorConfigOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, T defaultValue)
 => TryGetEditorConfigOption(analyzerConfigOptions, option, new Optional <T?>(defaultValue), out var value) ? value ! : throw ExceptionUtilities.Unreachable;
 public static bool TryGetEditorConfigOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, out T value)
 => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: false, out value);
        public static NamingStylePreferences ParseDictionary(AnalyzerConfigOptions allRawConventions)
        {
            var trimmedDictionary = TrimDictionary(allRawConventions);

            var symbolSpecifications = ArrayBuilder <SymbolSpecification> .GetInstance();

            var namingStyles = ArrayBuilder <NamingStyle> .GetInstance();

            var namingRules = ArrayBuilder <SerializableNamingRule> .GetInstance();

            var ruleNames = new Dictionary <(Guid symbolSpecificationID, Guid namingStyleID, ReportDiagnostic enforcementLevel), string>();

            foreach (var namingRuleTitle in GetRuleTitles(trimmedDictionary))
            {
                if (TryGetSymbolSpec(namingRuleTitle, trimmedDictionary, out var symbolSpec) &&
                    TryGetNamingStyleData(namingRuleTitle, trimmedDictionary, out var namingStyle) &&
                    TryGetSerializableNamingRule(namingRuleTitle, symbolSpec, namingStyle, trimmedDictionary, out var serializableNamingRule))
                {
                    symbolSpecifications.Add(symbolSpec);
                    namingStyles.Add(namingStyle);
                    namingRules.Add(serializableNamingRule);

                    var ruleKey = (serializableNamingRule.SymbolSpecificationID, serializableNamingRule.NamingStyleID, serializableNamingRule.EnforcementLevel);
                    if (ruleNames.TryGetValue(ruleKey, out var existingName))
                    {
                        // For duplicated rules, only preserve the one with a name that would sort first
                        var ordinalIgnoreCaseOrdering = StringComparer.OrdinalIgnoreCase.Compare(namingRuleTitle, existingName);
                        if (ordinalIgnoreCaseOrdering > 0)
                        {
                            continue;
                        }
                        else if (ordinalIgnoreCaseOrdering == 0)
                        {
                            var ordinalOrdering = StringComparer.Ordinal.Compare(namingRuleTitle, existingName);
                            if (ordinalOrdering > 0)
                            {
                                continue;
                            }
                        }
                    }

                    ruleNames[ruleKey] = namingRuleTitle;
                }
            }

            var preferences = new NamingStylePreferences(
                symbolSpecifications.ToImmutableAndFree(),
                namingStyles.ToImmutableAndFree(),
                namingRules.ToImmutableAndFree());

            // Deterministically order the naming style rules according to the symbols matched by the rule. The rules
            // are applied in order; later rules are only relevant if earlier rules fail to specify an order.
            //
            // 1. If the modifiers required by rule 'x' are a strict superset of the modifiers required by rule 'y',
            //    then rule 'x' is evaluated before rule 'y'.
            // 2. If the accessibilities allowed by rule 'x' are a strict subset of the accessibilities allowed by rule
            //    'y', then rule 'x' is evaluated before rule 'y'.
            // 3. If the set of symbols matched by rule 'x' are a strict subset of the symbols matched by rule 'y', then
            //    rule 'x' is evaluated before rule 'y'.
            //
            // If none of the above produces an order between two rules 'x' and 'y', then the rules are ordered
            // according to their name, first by OrdinalIgnoreCase and finally by Ordinal.
            //
            // Historical note: rules used to be ordered by their position in the .editorconfig file. However, this
            // relied on an implementation detail of the .editorconfig parser which is not preserved by all
            // implementations. In a review of .editorconfig files in the wild, the rules applied in this section were
            // the closest deterministic match for the files without having any reliance on order. For any pair of rules
            // which a user has trouble ordering, the intersection of the two rules can be broken out into a new rule
            // will always match earlier than the broader rules it was derived from.
            var orderedRules = preferences.Rules.NamingRules
                               .OrderBy(rule => rule, NamingRuleModifierListComparer.Instance)
                               .ThenBy(rule => rule, NamingRuleAccessibilityListComparer.Instance)
                               .ThenBy(rule => rule, NamingRuleSymbolListComparer.Instance)
                               .ThenBy(rule => ruleNames[(rule.SymbolSpecification.ID, rule.NamingStyle.ID, rule.EnforcementLevel)], StringComparer.OrdinalIgnoreCase)
Esempio n. 18
0
 protected TriviaData(AnalyzerConfigOptions options, string language)
 {
     Contract.ThrowIfNull(options);
     Options   = options;
     _language = language;
 }
Esempio n. 19
0
 public override void AddSuppressOperations(List <SuppressOperation> list, SyntaxNode node, AnalyzerConfigOptions options, in NextSuppressOperationAction nextOperation)
Esempio n. 20
0
 public static CSharpSyntaxWrappingOptions Create(AnalyzerConfigOptions options, CodeActionOptions ideOptions)
 => new(
        private static IEnumerable <CodeStyleSetting> GetExpressionCodeStyleOptions(
            AnalyzerConfigOptions options,
            OptionSet visualStudioOptions,
            OptionUpdater updater
            )
        {
            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferObjectInitializer,
                             description: EditorFeaturesResources.Prefer_object_initializer,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferCollectionInitializer,
                             description: EditorFeaturesResources.Prefer_collection_initializer,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
                             description: EditorFeaturesResources.Prefer_simplified_boolean_expressions,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferConditionalExpressionOverAssignment,
                             description: EditorFeaturesResources.Prefer_conditional_expression_over_if_with_assignments,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferConditionalExpressionOverReturn,
                             description: EditorFeaturesResources.Prefer_conditional_expression_over_if_with_returns,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferExplicitTupleNames,
                             description: EditorFeaturesResources.Prefer_explicit_tuple_name,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferInferredTupleNames,
                             description: EditorFeaturesResources.Prefer_inferred_tuple_names,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames,
                             description: EditorFeaturesResources.Prefer_inferred_anonymous_type_member_names,
                             options,
                             visualStudioOptions,
                             updater
                             ));

            yield return(CodeStyleSetting.Create(
                             CodeStyleOptions2.PreferCompoundAssignment,
                             description: EditorFeaturesResources.Prefer_compound_assignments,
                             options,
                             visualStudioOptions,
                             updater
                             ));
        }
Esempio n. 22
0
 public static T GetOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, Options.Option <T> option)
 => GetOptionWithAssertOnFailure <T>(analyzerConfigOptions, option);
 public ComplexTrivia(AnalyzerConfigOptions options, TreeData treeInfo, SyntaxToken token1, SyntaxToken token2)
     : base(options, treeInfo, token1, token2)
 {
 }
Esempio n. 24
0
 public static T GetOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2 <T> option)
 => GetOptionWithAssertOnFailure <T>(analyzerConfigOptions, option);
Esempio n. 25
0
 protected abstract AbstractFormattingResult Format(SyntaxNode node, AnalyzerConfigOptions options, IEnumerable <AbstractFormattingRule> rules, SyntaxToken token1, SyntaxToken token2, CancellationToken cancellationToken);
Esempio n. 26
0
 public static bool TryGetEditorConfigOptionOrDefault <T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, out T value)
 => TryGetEditorConfigOption(analyzerConfigOptions, option, (T?)option.DefaultValue, out value !);
 public abstract SyntaxFormattingOptions GetFormattingOptions(AnalyzerConfigOptions options);
Esempio n. 28
0
 public static bool TryGetEditorConfigOption <T>(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, [MaybeNullWhen(false)] out T value)
 => TryGetEditorConfigOption(analyzerConfigOptions, option, defaultValue: default, out value);
Esempio n. 29
0
        /// <summary>
        /// return AdjustSpacesOperation for the node provided by the given formatting rules
        /// </summary>
        internal static AdjustSpacesOperation GetAdjustSpacesOperation(IEnumerable <AbstractFormattingRule> formattingRules, SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options)
        {
            var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options);

            return(chainedFormattingRules.GetAdjustSpacesOperation(previousToken, currentToken));
        }
Esempio n. 30
0
 public CompilerAnalyzerConfigOptionsProvider(AnalyzerConfigOptions globalOptions) => GlobalOptions = globalOptions;