private static void AddLineBreak <T>(ref T node) where T : SyntaxNode { var trivia = SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.EndOfLineTrivia, "\n")); node = node.WithTrailingTrivia(trivia); node = node.WithLeadingTrivia(SyntaxTriviaList.Empty); }
public void TestFreeFormTokenFactory_DefaultText() { for ( SyntaxKind kind = InternalSyntax.SyntaxToken.FirstTokenWithWellKnownText; kind <= InternalSyntax.SyntaxToken.LastTokenWithWellKnownText; kind++ ) { if (!SyntaxFacts.IsAnyToken(kind)) { continue; } var defaultText = SyntaxFacts.GetText(kind); var actualRed = SyntaxFactory.Token( SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), kind, defaultText, defaultText, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker) ); var actualGreen = actualRed.Node; var expectedGreen = InternalSyntax.SyntaxFactory.Token( InternalSyntax.SyntaxFactory.ElasticZeroSpace, kind, InternalSyntax.SyntaxFactory.ElasticZeroSpace ); Assert.Same(expectedGreen, actualGreen); // Don't create a new token if we don't have to. } }
public static SyntaxToken BuildMethodIdentifier(string methodName) { var methodIdentifier = SyntaxFactory.Identifier(SyntaxTriviaList.Create(SyntaxFactory.Space), methodName, SyntaxTriviaList.Create(SyntaxFactory.Space)); return(methodIdentifier); }
public static SyntaxNode AddContractNamespaceIfNeeded(SyntaxNode tree) { Contract.Ensures(Contract.Result <SyntaxNode>() != null); // TODO: super naive pproach // Getting all using statements and looking for System there var root = tree; var usings = root.DescendantNodesAndSelf().OfType <NamespaceDeclarationSyntax>().SelectMany(nd => nd.Usings) .Union( root.DescendantNodesAndSelf().OfType <CompilationUnitSyntax>().SelectMany(nd => nd.Usings)).ToArray(); bool contractNamespaceUsingExists = usings.Any(x => x.Name.GetText().ToString() == typeof(Contract).Namespace); if (contractNamespaceUsingExists) { return(tree); } var compilation = root.DescendantNodesAndSelf().OfType <CompilationUnitSyntax>().First(); var newUsings = compilation.Usings.Add( SyntaxFactory.UsingDirective( SyntaxFactory.IdentifierName(typeof(Contract).Namespace)) .NormalizeWhitespace() .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.CarriageReturnLineFeed))); return(tree.ReplaceNode(compilation, compilation.WithUsings(newUsings))); }
public static ArrayCreationExpressionSyntax CreateArrayOf(string typeName, ExpressionSyntax[] expressions, int ranksAmount = 1) { var newKeyword = SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.NewKeyword, SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))); var syntaxList = new SeparatedSyntaxList <ExpressionSyntax>(); for (var i = 0; i < expressions.Length; i++) { syntaxList = syntaxList.Add(expressions[i]); } var rankSpecifiers = new SyntaxList <ArrayRankSpecifierSyntax>(); for (var i = 0; i < ranksAmount; i++) { rankSpecifiers = rankSpecifiers.Add( SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), new SeparatedSyntaxList <ExpressionSyntax> { SyntaxFactory.OmittedArraySizeExpression( SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken) ) }, SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ) ); } return(SyntaxFactory.ArrayCreationExpression( newKeyword, SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(typeName), rankSpecifiers), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, syntaxList))); }
public async Task <CompilationUnitSyntax> GenerateAsync() { var defines = new SvoDefine(Arguments); var generated = SyntaxTriviaList.Create(SyntaxFactory.Comment(GeneratedByAToolPreamble)); var defined = defines.AsTrivia(); var trivia = generated.AddRange(defined); var members = new List <MemberDeclarationSyntax>(); await Structure(members); await IEquatable(members); await IComparable(members); await ISerializable(members); await IXmlSerializable(members); await IJsonSerializable(members); await IFormattable(members); await Parsing(members); await Validation(members); var externs = new SyntaxList <ExternAliasDirectiveSyntax>(Array.Empty <ExternAliasDirectiveSyntax>()); var usings = new SyntaxList <UsingDirectiveSyntax>(Array.Empty <UsingDirectiveSyntax>()); var attributes = new SyntaxList <AttributeListSyntax>(Array.Empty <AttributeListSyntax>()); var compilation = SyntaxFactory.CompilationUnit(externs, usings, attributes, new SyntaxList <MemberDeclarationSyntax>(members)); return(compilation .WithLeadingTrivia(trivia) .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed) .NormalizeWhitespace()); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var attributeRemover = new AttributeRemover(node.AttributeLists, "TestFixture"); if (attributeRemover.IsHavingAttribute) { if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword))) { var publicKeyword = SyntaxFactory.Token(SyntaxKind.PublicKeyword) .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.Space)); node = node.WithModifiers(node.Modifiers.Add(publicKeyword)); } node = node.WithAttributeLists(attributeRemover.Remove()); } if (node.DescendantNodes().Any(n => n is MethodDeclarationSyntax m && m.AttributeLists.Contains("TearDown"))) { node = node.AddBaseListTypes( SyntaxFactory.SimpleBaseType( SyntaxFactory.IdentifierName("IDisposable")).WithoutTrivia()); node = node.WithIdentifier(node.Identifier.WithoutTrivia()); } return(base.VisitClassDeclaration(node)); }
public void TestFreeFormTokenFactory_CustomText() { for (SyntaxKind kind = InternalSyntax.SyntaxToken.FirstTokenWithWellKnownText; kind <= InternalSyntax.SyntaxToken.LastTokenWithWellKnownText; kind++) { if (!SyntaxFacts.IsAnyToken(kind)) { continue; } var defaultText = SyntaxFacts.GetText(kind); var text = ToXmlEntities(defaultText); var valueText = defaultText; var token = SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), kind, text, valueText, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)); Assert.Equal(kind, token.Kind()); Assert.Equal(text, token.Text); Assert.Equal(valueText, token.ValueText); if (string.IsNullOrEmpty(valueText)) { Assert.IsType <InternalSyntax.SyntaxToken.SyntaxTokenWithTrivia>(token.Node); } else { Assert.IsType <InternalSyntax.SyntaxToken.SyntaxTokenWithValueAndTrivia <string> >(token.Node); } } }
private static SeparatedSyntaxList <ExpressionSyntax> GetInitializerItems( IEnumerable <Icon> icons) { var comma = SyntaxFactory.Token(SyntaxKind.CommaToken); var trailingTriviaList = SyntaxTriviaList.Create(SyntaxFactory.ElasticCarriageReturnLineFeed); var separator = SyntaxFactory.Identifier(SyntaxTriviaList.Empty, comma.Text, trailingTriviaList); var initializerExpressionSyntaxList = icons.Select(icon => { //Indent var indent = SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")); //create a member access expression var memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("PackIconKind"), SyntaxFactory.IdentifierName(icon.Name)); //create a string literal expression var literalExpressionSyntax = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(icon.Data)); var separatedSyntaxList = SyntaxFactory.SeparatedList(new ExpressionSyntax[] { memberAccessExpressionSyntax, literalExpressionSyntax }); var initializerExpressionSyntax = SyntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, separatedSyntaxList) .WithLeadingTrivia(indent); return((ExpressionSyntax)initializerExpressionSyntax); }).ToList(); var result = SyntaxFactory.SeparatedList(initializerExpressionSyntaxList, Enumerable.Repeat(separator, initializerExpressionSyntaxList.Count - 1)); return(result); }
private static void RemoveWhiteSpaces(ref SyntaxTriviaList trivia) { var old = trivia.Where(x => !x.IsKind(SyntaxKind.WhitespaceTrivia)); var newTrivia = SyntaxTriviaList.Create(new SyntaxTrivia()); trivia = newTrivia.AddRange(old); }
private static void RemoveLineBreaks(ref SyntaxTriviaList trivia) { var old = trivia.Where(x => !x.IsKind(SyntaxKind.EndOfLineTrivia)); var newTrivia = SyntaxTriviaList.Create(new SyntaxTrivia()); trivia = newTrivia.AddRange(old); }
private string UpdateEnum(string sourceFile, IEnumerable <Tuple <string, string> > nameDataPairs) { var sourceText = SourceText.From(new FileStream(sourceFile, FileMode.Open)); var syntaxTree = CSharpSyntaxTree.ParseText(sourceText); var rootNode = syntaxTree.GetRoot(); var namespaceDeclarationNode = rootNode.ChildNodes().Single(); var enumDeclarationSyntaxNode = namespaceDeclarationNode.ChildNodes().OfType <EnumDeclarationSyntax>().Single(); var emptyEnumDeclarationSyntaxNode = enumDeclarationSyntaxNode.RemoveNodes(enumDeclarationSyntaxNode.ChildNodes().OfType <EnumMemberDeclarationSyntax>(), SyntaxRemoveOptions.KeepDirectives); var leadingTriviaList = SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")); var enumMemberDeclarationSyntaxs = nameDataPairs.Select( tuple => SyntaxFactory.EnumMemberDeclaration(SyntaxFactory.Identifier(leadingTriviaList, tuple.Item1, SyntaxTriviaList.Empty))).ToArray(); var generatedEnumDeclarationSyntax = emptyEnumDeclarationSyntaxNode.AddMembers(enumMemberDeclarationSyntaxs); generatedEnumDeclarationSyntax = AddLineFeedsToCommas(generatedEnumDeclarationSyntax); var generatedNamespaceDeclarationSyntaxNode = namespaceDeclarationNode.ReplaceNode(enumDeclarationSyntaxNode, generatedEnumDeclarationSyntax); var generatedRootNode = rootNode.ReplaceNode(namespaceDeclarationNode, generatedNamespaceDeclarationSyntaxNode); return(generatedRootNode.ToFullString()); }
public SyntaxTree RewriteAndMerge(SyntaxTree[] syntaxTrees, CSharpCompilation compilation, string[] excludedTypes = null) { var rewrittenTrees = Rewrite(syntaxTrees, compilation, excludedTypes).ToArray(); var usings = rewrittenTrees.SelectMany(t => t.GetCompilationUnitRoot().Usings).ToList(); // Add "Resharper disable all" comment usings[usings.Count - 1] = usings[usings.Count - 1].WithTrailingTrivia( SyntaxTriviaList.Create(SyntaxFactory.Comment("\n// Resharper disable all")) ); return(SyntaxFactory.SyntaxTree( SyntaxFactory.CompilationUnit() .WithUsings(SyntaxFactory.List(usings)) .WithMembers(SyntaxFactory.List <MemberDeclarationSyntax>( rewrittenTrees .SelectMany(t => t.GetCompilationUnitRoot().Members) .Cast <NamespaceDeclarationSyntax>() .SelectMany(ns => ns.Members) .Cast <ClassDeclarationSyntax>() .GroupBy(cls => cls.FirstAncestorOrSelf <NamespaceDeclarationSyntax>().Name.ToString()) .Select(g => SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(g.Key)) .WithMembers(SyntaxFactory.List <MemberDeclarationSyntax>(g)) ) )) .WithEndOfFileToken(SyntaxFactory.Token(SyntaxKind.EndOfFileToken)) .NormalizeWhitespace() )); }
public bool TryGetSorted(SyntaxNode node, out MemberDeclarationSyntax sortedNode) { sortedNode = null; var member = node as MemberDeclarationSyntax; if (member == null || member is TypeDeclarationSyntax || member is NamespaceDeclarationSyntax) { return(false); } var type = member.FirstAncestorOrSelf <TypeDeclarationSyntax>(); if (type == null) { return(false); } if (this.sorted.Item.TryGetValue(type, out List <MemberDeclarationSyntax> sortedMembers)) { var index = type.Members.IndexOf(member); if (index == -1) { return(false); } sortedNode = sortedMembers[index]; if (index == 0) { if (sortedNode.HasLeadingTrivia) { var leadingTrivia = sortedNode.GetLeadingTrivia(); if (leadingTrivia.Any() && leadingTrivia[0].IsKind(SyntaxKind.EndOfLineTrivia)) { sortedNode = sortedNode.WithLeadingTrivia(leadingTrivia.RemoveAt(0)); } } } else if (!(sortedNode is FieldDeclarationSyntax)) { if (sortedNode.HasLeadingTrivia) { var leadingTrivia = sortedNode.GetLeadingTrivia(); if (!leadingTrivia[0].IsKind(SyntaxKind.EndOfLineTrivia)) { sortedNode = sortedNode.WithLeadingTrivia(leadingTrivia.Insert(0, SyntaxFactory.EndOfLine(Environment.NewLine))); } } else { sortedNode = sortedNode.WithLeadingTrivia(SyntaxTriviaList.Create(SyntaxFactory.EndOfLine(Environment.NewLine))); } } return(true); } return(true); }
private static SyntaxTriviaList CreateDelimiterTrailer(bool multiline, int indent) { SyntaxTriviaList delimiterTrailing = multiline ? SyntaxTriviaList.Create(SyntaxFactory.EndOfLine(Environment.NewLine)).Add(SyntaxFactory.Whitespace(new string(' ', indent))) : SyntaxTriviaList.Create(SyntaxFactory.Space); return(delimiterTrailing); }
private static VB.Syntax.StatementSyntax CreateBadStatement(string text, Type type) { string comment = CreateCouldNotBeConvertedComment(text, type); SyntaxTrivia trivia = VB.SyntaxFactory.CommentTrivia(comment); SyntaxToken token = VB.SyntaxFactory.Token(SyntaxTriviaList.Create(trivia), VB.SyntaxKind.EmptyToken); return(VB.SyntaxFactory.EmptyStatement(token)); }
private static ObjectCreationExpressionSyntax CreateObjectOf(TypeSyntax type, ArgumentListSyntax args, InitializerExpressionSyntax initializer = null) { return(SyntaxFactory.ObjectCreationExpression( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.NewKeyword, SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))), type, args, initializer)); }
public static InitializerExpressionSyntax FixInitializerExpressionFormatting(this InitializerExpressionSyntax initializerExpressionSyntax, ObjectCreationExpressionSyntax objectCreationExpression) { var trivia = objectCreationExpression.ArgumentList?.CloseParenToken.TrailingTrivia ?? objectCreationExpression.Type.GetTrailingTrivia(); if (trivia.ToFullString().Contains(Environment.NewLine)) { return(initializerExpressionSyntax); } return(initializerExpressionSyntax .WithLeadingTrivia(SyntaxTriviaList.Create(SyntaxFactory.EndOfLine(Environment.NewLine)))); }
public static SyntaxNode ReplaceNamespaceUsings(SyntaxNode root, string originalNamespace, string newNamespace) { // The method removes 'using System.Diagnostics.Contracts;' and renames it to 'using System.Diagnostics.ContractsLight;'. var newUsing = SyntaxFactory.UsingDirective( SyntaxFactory.ParseName(newNamespace)) .NormalizeWhitespace() .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.CarriageReturnLineFeed)); var replacement = new Dictionary <SyntaxNode, SyntaxNode>(); // TODO: super naive approach foreach (var rootNamespace in root.DescendantNodesAndSelf().OfType <NamespaceDeclarationSyntax>().ToList()) { if (ReplaceInsideNamespace(rootNamespace, newUsing, originalNamespace, out var newNamespaceNode)) { replacement[rootNamespace] = newNamespaceNode; } } if (replacement.Count != 0) { return(root.ReplaceNodes(replacement.Keys, (node, syntaxNode) => replacement[node])); } // Or at the top level var compilation = root.FindNode <CompilationUnitSyntax>(); if (ReplaceForTopLevel(compilation, out var newCompilation)) { return(root.ReplaceNode(compilation, newCompilation)); } var newUsings = compilation.Usings.Add(newUsing); return(root.ReplaceNode(compilation, compilation.WithUsings(newUsings))); // Local functions bool ReplaceForTopLevel(CompilationUnitSyntax compilationRoot, out CompilationUnitSyntax?newCompilationRoot) { var namespaceUsings = compilationRoot.Usings; if (FindIndex(compilationRoot.Usings, originalNamespace, out int namespaceIndex)) { newCompilationRoot = compilationRoot.WithUsings(namespaceUsings.Replace(namespaceUsings[namespaceIndex], newUsing)); return(true); } newCompilationRoot = null; return(false); } }
protected async override Task <SyntaxNode> RewriteFieldNameAndAccessibility(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declarator = root.GetAnnotatedNodes <VariableDeclarationSyntax>(declarationAnnotation).FirstOrDefault(); // There may be no field to rewrite if this document is part of a set of linked files // and the declaration is not conditionally compiled in this document's project. if (declarator == null) { return(root); } var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); var newIdentifier = SyntaxFactory.Identifier( leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation); root = root.ReplaceNode(declarator, updatedDeclarator); document = document.WithSyntaxRoot(root); var declaration = root.GetAnnotatedNodes <SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax; if (declaration != null) { var fieldSyntax = declaration.Parent as FieldDeclarationSyntax; var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword }; if (makePrivate) { var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers( SyntaxFactory.TokenList(modifiers)) .WithAdditionalAnnotations(Formatter.Annotation) .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia()) .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia())); } } return(root); }
public BqlFormatter(string endOfLineCharacter, bool useTabs, int tabSize, int indentSize) { EndOfLineTrivia = SyntaxTriviaList.Create(SyntaxFactory.EndOfLine(endOfLineCharacter)); if (useTabs && indentSize >= tabSize) { var indentItems = GetUseTabsModeIndentTrivias(indentSize, tabSize); IndentationTrivia = indentItems.ToSyntaxTriviaList(); } else { IndentationTrivia = SyntaxTriviaList.Create(SyntaxFactory.Whitespace(new string(' ', indentSize))); } }
private static AccessorDeclarationSyntax GetDefaultGetter(BaseFieldDeclarationSyntax backingField) { var body = SyntaxFactory.Block( SyntaxFactory.List(new[] { SyntaxFactory.ReturnStatement( SyntaxFactory.IdentifierName(backingField.Declaration.Variables.First().Identifier) .WithLeadingTrivia(SyntaxTriviaList.Create(SyntaxFactory.Space))) }) ); var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, LockBuilder.BuildLockBlock(body)); return(getter); }
private static List <BaseFieldDeclarationSyntax> DeclarationSplitter( Document document, VariableDeclarationSyntax declaration, Func <VariableDeclarationSyntax, BaseFieldDeclarationSyntax> declarationFactory, SyntaxTriviaList declarationTrailingTrivia) { SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables; VariableDeclaratorSyntax first = variables.First(); BaseFieldDeclarationSyntax previous = null; var newFieldDeclarations = new List <BaseFieldDeclarationSyntax>(variables.Count); foreach (SyntaxNodeOrToken nodeOrToken in variables.GetWithSeparators()) { if (previous == null) { VariableDeclaratorSyntax variable = (VariableDeclaratorSyntax)nodeOrToken.AsNode(); variable = variable.WithIdentifier(variable.Identifier.WithoutLeadingWhitespace()); var variableDeclarator = SyntaxFactory.SingletonSeparatedList(variable); previous = declarationFactory(declaration.WithVariables(variableDeclarator)); if (variable != first) { var triviaList = previous.GetLeadingTrivia().WithoutDirectiveTrivia(); previous = previous.WithLeadingTrivia(triviaList); } } else { SyntaxToken commaToken = nodeOrToken.AsToken(); SyntaxTriviaList trailingTrivia = commaToken.TrailingTrivia; if (trailingTrivia.Any()) { if (!trailingTrivia.Last().IsKind(SyntaxKind.EndOfLineTrivia)) { trailingTrivia = trailingTrivia.WithoutTrailingWhitespace().Add(FormattingHelper.GetNewLineTrivia(document)); } } else { trailingTrivia = SyntaxTriviaList.Create(FormattingHelper.GetNewLineTrivia(document)); } newFieldDeclarations.Add(previous.WithTrailingTrivia(trailingTrivia)); previous = null; } } newFieldDeclarations.Add(previous.WithTrailingTrivia(declarationTrailingTrivia)); return(newFieldDeclarations); }
public void TestEqualsGreaterThanTokenProperty() { var syntaxNode = this.CreateSwitchExpressionArm(); var wrapper = (SwitchExpressionArmSyntaxWrapper)syntaxNode; Assert.Equal(syntaxNode.EqualsGreaterThanToken, wrapper.EqualsGreaterThanToken); Assert.Throws <ArgumentException>(() => wrapper.WithEqualsGreaterThanToken(SyntaxFactory.Token(SyntaxKind.EqualsEqualsToken))); var newToken = SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "/* 1 */")), SyntaxKind.EqualsGreaterThanToken, SyntaxTriviaList.Empty); var wrapperWithModifiedToken = wrapper.WithEqualsGreaterThanToken(newToken); Assert.True(newToken.IsEquivalentTo(wrapperWithModifiedToken.EqualsGreaterThanToken)); }
public void TestSwitchKeywordProperty() { var switchExpression = this.CreateSwitchExpression(); var wrapper = (SwitchExpressionSyntaxWrapper)switchExpression; Assert.Equal(switchExpression.SwitchKeyword, wrapper.SwitchKeyword); var newSwitchKeyword = SyntaxFactory.Token( SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "/* 1 */")), SyntaxKind.SwitchKeyword, SyntaxTriviaList.Empty); var wrapperWithSwitchKeyword = wrapper.WithSwitchKeyword(newSwitchKeyword); Assert.True(newSwitchKeyword.IsEquivalentTo(wrapperWithSwitchKeyword.SwitchKeyword)); }
public void TestOpenBraceTokenProperty() { var switchExpression = this.CreateSwitchExpression(); var wrapper = (SwitchExpressionSyntaxWrapper)switchExpression; Assert.Equal(switchExpression.OpenBraceToken, wrapper.OpenBraceToken); var newOpenBraceToken = SyntaxFactory.Token( SyntaxTriviaList.Create(SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "/* 1 */")), SyntaxKind.OpenBraceToken, SyntaxTriviaList.Empty); var wrapperWithOpenBrace = wrapper.WithOpenBraceToken(newOpenBraceToken); Assert.True(newOpenBraceToken.IsEquivalentTo(wrapperWithOpenBrace.OpenBraceToken)); }
public BqlFormatter(string endOfLineCharacter, bool useTabs, int tabSize, int indentSize) { EndOfLineTrivia = SyntaxTriviaList.Create(SyntaxFactory.EndOfLine(endOfLineCharacter)); if (useTabs && indentSize >= tabSize) { var items = Enumerable .Repeat(SyntaxFactory.Tab, indentSize / tabSize) .Append(SyntaxFactory.Whitespace(new string(' ', indentSize % tabSize))); IndentationTrivia = items.ToSyntaxTriviaList(); } else { IndentationTrivia = SyntaxTriviaList.Create(SyntaxFactory.Whitespace(new string(' ', indentSize))); } }
public override SyntaxNode VisitBlock(BlockSyntax node) { node = (BlockSyntax)base.VisitBlock(node); var switchStatements = node .Descendants <SwitchStatementSyntax>(); foreach (var switchStatement in switchStatements) { var governingExpression = switchStatement.Expression .WithTrailingTrivia(Space); var arms = switchStatement.Sections .Select(ConstructSwitchArm) .ToList(); var armsList = SeparatedList( arms, Enumerable.Repeat(arms, arms.Count - 1) .Select(a => Token( SyntaxTriviaList.Empty, SyntaxKind.CommaToken, SyntaxTriviaList.Create(EndOfLine(Environment.NewLine))))); var switchExpression = SwitchExpression( governingExpression, Token(SyntaxKind.SwitchKeyword).WithTrailingTrivia(EndOfLine(Environment.NewLine)), switchStatement.OpenBraceToken, armsList, switchStatement.CloseBraceToken.WithTrailingTrivia(SyntaxTriviaList.Empty)) .WithLeadingTrivia(switchStatement.GetLeadingTrivia()); var position = node.Statements.IndexOf(switchStatement); node = node.WithStatements( node.Statements .Remove(switchStatement) .Insert( position, ExpressionStatement(switchExpression) .WithTrailingTrivia(EndOfLine(Environment.NewLine)))); } return(node); }
public static SyntaxTriviaList GetClosestWhitespaceTrivia(this SyntaxNode node, bool leading) { var list = leading ? node.GetLeadingTrivia() : node.GetTrailingTrivia(); if (list.Count > 0) { var lastTrivia = list.Last(); switch ((SyntaxKind)lastTrivia.RawKind) { case SyntaxKind.WhitespaceTrivia: return(SyntaxTriviaList.Create(lastTrivia)); case SyntaxKind.EndOfLineTrivia: return(SyntaxTriviaList.Create(lastTrivia)); } } return(SyntaxTriviaList.Empty); }
public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span) as MethodDeclarationSyntax; if (node == null) { return; } Func <SyntaxToken, bool> isModifierToRemove = m => (m.IsKind(SyntaxKind.PrivateKeyword) || m.IsKind(SyntaxKind.ProtectedKeyword) || m.IsKind(SyntaxKind.InternalKeyword)); // Get trivia for new modifier var leadingTrivia = SyntaxTriviaList.Empty; var trailingTrivia = SyntaxTriviaList.Create(SyntaxFactory.Space); var removedModifiers = node.Modifiers.Where(isModifierToRemove); if (removedModifiers.Any()) { leadingTrivia = removedModifiers.First().LeadingTrivia; } else { // Method begins directly with return type, use its leading trivia leadingTrivia = node.ReturnType.GetLeadingTrivia(); } var newMethod = node.WithModifiers(SyntaxFactory.TokenList(new SyntaxTokenList() .Add(SyntaxFactory.Token(leadingTrivia, SyntaxKind.PublicKeyword, trailingTrivia)) .AddRange(node.Modifiers.ToArray().Where(m => !isModifierToRemove(m))))) .WithReturnType(node.ReturnType.WithoutLeadingTrivia()); var newRoot = root.ReplaceNode(node, newMethod); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Make method public", document.WithSyntaxRoot(newRoot)), diagnostic); }