コード例 #1
0
 private static SyntaxList<MemberDeclarationSyntax> MakeInterfaceSyntaxList(IEnumerable<MemberDeclarationSyntax> members)
 {
     var newMembers = ExtractInterfaceMembers(members).ToArray();
     var syntaxList = new SyntaxList<MemberDeclarationSyntax>();
     syntaxList = syntaxList.AddRange(newMembers);
     return syntaxList;
 }
コード例 #2
0
            public override SyntaxNode VisitBlock(BlockSyntax node)
            {
                BlockSyntax block = (BlockSyntax)base.VisitBlock(node);
                SyntaxList<StatementSyntax> curList = new SyntaxList<StatementSyntax>();
                Dictionary<string, SyntaxNode> replacements = new Dictionary<string, SyntaxNode>();

                int numbering = 1;
                foreach (var stmt in block.Statements)
                {
                    SyntaxList<StatementSyntax> preList = new SyntaxList<StatementSyntax>();
                    var stm = stmt.ReplaceNodes(nodes: stmt.DescendantNodes().Reverse(), computeReplacementNode: (original, origWithReplacedDesc) =>
                    {
                        Console.WriteLine(origWithReplacedDesc.GetType() + ": " + origWithReplacedDesc);

                        if (origWithReplacedDesc.IsKind(SyntaxKind.InvocationExpression)
                            || origWithReplacedDesc.IsKind(SyntaxKind.ObjectCreationExpression))
                        {
                            return SimplifyMethodAndConstructorInvocation(ref numbering, ref preList, original, origWithReplacedDesc);
                        }
                        return origWithReplacedDesc;
                    });
                    curList = curList.AddRange(preList);
                    curList = curList.Add(stm);
                }
                return block.WithStatements(curList);
            }
コード例 #3
0
        public sealed override async Task ComputeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
                             
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            var token = root.FindToken(diagnosticSpan.Start);

            if (token.IsKind(SyntaxKind.CatchKeyword))
            {
                var catchBlock = (CatchClauseSyntax)token.Parent;
                var tryStmt = (TryStatementSyntax)catchBlock.Parent;

                var throwStatement = SyntaxFactory.ThrowStatement();
                var newStatements = new SyntaxList<StatementSyntax>().Add(throwStatement);
                var newBlock = SyntaxFactory.Block().WithStatements(newStatements);
                var newCatchBlock = SyntaxFactory.CatchClause().WithBlock(newBlock).WithAdditionalAnnotations(Formatter.Annotation);

                var newRoot = root.ReplaceNode(catchBlock, newCatchBlock);

                context.RegisterFix(
                    CodeAction.Create("throw", context.Document.WithSyntaxRoot(newRoot)),
                    diagnostic);
            }
        }
コード例 #4
0
 public static XmlElementSyntax Element(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
 {
     return SyntaxFactory.XmlElement(
         SyntaxFactory.XmlElementStartTag(name),
         content,
         SyntaxFactory.XmlElementEndTag(name));
 }
        private static void ProcessUsingsAndReportDiagnostic(SyntaxList<UsingDirectiveSyntax> usings, SyntaxNodeAnalysisContext context)
        {
            string systemUsingDirectivesShouldBeBeforeThisName = null;
            for (var i = 1; i < usings.Count; i++)
            {
                var usingDirective = usings[i];

                if (usingDirective.Alias != null || !usingDirective.StaticKeyword.IsKind(SyntaxKind.None) || usingDirective.IsPrecededByPreprocessorDirective())
                {
                    continue;
                }

                if (usingDirective.IsSystemUsingDirective())
                {
                    if (systemUsingDirectivesShouldBeBeforeThisName != null)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, usingDirective.GetLocation(), usingDirective.Name.ToNormalizedString(), systemUsingDirectivesShouldBeBeforeThisName));
                        continue;
                    }

                    var previousUsing = usings[i - 1];

                    if (!previousUsing.IsSystemUsingDirective() || previousUsing.StaticKeyword.Kind() != SyntaxKind.None)
                    {
                        systemUsingDirectivesShouldBeBeforeThisName = previousUsing.Name.ToNormalizedString();
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, usingDirective.GetLocation(), usingDirective.Name.ToNormalizedString(), systemUsingDirectivesShouldBeBeforeThisName));
                    }
                }
            }
        }
コード例 #6
0
 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 static void ProcessUsings(SyntaxNodeAnalysisContext context, SyntaxList<UsingDirectiveSyntax> usings)
        {
            var usingDirectives = new List<UsingDirectiveSyntax>();
            var systemUsingDirectives = new List<UsingDirectiveSyntax>();

            foreach (var usingDirective in usings)
            {
                if (IsAliasOrStaticUsingDirective(usingDirective))
                {
                    continue;
                }

                if (usingDirective.IsPrecededByPreprocessorDirective())
                {
                    CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, usingDirectives);
                    CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, systemUsingDirectives);
                    usingDirectives.Clear();
                    systemUsingDirectives.Clear();
                }

                if (HasNamespaceAliasQualifier(usingDirective) || !usingDirective.IsSystemUsingDirective())
                {
                    usingDirectives.Add(usingDirective);
                }
                else
                {
                    systemUsingDirectives.Add(usingDirective);
                }
            }

            CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, usingDirectives);
            CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, systemUsingDirectives);
        }
        private static void CheckUsingDeclarations(SyntaxNodeAnalysisContext context, SyntaxList<UsingDirectiveSyntax> usingDirectives)
        {
            UsingDirectiveSyntax lastStaticUsingDirective = null;

            foreach (var usingDirective in usingDirectives)
            {
                if (usingDirective.IsPrecededByPreprocessorDirective())
                {
                    lastStaticUsingDirective = null;
                }

                if (usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword))
                {
                    if (lastStaticUsingDirective != null)
                    {
                        var firstName = lastStaticUsingDirective.Name.ToNormalizedString();
                        var secondName = usingDirective.Name.ToNormalizedString();

                        if (CultureInfo.InvariantCulture.CompareInfo.Compare(firstName, secondName, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth) > 0)
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Descriptor, lastStaticUsingDirective.GetLocation(), new[] { firstName, secondName }));
                            return;
                        }
                    }

                    lastStaticUsingDirective = usingDirective;
                }
            }
        }
コード例 #9
0
 internal static SyntaxList<UsingDirectiveSyntax> Sort(SyntaxList<UsingDirectiveSyntax> directives) =>
     SyntaxFactory.List(
         directives.
             OrderBy(x => x.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? 1 : x.Alias == null ? 0 : 2).
             ThenBy(x => x.Alias?.ToString()).
             ThenBy(x => x.Name.ToString())
             .Distinct(new AutoRest.Core.Utilities.EqualityComparer<UsingDirectiveSyntax>((a, b) => a.Name.ToString() == b.Name.ToString(), a=> 0 )));
コード例 #10
0
        private static bool TryGetThreadStaticAttribute(SyntaxList<AttributeListSyntax> attributeLists, SemanticModel semanticModel, out AttributeSyntax threadStaticAttribute)
        {
            threadStaticAttribute = null;

            if (!attributeLists.Any())
            {
                return false;
            }

            foreach (var attributeList in attributeLists)
            {
                foreach (var attribute in attributeList.Attributes)
                {
                    var attributeType = semanticModel.GetTypeInfo(attribute).Type;

                    if (attributeType != null &&
                        attributeType.ToDisplayString() == ThreadStaticAttributeName)
                    {
                        threadStaticAttribute = attribute;
                        return true;
                    }
                }
            }

            return false;
        }
コード例 #11
0
 public static XmlElementSyntax MultiLineElement(XmlNameSyntax name, string newLineText, SyntaxList<XmlNodeSyntax> content)
 {
     return SyntaxFactory.XmlElement(
         SyntaxFactory.XmlElementStartTag(name),
         content.Insert(0, NewLine(newLineText)).Add(NewLine(newLineText)),
         SyntaxFactory.XmlElementEndTag(name));
 }
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var document = context.Document;
            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
                return;
            var span = context.Span;
            if (!span.IsEmpty)
                return;
            var cancellationToken = context.CancellationToken;
            if (cancellationToken.IsCancellationRequested)
                return;
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            if (model.IsFromGeneratedCode(cancellationToken))
                return;
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            var token = root.FindToken(span.Start);
            var parameter = token.Parent as ParameterSyntax;

            if (parameter != null)
            {
                var ctor = parameter.Parent.Parent as ConstructorDeclarationSyntax;
                if (ctor == null)
                    return;

                context.RegisterRefactoring(
                    CodeActionFactory.Create(
                        parameter.Span,
                        DiagnosticSeverity.Info,
                        GettextCatalog.GetString("Initialize auto-property from parameter"),
                        t2 =>
                        {
                            var propertyName = GetPropertyName(parameter.Identifier.ToString());
                            var accessorDeclList = new SyntaxList<AccessorDeclarationSyntax>().Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))).Add(SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
                            var newProperty = SyntaxFactory.PropertyDeclaration(parameter.Type, propertyName)
                                .WithAccessorList(SyntaxFactory.AccessorList(accessorDeclList))
                                .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                                .WithAdditionalAnnotations(Formatter.Annotation);

                            var assignmentStatement = SyntaxFactory.ExpressionStatement(
                                SyntaxFactory.AssignmentExpression(
                                    SyntaxKind.SimpleAssignmentExpression,
                                    propertyName != parameter.Identifier.ToString() ? (ExpressionSyntax)SyntaxFactory.IdentifierName(propertyName) : SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(parameter.Identifier)),
                                    SyntaxFactory.IdentifierName(parameter.Identifier)
                                )
                            ).WithAdditionalAnnotations(Formatter.Annotation);

                            root = root.TrackNodes(ctor);
                            var newRoot = root.InsertNodesBefore(root.GetCurrentNode(ctor), new List<SyntaxNode>() {
                                newProperty
                            });
                            newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(ctor), ctor.WithBody(
                                ctor.Body.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { assignmentStatement }.Concat(ctor.Body.Statements)))
                            ));

                            return Task.FromResult(document.WithSyntaxRoot(newRoot));
                        })
                );
            }
        }
コード例 #13
0
 /// <summary>
 /// Retourne les assignations dans une listes d'expressions.
 /// </summary>
 /// <param name="expressions">Liste d'expressions.</param>
 /// <param name="modèleSémantique">Modèle sémantique.</param>
 /// <returns>La liste d'assignations.</returns>
 public static IEnumerable<StatementSyntax> TrouverAssignations(SyntaxList<StatementSyntax> expressions, SemanticModel modèleSémantique) =>
     expressions.Where(e =>
     {
         var expression = (e as ExpressionStatementSyntax)?.Expression as AssignmentExpressionSyntax;
         return expression?.Kind() == SyntaxKind.SimpleAssignmentExpression
             && modèleSémantique.GetSymbolInfo(expression.Left).Symbol?.Kind == SymbolKind.Field
             && modèleSémantique.GetSymbolInfo(expression.Right).Symbol?.Kind == SymbolKind.Parameter;
     });
コード例 #14
0
        private static SwitchSectionSyntax CreateSection(SwitchLabelSyntax label, StatementSyntax statement)
        {
            var labels = new SyntaxList<SwitchLabelSyntax>();
            labels = labels.Add(label);

            return SyntaxFactory.SwitchSection(
                labels, CreateSectionStatements(statement)
                );
        }
コード例 #15
0
 public static SyntaxList<AttributeListSyntax> AttributeListList(params AttributeSyntax[] attributes)
 {
     var list = new SyntaxList<AttributeListSyntax>();
     foreach (AttributeSyntax attributeSyntax in attributes)
     {
         list = list.Add(AttributeList(attributeSyntax));
     }
     return list;
 }
コード例 #16
0
ファイル: Match.cs プロジェクト: mpmedia/Excess
        private static StatementSyntax caseStatement(SyntaxList<StatementSyntax> statements)
        {
            Debug.Assert(statements.Any());

            if (statements.Count == 1)
                return statements.First();

            return CSharp.Block(statements);
        }
コード例 #17
0
        private static bool HasThreadStaticAttribute(SyntaxList<AttributeListSyntax> attributeLists, SemanticModel semanticModel)
        {
            if (!attributeLists.Any())
            {
                return false;
            }

            return attributeLists.Any(attributeList => 
                attributeList.Attributes.Any(attribute => semanticModel.GetTypeInfo(attribute).Type.Is(KnownType.System_ThreadStaticAttribute)));
        }
コード例 #18
0
        internal static PropertyDeclarationSyntax CreateAutoProperty(TypeSyntax type, string identifier, SyntaxList<AccessorDeclarationSyntax> accessors, SyntaxKind? accessibility)
        {
            var newProperty = SyntaxFactory.PropertyDeclaration(type, identifier)
                .WithAccessorList(SyntaxFactory.AccessorList(accessors));

            if (accessibility.HasValue)
                newProperty = newProperty.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(accessibility.Value)));

            return newProperty.WithAdditionalAnnotations(Formatter.Annotation);
        }
コード例 #19
0
        public static void Organize(
            SyntaxList<ExternAliasDirectiveSyntax> externAliasList,
            SyntaxList<UsingDirectiveSyntax> usingList,
            bool placeSystemNamespaceFirst,
            out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList,
            out SyntaxList<UsingDirectiveSyntax> organizedUsingList)
        {
            if (externAliasList.Count > 0 || usingList.Count > 0)
            {
                // Merge the list of usings and externs into one list.  
                // order them in the order that they were originally in the
                // file.
                var initialList = usingList.Cast<SyntaxNode>()
                                           .Concat(externAliasList)
                                           .OrderBy(n => n.SpanStart).ToList();

                if (!initialList.SpansPreprocessorDirective())
                {
                    // If there is a banner comment that precedes the nodes,
                    // then remove it and store it for later.
                    IEnumerable<SyntaxTrivia> leadingTrivia;
                    initialList[0] = initialList[0].GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out leadingTrivia);

                    var comparer = placeSystemNamespaceFirst
                        ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
                        : UsingsAndExternAliasesDirectiveComparer.NormalInstance;

                    var finalList = initialList.OrderBy(comparer).ToList();

                    // Check if sorting the list actually changed anything.  If not, then we don't
                    // need to make any changes to the file.
                    if (!finalList.SequenceEqual(initialList))
                    {
                        // Make sure newlines are correct between nodes.
                        EnsureNewLines(finalList);

                        // Reattach the banner.
                        finalList[0] = finalList[0].WithPrependedLeadingTrivia(leadingTrivia);

                        // Now split out the externs and usings back into two separate lists.
                        organizedExternAliasList = finalList.Where(t => t is ExternAliasDirectiveSyntax)
                                                            .Cast<ExternAliasDirectiveSyntax>()
                                                            .ToSyntaxList();
                        organizedUsingList = finalList.Where(t => t is UsingDirectiveSyntax)
                                                      .Cast<UsingDirectiveSyntax>()
                                                      .ToSyntaxList();
                        return;
                    }
                }
            }

            organizedExternAliasList = externAliasList;
            organizedUsingList = usingList;
        }
コード例 #20
0
        private ImmutableArray<BoundPatternSwitchSection> BindPatternSwitchSections(BoundExpression boundSwitchExpression, SyntaxList<SwitchSectionSyntax> sections, Binder originalBinder, ref DefaultSwitchLabelSyntax defaultLabel, DiagnosticBag diagnostics)
        {
            // Bind match sections
            var boundPatternSwitchSectionsBuilder = ArrayBuilder<BoundPatternSwitchSection>.GetInstance();
            foreach (var sectionSyntax in sections)
            {
                boundPatternSwitchSectionsBuilder.Add(BindPatternSwitchSection(boundSwitchExpression, sectionSyntax, originalBinder, ref defaultLabel, diagnostics));
            }

            return boundPatternSwitchSectionsBuilder.ToImmutableAndFree();
        }
 private static Dictionary<string, string> ExtractMembersFromClass(SyntaxList<MemberDeclarationSyntax> classMembers)
 {
     var members = new Dictionary<string, string>();
     foreach (var m in classMembers)
     {
         var name = "";
         if (m.IsKind(SyntaxKind.MethodDeclaration))
         {
             var eve = m as MethodDeclarationSyntax;
             name = eve.Identifier.Text;
         }
         if (m.IsKind(SyntaxKind.EventDeclaration))
         {
             var theEvent = m as EventDeclarationSyntax;
             name = theEvent.Identifier.Text;
         }
         if (m.IsKind(SyntaxKind.EventFieldDeclaration))
         {
             var eventField = m as EventFieldDeclarationSyntax;
             foreach (var v in eventField.Declaration.Variables)
             {
                 members.Add(v.Identifier.Text, eventField.Declaration.Type.ToString());
             }
         }
         if (m.IsKind(SyntaxKind.FieldDeclaration))
         {
             var field = m as FieldDeclarationSyntax;
             foreach (var v in field.Declaration.Variables)
             {
                 members.Add(v.Identifier.Text, field.Declaration.Type.ToString());
             }
         }
         if (m.IsKind(SyntaxKind.PropertyDeclaration))
         {
             var property = m as PropertyDeclarationSyntax;
             name = property.Identifier.Text;
         }
         if (m.IsKind(SyntaxKind.DelegateDeclaration))
         {
             var theDelegate = m as DelegateDeclarationSyntax;
             name = theDelegate.Identifier.Text;
         }
         if (m.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.EnumDeclaration, SyntaxKind.InterfaceDeclaration))
         {
             var type = m as BaseTypeDeclarationSyntax;
             name = type.Identifier.Text;
         }
         if (name != "")
         {
             members.Add(name, "");
         }
     }
     return members;
 }
コード例 #22
0
 /// <summary>
 /// Retourne les conditions sur les paramètres dans une listes d'expressions.
 /// </summary>
 /// <param name="expressions">Liste d'expressions.</param>
 /// <param name="paramètres">Les paramètres du constructeur.</param>
 /// <param name="modèleSémantique">Modèle sémantique.</param>
 /// <returns>La liste d'assignations.</returns>
 public static IEnumerable<IfStatementSyntax> TrouveConditionsParametres(SyntaxList<StatementSyntax> expressions, ParameterListSyntax paramètres, SemanticModel modèleSémantique) =>
     expressions
         .OfType<IfStatementSyntax>()
         .Where(e =>
             (e.Condition
                 ?.DescendantNodes()?.OfType<IdentifierNameSyntax>()
                 ?.Any(identifiant => modèleSémantique.GetSymbolInfo(identifiant).Symbol?.Kind == SymbolKind.Parameter)
             ?? false)
         && (e.Statement
                 ?.DescendantNodes()?.OfType<IdentifierNameSyntax>()
                 ?.All(identifiant => modèleSémantique.GetSymbolInfo(identifiant).Symbol?.Kind != SymbolKind.Field)
             ?? false));
コード例 #23
0
ファイル: LookupPosition.cs プロジェクト: riversky/roslyn
        internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList)
        {
            int count = attributesSyntaxList.Count;
            if (count == 0)
            {
                return false;
            }

            var startToken = attributesSyntaxList[0].OpenBracketToken;
            var endToken = attributesSyntaxList[count - 1].CloseBracketToken;
            return IsBetweenTokens(position, startToken, endToken);
        }
コード例 #24
0
        private static bool HasThreadStaticAttribute(SyntaxList<AttributeListSyntax> attributeLists, SemanticModel semanticModel)
        {
            if (!attributeLists.Any())
            {
                return false;
            }

            return attributeLists
                .Any(attributeList => attributeList.Attributes
                    .Select(attribute => semanticModel.GetTypeInfo(attribute).Type)
                    .Any(attributeType => attributeType != null &&
                                          attributeType.ToDisplayString() == ThreadStaticAttributeName));
        }
コード例 #25
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
            SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>();
            foreach (MemberDeclarationSyntax member in node.Members)
            {
                if (member.CSharpKind() == SyntaxKind.PropertyDeclaration)
                {
                    PropertyDeclarationSyntax prop = (PropertyDeclarationSyntax)member;
                    SyntaxList<AccessorDeclarationSyntax> newAccessors = new SyntaxList<AccessorDeclarationSyntax>();
                    bool implementfield = false;
                    foreach (AccessorDeclarationSyntax accessor in prop.AccessorList.Accessors)
                    {
                        if (accessor.Body == null)
                        {
                            switch (accessor.CSharpKind())
                            {
                                case SyntaxKind.GetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName("_" + prop.Identifier.ValueText)))));
                                    break;
                                case SyntaxKind.SetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(SyntaxFactory.Block(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName("_" + prop.Identifier.ValueText), SyntaxFactory.IdentifierName("value"))))));
                                    break;
                                default:
                                    newAccessors = newAccessors.Add(accessor);
                                    break;
                            }
                        }
                        else
                        {
                            newAccessors = newAccessors.Add(accessor);
                        }
                    }
                    if (implementfield)
                    {
                        SeparatedSyntaxList<VariableDeclaratorSyntax> variables = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
                        variables = variables.Add(SyntaxFactory.VariableDeclarator("_" + prop.Identifier.ValueText));
                        newMembers = newMembers.Add(SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(prop.Type, variables)).WithModifiers(prop.Modifiers));
                    }

                    newMembers = newMembers.Add(prop.WithAccessorList(prop.AccessorList.WithAccessors(newAccessors)));
                }
                else
                {
                    newMembers = newMembers.Add(member);
                }
            }
            return node.WithMembers(newMembers);
        }
        private static void HandleUsingDirectives(SyntaxNodeAnalysisContext context, SyntaxList<UsingDirectiveSyntax> usingDirectives)
        {
            if (usingDirectives.Count == 0)
            {
                return;
            }

            var usingAliasNames = new List<string>();
            UsingDirectiveSyntax prevAliasUsingDirective = null;

            foreach (var usingDirective in usingDirectives)
            {
                if (usingDirective.IsPrecededByPreprocessorDirective())
                {
                    usingAliasNames.Clear();
                    prevAliasUsingDirective = null;
                }

                // only interested in using alias directives
                if (usingDirective.Alias?.Name?.IsMissing != false)
                {
                    continue;
                }

                string currentAliasName = usingDirective.Alias.Name.Identifier.ValueText;
                if (prevAliasUsingDirective != null)
                {
                    string currentLowerInvariant = currentAliasName.ToLowerInvariant();
                    string prevAliasName = prevAliasUsingDirective.Alias.Name.Identifier.ValueText;
                    if (string.CompareOrdinal(prevAliasName.ToLowerInvariant(), currentLowerInvariant) > 0)
                    {
                        // Find alias before which should be placed current alias
                        foreach (string aliasName in usingAliasNames)
                        {
                            if (string.CompareOrdinal(aliasName.ToLowerInvariant(), currentLowerInvariant) > 0)
                            {
                                prevAliasName = aliasName;
                                break;
                            }
                        }

                        // Using alias directive for '{currentAliasName}' must appear before using alias directive for '{prevAliasName}'
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, usingDirective.GetLocation(), currentAliasName, prevAliasName));
                        return;
                    }
                }

                usingAliasNames.Add(currentAliasName);
                prevAliasUsingDirective = usingDirective;
            }
        }
コード例 #27
0
            protected bool RequiresNullChecks(SyntaxList<AttributeListSyntax> attrs)
            {
                var symbols = attrs.Select(a => _model.GetSymbolInfo(a));
                foreach (var symbol in symbols)
                {
                    var attributeClassName = symbol.Symbol?.ContainingNamespace + "." + symbol.Symbol?.ContainingType;
                    if (attributeClassName == IGNORE_NULL_CHECKS_ATTRIBUTE)
                    {
                        return false;
                    }
                }

                return true;
            }
コード例 #28
0
ファイル: EventGenerator.cs プロジェクト: XieShuquan/roslyn
        private static MemberDeclarationSyntax BeforeMember(
            SyntaxList<MemberDeclarationSyntax> members,
            MemberDeclarationSyntax eventDeclaration)
        {
            // If it's a field style event, then it goes before everything else if we don't have any
            // existing fields/events.
            if (eventDeclaration.Kind() == SyntaxKind.FieldDeclaration)
            {
                return members.FirstOrDefault();
            }

            // Otherwise just place it before the methods.
            return FirstMethod(members);
        }
コード例 #29
0
 public static PropertyDeclarationSyntax PropertyDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList, ArrowExpressionClauseSyntax expressionBody, EqualsValueClauseSyntax initializer, SyntaxToken semicolonToken)
 {
     return PropertyDeclaration(
         attributeLists,
         modifiers,
         refKeyword: default(SyntaxToken),
         type: type,
         explicitInterfaceSpecifier: explicitInterfaceSpecifier, 
         identifier: identifier, 
         accessorList: accessorList, 
         expressionBody: expressionBody, 
         initializer: initializer, 
         semicolonToken: semicolonToken);
 }
コード例 #30
0
 public static TypeDeclarationSyntax TypeDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributes, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, BaseListSyntax baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
 {
     switch (kind)
     {
         case SyntaxKind.ClassDeclaration:
             return SyntaxFactory.ClassDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken);
         case SyntaxKind.StructDeclaration:
             return SyntaxFactory.StructDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken);
         case SyntaxKind.InterfaceDeclaration:
             return SyntaxFactory.InterfaceDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken);
         default:
             throw new ArgumentException("kind");
     }
 }
コード例 #31
0
 public LocalFunctionStatementSyntax Update(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
 {
     return(Update(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken));