Beispiel #1
0
        public static Task <Document> AddNewLineBeforeInsteadOfAfterAsync(
            Document document,
            SyntaxNodeOrToken left,
            SyntaxNodeOrToken middle,
            SyntaxNodeOrToken right,
            CancellationToken cancellationToken = default)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            SyntaxTriviaList trailingTrivia = middle.GetTrailingTrivia();

            if (IsOptionalWhitespaceThenEndOfLineTrivia(trailingTrivia))
            {
                sb.Append(DetermineEndOfLine(middle).ToString());
            }
            else
            {
                sb.Append(trailingTrivia.ToString());
            }

            sb.Append(right.GetLeadingTrivia().ToString());
            sb.Append(middle.ToString());
            sb.Append(" ");

            return(document.WithTextChangeAsync(
                       TextSpan.FromBounds(left.Span.End, right.SpanStart),
                       StringBuilderCache.GetStringAndFree(sb),
                       cancellationToken));
        }
Beispiel #2
0
        public static Task <Document> AddNewLineAfterInsteadOfBeforeAsync(
            Document document,
            SyntaxNodeOrToken left,
            SyntaxNodeOrToken middle,
            SyntaxNodeOrToken right,
            CancellationToken cancellationToken = default)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            sb.Append(" ");
            sb.Append(middle.ToString());

            SyntaxTriviaList trailingTrivia = left.GetTrailingTrivia();

            if (SyntaxTriviaAnalysis.IsOptionalWhitespaceThenEndOfLineTrivia(trailingTrivia))
            {
                sb.Append(SyntaxTriviaAnalysis.GetEndOfLine(left).ToString());
            }
            else
            {
                sb.Append(trailingTrivia.ToString());
            }

            sb.Append(middle.GetLeadingTrivia().ToString());

            string newText = StringBuilderCache.GetStringAndFree(sb);

            var textChange = new TextChange(
                TextSpan.FromBounds(left.Span.End, right.SpanStart),
                newText);

            return(document.WithTextChangeAsync(textChange, cancellationToken));
        }
Beispiel #3
0
        private static string CommentOutLines(SourceText sourceText, int startLine, int endLine, int minIndentLength)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            for (int i = startLine; i <= endLine; i++)
            {
                TextLine textLine = sourceText.Lines[i];
                string   s        = textLine.ToString();

                if (StringUtility.IsEmptyOrWhitespace(s))
                {
                    sb.Append(s);
                }
                else
                {
                    sb.Append(s, 0, minIndentLength);
                    sb.Append("//");
                    sb.Append(s, minIndentLength, s.Length - minIndentLength);
                }

                sb.Append(sourceText.GetSubText(TextSpan.FromBounds(textLine.Span.End, textLine.SpanIncludingLineBreak.End)));
            }

            return(StringBuilderCache.GetStringAndFree(sb));
        }
Beispiel #4
0
        public static Task <Document> RefactorAsync(
            Document document,
            ConditionalExpressionSyntax conditionalExpression,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax condition     = conditionalExpression.Condition;
            ExpressionSyntax whenTrue      = conditionalExpression.WhenTrue;
            ExpressionSyntax whenFalse     = conditionalExpression.WhenFalse;
            SyntaxToken      questionToken = conditionalExpression.QuestionToken;
            SyntaxToken      colonToken    = conditionalExpression.ColonToken;

            StringBuilder sb = StringBuilderCache.GetInstance();

            var builder = new SyntaxNodeTextBuilder(conditionalExpression, sb);

            builder.AppendLeadingTrivia();
            builder.AppendSpan(condition);

            Write(condition, whenTrue, questionToken, "? ", builder);

            Write(whenTrue, whenFalse, colonToken, ": ", builder);

            builder.AppendTrailingTrivia();

            ExpressionSyntax newNode = SyntaxFactory.ParseExpression(StringBuilderCache.GetStringAndFree(sb));

            return(document.ReplaceNodeAsync(conditionalExpression, newNode, cancellationToken));
        }
        public static ImmutableArray <CommandItem> GetCommandItems(IEnumerable <Command> commands, Filter?filter = null)
        {
            if (!commands.Any())
            {
                return(ImmutableArray <CommandItem> .Empty);
            }

            int width = commands.Max(f => f.Name.Length) + SeparatorWidth;

            ImmutableArray <CommandItem> .Builder builder = ImmutableArray.CreateBuilder <CommandItem>();

            foreach (Command command in commands)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                sb.Append(command.Name);
                sb.AppendSpaces(width - command.Name.Length);
                sb.Append(command.Description);

                string text = StringBuilderCache.GetStringAndFree(sb);

                if (filter?.IsMatch(text) != false)
                {
                    builder.Add(new CommandItem(command, text));
                }
            }

            return(builder.ToImmutableArray());
        }
Beispiel #6
0
        public static ImmutableArray <OptionValueItem> GetOptionValueItems(IEnumerable <OptionValue> optionValues, int width1, int width2)
        {
            ImmutableArray <OptionValueItem> .Builder builder = ImmutableArray.CreateBuilder <OptionValueItem>();

            foreach (OptionValue optionValue in optionValues)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                string value = GetValue(optionValue);

                sb.Append(value);
                sb.AppendSpaces(width1 - value.Length);

                string shortValue = GetShortValue(optionValue);

                if (string.IsNullOrEmpty(shortValue))
                {
                    shortValue = "-";
                }

                sb.Append(shortValue);

                string?description = optionValue.Description;

                if (!string.IsNullOrEmpty(description))
                {
                    sb.AppendSpaces(width2 - shortValue.Length);
                    sb.Append(description);
                }

                builder.Add(new OptionValueItem(optionValue, StringBuilderCache.GetStringAndFree(sb)));
            }

            return(builder.ToImmutableArray());
Beispiel #7
0
        public static ImmutableArray <ArgumentItem> GetArgumentItems(
            IEnumerable <CommandArgument> arguments,
            Filter filter = null)
        {
            int width = CalculateArgumentsWidths(arguments);

            ImmutableArray <ArgumentItem> .Builder builder = ImmutableArray.CreateBuilder <ArgumentItem>();

            bool anyIsOptional = arguments.Any(f => !f.IsRequired);

            foreach (CommandArgument argument in arguments)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                sb.Append(argument.Name);

                if (!string.IsNullOrEmpty(argument.Description))
                {
                    sb.AppendSpaces(width - argument.Name.Length - ((argument.IsRequired) ? 0 : 2));
                }

                string syntax      = StringBuilderCache.GetStringAndFree(sb);
                string description = argument.Description ?? "";

                var argumentItem = new ArgumentItem(argument, syntax, description);

                if (filter?.IsMatch(argumentItem.Text) != false)
                {
                    builder.Add(argumentItem);
                }
            }

            return(builder.ToImmutableArray());
        }
Beispiel #8
0
        private static string AddSlashes(string innerXml)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            string indent = null;

            using (var sr = new StringReader(innerXml))
            {
                string s;

                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Length > 0)
                    {
                        indent ??= Regex.Match(s, "^ *").Value;

                        sb.Append("/// ");
                        s = Regex.Replace(s, $"^{indent}", "");

                        sb.AppendLine(s);
                    }
                }
            }

            return(StringBuilderCache.GetStringAndFree(sb));
        }
Beispiel #9
0
        private static Task <Document> RefactorAsync(
            Document document,
            PragmaWarningDirectiveTriviaSyntax directive,
            CancellationToken cancellationToken)
        {
            SyntaxTrivia trivia = directive.ParentTrivia;

            SyntaxTriviaList list = trivia.GetContainingList();

            int index = list.IndexOf(trivia);

            int start = directive.EndOfDirectiveToken.SpanStart;

            StringBuilder sb = StringBuilderCache.GetInstance();

            int i = index + 1;

            SyntaxKind disableOrRestoreKind = directive.DisableOrRestoreKeyword.Kind();

            int end = start;

            bool addComma = !directive.ErrorCodes.HasTrailingSeparator();

            while (i < list.Count)
            {
                SyntaxTrivia trivia2 = list[i];

                if (trivia2.IsWhitespaceOrEndOfLineTrivia())
                {
                    i++;
                    continue;
                }

                if (trivia2.GetStructure() is PragmaWarningDirectiveTriviaSyntax directive2 &&
                    disableOrRestoreKind == directive2.DisableOrRestoreKeyword.Kind())
                {
                    if (addComma)
                    {
                        sb.Append(",");
                    }

                    sb.Append(" ");

                    SeparatedSyntaxList <ExpressionSyntax> errorCodes = directive2.ErrorCodes;
                    sb.Append(errorCodes.ToString());

                    addComma = !errorCodes.HasTrailingSeparator();

                    end = directive2.ErrorCodes.Span.End;
                }

                i++;
            }

            return(document.WithTextChangeAsync(
                       TextSpan.FromBounds(start, end),
                       StringBuilderCache.GetStringAndFree(sb),
                       cancellationToken));
        }
Beispiel #10
0
        protected void WriteProperties(SearchContext context, FileMatch fileMatch, ColumnWidths?columnWidths)
        {
            if (!ShouldLog(Verbosity.Minimal))
            {
                return;
            }

            if (!Options.Format.FileProperties.Any())
            {
                return;
            }

            StringBuilder sb = StringBuilderCache.GetInstance();

            if (columnWidths != null)
            {
                sb.Append(' ', columnWidths.NameWidth - fileMatch.Path.Length);
            }

            foreach (FileProperty fileProperty in Options.Format.FileProperties)
            {
                if (fileProperty == FileProperty.Size)
                {
                    sb.Append("  ");

                    long size = (fileMatch.IsDirectory)
                        ? (context.DirectorySizeMap?[fileMatch.Path] ?? FileSystemHelpers.GetDirectorySize(fileMatch.Path))
                                : new FileInfo(fileMatch.Path).Length;

                    string sizeText = size.ToString("n0");

                    if (columnWidths != null)
                    {
                        sb.Append(' ', columnWidths.SizeWidth - sizeText.Length);
                    }

                    sb.Append(sizeText);

                    context.Telemetry.FilesTotalSize += size;
                }
                else if (fileProperty == FileProperty.CreationTime)
                {
                    sb.Append("  ");
                    sb.Append(File.GetCreationTime(fileMatch.Path).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else if (fileProperty == FileProperty.ModifiedTime)
                {
                    sb.Append("  ");
                    sb.Append(File.GetLastWriteTime(fileMatch.Path).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else
                {
                    throw new InvalidOperationException($"Unknown enum value '{fileProperty}'.");
                }
            }

            Write(StringBuilderCache.GetStringAndFree(sb), Verbosity.Minimal);
        }
Beispiel #11
0
        public static Task <Document> ConvertToInterpolatedStringAsync(
            Document document,
            LiteralExpressionSyntax literalExpression,
            int interpolationStartIndex = -1,
            int interpolationLength     = 0,
            bool addNameOf = false,
            CancellationToken cancellationToken = default)
        {
            string s = literalExpression.Token.Text;

            StringBuilder sb = StringBuilderCache.GetInstance();

            sb.Append('$');

            int length = sb.Length;

            sb.Append(s, 0, interpolationStartIndex);
            sb.Replace("{", "{{", length);
            sb.Replace("}", "}}", length);

            sb.Append('{');

            if (addNameOf)
            {
                sb.Append(
                    NameOfExpression(
                        StringLiteralParser.Parse(
                            s,
                            interpolationStartIndex,
                            interpolationLength,
                            isVerbatim: s.StartsWith("@"),
                            isInterpolatedText: false)));
            }

            int closeBracePosition = sb.Length;

            sb.Append('}');

            length = sb.Length;

            int startIndex = interpolationStartIndex + interpolationLength;

            sb.Append(s, startIndex, s.Length - startIndex);

            sb.Replace("{", "{{", length);
            sb.Replace("}", "}}", length);

            ExpressionSyntax newNode = ParseExpression(StringBuilderCache.GetStringAndFree(sb));

            SyntaxToken closeBrace = newNode.FindToken(closeBracePosition);

            newNode = newNode
                      .ReplaceToken(closeBrace, closeBrace.WithNavigationAnnotation())
                      .WithTriviaFrom(literalExpression);

            return(document.ReplaceNodeAsync(literalExpression, newNode, cancellationToken));
        }
Beispiel #12
0
            private static string Replace(string s, int index, string replacement)
            {
                StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength + replacement.Length)
                                   .Append(s, 0, index)
                                   .Append(replacement)
                                   .Append(s, index + TokensLength, s.Length - index - TokensLength);

                return(StringBuilderCache.GetStringAndFree(sb));
            }
Beispiel #13
0
        public static (string source, List <TextSpan> spans) GetMarkedSpans(string s)
        {
            StringBuilder sb = StringBuilderCache.GetInstance(s.Length - OpenMarker.Length - CloseMarker.Length);

            List <TextSpan> spans = null;

            int lastPos = 0;

            bool inSpan = false;

            int length = s.Length;

            for (int i = 0; i < length; i++)
            {
                switch (s[i])
                {
                case '<':
                {
                    if (IsOpenMarker(s, length, i))
                    {
                        sb.Append(s, lastPos, i - lastPos);

                        i      += 2;
                        lastPos = i + 1;
                        inSpan  = true;
                        continue;
                    }

                    break;
                }

                case '>':
                {
                    if (inSpan &&
                        IsCloseMarker(s, length, i))
                    {
                        var span = new TextSpan(sb.Length, i - lastPos);

                        (spans ?? (spans = new List <TextSpan>())).Add(span);

                        sb.Append(s, lastPos, i - lastPos);

                        i      += 2;
                        lastPos = i + 1;
                        inSpan  = false;
                        continue;
                    }

                    break;
                }
                }
            }

            sb.Append(s, lastPos, s.Length - lastPos);

            return(StringBuilderCache.GetStringAndFree(sb), spans);
        }
Beispiel #14
0
        private static List <string> CreateRegularStringLiterals(string text)
        {
            var values = new List <string>();

            StringBuilder sb = StringBuilderCache.GetInstance();

            for (int i = 0; i < text.Length; i++)
            {
                switch (text[i])
                {
                case '"':
                {
                    sb.Append(Backslash);
                    sb.Append(Quote);
                    break;
                }

                case '\\':
                {
                    sb.Append(Backslash);
                    sb.Append(Backslash);
                    break;
                }

                case '\r':
                {
                    if (i < text.Length - 1 &&
                        text[i + 1] == '\n')
                    {
                        i++;
                    }

                    values.Add(sb.ToString());
                    sb.Clear();
                    break;
                }

                case '\n':
                {
                    values.Add(sb.ToString());
                    sb.Clear();
                    break;
                }

                default:
                {
                    sb.Append(text[i]);
                    break;
                }
                }
            }

            values.Add(StringBuilderCache.GetStringAndFree(sb));

            return(values);
        }
Beispiel #15
0
        public static ImmutableArray <OptionItem> GetOptionItems(IEnumerable <CommandOption> options, Filter filter = null)
        {
            int width = CalculateOptionsWidths(options);

            bool anyIsOptional   = options.Any(f => !f.IsRequired);
            bool anyHasShortName = options.Any(f => !string.IsNullOrEmpty(f.ShortName));

            ImmutableArray <OptionItem> .Builder builder = ImmutableArray.CreateBuilder <OptionItem>();

            foreach (CommandOption option in options)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                if (!string.IsNullOrEmpty(option.ShortName))
                {
                    sb.Append("-");
                    sb.Append(option.ShortName);

                    if (!string.IsNullOrEmpty(option.Name))
                    {
                        sb.Append(", ");
                    }
                }
                else if (anyHasShortName)
                {
                    sb.Append(' ', 4);
                }

                if (!string.IsNullOrEmpty(option.Name))
                {
                    sb.Append("--");
                    sb.Append(option.Name);
                }

                sb.AppendSpaces(1);

                if (!string.IsNullOrEmpty(option.MetaValue))
                {
                    sb.Append(option.MetaValue);
                }

                sb.AppendSpaces(width - sb.Length + SeparatorWidth);

                string syntax      = StringBuilderCache.GetStringAndFree(sb);
                string description = option.Description ?? "";

                var optionItem = new OptionItem(option, syntax: syntax, description);

                if (filter?.IsMatch(optionItem.Text) != false)
                {
                    builder.Add(optionItem);
                }
            }

            return(builder.ToImmutableArray());
        }
        private static StringLiteralParserResult ParseVerbatim(
            string text,
            int start,
            int length,
            bool throwOnError       = false,
            bool isInterpolatedText = false)
        {
            StringBuilder sb = null;

            for (int pos = start; pos < start + length; pos++)
            {
                char ch = text[pos];
                if (ch == '\"')
                {
                    pos++;

                    if (pos >= text.Length)
                    {
                        return(Fail(throwOnError, MissingEscapeSequenceMessage));
                    }

                    if (text[pos] == '\"')
                    {
                        ch = '\"';
                    }
                    else
                    {
                        return(Fail(throwOnError, UnrecognizedEscapeSequenceMessage));
                    }
                }
                else if (isInterpolatedText)
                {
                    if (ch == '{' || ch == '}')
                    {
                        pos++;

                        if (pos >= text.Length)
                        {
                            return(Fail(throwOnError, MissingEscapeSequenceMessage));
                        }

                        if (ch != text[pos])
                        {
                            return(Fail(throwOnError, UnrecognizedEscapeSequenceMessage));
                        }
                    }
                }

                (sb ??= StringBuilderCache.GetInstance(text.Length)).Append(ch);
            }

            return(new StringLiteralParserResult((sb != null)
                ? StringBuilderCache.GetStringAndFree(sb)
                : text.Substring(start, length)));
        }
        internal LiteralExpressionSyntax ToMultiLineStringLiteralExpression()
        {
            ThrowInvalidOperationIfNotInitialized();

            ThrowIfContainsNonStringLiteralExpression(Analyze());

            StringBuilder sb = StringBuilderCache.GetInstance();

            sb.Append('@');
            sb.Append('"');

            ExpressionSyntax[] expressions = Expressions(leftToRight: true).ToArray();

            for (int i = 0; i < expressions.Length; i++)
            {
                if (expressions[i].IsKind(SyntaxKind.StringLiteralExpression))
                {
                    var literal = (LiteralExpressionSyntax)expressions[i];

                    int length = sb.Length;

                    sb.Append(literal.Token.ValueText);

                    sb.Replace("\"", "\"\"", length);

                    if (sb.Length > length &&
                        sb[sb.Length - 1] == '\n')
                    {
                        sb.Remove(sb.Length - 1, 1);

                        if (sb.Length - length > 1 &&
                            sb[sb.Length - 1] == '\r')
                        {
                            sb.Remove(sb.Length - 1, 1);
                        }

                        sb.AppendLine();
                    }
                    else if (i < expressions.Length - 1)
                    {
                        TextSpan span = TextSpan.FromBounds(expressions[i].Span.End, expressions[i + 1].SpanStart);

                        if (BinaryExpression.SyntaxTree.IsMultiLineSpan(span))
                        {
                            sb.AppendLine();
                        }
                    }
                }
            }

            sb.Append('"');

            return((LiteralExpressionSyntax)ParseExpression(StringBuilderCache.GetStringAndFree(sb)));
        }
Beispiel #18
0
        public string ToString(MarkdownWriterSettings settings)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            using (var writer = new MarkdownStringWriter(sb, settings))
            {
                WriteTo(writer);

                return(StringBuilderCache.GetStringAndFree(writer.GetStringBuilder()));
            }
        }
Beispiel #19
0
        private static (string source, ImmutableArray <(string kind, TextSpan span)> annotations) FindAnnotatedSpansAndRemoveImpl(
            string text,
            string annotationIdentifier = null)
        {
            int offset  = 0;
            int lastPos = 0;

            Match match = _annotatedSpanRegex.Match(text);

            if (!match.Success)
            {
                return(text, ImmutableArray <(string, TextSpan)> .Empty);
            }

            StringBuilder sb = StringBuilderCache.GetInstance(text.Length);

            ImmutableArray <(string, TextSpan)> .Builder annotations = null;

            do
            {
                Group content = match.Groups["content"];

                sb.Append(text, lastPos, match.Index);
                sb.Append(content.Value);

                string identifier = match.Groups["identifier"].Value;

                if (annotationIdentifier == null ||
                    string.Equals(annotationIdentifier, identifier, StringComparison.Ordinal))
                {
                    var span = new TextSpan(match.Index - offset, content.Length);

                    (annotations ??= ImmutableArray.CreateBuilder <(string, TextSpan)>()).Add((identifier, span));
                }

                lastPos = match.Index + match.Length;
                offset += match.Length - content.Length;

                match = match.NextMatch();
            } while (match.Success);

            sb.Append(text, lastPos, text.Length - lastPos);

            return(
                StringBuilderCache.GetStringAndFree(sb),
                annotations?.ToImmutableArray() ?? ImmutableArray <(string, TextSpan)> .Empty);
        }
Beispiel #20
0
        private static async Task <Document> RefactorAsync(
            Document document,
            SyntaxTrivia trivia,
            ThrowInfo throwInfo,
            MemberDeclarationSyntax memberDeclaration,
            ISymbol declarationSymbol,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var throwInfos = new List <ThrowInfo>()
            {
                throwInfo
            };

            INamedTypeSymbol exceptionSymbol = semanticModel.GetTypeByMetadataName("System.Exception");

            foreach (ThrowInfo info in GetOtherUndocumentedExceptions(memberDeclaration, declarationSymbol, node => node != throwInfo.Node, exceptionSymbol, semanticModel, cancellationToken))
            {
                if (!throwInfos.Any(f => f.ExceptionSymbol == info.ExceptionSymbol))
                {
                    throwInfos.Add(info);
                }
            }

            string indent = GetIndent(memberDeclaration.GetLeadingTrivia());

            StringBuilder sb = StringBuilderCache.GetInstance();

            foreach (ThrowInfo info in throwInfos)
            {
                sb.Append(indent);

                IParameterSymbol parameterSymbol = info.GetParameterSymbol(semanticModel, cancellationToken);

                AppendExceptionDocumentation(trivia, info.ExceptionSymbol, parameterSymbol, semanticModel, ref sb);
            }

            string newText = StringBuilderCache.GetStringAndFree(sb);

            var textChange = new TextChange(new TextSpan(trivia.FullSpan.End, 0), newText);

            SourceText newSourceText = sourceText.WithChanges(textChange);

            return(document.WithText(newSourceText));
        }
Beispiel #21
0
        public static (string source, ImmutableDictionary <string, ImmutableArray <TextSpan> > spans) FindAnnotatedSpansAndRemove(string text)
        {
            int offset  = 0;
            int lastPos = 0;

            Match match = _annotatedSpanRegex.Match(text);

            if (!match.Success)
            {
                return(text, ImmutableDictionary <string, ImmutableArray <TextSpan> > .Empty);
            }

            StringBuilder sb = StringBuilderCache.GetInstance(text.Length);

            ImmutableDictionary <string, List <TextSpan> > .Builder dic = ImmutableDictionary.CreateBuilder <string, List <TextSpan> >();

            do
            {
                Group content = match.Groups["content"];

                sb.Append(text, lastPos, match.Index);
                sb.Append(content.Value);

                string identifier = match.Groups["identifier"].Value;
                if (!dic.TryGetValue(identifier, out List <TextSpan> spans))
                {
                    spans           = new List <TextSpan>();
                    dic[identifier] = spans;
                }

                spans.Add(new TextSpan(match.Index - offset, content.Length));

                lastPos = match.Index + match.Length;
                offset += match.Length - content.Length;

                match = match.NextMatch();
            } while (match.Success);

            sb.Append(text, lastPos, text.Length - lastPos);

            return(
                StringBuilderCache.GetStringAndFree(sb),
                dic.ToImmutableDictionary(f => f.Key, f => f.Value.ToImmutableArray()));
        }
Beispiel #22
0
        private static string CreateRegularStringLiteral(string text)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            for (int i = 0; i < text.Length; i++)
            {
                switch (text[i])
                {
                case '"':
                {
                    sb.Append(Backslash);
                    sb.Append(Quote);
                    break;
                }

                case '\\':
                {
                    sb.Append(Backslash);
                    sb.Append(Backslash);
                    break;
                }

                case '\r':
                {
                    sb.Append(@"\r");
                    break;
                }

                case '\n':
                {
                    sb.Append(@"\n");
                    break;
                }

                default:
                {
                    sb.Append(text[i]);
                    break;
                }
                }
            }

            return(StringBuilderCache.GetStringAndFree(sb));
        }
        public static ImmutableArray <ArgumentItem> GetArgumentItems(
            IEnumerable <CommandArgument> arguments,
            Filter?filter = null)
        {
            int width = CalculateArgumentsWidths(arguments);

            ImmutableArray <ArgumentItem> .Builder builder = ImmutableArray.CreateBuilder <ArgumentItem>();

            bool anyIsOptional = arguments.Any(f => !f.IsRequired);

            foreach (CommandArgument argument in arguments)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                if (!argument.IsRequired)
                {
                    sb.Append("[");
                }
                else if (anyIsOptional)
                {
                    sb.Append(" ");
                }

                sb.Append(argument.Name);

                if (!argument.IsRequired)
                {
                    sb.Append("]");
                }

                if (!string.IsNullOrEmpty(argument.Description))
                {
                    sb.AppendSpaces(width - argument.Name.Length - ((argument.IsRequired) ? 0 : 2));
                    sb.Append(argument.Description);
                }

                builder.Add(new ArgumentItem(argument, StringBuilderCache.GetStringAndFree(sb)));
            }

            return((filter != null)
                ? builder.Where(f => filter.IsMatch(f.Text)).ToImmutableArray()
                : builder.ToImmutableArray());
        }
        internal LiteralExpressionSyntax ToStringLiteralExpression()
        {
            ThrowInvalidOperationIfNotInitialized();

            StringConcatenationAnalysis analysis = Analyze();

            ThrowIfContainsNonStringLiteralExpression(analysis);

            StringBuilder sb = StringBuilderCache.GetInstance();

            if (!analysis.ContainsNonVerbatimExpression)
            {
                sb.Append('@');
            }

            sb.Append('"');

            foreach (ExpressionSyntax expression in Expressions(leftToRight: true))
            {
                StringLiteralExpressionInfo literal = SyntaxInfo.StringLiteralExpressionInfo(expression);

                if (literal.Success)
                {
                    if (analysis.ContainsNonVerbatimExpression && literal.IsVerbatim)
                    {
                        int startIndex = sb.Length;
                        sb.Append(literal.ValueText);
                        sb.Replace(@"\", @"\\", startIndex);
                        sb.Replace("\"", @"\" + "\"", startIndex);
                        sb.Replace("\n", @"\n", startIndex);
                        sb.Replace("\r", @"\r", startIndex);
                    }
                    else
                    {
                        sb.Append(literal.InnerText);
                    }
                }
            }

            sb.Append('"');

            return((LiteralExpressionSyntax)ParseExpression(StringBuilderCache.GetStringAndFree(sb)));
        }
Beispiel #25
0
        private static Task <Document> RefactorAsync(
            Document document,
            SyntaxTrivia trivia,
            ThrowInfo throwInfo,
            MemberDeclarationSyntax memberDeclaration,
            ISymbol declarationSymbol,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            var throwInfos = new List <ThrowInfo>()
            {
                throwInfo
            };

            INamedTypeSymbol exceptionSymbol = semanticModel.GetTypeByMetadataName("System.Exception");

            foreach (ThrowInfo info in GetOtherUndocumentedExceptions(memberDeclaration, declarationSymbol, node => node != throwInfo.Node, exceptionSymbol, semanticModel, cancellationToken))
            {
                if (!throwInfos.Any(f => SymbolEqualityComparer.Default.Equals(f.ExceptionSymbol, info.ExceptionSymbol)))
                {
                    throwInfos.Add(info);
                }
            }

            string indent = GetIndent(memberDeclaration.GetLeadingTrivia());

            StringBuilder sb = StringBuilderCache.GetInstance();

            foreach (ThrowInfo info in throwInfos)
            {
                sb.Append(indent);

                IParameterSymbol parameterSymbol = info.GetParameterSymbol(semanticModel, cancellationToken);

                AppendExceptionDocumentation(trivia, info.ExceptionSymbol, parameterSymbol, semanticModel, ref sb);
            }

            return(document.WithTextChangeAsync(
                       new TextSpan(trivia.FullSpan.End, 0),
                       StringBuilderCache.GetStringAndFree(sb),
                       cancellationToken));
        }
Beispiel #26
0
        public static ImmutableArray <OptionValueItem> GetOptionValueItems(
            IEnumerable <OptionValue> optionValues,
            int maxWidth)
        {
            int maxShortNameWidth = optionValues.Max(f => GetShortValue(f).Length);

            ImmutableArray <OptionValueItem> .Builder builder = ImmutableArray.CreateBuilder <OptionValueItem>();

            foreach (OptionValue optionValue in optionValues)
            {
                StringBuilder sb = StringBuilderCache.GetInstance();

                string shortValue = GetShortValue(optionValue);

                if (!string.IsNullOrEmpty(shortValue))
                {
                    sb.Append(' ', maxShortNameWidth - shortValue.Length);
                    sb.Append(shortValue);
                    sb.Append(", ");
                }
                else
                {
                    sb.Append(' ', maxShortNameWidth + 2);
                }

                string value = GetValue(optionValue);

                sb.Append(value);
                sb.AppendSpaces(maxWidth - sb.Length);

                string description = optionValue.Description ?? "";

                builder.Add(new OptionValueItem(optionValue, StringBuilderCache.GetStringAndFree(sb), description));
            }

            return(builder.ToImmutableArray());
        }
        private static ExpressionSyntax GetReturnExpression(string value, bool isVerbatim)
        {
            StringBuilder sb = StringBuilderCache.GetInstance(capacity: value.Length);

            sb.Append('$');

            if (isVerbatim)
            {
                sb.Append('@');
            }

            sb.Append('"');

            int length = value.Length;

            int i = 0;

            int lastPos = i;

            while (true)
            {
                lastPos = i;

                AppendInterpolatedText();

                if (i == length)
                {
                    break;
                }

                i++;

                lastPos = i;

                AppendInterpolation();

                if (i == length)
                {
                    break;
                }

                i++;
            }

            sb.Append(value, lastPos, i - lastPos);
            sb.Append("\"");

            return(SyntaxFactory.ParseExpression(StringBuilderCache.GetStringAndFree(sb)));

            void AppendInterpolatedText()
            {
                while (i < length)
                {
                    switch (value[i])
                    {
                    case '{':
                    {
                        sb.Append(value, lastPos, i - lastPos);
                        return;
                    }

                    case '\\':
                    {
                        sb.Append(value, lastPos, i - lastPos);

                        i++;

                        if (i < length)
                        {
                            char ch = value[i];

                            if (ch == '{' ||
                                ch == '}')
                            {
                                sb.Append(ch);
                                sb.Append(ch);
                                i++;
                                lastPos = i;
                                continue;
                            }
                        }

                        sb.Append((isVerbatim) ? "\\" : "\\\\");
                        lastPos = i;
                        continue;
                    }

                    case '"':
                    {
                        sb.Append(value, lastPos, i - lastPos);
                        sb.Append((isVerbatim) ? "\"\"" : "\\\"");
                        i++;
                        lastPos = i;
                        continue;
                    }
                    }

                    i++;
                }
            }

            void AppendInterpolation()
            {
                while (i < length)
                {
                    switch (value[i])
                    {
                    case '}':
                    {
                        sb.Append('{');
                        sb.Append(value, lastPos, i - lastPos);
                        sb.Append('}');
                        return;
                    }

                    case '(':
                    {
                        i++;
                        break;
                    }

                    case ',':
                    {
                        sb.Append('{');
                        sb.Append(value, lastPos, i - lastPos);
                        sb.Append('}');

                        i += 3;
                        return;
                    }
                    }

                    i++;
                }
            }
        }
Beispiel #28
0
            public override TextParserResult GetSpans(string s, IComparer <LinePositionSpanInfo> comparer = null)
            {
                StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength);

                var startPending = false;
                LinePositionInfo            start = default;
                Stack <LinePositionInfo>    stack = null;
                List <LinePositionSpanInfo> spans = null;

                int lastPos = 0;

                int line   = 0;
                int column = 0;

                int length = s.Length;

                int i = 0;

                while (i < length)
                {
                    switch (s[i])
                    {
                    case '\r':
                    {
                        if (PeekNextChar() == '\n')
                        {
                            i++;
                        }

                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '\n':
                    {
                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '[':
                    {
                        char nextChar = PeekNextChar();
                        if (nextChar == '|')
                        {
                            sb.Append(s, lastPos, i - lastPos);

                            var start2 = new LinePositionInfo(sb.Length, line, column);

                            if (stack != null)
                            {
                                stack.Push(start2);
                            }
                            else if (!startPending)
                            {
                                start        = start2;
                                startPending = true;
                            }
                            else
                            {
                                stack = new Stack <LinePositionInfo>();
                                stack.Push(start);
                                stack.Push(start2);
                                startPending = false;
                            }

                            i      += 2;
                            lastPos = i;
                            continue;
                        }
                        else if (nextChar == '[' &&
                                 PeekChar(2) == '|' &&
                                 PeekChar(3) == ']')
                        {
                            i++;
                            column++;
                            CloseSpan();
                            i      += 3;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }

                    case '|':
                    {
                        if (PeekNextChar() == ']')
                        {
                            CloseSpan();
                            i      += 2;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }
                    }

                    column++;
                    i++;
                }

                if (startPending ||
                    stack?.Count > 0)
                {
                    throw new InvalidOperationException();
                }

                sb.Append(s, lastPos, s.Length - lastPos);

                spans?.Sort(comparer ?? LinePositionSpanInfoComparer.Index);

                return(new TextParserResult(
                           StringBuilderCache.GetStringAndFree(sb),
                           spans?.ToImmutableArray() ?? ImmutableArray <LinePositionSpanInfo> .Empty));

                char PeekNextChar()
                {
                    return(PeekChar(1));
                }

                char PeekChar(int offset)
                {
                    return((i + offset >= s.Length) ? '\0' : s[i + offset]);
                }

                void CloseSpan()
                {
                    if (stack != null)
                    {
                        start = stack.Pop();
                    }
                    else if (startPending)
                    {
                        startPending = false;
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }

                    var end = new LinePositionInfo(sb.Length + i - lastPos, line, column);

                    var span = new LinePositionSpanInfo(start, end);

                    (spans ??= new List <LinePositionSpanInfo>()).Add(span);

                    sb.Append(s, lastPos, i - lastPos);
                }
            }
        private static SyntaxTriviaList Generate(
            SeparatedSyntaxList <TypeParameterSyntax> typeParameters = default(SeparatedSyntaxList <TypeParameterSyntax>),
            SeparatedSyntaxList <ParameterSyntax> parameters         = default(SeparatedSyntaxList <ParameterSyntax>),
            bool canGenerateReturns = false,
            DocumentationCommentGeneratorSettings settings = null)
        {
            settings ??= DocumentationCommentGeneratorSettings.Default;

            ImmutableArray <string> summary = settings.Summary;

            StringBuilder sb = StringBuilderCache.GetInstance();

            sb.Append(settings.Indentation);
            sb.Append("/// <summary>");

            if (settings.SingleLineSummary &&
                summary.Length <= 1)
            {
                if (summary.Length == 1)
                {
                    sb.Append(summary[0]);
                }

                sb.AppendLine("</summary>");
            }
            else
            {
                sb.AppendLine();

                if (summary.Any())
                {
                    foreach (string comment in summary)
                    {
                        sb.Append(settings.Indentation);
                        sb.Append("/// ");
                        sb.AppendLine(comment);
                    }
                }
                else
                {
                    sb.Append(settings.Indentation);
                    sb.AppendLine("/// ");
                }

                sb.Append(settings.Indentation);
                sb.AppendLine("/// </summary>");
            }

            foreach (TypeParameterSyntax typeParameter in typeParameters)
            {
                sb.Append(settings.Indentation);
                sb.Append("/// <typeparam name=\"");
                sb.Append(typeParameter.Identifier.ValueText);
                sb.AppendLine("\"></typeparam>");
            }

            foreach (ParameterSyntax parameter in parameters)
            {
                sb.Append(settings.Indentation);
                sb.Append("/// <param name=\"");
                sb.Append(parameter.Identifier.ValueText);
                sb.AppendLine("\"></param>");
            }

            if (canGenerateReturns &&
                settings.Returns)
            {
                sb.Append(settings.Indentation);
                sb.AppendLine("/// <returns></returns>");
            }

            return(SyntaxFactory.ParseLeadingTrivia(StringBuilderCache.GetStringAndFree(sb)));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            InterpolatedStringExpressionSyntax interpolatedString,
            CancellationToken cancellationToken)
        {
            StringBuilder sb = StringBuilderCache.GetInstance();

            var b = new SyntaxNodeTextBuilder(interpolatedString, sb);

            var arguments = new List <ArgumentSyntax>()
            {
                null
            };

            if (interpolatedString.IsVerbatim())
            {
                b.Append("@");
            }

            b.Append("\"");

            int index = 0;

            foreach (InterpolatedStringContentSyntax content in interpolatedString.Contents)
            {
                switch (content.Kind())
                {
                case SyntaxKind.Interpolation:
                {
                    var interpolation = (InterpolationSyntax)content;

                    b.Append("{");
                    b.Append(index.ToString(CultureInfo.InvariantCulture));
                    index++;

                    InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause;
                    if (alignmentClause != null)
                    {
                        b.Append(",");
                        b.AppendSpan(alignmentClause.Value);
                    }

                    InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause;
                    if (formatClause != null)
                    {
                        b.Append(":");
                        b.AppendSpan(formatClause.FormatStringToken);
                    }

                    b.Append("}");

                    arguments.Add(Argument(interpolation.Expression));
                    break;
                }

                case SyntaxKind.InterpolatedStringText:
                {
                    b.AppendSpan(content);
                    break;
                }
                }
            }

            b.Append("\"");

            arguments[0] = Argument(ParseExpression(StringBuilderCache.GetStringAndFree(sb)));

            InvocationExpressionSyntax invocation = SimpleMemberInvocationExpression(
                CSharpTypeFactory.StringType(),
                IdentifierName("Format"),
                ArgumentList(SeparatedList(arguments)));

            invocation = invocation.WithTriviaFrom(interpolatedString).WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(interpolatedString, invocation, cancellationToken));
        }