public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var symbol = model.GetDeclaredSymbol(node);
            VisitDeclaration(symbol, node.Span);

            base.VisitClassDeclaration(node);
        }
        protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var newTypeDeclaration = (TypeDeclarationSyntax)base.VisitClassDeclaration(node);

            if (_fields.Count > 0 || _methods.Count > 0)
            {
                var members = new List<MemberDeclarationSyntax>(newTypeDeclaration.Members);
                members.InsertRange(0, _methods);
                members.InsertRange(0, _fields);

                return ((ClassDeclarationSyntax)newTypeDeclaration).Update(
                    newTypeDeclaration.Attributes,
                    newTypeDeclaration.Modifiers,
                    newTypeDeclaration.Keyword,
                    newTypeDeclaration.Identifier,
                    newTypeDeclaration.TypeParameterListOpt,
                    newTypeDeclaration.BaseListOpt,
                    newTypeDeclaration.ConstraintClauses,
                    newTypeDeclaration.OpenBraceToken,
                    Syntax.List(members.AsEnumerable()),
                    newTypeDeclaration.CloseBraceToken,
                    newTypeDeclaration.SemicolonTokenOpt);
            }

            return newTypeDeclaration;
        }
        private ClassDeclarationSyntax MoveField(ClassDeclarationSyntax node)
        {
            //SyntaxList is immutable, so we need a regular list of members, to add our field to
            var list=node.Members.ToList<MemberDeclarationSyntax>();

            //change visibility to protected so that it can still be used in child classes
            var field = fds.Update(fds.Attributes,
                 Syntax.TokenList(Syntax.Token(SyntaxKind.ProtectedKeyword)),
                 fds.Declaration,
                 fds.SemicolonToken);
            //add field as the first member in the parent class
            list.Insert(0,field);

            //if a property for the field exists, move it to parent class as well
            if (prop!=null)
                list.Add(prop);

            //make a SyntaxList out of the list
            var syntaxlist = Syntax.List<MemberDeclarationSyntax>(list.ToArray<MemberDeclarationSyntax>());

            //"update" the class node - create another syntax tree with a changed node
            var newclass= node.Update( node.Attributes,
                node.Modifiers,
                node.Keyword,
                node.Identifier,
                node.TypeParameterListOpt,
                node.BaseListOpt,
                node.ConstraintClauses,
                node.OpenBraceToken,
                syntaxlist,
                node.CloseBraceToken,
                node.SemicolonTokenOpt);
            return newclass;
        }
        /// <summary>
        /// Checks if any property in the class given as parameter has a getter for the field we are moving.
        /// </summary>
        /// <param name="node">Syntax node of the class the field belongs to.</param>
        /// <param name="semanticModel">Semantic model for the code we are processing.</param>
        /// <returns></returns>
        private PropertyDeclarationSyntax getProperty(ClassDeclarationSyntax node, SemanticModel semanticModel)
        {
            foreach (var p in node.Members.Where(m => m.Kind == SyntaxKind.PropertyDeclaration))
            {
                var property = p as PropertyDeclarationSyntax;

                var accessors = property.AccessorList.Accessors;
                var getter = accessors.FirstOrDefault(ad => ad.Kind == SyntaxKind.GetAccessorDeclaration);

                var statements = getter.BodyOpt.Statements;
                if (statements.Count != 0)
                {
                    var returnStatement = statements.FirstOrDefault() as ReturnStatementSyntax;
                    if (returnStatement != null && returnStatement.ExpressionOpt != null)
                    {
                        var semanticInfo = document.GetSemanticModel().GetSemanticInfo(returnStatement.ExpressionOpt);
                        var fieldSymbol = semanticInfo.Symbol as FieldSymbol;

                        if (fieldSymbol != null && fieldSymbol == semanticModel.GetDeclaredSymbol(field))
                        {
                            return property;
                        }
                    }
                }
            }

            return null;
        }
示例#5
0
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            if (node.Attributes.Any(a => a.DescendantNodes().OfType<AttributeSyntax>().Any(s => s.Name.GetText() == typeof(JavaScript).Name)))
                Classes.Add(node);

            base.VisitClassDeclaration(node);
        }
        public ClassInfo GetClassInfo(ClassDeclarationSyntax classDeclaration)
        {
            _walker.Visit(classDeclaration);

            ClassInfo classInfo = new ClassInfo(classDeclaration, _semanticModel, _semanticModel.GetDeclaredSymbol(classDeclaration));

            classInfo.Locks.AddRange(_walker.Locks);
            classInfo.GuardedFields.AddRange(_walker.GuardedFields);
            classInfo.Members.AddRange(_walker.Members);

            foreach (LockInfo lockInfo in classInfo.Locks)
            {
                lockInfo.Parent = classInfo;
            }

            foreach (GuardedFieldInfo fieldInfo in classInfo.GuardedFields)
            {
                fieldInfo.Parent = classInfo;
            }

            foreach (MemberInfo memberInfo in classInfo.Members)
            {
                memberInfo.Parent = classInfo;
            }

            return classInfo;
        }
 public FieldMover(SemanticModel semanticModel, Symbol symbol, FieldDeclarationSyntax fds, PropertyDeclarationSyntax prop,  ClassDeclarationSyntax parent)
 {
     this.semanticModel = semanticModel;
     this.parent = parent;
     this.fieldSymbol = symbol;
     this.fds = fds;
     this.prop = prop;
 }
示例#8
0
 public CallGraphTest()
 {
     source = FileUtil.ReadAllText(path);
     tree = ASTUtil.GetSyntaxTreeFromSource(source);
     classDeclaration = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().
         First(c => c.Identifier.Value.Equals("CallGraphTest"));
     graph = new CallGraphBuilder(classDeclaration, tree).BuildCallGraph();
 }
 protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     if (node == parent)
     {
         //show a pop-up with how the refactoring will look
         return CodeActionAnnotations.FormattingAnnotation.AddAnnotationTo(
             MoveField(node));
     }
     return base.VisitClassDeclaration(node);
 }
        public CodeAction(ICodeActionEditFactory editFactory, IDocument document, FieldDeclarationSyntax member, ClassDeclarationSyntax parent)
        {
            this.editFactory = editFactory;
            this.document = document;
            this.field = member;
            this.parentClass = parent;

            this.Description = "Move member to parent class";
            this.Icon = null;
        }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var visitClassDeclaration = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);

            visitClassDeclaration = visitClassDeclaration.AddMembers(delegateDeclarations.ToArray())
                                                         .AddMembers(methodDeclarations.ToArray());

            var identifier = Syntax.Identifier(node.Identifier.ValueText + "Dynamic");

            return visitClassDeclaration.WithIdentifier(identifier);
        }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
            MethodDeclarationSyntax prector = Syntax.MethodDeclaration(Syntax.PredefinedType(Syntax.Token(SyntaxKind.VoidKeyword)), ".prector");
            List<StatementSyntax> Initializers = new List<StatementSyntax>();
            foreach (MemberDeclarationSyntax member in node.Members)
            {
                if (member.Kind == SyntaxKind.FieldDeclaration)
                {
                    FieldDeclarationSyntax fds = (FieldDeclarationSyntax)member;
                    foreach (VariableDeclaratorSyntax vds in fds.Declaration.Variables)
                    {
                        if (vds.Initializer != null)
                        {
                            Initializers.Add(Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName(vds.Identifier), vds.Initializer.Value)));
                        }
                    }
                }
            }

            if (Initializers.Count == 0)
                return node;

            int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax));

            prector = prector.AddBodyStatements(Initializers.ToArray());
            node = node.AddMembers(prector);

            if (constructors == 0)
            {
                ConstructorDeclarationSyntax ctor = Syntax.ConstructorDeclaration(node.Identifier);
                ctor = ctor.AddBodyStatements(Syntax.ExpressionStatement(Syntax.InvocationExpression(Syntax.IdentifierName(".prector"))));
                ctor = ctor.AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword));
                return node.AddMembers(ctor);
            }

            SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>();

            foreach (MemberDeclarationSyntax member in node.Members)
            {
                if (member.Kind == SyntaxKind.ConstructorDeclaration)
                {
                    newMembers = newMembers.Add((MemberDeclarationSyntax)ConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member));
                }
                else
                {
                    newMembers = newMembers.Add(member);
                }
            }

            return node.WithMembers(newMembers);
        }
        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.Kind == 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.Kind)
                            {
                                case SyntaxKind.GetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(Syntax.Block(Syntax.ReturnStatement(Syntax.IdentifierName("_" + prop.Identifier.ValueText)))));
                                    break;
                                case SyntaxKind.SetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(Syntax.Block(Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName("_" + prop.Identifier.ValueText), Syntax.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(Syntax.VariableDeclarator("_" + prop.Identifier.ValueText));
                        newMembers = newMembers.Add(Syntax.FieldDeclaration(Syntax.VariableDeclaration(prop.Type, variables)));
                    }

                    newMembers = newMembers.Add(prop.WithAccessorList(prop.AccessorList.WithAccessors(newAccessors)));
                }
                else
                {
                    newMembers = newMembers.Add(member);
                }
            }
            return node.WithMembers(newMembers);
        }
        private ClassDeclarationSyntax GetParentClass(SyntaxTree tree, ClassDeclarationSyntax theclass)
        {
            if (theclass != null && theclass.BaseListOpt!=null)
            {
                var parent = theclass.BaseListOpt.GetLastToken();
                if (parent != null)
                {
                    var node = tree.Root.DescendentNodes().OfType<ClassDeclarationSyntax>().Where(p => p.Identifier.GetText() == parent.GetText()).First();
                    return node;
                }
            }

            return null;
        }
示例#15
0
        private BeginEndRegionTrivia GetRegion(ClassDeclarationSyntax classDeclaration, string name)
        {
            using (var triviaEnumerator = classDeclaration.DescendantTrivia().GetEnumerator())
                while (triviaEnumerator.MoveNext())
                {
                    var beginRegionTrivia = triviaEnumerator.Current;

                    if (SyntaxKind.RegionDirective == beginRegionTrivia.Kind)
                    {
                        var text = beginRegionTrivia.GetText().Trim();

                        if (text.Trim().EndsWith(name))
                        {
                            // The #region is found, now looking for the matching #endregion
                            var prev = beginRegionTrivia;
                            var depth = 0;
                            while (triviaEnumerator.MoveNext())
                            {
                                var endRegionTrivia = triviaEnumerator.Current;

                                // Handle nested #regions...
                                if (SyntaxKind.RegionDirective == endRegionTrivia.Kind)
                                {
                                    depth++;
                                }
                                else if (SyntaxKind.EndRegionDirective == endRegionTrivia.Kind)
                                {
                                    if (0 == depth)
                                        return new BeginEndRegionTrivia()
                                        {
                                            beginRegionTrivia = beginRegionTrivia,
                                            endRegionTrivia = prev, // this places the text within the whitespace
                                            whiteSpace = prev.GetText()
                                        };
                                    else
                                        depth--;
                                }

                                prev = endRegionTrivia;
                            }
                        }
                    }
                }

            // No matching #region and #endregion found
            return null;
        }
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            LS2IL.TypeExtraInfo.ClassMetadataGenerator wasClass = CurrentClass;

            NamedTypeSymbol s = Model.GetDeclaredSymbol(node);

            TypeExtraInfo tei = Chunk.AddTypeExtraInfo(s, Model);
            CurrentClass = tei.MetadataGenerator;

            foreach (MemberDeclarationSyntax mds in node.Members)
            {
                CurrentClass.AddMember(mds);
            }

            base.VisitClassDeclaration(node);
            CurrentClass = wasClass;
        }
        protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var callsTruthiness =
                node.DescendentNodes().OfType<InvocationExpressionSyntax>()
                .Select(i => i.Expression).OfType<IdentifierNameSyntax>()
                .Any(a => a.PlainName == "__Truthy");

            var allMethods = node.DescendentNodes().OfType<MethodDeclarationSyntax>().ToList();

            if (callsTruthiness)
            {
                SyntaxList<MemberDeclarationSyntax> newMembers = Syntax.List(node.Members.Union(new[] { TruthyMethod }));

                return node.Update(node.Attributes, node.Modifiers, node.Keyword, node.Identifier, node.TypeParameterListOpt, node.BaseListOpt, node.ConstraintClauses, node.OpenBraceToken, newMembers, node.CloseBraceToken, node.SemicolonTokenOpt);
            }

            return base.VisitClassDeclaration(node);
        }
示例#18
0
        public static ClassDeclarationSyntax ClassDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), string identifier = null, TypeParameterListSyntax typeParameterList = null, BaseListSyntax baseList = null, IEnumerable<TypeParameterConstraintClauseSyntax> constraintClauses = null, IEnumerable<MemberDeclarationSyntax> members = null)
        {
            var result = new ClassDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            result.Identifier = identifier;
            result.TypeParameterList = typeParameterList;
            result.BaseList = baseList;
            if (constraintClauses != null)
                result.ConstraintClauses.AddRange(constraintClauses);
            if (members != null)
                result.Members.AddRange(members);

            return result;
        }
 public InClassExtractMethodDetector(ClassDeclarationSyntax classBefore,
     ClassDeclarationSyntax classAfter)
 {
     this.classBefore = classBefore;
     this.classAfter = classAfter;
     logger = NLoggerUtil.GetNLogger(typeof(InClassExtractMethodDetector));
 }
示例#20
0
 public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     return(VisitTypeDeclaration(node));
 }
 public static bool IsSealed(this ClassDeclarationSyntax classDeclaration)
 {
     return(classDeclaration.Modifiers
            .Any(x => x.IsKind(SyntaxKind.SealedKeyword)));
 }
        private void Test(string expected, params AttributeListSyntax[] attributes)
        {
            var node = new ClassDeclarationSyntax
            {
                Identifier = "Class"
            };

            node.AttributeLists.AddRange(attributes);

            Test(
                expected +
            @"class Class
            {
            }
            ",
                node
            );
        }
示例#23
0
 public override void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     sb.AppendLine(node.Keyword.ValueText + " " + node.Identifier.ValueText);
     base.VisitClassDeclaration(node);
 }
 /// <summary>
 /// Checks for special properties.
 /// </summary>
 /// <param name="state">State</param>
 /// <param name="compilation">Compilation</param>
 protected override void CheckForSpecialProperties(ClassDeclarationSyntax state,
                                                   CodeAnalysis.Compilation compilation)
 {
     this.CheckForLivenessAttribute(state, compilation);
 }
 /// <summary>
 /// Returns true if the given class declaration is a state.
 /// </summary>
 /// <param name="compilation">Compilation</param>
 /// <param name="classDecl">Class declaration</param>
 /// <returns>Boolean value</returns>
 protected override bool IsState(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl)
 {
     return(Querying.IsMachineState(compilation, classDecl));
 }
 //
 // Summary:
 //     Called when the visitor visits a ClassDeclarationSyntax node.
 public virtual void VisitClassDeclaration(ClassDeclarationSyntax node);
 public override void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     VisitTypeDeclarationImpl(node, _model.GetDeclaredSymbol(node));
     base.VisitClassDeclaration(node);
 }
示例#28
0
 public IEnumerable <MethodDeclarationSyntax> GetMethodsFromClass(
     ClassDeclarationSyntax @class,
     params Modifier[] modifiers) => GetMembersFromClass <MethodDeclarationSyntax>(@class, modifiers);
示例#29
0
        public static async Task <Solution> CreateMatchMethods(
            Document document, ClassDeclarationSyntax classSyntax, SyntaxNode root, CancellationToken cancellationToken)
        {
            AttributeSyntax CreateMatchMethodAttribute(SyntaxAnnotation syntaxAnnotation)
            {
                return(SyntaxFactory.Attribute(
                           SyntaxFactory.IdentifierName("CreateMatchMethods"),
                           SyntaxFactory.AttributeArgumentList(
                               SyntaxFactory.SeparatedList(new[]
                {
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.TypeOfExpression(
                            SyntaxFactory.IdentifierName(classSyntax.Identifier.Text))),
                }))).WithAdditionalAnnotations(syntaxAnnotation));
            }

            var originalSolution = document.Project.Solution;

            var staticExtensionsClassName = classSyntax.Identifier.Text + "ExtensionMethods";

            var annotationForAttributeSyntax = new SyntaxAnnotation();


            var hostClass =
                classSyntax.Parent.ChildNodes().OfType <ClassDeclarationSyntax>()
                .Where(x => x.IsStatic() && x.Identifier.Text == staticExtensionsClassName)
                .FirstOrNoValue();

            if (hostClass.HasNoValue)
            {
                var newHostClass =
                    Utilities
                    .CreateEmptyPublicStaticClass(staticExtensionsClassName)
                    .WithAttributeLists(SyntaxFactory.List(new[]
                {
                    SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[]
                    {
                        CreateMatchMethodAttribute(annotationForAttributeSyntax),
                    }))
                }));

                var newSolutionWithHostClassAdded = originalSolution.WithDocumentSyntaxRoot(document.Id,
                                                                                            root.InsertNodesAfter(classSyntax, new[] { newHostClass }));

                var newDocument = newSolutionWithHostClassAdded.GetDocument(document.Id);

                var newDocumentRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                return(await CreateMatchMethods(
                           newDocument,
                           (AttributeSyntax)newDocumentRoot.GetAnnotatedNodes(annotationForAttributeSyntax).Single(),
                           newDocumentRoot,
                           cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var hostClassValue    = hostClass.GetValue();
                var existingAttribute = hostClassValue.AttributeLists.SelectMany(x => x.Attributes)
                                        .FirstOrNoValue(Utilities.IsCreateMatchMethodsAttribute);

                if (existingAttribute.HasNoValue)
                {
                    var updatedHostClass = hostClassValue.AddAttributeLists(SyntaxFactory.AttributeList(
                                                                                SyntaxFactory.SeparatedList(new[]
                    {
                        CreateMatchMethodAttribute(annotationForAttributeSyntax),
                    })));


                    var newSolutionWithHostClassAdded = originalSolution.WithDocumentSyntaxRoot(document.Id,
                                                                                                root.ReplaceNode(hostClassValue, updatedHostClass));

                    var newDocument = newSolutionWithHostClassAdded.GetDocument(document.Id);

                    var newDocumentRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                    return(await CreateMatchMethods(
                               newDocument,
                               (AttributeSyntax)newDocumentRoot.GetAnnotatedNodes(annotationForAttributeSyntax).Single(),
                               newDocumentRoot,
                               cancellationToken).ConfigureAwait(false));
                }
                else
                {
                    return(await CreateMatchMethods(
                               document,
                               existingAttribute.GetValue(),
                               root,
                               cancellationToken).ConfigureAwait(false));
                }
            }
        }
示例#30
0
        private async Task <Document> AddMixinAttribute(CodeRefactoringContext context, ClassDeclarationSyntax @class, TypeSyntax baseType, CancellationToken ct)
        {
            var root = await context.Document.GetSyntaxRootAsync(ct).ConfigureAwait(false);

            var newClass = @class.WithAttributeLists(@class.AttributeLists.Add(
                                                         AttributeList(
                                                             SeparatedList(new[] {
                Attribute(IdentifierName(nameof(Mixin)),
                          AttributeArgumentList(SeparatedList(new[] { AttributeArgument(TypeOfExpression(baseType.WithoutTrivia())) }))
                          )
            })
                                                             ).WithAdditionalAnnotations(Formatter.Annotation)
                                                         ));

            root = root.ReplaceNode(@class, newClass);

            return(context.Document.WithSyntaxRoot(root));
        }
示例#31
0
 public static GenericInfo GenericInfo(ClassDeclarationSyntax classDeclaration)
 {
     return(Syntax.GenericInfo.Create(classDeclaration));
 }
示例#32
0
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var model = CreateModel(node);

            Models.Add(model);
        }
示例#33
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, ClassDeclarationSyntax classDeclaration)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddTypeParameter))
            {
                AddTypeParameterRefactoring.ComputeRefactoring(context, classDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExtractTypeDeclarationToNewFile))
            {
                ExtractTypeDeclarationToNewFileRefactoring.ComputeRefactorings(context, classDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.GenerateBaseConstructors) &&
                classDeclaration.Identifier.Span.Contains(context.Span))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                List <IMethodSymbol> constructors = GenerateBaseConstructorsRefactoring.GetMissingBaseConstructors(classDeclaration, semanticModel, context.CancellationToken);

                if (constructors?.Count > 0)
                {
                    context.RegisterRefactoring(
                        (constructors.Count == 1) ? "Generate base constructor" : "Generate base constructors",
                        cancellationToken => GenerateBaseConstructorsRefactoring.RefactorAsync(context.Document, classDeclaration, constructors.ToArray(), semanticModel, cancellationToken));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ImplementIEquatableOfT))
            {
                await ImplementIEquatableOfTRefactoring.ComputeRefactoringAsync(context, classDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SortMemberDeclarations) &&
                classDeclaration.BracesSpan().Contains(context.Span))
            {
                SortMemberDeclarationsRefactoring.ComputeRefactoring(context, classDeclaration);
            }
        }
        static Controller AnalyzeApiControllerActions(
            Compilation compilation,
            ClassDeclarationSyntax classDeclaration,
            SemanticModel semanticModel,
            Dictionary <string, Compilation> referencedSymbols)
        {
            var routePrefixSymbol = compilation.GetTypeByMetadataName("System.Web.Http.RoutePrefixAttribute");

            // Get the class and containing namespace symbols.

            var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);

            var namespaceSymbol = classSymbol.ContainingNamespace;

            var controller = new Controller
            {
                DocumentationCommentId = classSymbol.GetDocumentationCommentId(),

                Namespace = classSymbol.ContainingNamespace?.ToFullName(),

                Name = classSymbol.Name,

                Actions = new List <Action>()
            };

            // Go through the class's XML comments, if any.

            var classCommentXml = classSymbol.GetDocumentationCommentXml();

            if (!string.IsNullOrWhiteSpace(classCommentXml))
            {
                var classCommentRoot = XElement.Parse(classCommentXml);

                var summary = classCommentRoot.Element("summary");

                if (summary != null)
                {
                    foreach (var cref in summary.GetCrefs())
                    {
                        if (!referencedSymbols.ContainsKey(cref))
                        {
                            referencedSymbols.Add(cref, compilation);
                        }
                    }

                    controller.Summary = summary.ToMarkup();
                }

                var remarks = classCommentRoot.Element("remarks");

                if (remarks != null)
                {
                    foreach (var cref in remarks.GetCrefs())
                    {
                        if (!referencedSymbols.ContainsKey(cref))
                        {
                            referencedSymbols.Add(cref, compilation);
                        }
                    }

                    controller.Remarks = remarks.ToMarkup();
                }
            }

            // Go through the class's attributes, if any.

            var routePrefix = string.Empty;

            foreach (var attributeList in classDeclaration.AttributeLists)
            {
                foreach (var attribute in attributeList.Attributes)
                {
                    // For each attribute, try to pull a recognized value.

                    var attributeTypeInfo = semanticModel.GetTypeInfo(attribute);

                    if (attributeTypeInfo.Type.MetadataName == routePrefixSymbol.MetadataName)
                    {
                        var routePrefixArgument = attribute
                                                  .ArgumentList
                                                  .Arguments
                                                  .Single()
                                                  .Expression as LiteralExpressionSyntax;

                        routePrefix = routePrefixArgument.Token.ValueText + "/";
                    }
                }
            }

            // Get all public methods.

            var actionMethodDeclarations = classDeclaration
                                           .DescendantNodes()
                                           .Where(n => n.IsKind(SyntaxKind.MethodDeclaration))
                                           .Cast <MethodDeclarationSyntax>()
                                           .Where(m => m.Modifiers.Any(mo => mo.ValueText == "public"))
                                           .ToList();

            foreach (var actionMethodDeclaration in actionMethodDeclarations)
            {
                var action = AnalyzeActionMethod(
                    compilation,
                    semanticModel,
                    actionMethodDeclaration,
                    referencedSymbols,
                    routePrefix);

                if (!string.IsNullOrWhiteSpace(action.Method))
                {
                    controller.Actions.Add(action);
                }
            }

            return(controller);
        }
示例#35
0
        private async Task <Document> HandleMacroInsideClass(Document document, Location diagnosticLocation, CancellationToken cancellationToken, ClassDeclarationSyntax block)
        {
            foreach (var statement in block.Members)
            {
                var triviaList = statement.GetLeadingTrivia();
                if (Contains(statement.GetLocation(), diagnosticLocation) &&
                    TryGetMacroDescriptor(triviaList, out var macroDescriptor, out var leadingTrivia))
                {
                    if (registeredMacros.TryGetValue(macroDescriptor.MacroName, out var macro))
                    {
                        var macroContext = await CreateMacroContext(document, diagnosticLocation, cancellationToken);

                        var newContent = TransformContent(macro, macroDescriptor, macroContext);
                        var syntaxTree = SyntaxFactory.ParseSyntaxTree(newContent);
                        var newBlock   = block.ReplaceNode(statement, syntaxTree.GetRoot().ChildNodes().Concat(new SyntaxNode[]
                        {
                            statement.WithLeadingTrivia(triviaList.LastOrDefault())
                        }));
                        return(await ReplaceNodes(document, block, newBlock.WithAdditionalAnnotations(Formatter.Annotation),
                                                  cancellationToken));
                    }
                    return(document);
                }
            }

            {
                if (Contains(block.CloseBraceToken.GetLocation(), diagnosticLocation) &&
                    TryGetMacroDescriptor(block.CloseBraceToken.LeadingTrivia, out var macroDescriptor1, out var leadingTrivia))
                {
                    if (registeredMacros.TryGetValue(macroDescriptor1.MacroName, out var macro))
                    {
                        var macroContext = await CreateMacroContext(document, diagnosticLocation, cancellationToken);

                        var newContent = TransformContent(macro, macroDescriptor1, macroContext);
                        var syntaxTree = SyntaxFactory.ParseSyntaxTree(newContent);
                        var newBlock   =
                            block.AddMembers(syntaxTree.GetRoot().ChildNodes().OfType <MemberDeclarationSyntax>().ToArray());
                        newBlock = newBlock.WithCloseBraceToken(
                            block.CloseBraceToken.WithLeadingTrivia(block.CloseBraceToken.LeadingTrivia.LastOrDefault()));
                        return(await ReplaceNodes(document, block, newBlock.WithAdditionalAnnotations(Formatter.Annotation),
                                                  cancellationToken));
                    }
                }
            }
            return(document);
        }
示例#36
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out BaseListSyntax baseList))
            {
                return;
            }

            if (baseList.ContainsDiagnostics)
            {
                return;
            }

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                switch (diagnostic.Id)
                {
                case CompilerDiagnosticIdentifiers.BaseClassMustComeBeforeAnyInterface:
                {
                    if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface))
                    {
                        return;
                    }

                    SeparatedSyntaxList <BaseTypeSyntax> types = baseList.Types;

                    if (types.Count > 1)
                    {
                        BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span));

                        CodeAction codeAction = CodeAction.Create(
                            $"Move '{baseType.Type}' before any interface",
                            cancellationToken =>
                            {
                                BaseTypeSyntax firstType = types[0];

                                SeparatedSyntaxList <BaseTypeSyntax> newTypes = types
                                                                                .Replace(baseType, firstType.WithTriviaFrom(baseType))
                                                                                .ReplaceAt(0, baseType.WithTriviaFrom(firstType));

                                BaseListSyntax newBaseList = baseList.WithTypes(newTypes);

                                return(context.Document.ReplaceNodeAsync(baseList, newBaseList, cancellationToken));
                            },
                            GetEquivalenceKey(diagnostic));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }

                case CompilerDiagnosticIdentifiers.StaticClassCannotDeriveFromType:
                case CompilerDiagnosticIdentifiers.StaticClassCannotImplementInterfaces:
                {
                    if (!(baseList.Parent is ClassDeclarationSyntax classDeclaration))
                    {
                        break;
                    }

                    if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeClassNonStatic))
                    {
                        ModifiersCodeFixRegistrator.RemoveModifier(
                            context,
                            diagnostic,
                            classDeclaration,
                            SyntaxKind.StaticKeyword,
                            title: "Make class non-static",
                            additionalKey: CodeFixIdentifiers.MakeClassNonStatic);
                    }

                    if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveBaseList))
                    {
                        CodeAction codeAction = CodeAction.Create(
                            "Remove base list",
                            cancellationToken =>
                            {
                                SyntaxToken token = baseList.GetFirstToken().GetPreviousToken();

                                SyntaxTriviaList trivia = token.TrailingTrivia.EmptyIfWhitespace()
                                                          .AddRange(baseList.GetLeadingTrivia().EmptyIfWhitespace())
                                                          .AddRange(baseList.GetTrailingTrivia());

                                ClassDeclarationSyntax newNode = classDeclaration
                                                                 .ReplaceToken(token, token.WithTrailingTrivia(trivia))
                                                                 .WithBaseList(null);

                                return(context.Document.ReplaceNodeAsync(classDeclaration, newNode, cancellationToken));
                            },
                            base.GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveBaseList));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }
                }
            }
        }
示例#37
0
 public override void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     ClassDeclaration = node;
     base.VisitClassDeclaration(node);
 }
示例#38
0
 public override void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     VisitBody(node);
 }
示例#39
0
        private ClassDeclarationSyntax AddSubscriptions(ClassDeclarationSyntax classSyntax, SemanticModel model, ClassDeclarationSyntax classDeclaration)
        {
            var commands = GetMethodList(classSyntax, model, "Command", "Subscribe");
            var events   = GetMethodList(classSyntax, model, "Event", "Subscribe");
            var queries  = GetMethodList(classSyntax, model, "Query", "Subscribe");

            if (commands.Count + queries.Count + events.Count > 0)
            {
                var baseClassInvoke = ExpressionStatement(AwaitExpression(InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, BaseExpression(), IdentifierName("OnStarted"))).WithArgumentList(ArgumentList(SingletonSeparatedList <ArgumentSyntax>(Argument(IdentifierName("context"))))), IdentifierName("ConfigureAwait"))).WithArgumentList(ArgumentList(SingletonSeparatedList <ArgumentSyntax>(Argument(LiteralExpression(SyntaxKind.FalseLiteralExpression)))))));

                List <StatementSyntax> statementSyntaxes = new List <StatementSyntax>
                {
                    baseClassInvoke
                };

                foreach (var method in commands)
                {
                    var parentSubscription = IsSubscribeToParent(method);

                    var invocation = InvocationExpression(GenericName(Identifier("Subscribe")).WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList <TypeSyntax>(IdentifierName(method.Parameter.Type.Name)))));
                    if (parentSubscription)
                    {
                        invocation = invocation.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(LiteralExpression(SyntaxKind.TrueLiteralExpression)))));
                    }

                    statementSyntaxes.Add(ExpressionStatement(invocation));
                }

                foreach (var method in events)
                {
                    var parentSubscription = IsSubscribeToParent(method);

                    var invocation = InvocationExpression(GenericName(Identifier("Subscribe")).WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList <TypeSyntax>(IdentifierName(method.Parameter.Type.Name)))));

                    if (parentSubscription)
                    {
                        invocation = invocation.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(LiteralExpression(SyntaxKind.TrueLiteralExpression)))));
                    }

                    statementSyntaxes.Add(ExpressionStatement(invocation));
                }

                foreach (var method in queries)
                {
                    var parentSubscription = IsSubscribeToParent(method);

                    InvocationExpressionSyntax invocation;
                    if (method.ReturnType is INamedTypeSymbol namedSymbol && namedSymbol.TypeArguments.Length > 0)
                    {
                        var arg = namedSymbol.TypeArguments[0];

                        invocation = InvocationExpression(GenericName(Identifier("Subscribe")).WithTypeArgumentList(TypeArgumentList(SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { IdentifierName(method.Parameter.Type.Name), Token(SyntaxKind.CommaToken), IdentifierName(arg.Name) }))));
                    }
                    else if (!string.IsNullOrWhiteSpace(method.ReturnType.Name))
                    {
                        invocation = InvocationExpression(GenericName(Identifier("Subscribe")).WithTypeArgumentList(TypeArgumentList(SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { IdentifierName(method.Parameter.Type.Name), Token(SyntaxKind.CommaToken), IdentifierName(method.ReturnType.Name) }))));
                    }
                    else
                    {
                        invocation = InvocationExpression(GenericName(Identifier("Subscribe")).WithTypeArgumentList(TypeArgumentList(SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { IdentifierName(method.Parameter.Type.Name), Token(SyntaxKind.CommaToken), IdentifierName(method.ReturnType.ToString()) }))));
                    }

                    if (parentSubscription)
                    {
                        invocation = invocation.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(LiteralExpression(SyntaxKind.TrueLiteralExpression)))));
                    }

                    statementSyntaxes.Add(ExpressionStatement(invocation));
                }
示例#40
0
        protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            AttributeSyntax attribute = node.Attributes
                  .SelectMany(a => a.ChildNodes().OfType<AttributeSyntax>())
                  .FirstOrDefault(a => a.Name.PlainName == "EnableSingleton");

            if (attribute == null)
                return base.VisitClassDeclaration(node);

            LiteralExpressionSyntax argument = (LiteralExpressionSyntax) attribute
                .ArgumentListOpt
                .Arguments
                .First()
                .Expression;

            VariableDeclaratorSyntax syncVariable = Syntax.VariableDeclarator(identifier: Syntax.Identifier("_sync"));
            FieldDeclarationSyntax syncField = Syntax.FieldDeclaration(
                modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PrivateKeyword), Syntax.Token(SyntaxKind.StaticKeyword)),
                declaration: Syntax.VariableDeclaration(
                    type: Syntax.ParseTypeName("System.Object"),
                    variables: Syntax.SeparatedList(syncVariable)));

            VariableDeclaratorSyntax instanceVariable = Syntax.VariableDeclarator(identifier: Syntax.Identifier("_instance"));
            FieldDeclarationSyntax instanceField = Syntax.FieldDeclaration(
                modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PrivateKeyword), Syntax.Token(SyntaxKind.StaticKeyword)),
                declaration: Syntax.VariableDeclaration(
                    type: Syntax.ParseTypeName(node.Identifier.ValueText),
                    variables: Syntax.SeparatedList(instanceVariable)));

            ConstructorDeclarationSyntax constructor = Syntax.ConstructorDeclaration(
                modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.StaticKeyword)),
                identifier: Syntax.Identifier(node.Identifier.ValueText),
                parameterList: Syntax.ParameterList(parameters: Syntax.SeparatedList<ParameterSyntax>()),
                bodyOpt: Syntax.Block(
                    statements: Syntax.List<StatementSyntax>(Syntax.ExpressionStatement(Syntax.ParseExpression("_sync = new Object()")))));

            IfStatementSyntax ifStatement = Syntax.IfStatement(
                ifKeyword: Syntax.Token(SyntaxKind.IfKeyword),
                condition: Syntax.BinaryExpression(SyntaxKind.EqualsExpression, Syntax.IdentifierName("_instance"),
                    right: Syntax.LiteralExpression(SyntaxKind.NullLiteralExpression)),
                statement: Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName("_instance"),
                    right: Syntax.ObjectCreationExpression(
                        newKeyword: Syntax.Token(SyntaxKind.NewKeyword),
                        type: Syntax.ParseTypeName(node.Identifier.ValueText),
                        argumentListOpt: Syntax.ArgumentList(arguments: Syntax.SeparatedList<ArgumentSyntax>())))));

            LockStatementSyntax lockStatement = Syntax.LockStatement(
                lockKeyword: Syntax.Token(SyntaxKind.LockKeyword),
                expression: Syntax.IdentifierName("_sync"),
                statement: Syntax.Block(
                    statements: Syntax.List<StatementSyntax>(ifStatement, Syntax.ParseStatement("return _instance"))));
            //Syntax.BinaryExpression(SyntaxKind.EqualsEqualsExpression, Syntax.IdentifierName("_instance"));
            //Syntax.LiteralExpression(SyntaxKind.NullKeyword);
            //Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName("_instance")));
            //Syntax.ObjectCreationExpression(
            //            type: Syntax.ParseTypeName(node.Identifier.ValueText),
            //            argumentListOpt: Syntax.ArgumentList(arguments: Syntax.SeparatedList<ArgumentSyntax>()),
            //            initializerOpt: Syntax.InitializerExpression(expressions: Syntax.SeparatedList<ExpressionSyntax>(Syntax.Identifier(node.Identifier.ValueText))));

            //StatementSyntax getter = Syntax.ReturnStatement(expressionOpt: cast);
            PropertyDeclarationSyntax instance = Syntax.PropertyDeclaration(
              modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword), Syntax.Token(SyntaxKind.StaticKeyword)),
              type: Syntax.ParseTypeName(node.Identifier.ValueText),
              identifier: Syntax.Identifier(argument.Token.ValueText),
              accessorList: Syntax.AccessorList(
                accessors: Syntax.List(
                  Syntax.AccessorDeclaration(
                    kind: SyntaxKind.GetAccessorDeclaration,
                    bodyOpt: Syntax.Block(
                      statements: Syntax.List<StatementSyntax>(lockStatement)
                      )
                    )
                  )
                )
             );

            var newTypeDeclaration = (TypeDeclarationSyntax)base.VisitClassDeclaration(node);
            var members = new List<MemberDeclarationSyntax>(newTypeDeclaration.Members);
            members.Add(syncField);
            members.Add(instanceField);
            members.Add(constructor);
            members.Add(instance);

            return ((ClassDeclarationSyntax)newTypeDeclaration).Update(
                newTypeDeclaration.Attributes,
                newTypeDeclaration.Modifiers,
                newTypeDeclaration.Keyword,
                newTypeDeclaration.Identifier,
                newTypeDeclaration.TypeParameterListOpt,
                newTypeDeclaration.BaseListOpt,
                newTypeDeclaration.ConstraintClauses,
                newTypeDeclaration.OpenBraceToken,
                Syntax.List(members.AsEnumerable()),
                newTypeDeclaration.CloseBraceToken,
                newTypeDeclaration.SemicolonTokenOpt);
        }
示例#41
0
 private static NamespaceDeclarationSyntax AddNamespace(ClassDeclarationSyntax classSyntax, ClassDeclarationSyntax classDeclaration)
 {
     return(NamespaceDeclaration((classSyntax.Parent as NamespaceDeclarationSyntax)?.Name).AddMembers(classDeclaration));
 }
示例#42
0
 private ClassDeclarationSyntax AddIActionResultProperties(ClassDeclarationSyntax node)
 => node
 .WithAutoStringProperty("Controller", SyntaxKind.PublicKeyword)
 .WithAutoStringProperty("Action", SyntaxKind.PublicKeyword)
 .WithAutoStringProperty("Protocol", SyntaxKind.PublicKeyword)
 .WithAutoProperty("RouteValueDictionary", IdentifierName("RouteValueDictionary"), SyntaxKind.PublicKeyword);
示例#43
0
        private static Dictionary <string, string> CreateConstants(
            IReadOnlyCollection <string> constantsToCreate,
            ClassDeclarationSyntax classNode,
            DocumentEditor editor)
        {
            var result = new Dictionary <string, string>();

            if (!constantsToCreate.Any())
            {
                return(result);
            }

            var trivia = classNode.GetLeadingTrivia().ToString();

            trivia = trivia.Substring(trivia.LastIndexOf('\n') + 1);

            string indent;

            if (string.IsNullOrEmpty(trivia))
            {
                indent = "    ";
            }
            else
            {
                indent = trivia + trivia;
            }

            var counter      = 0;
            var newConstants = new List <MemberDeclarationSyntax>();

            foreach (var constant in constantsToCreate)
            {
                counter++;

                var constantSubstring = SyntaxFactory.ParseToken(constant);
                var constName         = GetConstantName(constantSubstring.ValueText, result, classNode, counter);

                var constSyntax = SyntaxFactory.FieldDeclaration(
                    SyntaxFactory
                    .VariableDeclaration(
                        SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)))
                    .WithVariables(
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(constName))
                            .WithInitializer(
                                SyntaxFactory.EqualsValueClause(
                                    SyntaxFactory.LiteralExpression(
                                        SyntaxKind.StringLiteralExpression,
                                        constantSubstring))))))
                                  .WithModifiers(
                    SyntaxFactory.TokenList(
                        SyntaxFactory.Token(SyntaxKind.PrivateKeyword),
                        SyntaxFactory.Token(SyntaxKind.ConstKeyword)))
                                  .NormalizeWhitespace()
                                  .WithLeadingTrivia(SyntaxFactory.Whitespace(indent))
                                  .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                newConstants.Add(constSyntax);
                result.Add(constant, constName);
            }

            editor.InsertMembers(classNode, 0, newConstants);
            return(result);
        }
示例#44
0
 // ******************************************************************************
 // **************** Skip any nodes that change scope without a block node *******
 // ******************************************************************************
 // **
 // **
 protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     return node;
 }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, ClassDeclarationSyntax classDeclaration)
        {
            SyntaxToken identifier = classDeclaration.Identifier;

            if (identifier.IsMissing)
            {
                return;
            }

            TextSpan span = identifier.Span;

            BaseListSyntax baseList = classDeclaration.BaseList;

            if (baseList != null)
            {
                span = TextSpan.FromBounds(span.Start, baseList.Span.End);
            }

            TypeParameterListSyntax typeParameterList = classDeclaration.TypeParameterList;

            if (typeParameterList != null)
            {
                span = TextSpan.FromBounds(span.Start, typeParameterList.Span.End);
            }

            if (!span.Contains(context.Span))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            INamedTypeSymbol classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration, context.CancellationToken);

            if (classSymbol?.IsErrorType() != false)
            {
                return;
            }

            if (classSymbol.IsStatic)
            {
                return;
            }

            foreach (INamedTypeSymbol interfaceSymbol in classSymbol.AllInterfaces)
            {
                if (interfaceSymbol.HasMetadataName(MetadataNames.System_IEquatable_T) &&
                    SymbolEqualityComparer.Default.Equals(interfaceSymbol.TypeArguments.Single(), classSymbol))
                {
                    return;
                }
            }

            INamedTypeSymbol equatableSymbol = semanticModel.GetTypeByMetadataName("System.IEquatable`1");

            if (equatableSymbol == null)
            {
                return;
            }

            equatableSymbol = equatableSymbol.Construct(classSymbol);

            context.RegisterRefactoring(
                GetTitle(equatableSymbol, semanticModel, classDeclaration.SpanStart),
                ct => RefactorAsync(context.Document, classDeclaration, classSymbol, equatableSymbol, semanticModel, ct),
                RefactoringIdentifiers.ImplementIEquatableOfT);
        }
示例#46
0
        public static ClassDeclarationSyntax ClassDeclaration(string identifier = null)
        {
            var result = new ClassDeclarationSyntax();

            result.Identifier = identifier;

            return result;
        }
示例#47
0
        private static IEnumerable <ObjectCreationExpressionSyntax> GetObjectCreations(SyntaxNodeAnalysisContext context, ClassDeclarationSyntax classDeclaration, PropertyDeclarationSyntax propertyDeclarationSyntax, IPropertySymbol propertySymbol)
        {
            var objectCreations = classDeclaration.DescendantNodes()
                                  .OfType <AssignmentExpressionSyntax>()
                                  .Where(a => context.SemanticModel.GetSymbolInfo(a.Left).Symbol.Equals(propertySymbol) && a.Right is ObjectCreationExpressionSyntax)
                                  .Select(a => a.Right as ObjectCreationExpressionSyntax).ToList();

            var arrowExpressionClause = propertyDeclarationSyntax.DescendantNodes()
                                        .OfType <ArrowExpressionClauseSyntax>()
                                        .SingleOrDefault(a => a.Expression is ObjectCreationExpressionSyntax)
                                        ?.Expression as ObjectCreationExpressionSyntax;

            if (arrowExpressionClause != null)
            {
                objectCreations.Add(arrowExpressionClause);
            }

            var getAcessorDeclararion = propertyDeclarationSyntax.DescendantNodes()
                                        .OfType <AccessorDeclarationSyntax>()
                                        .SingleOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration));

            if (getAcessorDeclararion != null)
            {
                objectCreations.AddRange(getAcessorDeclararion.DescendantNodes()
                                         .OfType <ObjectCreationExpressionSyntax>());
            }

            return(objectCreations);
        }
 public static IEnumerable <EventFieldDeclarationSyntax> GetEventFiels(this ClassDeclarationSyntax classDeclaration)
 {
     return(classDeclaration.Members
            .Where(x => x.IsKind(SyntaxKind.EventFieldDeclaration))
            .OfType <EventFieldDeclarationSyntax>());
 }
示例#49
0
        public static ITypeSymbol AddType(DotNetProject project, string folder, string namspace, ClassDeclarationSyntax type)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }
            if (folder == null)
            {
                throw new ArgumentNullException(nameof(folder));
            }
            if (namspace == null)
            {
                throw new ArgumentNullException(nameof(namspace));
            }
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            var ns = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(namspace)).WithMembers(new SyntaxList <MemberDeclarationSyntax> ()
            {
                type
            });

            string fileName = project.LanguageBinding.GetFileName(Path.Combine(folder, type.Identifier.ToString()));

            using (var sw = new StreamWriter(fileName)) {
                sw.WriteLine(ns.ToString());
            }
            FileService.NotifyFileChanged(fileName);
            var roslynProject = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetCodeAnalysisProject(project);
            var id            = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetDocumentId(roslynProject.Id, fileName);

            if (id == null)
            {
                return(null);
            }
            var model      = roslynProject.GetDocument(id).GetSemanticModelAsync().Result;
            var typeSyntax = model.SyntaxTree.GetCompilationUnitRoot().ChildNodes().First().ChildNodes().First() as ClassDeclarationSyntax;

            return(model.GetDeclaredSymbol(typeSyntax));
        }
示例#50
0
 public DisposableChecker(ClassDeclarationSyntax classDeclaration, SemanticModel semanticModel)
 {
     this.classDeclaration = classDeclaration;
     this.semanticModel    = semanticModel;
     this.classSymbol      = semanticModel.GetDeclaredSymbol(classDeclaration);
 }
 public AdaptInterfaceCodeAction(IDocument document, ClassDeclarationSyntax classDeclaration, ParameterSyntax parameterSyntax)
 {
     this._document = document;
     _classDeclaration = classDeclaration;
     Description = "Adapt "+parameterSyntax.Type;
 }
 public virtual void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     DefaultVisit(node);
 }
 public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     var symbol = semanticModel.GetDeclaredSymbol(node);
     var visitedNode = base.VisitClassDeclaration(node);
     return VisitTypeDeclaration(visitedNode as TypeDeclarationSyntax, symbol);
 }
示例#54
0
            // Replace old ClassDeclarationSyntax with new one.
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                var updatedClassDeclaration = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);

                // Get TypeSymbol corresponding to the ClassDeclarationSyntax and check whether
                // it is the same as the TypeSymbol we are searching for.
                TypeSymbol classSymbol = SemanticModel.GetDeclaredSymbol(node);
                if (classSymbol.Equals(SearchSymbol))
                {
                    // Replace the identifier token containing the name of the class.
                    SyntaxToken updatedIdentifierToken =
                        Syntax.Identifier(
                            updatedClassDeclaration.Identifier.LeadingTrivia,
                            NewName,
                            updatedClassDeclaration.Identifier.TrailingTrivia);

                    updatedClassDeclaration = updatedClassDeclaration.WithIdentifier(updatedIdentifierToken);
                }

                return updatedClassDeclaration;
            }
 public static IEnumerable <PropertyDeclarationSyntax> GetProperties(this ClassDeclarationSyntax classDeclaration)
 {
     return(classDeclaration.Members
            .Where(x => x.IsKind(SyntaxKind.PropertyDeclaration))
            .OfType <PropertyDeclarationSyntax>());
 }
示例#56
0
 public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     return base.VisitClassDeclaration(node);
 }
示例#57
0
 public void VisitClassDeclaration(ClassDeclarationSyntax node)
 {
     VisitTypeDeclaration(node);
 }
示例#58
0
        private ClassDeclarationSyntax AddReciveMapMethod(ClassDeclarationSyntax classSyntax, SemanticModel model, ClassDeclarationSyntax classDeclaration)
        {
            var methodDeclaration = MethodDeclaration(ParseTypeName("Task"), "ReceiveAsyncInternal")
                                    .WithModifiers(TokenList(new[] { Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.AsyncKeyword), Token(SyntaxKind.OverrideKeyword) }))
                                    .WithParameterList(ParameterList(SingletonSeparatedList(Parameter(Identifier("context")).WithType(QualifiedName(IdentifierName("Proto"), IdentifierName("IContext"))))))
                                    .WithBody(Block(
                                                  GenerateSystemMessagesHandler(),
                                                  FormatMessage(),
                                                  FillContextData(),
                                                  GenerateCommandHandlers(classSyntax, model),
                                                  GenerateQueryHandlers(classSyntax, model),
                                                  GenerateEventdHandlers(classSyntax, model),
                                                  GetUnsupportedMessage())
                                              );

            classDeclaration = classDeclaration.AddMembers(methodDeclaration);
            return(classDeclaration);
        }
 public static IEnumerable <IndexerDeclarationSyntax> GetIndexers(this ClassDeclarationSyntax classDeclaration)
 {
     return(classDeclaration.Members
            .Where(x => x.IsKind(SyntaxKind.IndexerDeclaration))
            .OfType <IndexerDeclarationSyntax>());
 }
示例#60
-1
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            string className = node.Identifier.GetText();

            _writer.WriteLine("var {0} = function() {{", className);
            _writer.WriteLine("  var self = this;");

            base.VisitClassDeclaration(node);

            _writer.WriteLine("  return {");
            _writer.Write(_publicCode.ToString());
            _writer.WriteLine("  };");
            _writer.WriteLine("}};");
        }