private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            bool firstInLine = token.IsFirstInLine();
            bool precededBySpace = true;
            bool ignorePrecedingSpaceProblem = false;

            if (!firstInLine)
            {
                precededBySpace = token.IsPrecededByWhitespace(context.CancellationToken);

                // ignore if handled by SA1026
                ignorePrecedingSpaceProblem = precededBySpace && token.GetPreviousToken().IsKind(SyntaxKind.NewKeyword);
            }

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

            if (!firstInLine && precededBySpace && !ignorePrecedingSpaceProblem && !IsPartOfIndexInitializer(token))
            {
                // Opening square bracket must {not be preceded} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingProperties.RemovePreceding, "not be preceded"));
            }

            if (!lastInLine && followedBySpace)
            {
                // Opening square bracket must {not be followed} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingProperties.RemoveFollowing, "not be followed"));
            }
        }
        private bool TryFindMatchingToken(SyntaxToken token, out SyntaxToken match)
        {
            var parent = token.Parent;

            var braceTokens = (from child in parent.ChildNodesAndTokens()
                               where child.IsToken
                               let tok = child.AsToken()
                               where tok.RawKind == _openBrace.Kind || tok.RawKind == _closeBrace.Kind
                               where tok.Span.Length > 0
                               select tok).ToList();

            if (braceTokens.Count == 2 &&
                braceTokens[0].RawKind == _openBrace.Kind &&
                braceTokens[1].RawKind == _closeBrace.Kind)
            {
                if (braceTokens[0] == token)
                {
                    match = braceTokens[1];
                    return true;
                }
                else if (braceTokens[1] == token)
                {
                    match = braceTokens[0];
                    return true;
                }
            }

            match = default(SyntaxToken);
            return false;
        }
        public override SyntaxToken VisitToken(SyntaxToken token)
        {
            token = base.VisitToken(token);
            if (token.IsMissing)
            {
                return token;
            }

            bool changed;

            do
            {
                changed = false;
                if ((token.HasLeadingTrivia && token.LeadingTrivia.Count >= 2) ||
                    (token.HasTrailingTrivia && token.TrailingTrivia.Count >= 2))
                {
                    var newLeadingTrivia = RemoveBlankLines(token.LeadingTrivia, ref changed);
                    var newTrailingTrivia = RemoveBlankLines(token.TrailingTrivia, ref changed);

                    if (changed)
                    {
                        token = token.WithLeadingTrivia(Syntax.TriviaList(newLeadingTrivia));
                        token = token.WithTrailingTrivia(Syntax.TriviaList(newTrailingTrivia));
                    }
                }
            }
            while (changed);

            return token;
        }
		static bool TryDetermineOverridableMembers(SemanticModel semanticModel, SyntaxToken startToken, Accessibility seenAccessibility, out ISet<ISymbol> overridableMembers, CancellationToken cancellationToken)
		{
			var result = new HashSet<ISymbol>();
			var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, cancellationToken);
			if (containingType != null && !containingType.IsScriptClass && !containingType.IsImplicitClass)
			{
				if (containingType.TypeKind == TypeKind.Class || containingType.TypeKind == TypeKind.Struct)
				{
					var baseTypes = containingType.GetBaseTypes().Reverse();
					foreach (var type in baseTypes)
					{
						cancellationToken.ThrowIfCancellationRequested();

						// Prefer overrides in derived classes
						RemoveOverriddenMembers(result, type, cancellationToken);

						// Retain overridable methods
						AddProtocolMembers(semanticModel, result, containingType, type, cancellationToken);
					}
					// Don't suggest already overridden members
					RemoveOverriddenMembers(result, containingType, cancellationToken);
				}
			}

			// Filter based on accessibility
			if (seenAccessibility != Accessibility.NotApplicable)
			{
				result.RemoveWhere(m => m.DeclaredAccessibility != seenAccessibility);
			}

			overridableMembers = result;
			return overridableMembers.Count > 0;
		}
        private static int GetCollapsibleStart(SyntaxToken firstToken)
        {
            // If the *next* token has any leading comments, we use the end of the last one.
            // If not, we check *this* token to see if it has any trailing comments and use the last one;
            // otherwise, we use the end of this token.

            var start = firstToken.Span.End;

            var nextToken = firstToken.GetNextToken();
            if (nextToken.Kind() != SyntaxKind.None && nextToken.HasLeadingTrivia)
            {
                var lastLeadingCommentTrivia = nextToken.LeadingTrivia.GetLastComment();
                if (lastLeadingCommentTrivia != null)
                {
                    start = lastLeadingCommentTrivia.Value.Span.End;
                }
            }

            if (firstToken.HasTrailingTrivia)
            {
                var lastTrailingCommentTrivia = firstToken.TrailingTrivia.GetLastComment();
                if (lastTrailingCommentTrivia != null)
                {
                    start = lastTrailingCommentTrivia.Value.Span.End;
                }
            }

            return start;
        }
        public void AddIdentifier(SyntaxToken token)
        {
            if (token.IsMissing || token.ValueText == null)
            {
                return;
            }

            string name = token.ValueText;

            if (currentIdentifiersInScope.ContainsKey(name))
            {
                var conflictingTokens = currentIdentifiersInScope[name];
                conflictingTokens.Add(token);

                // If at least one of the identifiers is the one we're renaming,
                // track it. This means that conflicts unrelated to our rename (that
                // were there when we started) we won't flag.
                if (conflictingTokens.Contains(tokenBeingRenamed))
                {
                    foreach (var conflictingToken in conflictingTokens)
                    {
                        if (conflictingToken != tokenBeingRenamed)
                        {
                            // conflictingTokensToReport is a set, so we won't get duplicates
                            conflictingTokensToReport.Add(conflictingToken);
                        }
                    }
                }
            }
            else
            {
                // No identifiers yet, so record the first one
                currentIdentifiersInScope.Add(name, new List<SyntaxToken> { token });
            }
        }
 private TextSpan GetTextChangeSpan(SyntaxToken stringLiteral, int position)
 {
     return PathCompletionUtilities.GetTextChangeSpan(
         quotedPath: stringLiteral.ToString(),
         quotedPathStart: stringLiteral.SpanStart,
         position: position);
 }
            public override void VisitToken(SyntaxToken token)
            {
                if (!token.ContainsDirectives)
                {
                    return;
                }

                foreach (var directive in token.LeadingTrivia)
                {
                    switch (directive.CSharpKind())
                    {
                        case SyntaxKind.RegionDirectiveTrivia:
                            HandleRegionDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                        case SyntaxKind.IfDirectiveTrivia:
                            HandleIfDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                        case SyntaxKind.EndRegionDirectiveTrivia:
                            HandleEndRegionDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                        case SyntaxKind.EndIfDirectiveTrivia:
                            HandleEndIfDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                        case SyntaxKind.ElifDirectiveTrivia:
                            HandleElifDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                        case SyntaxKind.ElseDirectiveTrivia:
                            HandleElseDirective((DirectiveTriviaSyntax)directive.GetStructure());
                            break;
                    }
                }
            }
Example #9
0
            public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2)
            {
                var text = base.GetTextBetween(token1, token2);
                Contract.ThrowIfFalse(text == _debugNodeData.GetTextBetween(token1, token2));

                return text;
            }
        private static void AnalyzeOpenBrace(SyntaxTreeAnalysisContext context, SyntaxToken openBrace)
        {
            var prevToken = openBrace.GetPreviousToken();
            var triviaList = TriviaHelper.MergeTriviaLists(prevToken.TrailingTrivia, openBrace.LeadingTrivia);

            var done = false;
            var eolCount = 0;
            for (var i = triviaList.Count - 1; !done && (i >= 0); i--)
            {
                switch (triviaList[i].Kind())
                {
                case SyntaxKind.WhitespaceTrivia:
                    break;
                case SyntaxKind.EndOfLineTrivia:
                    eolCount++;
                    break;
                default:
                    if (triviaList[i].IsDirective)
                    {
                        // These have a built-in end of line
                        eolCount++;
                    }

                    done = true;
                    break;
                }
            }

            if (eolCount < 2)
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, openBrace.GetLocation()));
        }
        private bool IsAfterNameEqualsArgument(SyntaxToken token)
        {
            var argumentList = token.Parent as AttributeArgumentListSyntax;
            if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
            {
                foreach (var item in argumentList.Arguments.GetWithSeparators())
                {
                    if (item.IsToken && item.AsToken() == token)
                    {
                        return false;
                    }

                    if (item.IsNode)
                    {
                        var node = item.AsNode() as AttributeArgumentSyntax;
                        if (node.NameEquals != null)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
        protected override bool IsWithinNaturalLanguage(SyntaxToken token, int position)
        {
            switch (token.Kind())
            {
                case SyntaxKind.StringLiteralToken:
                    // This, in combination with the override of GetExtentOfWordFromToken() below, treats the closing
                    // quote as a separate token.  This maintains behavior with VS2013.
                    if (position == token.Span.End - 1 && token.Text.EndsWith("\"", StringComparison.Ordinal))
                    {
                        return false;
                    }

                    return true;

                case SyntaxKind.CharacterLiteralToken:
                    // Before the ' is considered outside the character
                    return position != token.SpanStart;

                case SyntaxKind.InterpolatedStringTextToken:
                case SyntaxKind.XmlTextLiteralToken:
                    return true;
            }

            return false;
        }
        private IEnumerable<SyntaxTrivia> GetPreviousEmptyLines(SyntaxToken openBrace)
        {
            var result = new List<SyntaxTrivia>();

            var lineOfOpenBrace = openBrace.GetLineSpan().StartLinePosition.Line;
            var lineToCheck = lineOfOpenBrace - 1;

            while (lineToCheck > -1)
            {
                var trivias = openBrace.LeadingTrivia
                    .Where(t => t.GetLineSpan().StartLinePosition.Line == lineToCheck)
                    .ToList();
                var endOfLineTrivia = trivias.Where(t => t.IsKind(SyntaxKind.EndOfLineTrivia)).ToList();
                if (endOfLineTrivia.Any() && trivias.Except(endOfLineTrivia).All(t => t.IsKind(SyntaxKind.WhitespaceTrivia)))
                {
                    lineToCheck--;
                    result.AddRange(trivias);
                }
                else
                {
                    break;
                }
            }

            return result;
        }
            private static SyntaxToken GetNewStartToken(SyntaxToken startToken, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer)
            {
                var trivia = startToken.LeadingTrivia.ToImmutableArray();

                // Insert the #pragma disable directive after all leading new line trivia but before first trivia of any other kind.
                int index;
                SyntaxTrivia firstNonEOLTrivia = trivia.FirstOrDefault(t => !fixer.IsEndOfLine(t));
                if (firstNonEOLTrivia == default(SyntaxTrivia))
                {
                    index = trivia.Length;
                }
                else
                {
                    index = trivia.IndexOf(firstNonEOLTrivia);
                }

                bool needsLeadingEOL;
                if (index > 0)
                {
                    needsLeadingEOL = !fixer.IsEndOfLine(trivia[index - 1]);
                }
                else if (startToken.FullSpan.Start == 0)
                {
                    needsLeadingEOL = false;
                }
                else
                {
                    needsLeadingEOL = true;
                }

                var pragmaWarningTrivia = fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, needsLeadingEOL);

                return startToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaWarningTrivia));
            }
Example #15
0
        private static void CheckDeclarationName(MemberDeclarationSyntax member, SyntaxToken identifier, SyntaxNodeAnalysisContext context)
        {
            var symbol = context.SemanticModel.GetDeclaredSymbol(member);
            if (ClassName.IsTypeComRelated(symbol?.ContainingType) ||
                symbol.IsInterfaceImplementationOrMemberOverride() ||
                symbol.IsExtern)
            {
                return;
            }

            if (identifier.ValueText.StartsWith("_", StringComparison.Ordinal) ||
                identifier.ValueText.EndsWith("_", StringComparison.Ordinal))
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, identifier.GetLocation(), MethodKindNameMapping[member.Kind()],
                    identifier.ValueText, MessageFormatUnderscore));
                return;
            }

            string suggestion;
            if (TryGetChangedName(identifier.ValueText, out suggestion))
            {
                var messageEnding = string.Format(MessageFormatNonUnderscore, suggestion);
                context.ReportDiagnostic(Diagnostic.Create(Rule, identifier.GetLocation(), MethodKindNameMapping[member.Kind()],
                    identifier.ValueText, messageEnding));
            }
        }
        private bool PossibleTypeArgument(ITextSnapshot snapshot, SyntaxToken token, CancellationToken cancellationToken)
        {
            var node = token.Parent as BinaryExpressionSyntax;

            // type argument can be easily ambiguous with normal < operations
            if (node == null || node.Kind() != SyntaxKind.LessThanExpression || node.OperatorToken != token)
            {
                return false;
            }

            // use binding to see whether it is actually generic type or method 
            var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
            if (document == null)
            {
                return false;
            }

            var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            // Analyze node on the left of < operator to verify if it is a generic type or method.
            var leftNode = node.Left;
            if (leftNode is ConditionalAccessExpressionSyntax)
            {
                // If node on the left is a conditional access expression, get the member binding expression 
                // from the innermost conditional access expression, which is the left of < operator. 
                // e.g: Case a?.b?.c< : we need to get the conditional access expression .b?.c and analyze its
                // member binding expression (the .c) to see if it is a generic type/method.
                // Case a?.b?.c.d< : we need to analyze .c.d
                // Case a?.M(x => x?.P)?.M2< : We need to analyze .M2
                leftNode = leftNode.GetInnerMostConditionalAccessExpression().WhenNotNull;
            }

            var info = model.GetSymbolInfo(leftNode, cancellationToken);
            return info.CandidateSymbols.Any(IsGenericTypeOrMethod);
        }
 private string GetPathThroughLastSlash(SyntaxToken stringLiteral, int position)
 {
     return PathCompletionUtilities.GetPathThroughLastSlash(
         quotedPath: stringLiteral.ToString(),
         quotedPathStart: stringLiteral.SpanStart,
         position: position);
 }
        private static void HandleLessThanToken(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 precededBySpace = firstInLine || token.IsPrecededByWhitespace();
            bool followedBySpace = token.IsFollowedByWhitespace();

            if (!firstInLine && precededBySpace)
            {
                // Opening generic brackets must not be {preceded} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), "preceded"));
            }

            if (followedBySpace)
            {
                // Opening generic brackets must not be {followed} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), "followed"));
            }
        }
Example #19
0
        public static IAliasSymbol GetAliasInfo(
            ISemanticFactsService semanticFacts, SemanticModel model, SyntaxToken token, CancellationToken cancellationToken)
        {
            if (semanticFacts == null)
            {
                return model.GetAliasInfo(token.Parent, cancellationToken);
            }

            var entry = GetCachedEntry(model);
            if (entry == null)
            {
                return model.GetAliasInfo(token.Parent, cancellationToken);
            }

            if (entry.AliasNameSet == null)
            {
                var set = semanticFacts.GetAliasNameSet(model, cancellationToken);
                Interlocked.CompareExchange(ref entry.AliasNameSet, set, null);
            }

            if (entry.AliasNameSet.Contains(token.ValueText))
            {
                return model.GetAliasInfo(token.Parent, cancellationToken);
            }

            return null;
        }
 protected override bool IsInvalidToken(SyntaxToken token)
 {
     // invalid token to be formatted
     return token.IsKind(SyntaxKind.None) ||
            token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
            token.IsKind(SyntaxKind.EndOfFileToken);
 }
        public int? FromIndentBlockOperations(
            SyntaxTree tree, SyntaxToken token, int position, CancellationToken cancellationToken)
        {
            // we use operation service to see whether it is a starting point of new indentation.
            // ex)
            //  if (true)
            //  {
            //     | <= this is new starting point of new indentation
            var operation = GetIndentationDataFor(tree.GetRoot(cancellationToken), token, position);

            // try find indentation based on indentation operation
            if (operation != null)
            {
                // make sure we found new starting point of new indentation.
                // such operation should start span after the token (a token that is right before the new indentation),
                // contains current position, and position should be before the existing next token
                if (token.Span.End <= operation.TextSpan.Start &&
                    operation.TextSpan.IntersectsWith(position) &&
                    position <= token.GetNextToken(includeZeroWidth: true).SpanStart)
                {
                    return GetIndentationOfCurrentPosition(tree, token, position, cancellationToken);
                }
            }

            return null;
        }
        private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            if (!token.Parent.IsKind(SyntaxKind.AttributeList))
            {
                return;
            }

            if (token.IsLastInLine())
            {
                return;
            }

            if (!token.HasTrailingTrivia)
            {
                return;
            }

            if (!token.TrailingTrivia[0].IsKind(SyntaxKind.WhitespaceTrivia))
            {
                return;
            }

            // Opening attribute brackets must not be followed by a space.
            context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingCodeFixProvider.RemoveFollowing));
        }
 public static MethodDeclarationSyntax MethodDeclaration(
     SyntaxList<AttributeListSyntax> attributeLists,
     SyntaxTokenList modifiers,
     TypeSyntax returnType,
     ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
     SyntaxToken identifier,
     TypeParameterListSyntax typeParameterList,
     ParameterListSyntax parameterList,
     SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses,
     BlockSyntax body,
     SyntaxToken semicolonToken)
 {
     return SyntaxFactory.MethodDeclaration(
         attributeLists,
         modifiers,
         default(SyntaxToken),
         returnType,
         explicitInterfaceSpecifier,
         identifier,
         typeParameterList,
         parameterList,
         constraintClauses,
         body,
         default(ArrowExpressionClauseSyntax),
         semicolonToken);
 }
        private SyntaxTriviaList CreatePragmaDirectiveTrivia(SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
        {
            var id = SyntaxFactory.IdentifierName(diagnostic.Id);
            var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
            var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
            var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective.WithAdditionalAnnotations(Formatter.Annotation));
            var endOfLineTrivia = SyntaxFactory.EndOfLine(@"
");
            var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);

            var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
            if (!string.IsNullOrWhiteSpace(title))
            {
                var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
                triviaList = triviaList.Add(titleComment);
            }

            if (needsLeadingEndOfLine)
            {
                triviaList = triviaList.Insert(0, endOfLineTrivia);
            }

            if (needsTrailingEndOfLine)
            {
                triviaList = triviaList.Add(endOfLineTrivia);
            }

            return triviaList;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UvssEventTriggerSyntax"/> class.
        /// </summary>
        internal UvssEventTriggerSyntax(
            SyntaxToken triggerKeyword,
            SyntaxToken eventKeyword,
            UvssEventNameSyntax eventName,
            UvssEventTriggerArgumentList argumentList,
            SyntaxToken qualifierToken,
            UvssBlockSyntax body)
            : base(SyntaxKind.EventTrigger)
        {
            this.TriggerKeyword = triggerKeyword;
            ChangeParent(triggerKeyword);

            this.EventKeyword = eventKeyword;
            ChangeParent(eventKeyword);

            this.EventName = eventName;
            ChangeParent(eventName);

            this.ArgumentList = argumentList;
            ChangeParent(argumentList);

            this.QualifierToken = qualifierToken;
            ChangeParent(qualifierToken);

            this.Body = body;
            ChangeParent(body);

            SlotCount = 6;
            UpdateIsMissing();
        }
        private async Task<SyntaxTriviaList> CreatePragmaDirectiveTriviaAsync(
            SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
        {
            var id = SyntaxFactory.IdentifierName(diagnostic.Id);
            var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
            var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
            pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)await formatNode(pragmaDirective).ConfigureAwait(false);
            var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective);
            var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
            var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);

            var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
            if (!string.IsNullOrWhiteSpace(title))
            {
                var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
                triviaList = triviaList.Add(titleComment);
            }

            if (needsLeadingEndOfLine)
            {
                triviaList = triviaList.Insert(0, endOfLineTrivia);
            }

            if (needsTrailingEndOfLine)
            {
                triviaList = triviaList.Add(endOfLineTrivia);
            }

            return triviaList;
        }
        private static void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            bool firstInLine = token.IsFirstInLine();
            bool precededBySpace = true;
            bool ignorePrecedingSpaceProblem = false;

            if (!firstInLine)
            {
                precededBySpace = token.IsPrecededByWhitespace();

                // ignore if handled by SA1026
                ignorePrecedingSpaceProblem = precededBySpace && token.GetPreviousToken().IsKind(SyntaxKind.NewKeyword);
            }

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

            if (!firstInLine && precededBySpace && !ignorePrecedingSpaceProblem && !lastInLine && followedBySpace)
            {
                // Opening square bracket must {neither preceded nor followed} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), "neither preceded nor followed"));
            }
            else if (!firstInLine && precededBySpace && !ignorePrecedingSpaceProblem)
            {
                // Opening square bracket must {not be preceded} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), "not be preceded"));
            }
            else if (!lastInLine && followedBySpace)
            {
                // Opening square bracket must {not be followed} by a space.
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), "not be followed"));
            }
        }
        private static void HandleCloseBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
        {
            if (token.IsMissing)
            {
                return;
            }

            if (!token.Parent.IsKind(SyntaxKind.AttributeList))
            {
                return;
            }

            if (token.IsFirstInLine())
            {
                return;
            }

            SyntaxToken precedingToken = token.GetPreviousToken();
            if (!precedingToken.HasTrailingTrivia)
            {
                return;
            }

            if (!precedingToken.TrailingTrivia.Last().IsKind(SyntaxKind.WhitespaceTrivia))
            {
                return;
            }

            // Closing attribute brackets must not be preceded by a space.
            context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), TokenSpacingProperties.RemoveImmediatePreceding));
        }
        /// <summary>
        /// Remove the extra new lines on the token which immediately follows an open brace.
        /// </summary>
        private static SyntaxToken FixOpenBraceNextToken(SyntaxToken token)
        {
            if (!token.HasLeadingTrivia)
            {
                return token;
            }

            if (token.Kind() == SyntaxKind.CloseBraceToken &&
                token.LeadingTrivia.All(x => x.IsKind(SyntaxKind.WhitespaceTrivia) || x.IsKind(SyntaxKind.EndOfLineTrivia)))
            {
                // This is an open / close brace combo with no content inbetween.  Just return the 
                // close brace and let the formatter handle the white space issues.  If there was a new line 
                // between the two it will be attached to the open brace and hence maintained. 
                return token.WithLeadingTrivia(SyntaxTriviaList.Empty);
            }

            // Remove all of the new lines at the top
            var triviaList = token.LeadingTrivia;
            var list = new List<SyntaxTrivia>(triviaList.Count);
            var index = MovePastSimpleNewLines(triviaList, 0);

            while (index < triviaList.Count)
            {
                list.Add(triviaList[index]);
                index++;
            }

            var newTriviaList = SyntaxFactory.TriviaList(list);
            return token.WithLeadingTrivia(newTriviaList);
        }
            public static AnalysisResult Trailing(SyntaxToken token)
            {
                var result = default(AnalysisResult);
                Analyze(token.TrailingTrivia, ref result);

                return result;
            }
Example #31
0
 public IEnumerable <TAnnotation> GetAnnotations(SyntaxToken token)
 {
     return(GetAnnotations(token.GetAnnotations(_annotationKind)));
 }
Example #32
0
 public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options, in NextGetAdjustNewLinesOperation nextOperation)
Example #33
0
 public SyntaxToken WithAdditionalAnnotations(SyntaxToken token, params TAnnotation[] annotations)
 {
     return(token.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray()));
 }
Example #34
0
 public bool HasAnnotation(SyntaxToken token, TAnnotation annotation)
 {
     return(token.HasAnnotation(this.GetRealAnnotation(annotation)));
 }
Example #35
0
 public bool HasAnnotations <TSpecificAnnotation>(SyntaxToken token) where TSpecificAnnotation : TAnnotation
 {
     return(this.GetAnnotations(token).OfType <TSpecificAnnotation>().Any());
 }
Example #36
0
 public bool HasAnnotations(SyntaxToken token)
 {
     return(token.HasAnnotations(_annotationKind));
 }
Example #37
0
 public IEnumerable <TSpecificAnnotation> GetAnnotations <TSpecificAnnotation>(SyntaxToken token) where TSpecificAnnotation : TAnnotation
 {
     return(this.GetAnnotations(token).OfType <TSpecificAnnotation>());
 }
Example #38
0
 private bool HasFormattableBracketParent(SyntaxToken token)
 {
     return(token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier, SyntaxKind.BracketedArgumentList, SyntaxKind.BracketedParameterList, SyntaxKind.ImplicitArrayCreationExpression));
 }
Example #39
0
        void FindSpellingMistakesForIdentifierSkippingFirstWord(SyntaxToken identifier, string firstSkipWord)
        {
            var wordParts = IdentifierWordParser.SplitWordParts(identifier.Text);

            FindSpellingMistakesForIdentifierWordParts(wordParts, identifier, firstSkipWord);
        }
Example #40
0
 public SyntaxToken WithoutAnnotations(SyntaxToken token, params TAnnotation[] annotations)
 {
     return(token.WithoutAnnotations(GetRealAnnotations(annotations).ToArray()));
 }
Example #41
0
 public static SyntaxToken InsertTriviaInList(SyntaxToken root, SyntaxTrivia triviaInList, IEnumerable <SyntaxTrivia> newTrivia, bool insertBefore)
 {
     return(new TriviaListEditor(triviaInList, newTrivia, insertBefore ? ListEditKind.InsertBefore : ListEditKind.InsertAfter).VisitToken(root));
 }
Example #42
0
        public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation <AdjustSpacesOperation> nextOperation)
        {
            if (optionSet == null)
            {
                return(nextOperation.Invoke());
            }

            System.Diagnostics.Debug.Assert(previousToken.Parent != null && currentToken.Parent != null);

            var previousKind       = previousToken.Kind();
            var currentKind        = currentToken.Kind();
            var previousParentKind = previousToken.Parent.Kind();
            var currentParentKind  = currentToken.Parent.Kind();

            // For Method Declaration
            if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.IdentifierToken)
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName));
            }

            // For Generic Method Declaration
            if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.GreaterThanToken && previousParentKind == SyntaxKind.TypeParameterList)
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName));
            }

            // Case: public static implicit operator string(Program p) { return null; }
            if (previousToken.IsKeyword() && currentToken.IsOpenParenInParameterListOfAConversionOperatorDeclaration())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName));
            }

            // Case: public static Program operator !(Program p) { return null; }
            if (previousToken.Parent.IsKind(SyntaxKind.OperatorDeclaration) && currentToken.IsOpenParenInParameterListOfAOperationDeclaration())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName));
            }

            if (previousToken.IsOpenParenInParameterList() && currentToken.IsCloseParenInParameterList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses));
            }

            if (previousToken.IsOpenParenInParameterList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis));
            }

            if (currentToken.IsCloseParenInParameterList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis));
            }

            // For Method Call
            if (currentToken.IsOpenParenInArgumentList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName));
            }

            if (previousToken.IsOpenParenInArgumentList() && currentToken.IsCloseParenInArgumentList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses));
            }

            if (previousToken.IsOpenParenInArgumentList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses));
            }

            if (currentToken.IsCloseParenInArgumentList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses));
            }

            // For spacing around: typeof, default, and sizeof; treat like a Method Call
            if (currentKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName));
            }

            if (previousKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(previousParentKind))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses));
            }

            if (currentKind == SyntaxKind.CloseParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses));
            }

            // For Spacing b/n control flow keyword and paren. Parent check not needed.
            if (currentKind == SyntaxKind.OpenParenToken &&
                (previousKind == SyntaxKind.IfKeyword || previousKind == SyntaxKind.WhileKeyword || previousKind == SyntaxKind.SwitchKeyword ||
                 previousKind == SyntaxKind.ForKeyword || previousKind == SyntaxKind.ForEachKeyword || previousKind == SyntaxKind.CatchKeyword ||
                 previousKind == SyntaxKind.UsingKeyword || previousKind == SyntaxKind.WhenKeyword || previousKind == SyntaxKind.LockKeyword))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword));
            }

            // For spacing between parenthesis and expression
            if ((previousParentKind == SyntaxKind.ParenthesizedExpression && previousKind == SyntaxKind.OpenParenToken) ||
                (currentParentKind == SyntaxKind.ParenthesizedExpression && currentKind == SyntaxKind.CloseParenToken))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinExpressionParentheses));
            }

            // For spacing between the parenthesis and the cast expression
            if ((previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.OpenParenToken) ||
                (currentParentKind == SyntaxKind.CastExpression && currentKind == SyntaxKind.CloseParenToken))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinCastParentheses));
            }

            // Semicolons in an empty for statement.  i.e.   for(;;)
            if (previousParentKind == SyntaxKind.ForStatement &&
                this.IsEmptyForStatement((ForStatementSyntax)previousToken.Parent))
            {
                if (currentKind == SyntaxKind.SemicolonToken &&
                    (previousKind != SyntaxKind.SemicolonToken ||
                     optionSet.GetOption <bool>(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement)))
                {
                    return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement));
                }

                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement));
            }

            // For spacing between the parenthesis and the expression inside the control flow expression
            if (previousKind == SyntaxKind.OpenParenToken && IsControlFlowLikeKeywordStatementKind(previousParentKind))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses));
            }

            if (currentKind == SyntaxKind.CloseParenToken && IsControlFlowLikeKeywordStatementKind(currentParentKind))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses));
            }

            // For spacing after the cast
            if (previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.CloseParenToken)
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterCast));
            }

            // For spacing Before Square Braces
            if (currentKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(currentToken) && !previousToken.IsOpenBraceOrCommaOfObjectInitializer())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeOpenSquareBracket));
            }

            // For spacing empty square braces, also treat [,] as empty
            if (((currentKind == SyntaxKind.CloseBracketToken && previousKind == SyntaxKind.OpenBracketToken) ||
                 currentKind == SyntaxKind.OmittedArraySizeExpressionToken) &&
                HasFormattableBracketParent(previousToken))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets));
            }

            // For spacing square brackets within
            if (previousKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(previousToken))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets));
            }

            if (currentKind == SyntaxKind.CloseBracketToken && previousKind != SyntaxKind.OmittedArraySizeExpressionToken && HasFormattableBracketParent(currentToken))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets));
            }

            // attribute case ] *
            // Place a space between the attribute and the next member if they're on the same line.
            if (previousKind == SyntaxKind.CloseBracketToken && previousToken.Parent.IsKind(SyntaxKind.AttributeList))
            {
                var attributeOwner = previousToken.Parent?.Parent;
                if (attributeOwner is MemberDeclarationSyntax)
                {
                    return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }
            }

            // For spacing delimiters - after colon
            if (previousToken.IsColonInTypeBaseList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration));
            }

            // For spacing delimiters - before colon
            if (currentToken.IsColonInTypeBaseList())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration));
            }

            // For spacing delimiters - after comma
            if ((previousToken.IsCommaInArgumentOrParameterList() && currentKind != SyntaxKind.OmittedTypeArgumentToken) ||
                previousToken.IsCommaInInitializerExpression() ||
                (previousKind == SyntaxKind.CommaToken &&
                 currentKind != SyntaxKind.OmittedArraySizeExpressionToken &&
                 HasFormattableBracketParent(previousToken)))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterComma));
            }

            // For spacing delimiters - before comma
            if ((currentToken.IsCommaInArgumentOrParameterList() && previousKind != SyntaxKind.OmittedTypeArgumentToken) ||
                currentToken.IsCommaInInitializerExpression() ||
                (currentKind == SyntaxKind.CommaToken &&
                 previousKind != SyntaxKind.OmittedArraySizeExpressionToken &&
                 HasFormattableBracketParent(currentToken)))
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeComma));
            }

            // For Spacing delimiters - after Dot
            if (previousToken.IsDotInMemberAccessOrQualifiedName())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterDot));
            }

            // For spacing delimiters - before Dot
            if (currentToken.IsDotInMemberAccessOrQualifiedName())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeDot));
            }

            // For spacing delimiters - after semicolon
            if (previousToken.IsSemicolonInForStatement() && currentKind != SyntaxKind.CloseParenToken)
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement));
            }

            // For spacing delimiters - before semicolon
            if (currentToken.IsSemicolonInForStatement())
            {
                return(AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement));
            }

            // For spacing around the binary operators
            if (currentToken.Parent is BinaryExpressionSyntax ||
                previousToken.Parent is BinaryExpressionSyntax ||
                currentToken.Parent is AssignmentExpressionSyntax ||
                previousToken.Parent is AssignmentExpressionSyntax)
            {
                switch (optionSet.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator))
                {
                case BinaryOperatorSpacingOptions.Single:
                    return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));

                case BinaryOperatorSpacingOptions.Remove:
                    if (currentKind == SyntaxKind.IsKeyword ||
                        currentKind == SyntaxKind.AsKeyword ||
                        previousKind == SyntaxKind.IsKeyword ||
                        previousKind == SyntaxKind.AsKeyword)
                    {
                        // User want spaces removed but at least one is required for the "as" & "is" keyword
                        return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                    }
                    else
                    {
                        return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                    }

                case BinaryOperatorSpacingOptions.Ignore:
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces));

                default:
                    System.Diagnostics.Debug.Assert(false, "Invalid BinaryOperatorSpacingOptions");
                    break;
                }
            }

            // No space after $" and $@" and @$" at the start of an interpolated string
            if (previousKind == SyntaxKind.InterpolatedStringStartToken ||
                previousKind == SyntaxKind.InterpolatedVerbatimStringStartToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // No space before " at the end of an interpolated string
            if (currentKind == SyntaxKind.InterpolatedStringEndToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // No space before { or after } in interpolations
            if ((currentKind == SyntaxKind.OpenBraceToken && currentToken.Parent is InterpolationSyntax) ||
                (previousKind == SyntaxKind.CloseBraceToken && previousToken.Parent is InterpolationSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // Preserve space after { or before } in interpolations (i.e. between the braces and the expression)
            if ((previousKind == SyntaxKind.OpenBraceToken && previousToken.Parent is InterpolationSyntax) ||
                (currentKind == SyntaxKind.CloseBraceToken && currentToken.Parent is InterpolationSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces));
            }

            // No space before or after , in interpolation alignment clause
            if ((previousKind == SyntaxKind.CommaToken && previousToken.Parent is InterpolationAlignmentClauseSyntax) ||
                (currentKind == SyntaxKind.CommaToken && currentToken.Parent is InterpolationAlignmentClauseSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // No space before or after : in interpolation format clause
            if ((previousKind == SyntaxKind.ColonToken && previousToken.Parent is InterpolationFormatClauseSyntax) ||
                (currentKind == SyntaxKind.ColonToken && currentToken.Parent is InterpolationFormatClauseSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // Always put a space in the var form of deconstruction-declaration
            if (currentToken.IsOpenParenInVarDeconstructionDeclaration())
            {
                return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces));
            }

            // Index expressions
            if (previousKind == SyntaxKind.CaretToken && previousParentKind == SyntaxKindEx.IndexExpression)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
            }

            // Right of Range expressions
            if (previousKind == SyntaxKindEx.DotDotToken && previousParentKind == SyntaxKindEx.RangeExpression)
            {
#if !CODE_STYLE
                var rangeExpression = (RangeExpressionSyntax)previousToken.Parent;
                var hasRightOperand = rangeExpression.RightOperand != null;
#else
                var childSyntax     = previousToken.Parent.ChildNodesAndTokens();
                var hasRightOperand = childSyntax.Count > 1 && childSyntax[childSyntax.Count - 2].IsKind(SyntaxKindEx.DotDotToken);
#endif
                if (hasRightOperand)
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
                }
            }

            // Left of Range expressions
            if (currentKind == SyntaxKindEx.DotDotToken && currentParentKind == SyntaxKindEx.RangeExpression)
            {
#if !CODE_STYLE
                var rangeExpression = (RangeExpressionSyntax)currentToken.Parent;
                var hasLeftOperand  = rangeExpression.LeftOperand != null;
#else
                var childSyntax    = currentToken.Parent.ChildNodesAndTokens();
                var hasLeftOperand = childSyntax.Count > 1 && childSyntax[1].IsKind(SyntaxKindEx.DotDotToken);
#endif
                if (hasLeftOperand)
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces));
                }
            }

            // Put a space between the type and a positional pattern
            // ex: `e is Type ( /*positional*/ )`
            if (currentToken.IsKind(SyntaxKind.OpenParenToken) &&
                currentParentKind == SyntaxKindEx.PositionalPatternClause)
            {
#if !CODE_STYLE
                var recursivePatternType = ((RecursivePatternSyntax)currentToken.Parent.Parent).Type;
#else
                var childNodesAndTokens  = currentToken.Parent.Parent.ChildNodesAndTokens();
                var recursivePatternType = childNodesAndTokens.Count > 0 ? childNodesAndTokens[0].AsNode() as TypeSyntax : null;
#endif

                if (recursivePatternType != null)
                {
                    return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces));
                }
            }

            return(nextOperation.Invoke());
        }
Example #43
0
 public static SyntaxNode InsertTokenInList(SyntaxNode root, SyntaxToken tokenInList, IEnumerable <SyntaxToken> newTokens, bool insertBefore)
 {
     return(new TokenListEditor(tokenInList, newTokens, insertBefore ? ListEditKind.InsertBefore : ListEditKind.InsertAfter).Visit(root));
 }
Example #44
0
        void FindSpellingMistakesForIdentifier(SyntaxToken identifier)
        {
            var wordParts = IdentifierWordParser.SplitWordParts(identifier.Text);

            FindSpellingMistakesForIdentifierWordParts(wordParts, identifier);
        }
        internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, DiagnosticBag diagnostics, out bool modifierErrors)
        {
            DeclarationModifiers defaultAccess =
                (containingType.IsInterface) ? DeclarationModifiers.Public : DeclarationModifiers.Private;

            DeclarationModifiers allowedModifiers =
                DeclarationModifiers.AccessibilityMask |
                DeclarationModifiers.Const |
                DeclarationModifiers.New |
                DeclarationModifiers.ReadOnly |
                DeclarationModifiers.Static |
                DeclarationModifiers.Volatile |
                DeclarationModifiers.Fixed |
                DeclarationModifiers.Unsafe |
                DeclarationModifiers.Abstract; // filtered out later

            var errorLocation           = new SourceLocation(firstIdentifier);
            DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers(
                modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors);

            if ((result & DeclarationModifiers.Abstract) != 0)
            {
                diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation);
                result &= ~DeclarationModifiers.Abstract;
            }

            if ((result & DeclarationModifiers.Const) != 0)
            {
                if ((result & DeclarationModifiers.Static) != 0)
                {
                    // The constant '{0}' cannot be marked static
                    diagnostics.Add(ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText);
                }

                if ((result & DeclarationModifiers.ReadOnly) != 0)
                {
                    // The modifier 'readonly' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword));
                }

                if ((result & DeclarationModifiers.Volatile) != 0)
                {
                    // The modifier 'volatile' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword));
                }

                if ((result & DeclarationModifiers.Unsafe) != 0)
                {
                    // The modifier 'unsafe' is not valid for this item
                    diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword));
                }

                result |= DeclarationModifiers.Static; // "constants are considered static members"
            }
            else
            {
                // NOTE: always cascading on a const, so suppress.
                // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol
                // to determine whether or not unsafe is allowed.  Since this symbol and the containing type are
                // in the same compilation, it won't make a difference.  We do, however, have to pass the error
                // location explicitly.
                containingType.CheckUnsafeModifier(result, errorLocation, diagnostics);
            }

            return(result);
        }
Example #46
0
 public static SyntaxToken ReplaceTriviaInList(SyntaxToken root, SyntaxTrivia triviaInList, IEnumerable <SyntaxTrivia> newTrivia)
 {
     return(new TriviaListEditor(triviaInList, newTrivia, ListEditKind.Replace).VisitToken(root));
 }
Example #47
0
 private static TextLine GetLineOfToken(SyntaxToken token, SyntaxTree tree)
 {
     return(tree.GetText().Lines[token.GetLocation().GetLineSpan().StartLinePosition.Line]);
 }
Example #48
0
 public static SyntaxNode ReplaceTokenInList(SyntaxNode root, SyntaxToken tokenInList, IEnumerable <SyntaxToken> newTokens)
 {
     return(new TokenListEditor(tokenInList, newTokens, ListEditKind.Replace).Visit(root));
 }
 private static bool IsParenthesizedExpressionToken(ParenthesizedExpressionSyntax expr, SyntaxToken token)
 {
     return(expr.FullSpan.Contains(token.SpanStart) &&
            token != expr.CloseParenToken);
 }
 public int GetIndentationOfCurrentPosition(
     SyntaxTree tree, SyntaxToken token, int position, CancellationToken cancellationToken)
 {
     return(GetIndentationOfCurrentPosition(tree, token, position, extraSpaces: 0, cancellationToken: cancellationToken));
 }
 private static bool IsTupleArgumentListToken(TupleExpressionSyntax tupleExpression, SyntaxToken token)
 {
     return(tupleExpression.Arguments.FullSpan.Contains(token.SpanStart) &&
            token != tupleExpression.CloseParenToken);
 }
 protected abstract bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token);
Example #53
0
        private CodeBlockNode CreateFunctionDeclarationNode(SyntaxToken functionNameToken, List <FunctionParameter> parameters = null, SyntaxToken returnTypeToken = null, bool hasBody = true)
        {
            if (parameters == null)
            {
                parameters = new List <FunctionParameter>();
            }

            root.Children.Add(new FunctionDeclaration(tokens.Find((token) => token.Is(SyntaxTokenKind.FnKeyword)), functionNameToken, parameters, tokens.Find((token) => token.Is(SyntaxTokenKind.CloseParenthesis)), hasBody
        ? new CodeBlockNode(tokens.Find((token) => token.Is(SyntaxTokenKind.OpenBrace)))
            {
                ClosingBrace = tokens.Find((token) => token.Is(SyntaxTokenKind.CloseBrace))
            }
        : null, returnTypeToken));

            return(root);
        }
 private bool IsParenthesizedExpressionTriggerToken(SyntaxToken token)
 => token.IsKind(SyntaxKind.OpenParenToken) && token.Parent is ParenthesizedExpressionSyntax;
 protected abstract TokenClassifierBase GetTokenClassifier(SyntaxToken token, SemanticModel semanticModel);
 private bool IsTupleExpressionTriggerToken(SyntaxToken token)
 => SignatureHelpUtilities.IsTriggerParenOrComma <TupleExpressionSyntax>(token, IsTriggerCharacter);
 protected abstract bool IsNumericLiteral(SyntaxToken token);
 protected TokenClassifierBase(SyntaxToken token, SemanticModel semanticModel)
 {
     this.token         = token;
     this.semanticModel = semanticModel;
 }
 protected abstract bool IsIdentifier(SyntaxToken token);
 protected abstract bool IsStringLiteral(SyntaxToken token);