internal AbstractFormatEngine(
            TreeData treeData,
            OptionSet optionSet,
            ChainedFormattingRules formattingRules,
            SyntaxToken token1,
            SyntaxToken token2)
        {
            Contract.ThrowIfNull(optionSet);
            Contract.ThrowIfNull(treeData);
            Contract.ThrowIfNull(formattingRules);

            Contract.ThrowIfTrue(treeData.Root.IsInvalidTokenRange(token1, token2));

            this.OptionSet   = optionSet;
            this.TreeData    = treeData;
            _formattingRules = formattingRules;

            _token1 = token1;
            _token2 = token2;

            // get span and common root
            this.SpanToFormat = GetSpanToFormat();
            _commonRoot       = token1.GetCommonRoot(token2);
            if (token1 == default)
            {
                _language = token2.Language;
            }
            else
            {
                _language = token1.Language;
            }
        }
Exemple #2
0
        private IFormattingResult FormatIndividually(
            SyntaxNode node, OptionSet options, IEnumerable <AbstractFormattingRule> rules, IList <TextSpan> spansToFormat, CancellationToken cancellationToken)
        {
            List <AbstractFormattingResult> results = null;

            foreach (var pair in node.ConvertToTokenPairs(spansToFormat))
            {
                if (node.IsInvalidTokenRange(pair.Item1, pair.Item2))
                {
                    continue;
                }

                results ??= new List <AbstractFormattingResult>();
                results.Add(Format(node, options, rules, pair.Item1, pair.Item2, cancellationToken));
            }

            // quick simple case check
            if (results == null)
            {
                return(CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList <AbstractFormattingResult>()));
            }

            if (results.Count == 1)
            {
                return(results[0]);
            }

            // more expensive case
            return(CreateAggregatedFormattingResult(node, results));
        }
Exemple #3
0
        private static string GetNewLineOptionEditorConfigString(OptionSet optionSet)
        {
            var editorConfigStringBuilder = new List <string>(NewLineOptionsMap.Count);

            foreach (var kvp in NewLineOptionsMap)
            {
                var value = optionSet.GetOption(kvp.Key);
                if (value)
                {
                    Debug.Assert(s_newLineOptionsEditorConfigMap.ContainsValue(kvp.Value));
                    editorConfigStringBuilder.Add(
                        s_newLineOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value) !
                        );
                }
            }

            if (editorConfigStringBuilder.Count == 0)
            {
                // No NewLine option set.
                return("none");
            }
            else if (editorConfigStringBuilder.Count == s_newLineOptionsMapBuilder.Count)
            {
                // All NewLine options set.
                return("all");
            }
            else
            {
                return(string.Join(",", editorConfigStringBuilder.Order()));
            }
        }
Exemple #4
0
        public SyntaxNode AddImports(
            Compilation compilation,
            SyntaxNode root,
            SyntaxNode?contextLocation,
            IEnumerable <SyntaxNode> newImports,
            SyntaxGenerator generator,
            OptionSet options,
            bool allowInHiddenRegions,
            CancellationToken cancellationToken)
        {
            contextLocation ??= root;

            var placeSystemNamespaceFirst = options.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, compilation.Language);

            var globalImports   = GetGlobalImports(compilation, generator);
            var containers      = GetAllContainers(root, contextLocation);
            var filteredImports = newImports.Where(i => !HasExistingImport(i, containers, globalImports)).ToArray();

            var externAliases         = filteredImports.OfType <TExternSyntax>().ToArray();
            var usingDirectives       = filteredImports.OfType <TUsingOrAliasSyntax>().Where(IsSimpleUsing).ToArray();
            var staticUsingDirectives = filteredImports.OfType <TUsingOrAliasSyntax>().Where(IsStaticUsing).ToArray();
            var aliasDirectives       = filteredImports.OfType <TUsingOrAliasSyntax>().Where(IsAlias).ToArray();

            GetContainers(root, contextLocation, options,
                          out var externContainer, out var usingContainer, out var aliasContainer, out var staticUsingContainer);

            var newRoot = Rewrite(
                externAliases, usingDirectives, staticUsingDirectives, aliasDirectives,
                externContainer, usingContainer, staticUsingContainer, aliasContainer,
                placeSystemNamespaceFirst, allowInHiddenRegions, root, cancellationToken);

            return(newRoot);
        }
Exemple #5
0
        private void GetContainers(SyntaxNode root, SyntaxNode contextLocation, OptionSet options, out SyntaxNode externContainer, out SyntaxNode usingContainer, out SyntaxNode staticUsingContainer, out SyntaxNode aliasContainer)
        {
            var applicableContainer = GetFirstApplicableContainer(contextLocation);
            var contextSpine        = applicableContainer.GetAncestorsOrThis <SyntaxNode>().ToImmutableArray();

            // The node we'll add to if we can't find a specific namespace with imports of
            // the type we're trying to add.  This will be the closest namespace with any
            // imports in it
            var fallbackNode = contextSpine.FirstOrDefault(HasAnyImports);

            // If there aren't any existing imports then make sure we honour the inside namespace preference
            // for using directings if it's set
            if (fallbackNode is null && PlaceImportsInsideNamespaces(options))
            {
                fallbackNode = contextSpine.OfType <TNamespaceDeclarationSyntax>().FirstOrDefault();
            }

            // If all else fails use the root
            if (fallbackNode is null)
            {
                fallbackNode = root;
            }

            // The specific container to add each type of import to.  We look for a container
            // that already has an import of the same type as the node we want to add to.
            // If we can find one, we add to that container.  If not, we call back to the
            // innermost node with any imports.
            externContainer      = contextSpine.FirstOrDefault(HasExterns) ?? fallbackNode;
            usingContainer       = contextSpine.FirstOrDefault(HasUsings) ?? fallbackNode;
            staticUsingContainer = contextSpine.FirstOrDefault(HasStaticUsings) ?? fallbackNode;
            aliasContainer       = contextSpine.FirstOrDefault(HasAliases) ?? fallbackNode;
        }
Exemple #6
0
        private static UseVarPreference GetCurrentTypeStylePreferences(OptionSet optionSet)
        {
            var stylePreferences = UseVarPreference.None;

            var styleForIntrinsicTypes = optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes);
            var styleForApparent       = optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent);
            var styleForElsewhere      = optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere);

            if (styleForIntrinsicTypes.Value)
            {
                stylePreferences |= UseVarPreference.ForBuiltInTypes;
            }

            if (styleForApparent.Value)
            {
                stylePreferences |= UseVarPreference.WhenTypeIsApparent;
            }

            if (styleForElsewhere.Value)
            {
                stylePreferences |= UseVarPreference.Elsewhere;
            }

            return(stylePreferences);
        }
Exemple #7
0
        private static string GetSpacingWithParenthesesEditorConfigString(OptionSet optionSet)
        {
            var editorConfigStringBuilder = new List <string>();

            foreach (var kvp in SpacingWithinParenthesisOptionsMap)
            {
                var value = optionSet.GetOption(kvp.Key);
                if (value)
                {
                    Debug.Assert(
                        s_spacingWithinParenthesisOptionsEditorConfigMap.ContainsValue(kvp.Value)
                        );
                    editorConfigStringBuilder.Add(
                        s_spacingWithinParenthesisOptionsEditorConfigMap.GetKeyOrDefault(kvp.Value) !
                        );
                }
            }

            if (editorConfigStringBuilder.Count == 0)
            {
                // No spacing within parenthesis option set.
                return("false");
            }
            else
            {
                return(string.Join(",", editorConfigStringBuilder.Order()));
            }
        }
Exemple #8
0
        public TokenStream(TreeData treeData, OptionSet optionSet, TextSpan spanToFormat, AbstractTriviaDataFactory factory)
        {
            using (Logger.LogBlock(FunctionId.Formatting_TokenStreamConstruction, CancellationToken.None))
            {
                // initialize basic info
                _factory   = factory;
                _treeData  = treeData;
                _optionSet = optionSet;

                // use some heuristics to get initial size of list rather than blindly start from default size == 4
                var sizeOfList = spanToFormat.Length / MagicTextLengthToTokensRatio;
                _tokens = new List <SyntaxToken>(sizeOfList);
                _tokens.AddRange(_treeData.GetApplicableTokens(spanToFormat));

                Debug.Assert(this.TokenCount > 0);

                // initialize trivia related info
                _cachedOriginalTriviaInfo = new TriviaData[this.TokenCount - 1];

                // Func Cache
                _getTriviaData         = this.GetTriviaData;
                _getOriginalTriviaData = this.GetOriginalTriviaData;
            }

            DebugCheckTokenOrder();
        }
Exemple #9
0
        internal static IFormattingResult GetFormattingResult(
            SyntaxNode node,
            ISyntaxFormattingService syntaxFormattingService,
            IEnumerable <TextSpan> spans,
            OptionSet options,
            IEnumerable <AbstractFormattingRule> rules,
            CancellationToken cancellationToken
            )
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            if (syntaxFormattingService is null)
            {
                return(null);
            }

            options ??= CompilerAnalyzerConfigOptions.Empty;
            rules ??= GetDefaultFormattingRules(syntaxFormattingService);
            spans ??= SpecializedCollections.SingletonEnumerable(node.FullSpan);
            return(syntaxFormattingService.Format(
                       node,
                       spans,
                       shouldUseFormattingSpanCollapse: false,
                       options,
                       rules,
                       cancellationToken
                       ));
        }
Exemple #10
0
 public override TypeStyleResult AnalyzeTypeName(
     TypeSyntax typeName, SemanticModel semanticModel,
     OptionSet optionSet, CancellationToken cancellationToken)
 {
     if (typeName.StripRefIfNeeded().IsVar)
     {
         return(default);
Exemple #11
0
        internal static async Task <SyntaxTree> FormatAsync(
            SyntaxTree syntaxTree,
            ISyntaxFormattingService syntaxFormattingService,
            IEnumerable <TextSpan> spans,
            OptionSet options,
            IEnumerable <AbstractFormattingRule> rules,
            CancellationToken cancellationToken
            )
        {
            if (syntaxTree == null)
            {
                throw new ArgumentNullException(nameof(syntaxTree));
            }

            var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            var documentOptions = options ?? CompilerAnalyzerConfigOptions.Empty;

            return(syntaxTree.WithRootAndOptions(
                       Format(
                           root,
                           syntaxFormattingService,
                           spans,
                           documentOptions,
                           rules,
                           cancellationToken
                           ),
                       syntaxTree.Options
                       ));
        }
        /// <summary>
        /// Gets the editorconfig string representation for this storage location.
        /// </summary>
        public string GetEditorConfigString(T value, OptionSet optionSet)
        {
            var editorConfigStringForValue = _getEditorConfigStringForValue(value, optionSet);

            Debug.Assert(!string.IsNullOrEmpty(editorConfigStringForValue));
            Debug.Assert(editorConfigStringForValue.All(ch => !(char.IsWhiteSpace(ch) || char.IsUpper(ch))));
            return($"{KeyName} = {editorConfigStringForValue}");
        }
Exemple #13
0
 public static bool IsImplicitStylePreferred(
     OptionSet optionSet, bool isBuiltInTypeContext, bool isTypeApparentContext)
 {
     return(IsImplicitStylePreferred(
                GetCurrentTypeStylePreferences(optionSet),
                isBuiltInTypeContext,
                isTypeApparentContext));
 }
            public FormattedWhitespace(OptionSet optionSet, int lineBreaks, int indentation, string language)
                : base(optionSet, language)
            {
                this.LineBreaks = Math.Max(0, lineBreaks);
                this.Spaces     = Math.Max(0, indentation);

                _newString = CreateString(this.OptionSet.GetOption(FormattingOptions.NewLine, language));
            }
Exemple #15
0
            public State(
                SyntaxNode declaration,
                SemanticModel semanticModel,
                OptionSet optionSet,
                CancellationToken cancellationToken
                )
            {
                TypeStylePreference      = default;
                IsInIntrinsicTypeContext = default;
                IsTypeApparentInContext  = default;

                var styleForIntrinsicTypes = optionSet.GetOption(
                    CSharpCodeStyleOptions.VarForBuiltInTypes
                    );
                var styleForApparent = optionSet.GetOption(
                    CSharpCodeStyleOptions.VarWhenTypeIsApparent
                    );
                var styleForElsewhere = optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere);

                _forBuiltInTypes    = styleForIntrinsicTypes.Notification.Severity;
                _whenTypeIsApparent = styleForApparent.Notification.Severity;
                _elsewhere          = styleForElsewhere.Notification.Severity;

                var stylePreferences = UseVarPreference.None;

                if (styleForIntrinsicTypes.Value)
                {
                    stylePreferences |= UseVarPreference.ForBuiltInTypes;
                }

                if (styleForApparent.Value)
                {
                    stylePreferences |= UseVarPreference.WhenTypeIsApparent;
                }

                if (styleForElsewhere.Value)
                {
                    stylePreferences |= UseVarPreference.Elsewhere;
                }

                this.TypeStylePreference = stylePreferences;

                IsTypeApparentInContext =
                    declaration.IsKind(
                        SyntaxKind.VariableDeclaration,
                        out VariableDeclarationSyntax? varDecl
                        ) &&
                    IsTypeApparentInDeclaration(
                        varDecl,
                        semanticModel,
                        TypeStylePreference,
                        cancellationToken
                        );

                IsInIntrinsicTypeContext =
                    IsPredefinedTypeInDeclaration(declaration, semanticModel) ||
                    IsInferredPredefinedType(declaration, semanticModel);
            }
        public static T GetOption <T>(this OptionSet optionSet, Option <T> option)
        {
            if (!TryGetEditorConfigOption(optionSet, option, out T value))
            {
                value = option.DefaultValue;
            }

            return(value);
        }
Exemple #17
0
        public static T GetOption <T>(this OptionSet analyzerConfigOptions, PerLanguageOption <T> option, string language)
        {
            if (!TryGetEditorConfigOption(analyzerConfigOptions, option, out T value))
            {
                value = option.DefaultValue;
            }

            return(value);
        }
Exemple #18
0
            public Whitespace(OptionSet optionSet, int lineBreaks, int indentation, bool elastic, string language)
                : base(optionSet, language)
            {
                _elastic = elastic;

                // space and line breaks can be negative during formatting. but at the end, should be normalized
                // to >= 0
                this.LineBreaks = lineBreaks;
                this.Spaces     = indentation;
            }
            private CodeShapeAnalyzer(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList)
            {
                _context    = context;
                _optionSet  = context.OptionSet;
                _triviaList = triviaList;

                _indentation        = 0;
                _hasTrailingSpace   = false;
                _lastLineBreakIndex = firstTriviaInTree ? 0 : -1;
                _touchedNoisyCharacterOnCurrentLine = false;
            }
Exemple #20
0
        public TypeStyleResult(CSharpTypeStyleHelper helper, TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, bool isStylePreferred, ReportDiagnostic severity, CancellationToken cancellationToken) : this()
        {
            _helper            = helper;
            _typeName          = typeName;
            _semanticModel     = semanticModel;
            _optionSet         = optionSet;
            _cancellationToken = cancellationToken;

            IsStylePreferred = isStylePreferred;
            Severity         = severity;
        }
        public static IFormattingResult Format(
            SyntaxTrivia trivia,
            int initialColumn,
            OptionSet optionSet,
            ChainedFormattingRules formattingRules,
            CancellationToken cancellationToken)
        {
            var root      = trivia.GetStructure();
            var formatter = new CSharpStructuredTriviaFormatEngine(trivia, initialColumn, optionSet, formattingRules, root.GetFirstToken(includeZeroWidth: true), root.GetLastToken(includeZeroWidth: true));

            return(formatter.Format(cancellationToken));
        }
            public ModifiedComplexTrivia(OptionSet optionSet, ComplexTrivia original, int lineBreaks, int space)
                : base(optionSet, original.Token1.Language)
            {
                Contract.ThrowIfNull(original);

                _original = original;

                // linebreak and space can become negative during formatting. but it should be normalized to >= 0
                // at the end.
                this.LineBreaks = lineBreaks;
                this.Spaces     = space;
            }
 public DocumentationCommentExteriorCommentRewriter(
     bool forceIndentation,
     int indentation,
     int indentationDelta,
     OptionSet optionSet,
     bool visitStructuredTrivia = true)
     : base(visitIntoStructuredTrivia: visitStructuredTrivia)
 {
     _forceIndentation = forceIndentation;
     _indentation      = indentation;
     _indentationDelta = indentationDelta;
     _optionSet        = optionSet;
 }
 public NextGetAdjustSpacesOperation(
     ImmutableArray <AbstractFormattingRule> formattingRules,
     int index,
     SyntaxToken previousToken,
     SyntaxToken currentToken,
     OptionSet optionSet)
 {
     _formattingRules = formattingRules;
     _index           = index;
     _previousToken   = previousToken;
     _currentToken    = currentToken;
     _optionSet       = optionSet;
 }
Exemple #25
0
        protected AbstractTriviaDataFactory(TreeData treeInfo, OptionSet optionSet)
        {
            Contract.ThrowIfNull(treeInfo);
            Contract.ThrowIfNull(optionSet);

            this.TreeInfo  = treeInfo;
            this.OptionSet = optionSet;

            for (var i = 0; i < SpaceCacheSize; i++)
            {
                _spaces[i] = new Whitespace(this.OptionSet, space: i, elastic: false, language: treeInfo.Root.Language);
            }
        }
Exemple #26
0
 public CSharpFormatEngine(
     SyntaxNode node,
     OptionSet optionSet,
     IEnumerable <AbstractFormattingRule> formattingRules,
     SyntaxToken token1,
     SyntaxToken token2)
     : base(TreeData.Create(node),
            optionSet,
            formattingRules,
            token1,
            token2)
 {
 }
Exemple #27
0
 public NextIndentBlockOperationAction(
     ImmutableArray <AbstractFormattingRule> formattingRules,
     int index,
     SyntaxNode node,
     OptionSet optionSet,
     List <IndentBlockOperation> list)
 {
     _formattingRules = formattingRules;
     _index           = index;
     _node            = node;
     _optionSet       = optionSet;
     _list            = list;
 }
Exemple #28
0
 public static Task <SyntaxTree> FormatAsync(
     SyntaxTree syntaxTree,
     ISyntaxFormattingService syntaxFormattingService,
     TextSpan span,
     OptionSet options,
     CancellationToken cancellationToken
     ) =>
 FormatAsync(
     syntaxTree,
     syntaxFormattingService,
     SpecializedCollections.SingletonEnumerable(span),
     options,
     cancellationToken
     );
Exemple #29
0
 public static IList <TextChange> GetFormattedTextChanges(
     SyntaxNode node,
     ISyntaxFormattingService syntaxFormattingService,
     OptionSet options,
     CancellationToken cancellationToken
     ) =>
 GetFormattedTextChanges(
     node,
     syntaxFormattingService,
     SpecializedCollections.SingletonEnumerable(node.FullSpan),
     options,
     rules: null,
     cancellationToken: cancellationToken
     );
Exemple #30
0
 public static SyntaxNode Format(
     SyntaxNode node,
     ISyntaxFormattingService syntaxFormattingService,
     OptionSet options,
     CancellationToken cancellationToken
     ) =>
 Format(
     node,
     syntaxFormattingService,
     SpecializedCollections.SingletonEnumerable(node.FullSpan),
     options,
     rules: null,
     cancellationToken: cancellationToken
     );