public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            if (node.ShouldBeHidden())
            {
                return;
            }

            ++ClassDepth;
            if (ClassDepth == 1)
            {
                base.VisitClassDeclaration(node);
            }
            else if (node.ChildNodes().All(childNode => childNode is PropertyDeclarationSyntax || childNode is AttributeListSyntax))
            {
                // simple nested POCO
                var line   = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
                var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line);
                walker.Visit(node);
                this.Blocks.AddRange(walker.Blocks);
            }
            else
            {
                var methods = node.ChildNodes().OfType <MethodDeclarationSyntax>();
                if (!methods.Any(m => m.AttributeLists.SelectMany(a => a.Attributes).Any()))
                {
                    // nested class with methods that are not unit or integration tests e.g. example PropertyVisitor in Automap.doc.cs
                    var line   = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
                    var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line);
                    walker.Visit(node);
                    this.Blocks.AddRange(walker.Blocks);
                }
            }
            --ClassDepth;
        }
        internal Tuple <String, ParamsAttribute, ParamsWithStepsAttribute> TryGetParamInfoThrowIfInvalid(ClassDeclarationSyntax @class)
        {
            var fields = @class.ChildNodes().OfType <FieldDeclarationSyntax>()
                         .Where(f => f.AttributeLists.SelectMany(al => al.Attributes)
                                .Any(a => a.Name.ToString() == paramsAttribute || a.Name.ToString() == paramsWithStepsAttribute))
                         .ToList();
            var properties = @class.ChildNodes().OfType <PropertyDeclarationSyntax>()
                             .Where(p => p.AttributeLists.SelectMany(al => al.Attributes)
                                    .Any(a => a.Name.ToString() == paramsAttribute || a.Name.ToString() == paramsWithStepsAttribute))
                             .ToList();

            if (fields.Count + properties.Count > 1)
            {
                var msg = String.Format("Only one field/property can be annotated with [{0}] or [{1}]",
                                        paramsAttribute, paramsWithStepsAttribute);
                throw new InvalidOperationException(msg);
            }

            PrintFieldPropertyDebugInfo(fields, properties);

            if (fields.Count > 0)
            {
                return(ProcessFields(fields));
            }

            if (properties.Count > 0)
            {
                return(ProcessProperties(properties));
            }

            return(emptyParamResult);
        }
示例#3
0
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            if (node.ShouldBeHidden())
            {
                return;
            }

            ++ClassDepth;
            if (ClassDepth == 1)
            {
                // walk the top level class
                base.VisitClassDeclaration(node);
            }
            else if (node.ChildNodes().All(childNode => childNode.IsKind(SyntaxKind.PropertyDeclaration) ||
                                           childNode.IsKind(SyntaxKind.AttributeList)))
            {
                // we have a simple nested POCO class inside of a class
                AddNestedType(node);
            }
            else
            {
                var methods = node.ChildNodes().OfType <MethodDeclarationSyntax>();
                if (!methods.Any(m => m.AttributeLists.SelectMany(a => a.Attributes).Any()))
                {
                    // nested class with methods that are not unit or integration tests
                    // e.g. example PropertyVisitor in Automap.doc.cs
                    AddNestedType(node);
                }
            }
            --ClassDepth;
        }
示例#4
0
        void ExportClass(ClassDeclarationSyntax c)
        {
            string name      = "";
            string nameSpace = "";

            NamespaceDeclarationSyntax namespaceDeclarationSyntax = c.Parent as NamespaceDeclarationSyntax;

            if (namespaceDeclarationSyntax != null)
            {
                nameSpace = namespaceDeclarationSyntax.Name.ToString();
            }
            else
            {
                nameSpace = "gloable";
            }
            name = c.Identifier.Text;

            //type.ID = GetOrCreateGuid(c.AttributeLists);
            type.Name      = name;
            type.Namespace = nameSpace;

            //导出所有变量
            var virableNodes = c.ChildNodes().OfType <BaseFieldDeclarationSyntax>();

            foreach (var v in virableNodes)
            {
                ExportVariable(v);
            }

            //导出所有属性
            var propertyNodes = c.ChildNodes().OfType <BasePropertyDeclarationSyntax>();

            foreach (var v in propertyNodes)
            {
                ExportProperty(v);
            }


            //导出所有方法
            var funcNodes = c.ChildNodes().OfType <BaseMethodDeclarationSyntax>();

            foreach (var f in funcNodes)
            {
                ExportMethod(f);
            }

            var operatorNodes = c.ChildNodes().OfType <OperatorDeclarationSyntax>();

            foreach (var f in operatorNodes)
            {
                //ExportOperator(f, type);
            }
            var conversion_operatorNodes = c.ChildNodes().OfType <ConversionOperatorDeclarationSyntax>();

            foreach (var f in conversion_operatorNodes)
            {
                //ExportConversionOperator(f, type);
            }
        }
示例#5
0
        public CodeRefactoring GetRefactoring(IDocument document, TextSpan textSpan, CancellationToken cancellationToken)
        {
            SyntaxNode  root  = (SyntaxNode)document.GetSyntaxRoot(cancellationToken);
            SyntaxToken token = root.FindToken(textSpan.Start, findInsideTrivia: true);

            SyntaxNode parentNode = token.Parent;

            if (parentNode == null)
            {
                return(null);
            }

            // Verify is the selected token an identifier within field declaration
            if (token.Kind == SyntaxKind.IdentifierToken && parentNode.Kind == SyntaxKind.VariableDeclarator && token.Span.Start <= textSpan.End && textSpan.End <= token.Span.End)
            {
                VariableDeclaratorSyntax variableDeclarator = (VariableDeclaratorSyntax)parentNode;

                FieldDeclarationSyntax fieldDeclaration = parentNode.FirstAncestorOrSelf <FieldDeclarationSyntax>();

                // Skip if field has diagnostics
                if (fieldDeclaration == null || fieldDeclaration.HasDiagnostics)
                {
                    return(null);
                }

                ISemanticModel model = document.GetSemanticModel(cancellationToken);

                ISymbol declaredSymbol = model.GetDeclaredSymbol(variableDeclarator);

                ClassDeclarationSyntax typeDeclaration = fieldDeclaration.FirstAncestorOrSelf <ClassDeclarationSyntax>();
                if (typeDeclaration == null)
                {
                    return(null);
                }

                // Verify is there already a getter property that returns the value of field
                if (typeDeclaration.ChildNodes().OfType <PropertyDeclarationSyntax>().Any(n => IsGetterProperty(n, declaredSymbol, model)))
                {
                    return(null);
                }

                // Verify is there already a getter method that returns the value of field
                if (typeDeclaration.ChildNodes().OfType <MethodDeclarationSyntax>().Any(n => IsGetterMethod(n, declaredSymbol, model)))
                {
                    return(null);
                }

                return(new CodeRefactoring(
                           new[] { new EncapsulateFieldAction(document, declaredSymbol, fieldDeclaration, variableDeclarator) }
                           , variableDeclarator.Identifier.Span));
            }

            return(null);
        }
示例#6
0
        public static bool HasInitializableMembers(this ClassDeclarationSyntax c, SemanticModel sm)
        {
            return(false); // todo: figure out how to detect this.x=x type initializers; ignore for now

            return(c.ChildNodes().OfType <FieldDeclarationSyntax>()
                   .Any(f => f.RequiresInitialization(sm)));
        }
示例#7
0
        public async ValueTask <CSharpCompilation> EnrichAsync(CSharpCompilation target,
                                                               CancellationToken cancellationToken = default)
        {
            foreach (SyntaxTree syntaxTree in target.SyntaxTrees)
            {
                SyntaxNode rootNode = await syntaxTree.GetRootAsync(cancellationToken)
                                      .ConfigureAwait(false);

                ClassDeclarationSyntax?classDeclaration = rootNode
                                                          .DescendantNodes()
                                                          .OfType <ClassDeclarationSyntax>()
                                                          .FirstOrDefault(p => p.Identifier.ValueText == "TypeSerializerRegistry");

                MethodDeclarationSyntax?methodDeclaration = classDeclaration?
                                                            .ChildNodes()
                                                            .OfType <MethodDeclarationSyntax>()
                                                            .FirstOrDefault(p => p.Identifier.ValueText == "CreateDefaultRegistry");

                if (methodDeclaration?.ExpressionBody != null)
                {
                    MethodDeclarationSyntax newMethodDeclaration = methodDeclaration.WithExpressionBody(
                        methodDeclaration.ExpressionBody.WithExpression(
                            methodDeclaration.ExpressionBody.Expression.Enrich(_createDefaultRegistryEnrichers)));

                    rootNode = rootNode.ReplaceNode(methodDeclaration, newMethodDeclaration);

                    target = target.ReplaceSyntaxTree(syntaxTree,
                                                      syntaxTree.WithRootAndOptions(rootNode, syntaxTree.Options));
                }
            }

            return(target);
        }
        private IEnumerable <ICodePart> Visit(ClassDeclarationSyntax node)
        {
            var cls = SyntaxCodePart.Create <Class>(node, _model);

            cls.Children = node.ChildNodes().SelectMany(Visit).Where(c => c != null).ToList();
            yield return(cls);
        }
        private static ConstructorDeclarationSyntax[] GetPublicEligableConstructors(ClassDeclarationSyntax @class)
        {
            var publicConstructors = @class.ChildNodes()
                                     .Where(n => n.Fits(SyntaxKind.ConstructorDeclaration) &&
                                            n.ChildTokens().Any(x => x.Fits(SyntaxKind.PublicKeyword)));

            var marked = publicConstructors
                         .Where(n =>
            {
                var attrMarkerType = typeof(DependencyInjectionConstructorAttribute);
                return(n
                       .GetAttributeIdentifiers()
                       .Any(x => x.FitsAttrIdentifier(attrMarkerType)));
            })
                         .ToArray();

            if (marked.Any())
            {
                return(marked
                       .OfType <ConstructorDeclarationSyntax>()
                       .ToArray());
            }

            return(publicConstructors
                   .OfType <ConstructorDeclarationSyntax>()
                   .ToArray());
        }
示例#10
0
        //generation
        private static bool isService(ClassDeclarationSyntax @class, ExcessCompilation compilation, Scope scope)
        {
            if (!isConcurrentClass(@class, compilation, scope))
            {
                var isFunctionClass = @class.Identifier.ToString() == "Functions" && Roslyn.IsStatic(@class);
                if (isFunctionClass)
                {
                    return(@class.ChildNodes()
                           .OfType <MethodDeclarationSyntax>()
                           .Any(method => method
                                .AttributeLists
                                .Any(attrList => attrList
                                     .Attributes
                                     .Any(attr => attr.Name.ToString() == "route"))));
                }

                return(false);
            }

            return(@class
                   .AttributeLists
                   .Any(attrList => attrList
                        .Attributes
                        .Any(attr => attr.Name.ToString() == "Service")));
        }
示例#11
0
        private static SyntaxList <MemberDeclarationSyntax> GetTemplateMethods(ClassDeclarationSyntax clsInfo, SemanticModel model)
        {
            List <MemberDeclarationSyntax> classMethods = new List <MemberDeclarationSyntax>();

            string templateAttribute = "Test";

            //add setUp
            var constructor = (ConstructorDeclarationSyntax)clsInfo.ChildNodes().FirstOrDefault(n => n.Kind() == SyntaxKind.ConstructorDeclaration);

            if (constructor != null)
            {
                if (!clsInfo.Modifiers.Where(m => m.Kind().Equals(SyntaxKind.StaticKeyword)).Any())
                {
                    var constructorMethod = AddSetUpMethod(clsInfo, model, constructor);
                    classMethods.Add(constructorMethod);
                }
            }

            var publicMethods = clsInfo.DescendantNodes().OfType <MethodDeclarationSyntax>().Where(
                method => method.Modifiers.Any(modifier => modifier.ValueText == "public"));

            foreach (var method in publicMethods)
            {
                if (method != null)
                {
                    string classname  = char.ToLower(clsInfo.Identifier.ValueText[0]) + clsInfo.Identifier.ValueText.Substring(1);
                    var    testMethod = AddMethod(classname, model, method, method.Identifier.ValueText + "Test", templateAttribute);
                    classMethods.Add(testMethod);
                }
            }

            return(List(classMethods));
        }
示例#12
0
        private static IEnumerable <MemberDeclarationSyntax> createRemoteConstructors(ClassDeclarationSyntax @class, string typeName)
        {
            var constructor = @class
                              .ChildNodes()
                              .OfType <ConstructorDeclarationSyntax>()
                              .OrderBy(ctor => ctor.ParameterList.Parameters.Count)
                              .FirstOrDefault();

            var result = CSharp.ConstructorDeclaration(typeName)
                         .AddParameterListParameters(CSharp
                                                     .Parameter(CSharp.Identifier("id")).WithType(CSharp.ParseTypeName("Guid")))
                         .WithBody(CSharp.Block(Templates.RemoteIdAssign))
                         .WithModifiers(Roslyn.@public);

            if (constructor != null)
            {
                result = result.WithInitializer(CSharp.ConstructorInitializer(
                                                    SyntaxKind.BaseConstructorInitializer,
                                                    CSharp.ArgumentList(CSharp.SeparatedList(
                                                                            constructor
                                                                            .ParameterList
                                                                            .Parameters
                                                                            .Select(parameter => CSharp.Argument(
                                                                                        CSharp.DefaultExpression(parameter.Type)))))));
            }

            return(new MemberDeclarationSyntax[]
            {
                result
            });
        }
        private async Task <Document> AddMissingMapIdFors(Document document, ClassDeclarationSyntax classExpr, string messageType, CancellationToken cancellationToken)
        {
            var constructorExpr = classExpr.ChildNodes().SingleOrDefault(x => x is ConstructorDeclarationSyntax);

            if (constructorExpr == null)
            {
                return(document);
            }

            var oldblock = constructorExpr.ChildNodes().OfType <BlockSyntax>().First();

            var leadingTrivia   = GetLeadingWhiteSpaceForExpression(oldblock);
            ExpressionSyntax es = SyntaxFactory.ParseExpression($"this.MapIdFor<{messageType}>((m, md) => m.<ProcessId>);")
                                  .WithLeadingTrivia(leadingTrivia)
                                  .WithTrailingTrivia(SyntaxFactory.EndOfLine("\r\n"));

            var statement = SyntaxFactory.ExpressionStatement(es);
            var newblock  = oldblock.AddStatements(statement);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = oldRoot.ReplaceNode(oldblock, newblock);

            return(document.WithSyntaxRoot(newRoot));
        }
示例#14
0
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var isPartial  = node.ChildTokens().Any(x => x.Kind() == SyntaxKind.PartialKeyword);
            var defineName = node.ChildTokens().FirstOrDefault(x => x.Kind() == SyntaxKind.IdentifierToken).ToString();

            // ジェネリック型を定義している場合
            if (node.ChildNodes().OfType <TypeParameterListSyntax>().Any())
            {
                var listNode     = node.ChildNodes().OfType <TypeParameterListSyntax>().FirstOrDefault();
                var genericTypes = listNode
                                   .ChildNodes()
                                   .OfType <TypeParameterSyntax>()
                                   .Select(x => x.ChildTokens().FirstOrDefault(y => y.Kind() == SyntaxKind.IdentifierToken).ToString());

                defineName = $"{defineName}<{string.Join(", ", genericTypes)}>";
            }

            var startLength     = node.Span.Start;
            var endLength       = node.Span.End;
            var parentNamespace = GetNamespace(DefineKinds.Class, startLength, endLength);

            var baseTypeInfos = new List <BaseTypeInfo>();

            // 継承元クラス、またはインターフェースがある場合
            if (node.ChildNodes().OfType <BaseListSyntax>().Any())
            {
                var listNode  = node.ChildNodes().OfType <BaseListSyntax>().FirstOrDefault();
                var baseTypes = listNode.ChildNodes().OfType <SimpleBaseTypeSyntax>();

                baseTypeInfos = GetBaseTypeInfos(baseTypes, parentNamespace);
            }

            UserDefinitions.Add(new UserDefinition
            {
                DefineKinds    = DefineKinds.Class,
                IsPartial      = isPartial,
                Namespace      = parentNamespace,
                DefineName     = defineName,
                DefineFullName = $"{parentNamespace}.{defineName}",
                BaseTypeInfos  = baseTypeInfos,
                SourceFile     = SourceFile,
                StartLength    = startLength,
                EndLength      = endLength,
            });

            base.VisitClassDeclaration(node);
        }
 public static ClassDeclarationSyntax RemoveMethod(this ClassDeclarationSyntax classDeclarationSyntax, string methodName)
 {
     return(classDeclarationSyntax
            .RemoveNodes(
                classDeclarationSyntax.ChildNodes().OfType <MethodDeclarationSyntax>().Where(x => x.GetIdentifierValue() == methodName),
                SyntaxRemoveOptions.KeepTrailingTrivia
                ));
 }
 public static bool HasGeneratedAttribute(this ClassDeclarationSyntax classDeclarationSyntax)
 {
     return(classDeclarationSyntax.ChildNodes().OfType <AttributeListSyntax>()
            .Any(x => x.DescendantNodes().OfType <AttributeSyntax>()
                 .Any(a => a.DescendantNodes().OfType <QualifiedNameSyntax>()
                      .Any(qn => qn.DescendantTokens()
                           .Any(t => t.Kind() == SyntaxKind.IdentifierToken && (t.ValueText == "Generated" || t.ValueText == "DebuggerNonUserCode"))))));
 }
示例#17
0
        private static void PrintClassNode(ClassDeclarationSyntax member, int depth)
        {
            Console.WriteLine($"  CLASS {member.Identifier}");

            foreach (var childMember in member.ChildNodes())
            {
                PrintTree(childMember, depth);
            }
        }
 public static int GetCount(ClassDeclarationSyntax classNode)
 {
     return(classNode
            .ChildNodes()
            .Where(x => x is MethodDeclarationSyntax)
            .Select(CyclomaticComplexity.GetCount)
            .Sum()
            );
 }
示例#19
0
 private static IEnumerable <MethodDeclarationSyntax> createRemoteMethods(ClassDeclarationSyntax @class)
 {
     return(@class
            .ChildNodes()
            .OfType <MethodDeclarationSyntax>()
            .Where(method => method.Identifier.ToString() != "__concurrentmain" &&
                   isInternalConcurrent(method))
            .Select(method => createRemoteMethod(method)));
 }
示例#20
0
        private IEnumerable <SyntaxNode> GetIgnoredProperties(ClassDeclarationSyntax declaration, string className)
        {
            var nodes = declaration.ChildNodes()
                        .OfType <PropertyDeclarationSyntax>()
                        .Where(p => p.AttributeLists.SelectMany(a => a.Attributes)
                               .Any(a => a.Name.ToString() == nameof(ExcludeProperty) &&
                                    (!GetAttributeArguments(a).Any() || GetAttributeArguments(a).Contains(className))));

            return(nodes);
        }
示例#21
0
        /// <summary>
        /// Analyses all the eligible methods of the given machine to compute each
        /// method summary. This process continues until it reaches a fix point.
        /// </summary>
        /// <param name="machine">Machine</param>
        private static void AnalyseMethodsInMachine(ClassDeclarationSyntax machine)
        {
            int fixPoint = 0;

            foreach (var nestedClass in machine.ChildNodes().OfType <ClassDeclarationSyntax>())
            {
                foreach (var method in nestedClass.ChildNodes().OfType <MethodDeclarationSyntax>())
                {
                    if (!Utilities.ShouldAnalyseMethod(method) ||
                        AnalysisContext.Summaries.ContainsKey(method))
                    {
                        continue;
                    }

                    MethodSummaryAnalysis.ComputeSummaryForMethod(method, machine, nestedClass);
                    if (!AnalysisContext.Summaries.ContainsKey(method))
                    {
                        fixPoint++;
                    }
                }
            }

            foreach (var method in machine.ChildNodes().OfType <MethodDeclarationSyntax>())
            {
                if (!Utilities.ShouldAnalyseMethod(method) ||
                    AnalysisContext.Summaries.ContainsKey(method))
                {
                    continue;
                }

                MethodSummaryAnalysis.ComputeSummaryForMethod(method, machine, null);
                if (!AnalysisContext.Summaries.ContainsKey(method))
                {
                    fixPoint++;
                }
            }

            if (fixPoint > 0)
            {
                MethodSummaryAnalysis.AnalyseMethodsInMachine(machine);
            }
        }
示例#22
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var typeList = node.ChildNodes().OfType <TypeParameterListSyntax>();

            if (typeList.Any())
            {
                return(node.RemoveNodes(typeList, SyntaxRemoveOptions.KeepEndOfLine));
            }

            return(node);
        }
        private static Dictionary <ITypeSymbol, HashSet <ISymbol> > GetMemberCandidates(SyntaxNodeAnalysisContext context,
                                                                                        ClassDeclarationSyntax classDeclarationSyntax)
        {
            var fieldSymbols = classDeclarationSyntax
                               .ChildNodes()
                               .OfType <FieldDeclarationSyntax>()
                               .Select(syntax =>
                                       context.SemanticModel.GetDeclaredSymbol(syntax.Declaration.Variables.First()) as IFieldSymbol)
                               .ToImmutableArray();

            var propertySymbols = classDeclarationSyntax
                                  .ChildNodes()
                                  .OfType <PropertyDeclarationSyntax>()
                                  .Select(syntax => context.SemanticModel.GetDeclaredSymbol(syntax))
                                  .ToImmutableArray();

            var memberCandidates = new Dictionary <ITypeSymbol, HashSet <ISymbol> >();

            foreach (var fieldSymbol in fieldSymbols)
            {
                if (fieldSymbol.Type.TryGetEnumerableType(context.SemanticModel, out var implementationSymbol))
                {
                    var members = memberCandidates.GetOrInitialize(implementationSymbol, d => new HashSet <ISymbol>());
                    members.Add(fieldSymbol);
                }
            }

            foreach (var propertySymbol in propertySymbols)
            {
                if (propertySymbol.GetMethod.ReturnType.TryGetEnumerableType(context.SemanticModel,
                                                                             out var implementationSymbol))
                {
                    var members = memberCandidates.GetOrInitialize(implementationSymbol, d => new HashSet <ISymbol>());
                    members.Add(propertySymbol);
                }
            }

            return(memberCandidates);
        }
示例#24
0
            ClassDeclarationSyntax MoveBraceTrivia(ClassDeclarationSyntax node)
            {
                // If there is some node to move the brace trivia to, do so in order
                // to have it treated correctly by the composers. Otherwise it doesn't
                // matter.
                var firstChild = node.ChildNodes().FirstOrDefault();

                if (firstChild != null)
                {
                    var trailingTrivia = node.OpenBraceToken.TrailingTrivia;

                    // Skip the whitespace and line the brace itself is on
                    var i = 0;
                    while (i < trailingTrivia.Count && trailingTrivia[i].Kind() == SyntaxKind.WhitespaceTrivia)
                    {
                        i++;
                    }
                    if (i < trailingTrivia.Count && trailingTrivia[i].Kind() == SyntaxKind.EndOfLineTrivia)
                    {
                        i++;
                    }
                    node = node.WithOpenBraceToken(node.OpenBraceToken.WithTrailingTrivia(SyntaxFactory.EndOfLine("\n")));
                    if (i < trailingTrivia.Count)
                    {
                        node = node.ReplaceNode(firstChild, firstChild.WithLeadingTrivia(firstChild.GetLeadingTrivia().InsertRange(0, trailingTrivia.Skip(i))));
                    }
                }

                var lastChild = node.ChildNodes().LastOrDefault();

                if (lastChild != null)
                {
                    var leadingTrivia = node.CloseBraceToken.LeadingTrivia;
                    node = node.WithCloseBraceToken(node.CloseBraceToken.WithLeadingTrivia());
                    node = node.ReplaceNode(lastChild, lastChild.WithTrailingTrivia(lastChild.GetTrailingTrivia().AddRange(leadingTrivia)));
                }

                return(node);
            }
        /// <summary>
        /// Tries to parse and return the state transitions for the given machine.
        /// </summary>
        /// <param name="stateTransitions">State transitions</param>
        /// <param name="machine">Machine</param>
        /// <param name="model">SemanticModel</param>
        /// <returns>Boolean value</returns>
        private static bool TryParseStateTransitions(out Dictionary <ClassDeclarationSyntax,
                                                                     HashSet <ClassDeclarationSyntax> > stateTransitions, ClassDeclarationSyntax machine,
                                                     SemanticModel model)
        {
            stateTransitions = new Dictionary <ClassDeclarationSyntax, HashSet <ClassDeclarationSyntax> >();

            var defineGotoStateTransitionsMethod = machine.ChildNodes().
                                                   OfType <MethodDeclarationSyntax>().FirstOrDefault(v
                                                                                                     => v.Identifier.ValueText.Equals("DefineGotoStateTransitions") &&
                                                                                                     v.Modifiers.Any(SyntaxKind.OverrideKeyword) && v.ReturnType.ToString().
                                                                                                     Equals("System.Collections.Generic.Dictionary<Type, GotoStateTransitions>"));

            if (defineGotoStateTransitionsMethod == null)
            {
                return(false);
            }

            var returnStmt = defineGotoStateTransitionsMethod.DescendantNodes().
                             OfType <ReturnStatementSyntax>().First();
            var returnSymbol = model.GetSymbolInfo(returnStmt.Expression).Symbol;
            Dictionary <ClassDeclarationSyntax, IdentifierNameSyntax> stateMap = null;

            if (!StateTransitionAnalysis.TryParseStateMap(out stateMap, returnSymbol,
                                                          defineGotoStateTransitionsMethod, model))
            {
                return(false);
            }

            foreach (var state in stateMap)
            {
                if (state.Value == null)
                {
                    continue;
                }

                var dictionarySymbol      = model.GetSymbolInfo(state.Value).Symbol;
                var dictionaryInvocations = StateTransitionAnalysis.GetInvocationsFromSymbol(
                    dictionarySymbol, defineGotoStateTransitionsMethod);

                var transitions = ParseTransitions(dictionarySymbol,
                                                   defineGotoStateTransitionsMethod, model);
                if (transitions.Count == 0)
                {
                    continue;
                }

                stateTransitions.Add(state.Key, transitions);
            }

            return(true);
        }
示例#26
0
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                // Turn event fields into event declarations.
                var events = node.ChildNodes().OfType <EventFieldDeclarationSyntax>().ToArray();

                node = node.RemoveNodes(events, SyntaxRemoveOptions.KeepNoTrivia);

                node = node.AddMembers(events
                                       .Select(x => EventDeclaration(x.Declaration.Type, x.Declaration.Variables.First().Identifier)
                                               .WithModifiers(x.Modifiers))
                                       .ToArray());

                return(node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node));
            }
示例#27
0
        /// <summary>
        /// Computes the summary for the given method.
        /// </summary>
        /// <param name="method">Method</param>
        /// <param name="machine">Machine</param>
        /// <param name="state">State</param>
        private static void ComputeSummaryForMethod(MethodDeclarationSyntax method,
                                                    ClassDeclarationSyntax machine, ClassDeclarationSyntax state)
        {
            List <InvocationExpressionSyntax> givesUpSources = new List <InvocationExpressionSyntax>();

            foreach (var call in method.DescendantNodes().OfType <InvocationExpressionSyntax>())
            {
                var model = AnalysisContext.Compilation.GetSemanticModel(call.SyntaxTree);

                var callSymbol = model.GetSymbolInfo(call).Symbol;
                if (callSymbol == null)
                {
                    continue;
                }

                var definition = SymbolFinder.FindSourceDefinitionAsync(callSymbol, ProgramInfo.Solution).Result;
                if (definition == null)
                {
                    continue;
                }

                var callee       = Utilities.GetCallee(call);
                var calleeMethod = definition.DeclaringSyntaxReferences.First().GetSyntax()
                                   as BaseMethodDeclarationSyntax;

                if (Utilities.IsSourceOfGivingUpOwnership(call, model, callee) ||
                    AnalysisContext.Summaries.ContainsKey(calleeMethod))
                {
                    givesUpSources.Add(call);
                }
                else if (machine.ChildNodes().OfType <BaseMethodDeclarationSyntax>().Contains(calleeMethod) &&
                         !AnalysisContext.Summaries.ContainsKey(calleeMethod) &&
                         !calleeMethod.Modifiers.Any(SyntaxKind.AbstractKeyword))
                {
                    return;
                }
            }

            MethodSummary summary = MethodSummary.Factory.Summarize(method, machine, state);

            foreach (var givesUpNode in summary.GivesUpNodes)
            {
                MethodSummaryAnalysis.TryComputeGivesUpSetForSendControlFlowGraphNode(
                    givesUpNode, summary);
                MethodSummaryAnalysis.TryComputeGivesUpSetForCreateControlFlowGraphNode(
                    givesUpNode, summary);
                MethodSummaryAnalysis.TryComputeGivesUpSetForGenericControlFlowGraphNode(
                    givesUpNode, summary);
            }
        }
示例#28
0
            public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
            {
                node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);

                if (node.Identifier.ValueText == "Apis")
                {
                    if (!node.ChildNodes().Any())
                    {
                        return(null);
                    }
                }

                return(node);
            }
示例#29
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var type = node.ChildNodes().OfType <BaseListSyntax>().FirstOrDefault();

            var symbol = _model.GetDeclaredSymbol(node);

            if (type == null)
            {
                node = node.AddBaseListTypes(SyntaxFactory.SimpleBaseType
                                             (

                                                 SyntaxFactory.QualifiedName
                                                 (
                                                     SyntaxFactory.IdentifierName("System"),
                                                     SyntaxFactory.IdentifierName("Object").WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine))
                                                 )
                                             ));
                var eol = node.ChildTokens().OfType <SyntaxToken>().ElementAt(1);
                var ws  = eol.ReplaceTrivia(eol.TrailingTrivia.Last(), SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(eol, ws);
                var colon   = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                var colonws = colon.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(colon, colonws);
            }
            else if (symbol.BaseType.Name == "Object" && (symbol.BaseType.ToString() != "Object" && symbol.BaseType.ToString() != "System.Object"))
            {
                var blist = node.BaseList.Types.Insert(0, SyntaxFactory.SimpleBaseType(
                                                           SyntaxFactory.QualifiedName
                                                           (
                                                               SyntaxFactory.IdentifierName("System"),
                                                               SyntaxFactory.IdentifierName("Object")
                                                           )).WithTrailingTrivia(SyntaxFactory.Whitespace(" ")));
                node = node.ReplaceNode(node.BaseList, SyntaxFactory.BaseList(blist));
                SyntaxToken comma = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                foreach (SyntaxToken token in node.BaseList.ChildTokens().OfType <SyntaxToken>())
                {
                    if (token.ValueText == ",")
                    {
                        comma = token;
                    }
                }
                var ncomma = comma.WithTrailingTrivia(SyntaxFactory.Whitespace(" "));
                node = node.ReplaceToken(comma, ncomma);
                var colon   = node.BaseList.ChildTokens().OfType <SyntaxToken>().FirstOrDefault();
                var colonws = colon.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));
                node = node.ReplaceToken(colon, colonws);
            }

            return(base.VisitClassDeclaration(node));
        }
        /// <summary>
        /// Checks if the given name is a state of the given machine.
        /// </summary>
        /// <param name="name">string</param>
        /// <param name="machine">Machine</param>
        /// <returns>Boolean value</returns>
        private static bool IsStateOfTheMachine(string name, ClassDeclarationSyntax machine)
        {
            List <string> stateNames = new List <string>();

            foreach (var nestedClass in machine.ChildNodes().OfType <ClassDeclarationSyntax>())
            {
                stateNames.Add(nestedClass.Identifier.ValueText);
            }

            if (stateNames.Any(str => str.Equals(name)))
            {
                return(true);
            }

            return(false);
        }