private static BlockSyntax ProcessLoanCodeCondition(int loanCode, BlockSyntax currentBlock,
                                                            List <LiteralExpressionSyntax> initializationExpressions)
        {
            var assignmentStatement = ReinitializeTargetArrayy(currentBlock, initializationExpressions);

            currentBlock = currentBlock.AddStatements
                               (new StatementSyntax[] { assignmentStatement });

            var codeExpression = SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.IdentifierName("data"),
                SyntaxFactory.IdentifierName("Code" + loanCode));
            var target = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                              SyntaxFactory.IdentifierName("target"), SyntaxFactory.IdentifierName("Contains"));

            var argument     = SyntaxFactory.Argument(codeExpression);
            var argumentList = SyntaxFactory.SeparatedList(new[] { argument });

            var contains    = SyntaxFactory.InvocationExpression(target, SyntaxFactory.ArgumentList(argumentList));
            var notContains = SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression, contains,
                                                             SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression));
            var newConditional = SyntaxFactory.IfStatement(notContains, ReturnFalse());

            return(currentBlock.AddStatements(new StatementSyntax[] { newConditional }));
        }
예제 #2
0
        internal static MethodDeclarationSyntax MakeOnUpdateOverride(BlockSyntax blockSyntax, bool needToCompleteDependenciesFirst, Dictionary <Type, string> createdManagers)
        {
            if (needToCompleteDependenciesFirst)
            {
                return(MethodDeclaration(
                           PredefinedType(Token(SyntaxKind.VoidKeyword)),
                           Identifier("OnUpdate"))
                       .WithModifiers(
                           TokenList(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)))
                       .WithBody(
                           blockSyntax)
                       .NormalizeWhitespace());
            }

            foreach (var barrierSystem in createdManagers)
            {
                blockSyntax = blockSyntax.AddStatements(
                    ExpressionStatement(
                        InvocationExpression(
                            MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                IdentifierName(barrierSystem.Value),
                                IdentifierName(nameof(EntityCommandBufferSystem.AddJobHandleForProducer))))
                        .WithArgumentList(
                            ArgumentList(
                                SingletonSeparatedList(
                                    Argument(
                                        IdentifierName(InputDeps)))))));
            }

            blockSyntax = blockSyntax.AddStatements(
                ReturnStatement(IdentifierName(InputDeps))
                );

            return(MethodDeclaration(
                       IdentifierName("JobHandle"),
                       Identifier("OnUpdate"))
                   .WithModifiers(
                       TokenList(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)))
                   .WithParameterList(
                       ParameterList(
                           SingletonSeparatedList(
                               Parameter(
                                   Identifier(InputDeps))
                               .WithType(
                                   IdentifierName("JobHandle")))))
                   .WithBody(
                       blockSyntax)
                   .NormalizeWhitespace());
        }
예제 #3
0
        public override SyntaxNode VisitBlock(BlockSyntax node)
        {
            node = (BlockSyntax)base.VisitBlock(node);

            var matchingInvocations = node
                                      .Descendants <InvocationExpressionSyntax>()
                                      .Where(i => InvocationMatches(i, _method.Type, _method.Name))
                                      .ToList();

            foreach (var invocation in matchingInvocations)
            {
                var visitor = new ReplaceMethodVisitor(_context, _method, _newMethod1);
                node = node.ReplaceNode(
                    invocation,
                    visitor.VisitInvocationExpression(invocation)
                    .WithTriviaFrom(invocation));

                var variable = invocation.Expression
                               .Descendants <IdentifierNameSyntax>()
                               .First();

                node = node.AddStatements(ExpressionStatement(
                                              CreateInvocation(variable.ToString(), _newMethod2.Name, _newMethod2.Arguments))
                                          .WithTriviaFrom(node.Statements.Last()));
            }

            return(node);
        }
예제 #4
0
        private static void AddToCurrentBlock(StatementSyntax newStatement)
        {
            BlockSyntax oldBlock = root.DescendantNodes().OfType <BlockSyntax>().Where(n => n.HasAnnotation(currentBlock)).Single();
            BlockSyntax newBlock = oldBlock.AddStatements(newStatement);

            root = root.ReplaceNode(oldBlock, newBlock);
        }
예제 #5
0
        public static BlockSyntax Local(this BlockSyntax block, string name, ExpressionSyntax initializer, out VariableDeclaratorSyntax variable)
        {
            var declaration = Local(name, initializer, out variable);

            block = block.AddStatements(declaration);
            return(block);
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            MethodDeclarationSyntax methodDeclaration,
            CancellationToken cancellationToken)
        {
            BlockSyntax body = Block();

            TypeSyntax returnType = methodDeclaration.ReturnType;

            if (returnType?.IsVoid() == false)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);

                ExpressionSyntax expression = methodSymbol.ReturnType.GetDefaultValueSyntax(returnType);

                body = body.AddStatements(ReturnStatement(expression));
            }

            body = body.WithFormatterAnnotation();

            MethodDeclarationSyntax newNode = methodDeclaration
                                              .WithModifiers(methodDeclaration.Modifiers.Replace(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword))
                                              .WithBody(body)
                                              .WithSemicolonToken(default(SyntaxToken))
                                              .WithTrailingTrivia(methodDeclaration.GetTrailingTrivia());

            return(await document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken).ConfigureAwait(false));
        }
예제 #7
0
        private static BlockSyntax WriteDeSerializer(Type t, BlockSyntax b, ExpressionSyntax member)
        {
            b = b.AddStatements(LocalDeclarationStatement(VariableDeclaration(GenericName(Identifier("Span"))
                                                                              .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
                                                          .AddVariables(VariableDeclarator(Identifier("value")))));

            foreach (var p in t.GetProperties())
            {
                b = b.AddStatements(IfStatement(InvocationExpression(
                                                    MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("value"), IdentifierName("Equals")))
                                                .AddArgumentListArguments(Argument(SpanHelpers.NewSpan(p.Name))), Block()));
            }



            return(b);
        }
        private BlockSyntax AddReturnStatement(BlockSyntax node)
        {
            var leadingTrivia = node.Statements.Count > 0
                                ? node.Statements[0].GetLeadingWhitespace()
                                : Whitespace(node.GetLeadingWhitespace().ToFullString() + _transformResult.IndentTrivia.ToFullString());

            return(node.AddStatements(GetReturnTaskCompleted().WithLeadingTrivia(TriviaList(leadingTrivia))));
        }
 public static BlockSyntax DeclareVariable(this BlockSyntax block, string name, ExpressionSyntax value) =>
 block.AddStatements(
     LocalDeclarationStatement(
         Var()
         .WithVariables(
             SingletonSeparatedList(
                 VariableDeclarator(
                     Identifier(name))
                 .WithInitializer(
                     EqualsValueClause(value))))));
예제 #10
0
        public static BlockSyntax If(this BlockSyntax block, ExpressionSyntax condition, StatementSyntax ifTrue, StatementSyntax ifFalse = null)
        {
            var result = SyntaxFactory.IfStatement(condition, ifTrue);

            if (ifFalse != null)
            {
                result = result.WithElse(SyntaxFactory.ElseClause(ifFalse));
            }
            return(block.AddStatements(result));
        }
예제 #11
0
        private static BlockSyntax AddNotNullStatement(this BlockSyntax blockSyntax, string fieldName,
                                                       ExpressionSyntax fieldIdentifierName)
        {
            var fieldNotNullStatement = RoslynUtils.CheckNullStatement(
                fieldName,
                SyntaxFactory.ReturnStatement(fieldIdentifierName),
                invert: true
                );

            return(blockSyntax.AddStatements(fieldNotNullStatement));
        }
예제 #12
0
        void BuildCoroutineStack(IIteratorStackModel stack, ref BlockSyntax block)
        {
            PushContext(stack, context.IterationContext.UpdateMode, true);

            var ctx = (CoroutineContext)context;

            ctx.BuildComponent(stack, this);

            var statement = PopContext();

            block = block.AddStatements(statement.ToArray());
        }
예제 #13
0
        void BuildCoroutine(ref BlockSyntax block)
        {
            PushContext(context.IterationContext.Query, context.IterationContext.UpdateMode);

            var ctx = (CoroutineContext)context;

            ctx.BuildComponent(this);

            var statement = PopContext();

            block = block.AddStatements(statement.ToArray());
        }
        private static ClassDeclarationSyntax GenerateWriteGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface, int readReplicaCount)
        {
            string grainName                   = grainClass.Identifier.Text;
            string writerGrainName             = SwmrUtils.GetWriteInterfaceName(grainName);
            string writerInterfaceName         = SwmrUtils.GetWriteInterfaceName(swmrInterface.Name);
            ClassDeclarationSyntax writerGrain = GenerateClassSqueleton(writerGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", writerInterfaceName }));

            writerGrain = RoslynUtils.AddField(writerGrain, "ITopology<string>", "_topology");
            writerGrain = writerGrain.AddMembers(GenerateOnActivateAsyncMethod(readReplicaCount));

            string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name);

            foreach (ISymbol member in swmrInterface.GetMembers())
            {
                IMethodSymbol methodSymbol = member as IMethodSymbol;
                if (methodSymbol == null || IsReadOnlyMethod(methodSymbol) || new MethodInspector(methodSymbol).MethodName == "GetState")
                {
                    continue;
                }

                MethodInspector         methodInspector = new MethodInspector(methodSymbol);
                MethodDeclarationSyntax methodImpl      = GenerateMethodDeclaration(methodInspector);
                methodImpl = SwmrUtils.AddSessionIdParameter(methodImpl).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.AsyncKeyword)).WithSemicolonToken(SF.Token(SyntaxKind.None));

                BlockSyntax statmentBlock = SF.Block();
                statmentBlock = AddStatement(statmentBlock, "string grainId = this.GetPrimaryKeyString();");
                statmentBlock = AddStatement(statmentBlock, string.Format("{0} grain = GrainFactory.GetGrain<{0}>(grainId);", swmrInterface.Name));
                statmentBlock = AddStatement(statmentBlock, String.Format("{0} await grain.{1}({2});", methodInspector.ReturnType != "Task"? "var result =" : "", methodInspector.MethodName, string.Join(", ", methodInspector.MethodParams.Keys)));
                statmentBlock = AddStatement(statmentBlock, "GrainState state = await grain.GetState();");
                statmentBlock = AddStatement(statmentBlock, "string sessionNode = _topology.GetNode(sessionId);");
                statmentBlock = AddStatement(statmentBlock, "IEnumerable<string> otherNodes = _topology.Nodes.Where(node => node != sessionNode);");

                ForEachStatementSyntax forEachStatement = SF.ForEachStatement(
                    SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword)),
                    SF.Identifier("node"),
                    SF.IdentifierName("otherNodes"),
                    SF.Block(SF.ParseStatement(GenerateSetStateStmt(readReplicaInterfaceName, @"node")))
                    );

                statmentBlock = statmentBlock.AddStatements(forEachStatement);
                statmentBlock =
                    AddStatement(statmentBlock, (string.Format("{0} {1}", "await",
                                                               GenerateSetStateStmt(readReplicaInterfaceName, @"sessionNode"))));
                if (methodInspector.ReturnType != "Task")
                {
                    statmentBlock = AddStatement(statmentBlock, "return result;");
                }
                methodImpl  = methodImpl.WithBody(statmentBlock);
                writerGrain = writerGrain.AddMembers(methodImpl);
            }

            return(writerGrain);
        }
        private BlockSyntax PopulateRequiredConstructorBodyInitializers(BlockSyntax body, TransportModelEntity entityModel)
        {
            if (entityModel.TsDiscriminant is TransportModelEntityTsDiscriminantSyntaxKind kindDiscriminant)
            {
                body = body.AddStatements(
                    ExpressionStatement(
                        AssignmentExpression(
                            SyntaxKind.SimpleAssignmentExpression,
                            MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                ThisExpression(),
                                IdentifierName("kind")),
                            MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                IdentifierName($"{this.settings.CsTransportModelNamespace}.SyntaxKind"),
                                IdentifierName(kindDiscriminant.SyntaxKindValueName)))));
            }

            foreach (var property in entityModel.Members)
            {
                if (CsEmitterHelper.IsNodeCollection(property.Value.Type))
                {
                    body = body.AddStatements(
                        ExpressionStatement(
                            AssignmentExpression(
                                SyntaxKind.SimpleAssignmentExpression,
                                MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    ThisExpression(),
                                    IdentifierName(NameHelper.GetSafeVariableName(property.Key))),
                                ObjectCreationExpression(
                                    ParseTypeName(CsEmitterHelper.GetAstModelPropertyTypeName(property.Value, this.settings)),
                                    ArgumentList(SeparatedList <ArgumentSyntax>(new[] { Argument(ThisExpression()) })),
                                    null))));
                }
            }

            return(body);
        }
예제 #16
0
 public override SyntaxNode VisitBlock(BlockSyntax node)
 {
     if (_applicationStart)
     {
         _applicationStart = false;
         if (_notPartialClass)
         {
             using (var globalModelSR = new StreamReader(_globalAsaxCsModelPath))
             {
                 _globalModel = globalModelSR.ReadToEnd();
             }
             _globalModelCompilationUnit = SyntaxFactory.ParseCompilationUnit(_globalModel);
             var globalModelNamespace = _globalModelCompilationUnit.ChildNodes().OfType<NamespaceDeclarationSyntax>().First();
             var globalModelClass = globalModelNamespace.ChildNodes().OfType<ClassDeclarationSyntax>().First();
             var globalModelApplicationStart = globalModelClass.ChildNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "Application_Start");
             var globalModelApplicationStartBody = globalModelApplicationStart.Body;
             node = node.AddStatements(globalModelApplicationStartBody.Statements.ToArray());
         }
         return node.AddStatements(SyntaxFactory.ParseStatement("Global." + _edmxName + "ApplicationStart(unityContainer);"));
     }
     return base.VisitBlock(node);
 }
예제 #17
0
 public override SyntaxNode VisitBlock(BlockSyntax node)
 {
     if (_applicationStart)
     {
         _applicationStart = false;
         if (_notPartialClass)
         {
             using (var globalModelSR = new StreamReader(_globalAsaxCsModelPath))
             {
                 _globalModel = globalModelSR.ReadToEnd();
             }
             _globalModelCompilationUnit = SyntaxFactory.ParseCompilationUnit(_globalModel);
             var globalModelNamespace            = _globalModelCompilationUnit.ChildNodes().OfType <NamespaceDeclarationSyntax>().First();
             var globalModelClass                = globalModelNamespace.ChildNodes().OfType <ClassDeclarationSyntax>().First();
             var globalModelApplicationStart     = globalModelClass.ChildNodes().OfType <MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "Application_Start");
             var globalModelApplicationStartBody = globalModelApplicationStart.Body;
             node = node.AddStatements(globalModelApplicationStartBody.Statements.ToArray());
         }
         return(node.AddStatements(SyntaxFactory.ParseStatement("Global." + _edmxName + "ApplicationStart(unityContainer);")));
     }
     return(base.VisitBlock(node));
 }
        public void MethodDeclarationAddExpression()
        {
            BlockSyntax nodeBody = _node.Body;

            nodeBody = nodeBody.AddStatements(SyntaxFactory.ParseStatement("string testing = \"Testing\";"));
            _node    = _node.WithBody(nodeBody);

            const string expression            = "int i = 5;";
            var          addExpressionFunction = _methodDeclarationActions.GetAppendExpressionAction(expression);
            var          newNode = addExpressionFunction(_syntaxGenerator, _node);

            StringAssert.Contains(expression, newNode.ToFullString());
        }
예제 #19
0
        private static BlockSyntax AddRuleReturnValue(BlockSyntax currentBlock, GreetingRuleDetail rule)
        {
            var ruleGreeting = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                               SyntaxFactory.Literal(rule.Greeting));
            var lastName = SyntaxFactory.MemberAccessExpression
                               (SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("data"),
                               SyntaxFactory.IdentifierName("LastName"));
            var assignment = SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression,
                                                            ruleGreeting, lastName);
            var returnStatement = SyntaxFactory.ReturnStatement(assignment);

            return(currentBlock.AddStatements(new StatementSyntax[] { returnStatement }));
        }
예제 #20
0
        public override SyntaxNode VisitBlock(BlockSyntax node)
        {
            var newStatement =
                ExpressionStatement(
                    InvocationExpression(
                        IdentifierName("ShowReportableError"))
                    .WithArgumentList(
                        ArgumentList(
                            SingletonSeparatedList <ArgumentSyntax>(
                                Argument(IdentifierName(name))))))
                .NormalizeWhitespace();

            return(node.AddStatements(newStatement));
        }
예제 #21
0
        private static BlockSyntax ProcessEqualityComparison(string whichEquality,
                                                             int gender, BlockSyntax currentBlock)
        {
            var genderReference = SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.IdentifierName("data"),
                SyntaxFactory.IdentifierName(whichEquality));
            var condition = SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression,
                                                           genderReference, SyntaxFactory.LiteralExpression(
                                                               SyntaxKind.NumericLiteralExpression,
                                                               SyntaxFactory.Literal(gender)));
            var newConditional = SyntaxFactory.IfStatement(condition, ReturnNull());

            return(currentBlock.AddStatements(new StatementSyntax[] { newConditional }));
        }
        private static BlockSyntax ProcessLoanCodeRangeCondition(int loanCodeTypeId,
                                                                 BlockSyntax underwritingRule, SyntaxKind comparisonType, decimal codeValue)
        {
            var codeExpression = SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.IdentifierName("data"),
                SyntaxFactory.IdentifierName("Code" + loanCodeTypeId));
            var condition = SyntaxFactory.BinaryExpression(comparisonType,
                                                           codeExpression, SyntaxFactory.LiteralExpression(
                                                               SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(codeValue)));

            var newConditional = SyntaxFactory.IfStatement(condition, ReturnFalse());

            return(underwritingRule.AddStatements(new StatementSyntax[] { newConditional }));
        }
예제 #23
0
        private static BlockSyntax ProcessHourCondition(int hourValue, BlockSyntax currentBlock,
                                                        SyntaxKind comparisonType)
        {
            var hourExpression = SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.IdentifierName("data"),
                SyntaxFactory.IdentifierName("Hour"));
            var condition = SyntaxFactory.BinaryExpression(comparisonType,
                                                           hourExpression,
                                                           SyntaxFactory.LiteralExpression(
                                                               SyntaxKind.NumericLiteralExpression,
                                                               SyntaxFactory.Literal(hourValue)));
            var newConditional = SyntaxFactory.IfStatement(condition, ReturnNull());

            return(currentBlock.AddStatements(new StatementSyntax[] { newConditional }));
        }
예제 #24
0
        private async Task <Document> HandleMacroInsideTheBlock(Document document, Location diagnosticLocation, CancellationToken cancellationToken, BlockSyntax block)
        {
            foreach (var statement in block.Statements)
            {
                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.ParseStatement(newContent);
                        var newBlock   = block.ReplaceNode(statement, new SyntaxNode[]
                        {
                            syntaxTree.WithLeadingTrivia(leadingTrivia),
                            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.ParseStatement(newContent);
                        var newBlock   = block.AddStatements(syntaxTree.WithLeadingTrivia(leadingTrivia));
                        newBlock = newBlock.WithCloseBraceToken(
                            block.CloseBraceToken.WithLeadingTrivia(block.CloseBraceToken.LeadingTrivia.LastOrDefault()));
                        return(await ReplaceNodes(document, block, newBlock.WithAdditionalAnnotations(Formatter.Annotation),
                                                  cancellationToken));
                    }
                }
            }
            return(document);
        }
예제 #25
0
        public Func <SyntaxGenerator, MethodDeclarationSyntax, MethodDeclarationSyntax> GetAppendExpressionAction(string expression)
        {
            // TODO: This will add an expression at the bottom of a method body, in the future we should add granularity for where to add the expression within a method body
            Func <SyntaxGenerator, MethodDeclarationSyntax, MethodDeclarationSyntax> AppendExpression = (SyntaxGenerator syntaxGenerator, MethodDeclarationSyntax node) =>
            {
                StatementSyntax statementExpression = SyntaxFactory.ParseStatement(expression);
                if (!statementExpression.FullSpan.IsEmpty)
                {
                    BlockSyntax nodeBody = node.Body;
                    nodeBody = nodeBody.AddStatements(statementExpression);
                    node     = node.WithBody(nodeBody).NormalizeWhitespace();
                }
                return(node);
            };

            return(AppendExpression);
        }
예제 #26
0
        private static BlockSyntax AddLockStatement(
            this BlockSyntax blockSyntax,
            string lockObjectName,
            string fieldName,
            ExpressionSyntax fieldIdentifierName,
            ExpressionSyntax fieldAssignmentExpression)
        {
            var assignmentStatement = RoslynUtils.AssignmentExpression(fieldName, fieldAssignmentExpression);
            var fieldNullStatement  = RoslynUtils.CheckNullStatement(fieldName,
                                                                     assignmentStatement.ToStatement());

            var lockStat = RoslynUtils.LockStatement(
                SyntaxFactory.IdentifierName(lockObjectName),
                SyntaxFactory.Block(fieldNullStatement, SyntaxFactory.ReturnStatement(fieldIdentifierName))
                );

            return(blockSyntax.AddStatements(lockStat));
        }
예제 #27
0
        public static BlockSyntax GenerateRegisterCommandStatementsBlock(XDocument vsctDocument)
        {
            BlockSyntax blockSyntax = SyntaxFactory.Block();
            XElement    xelement    = vsctDocument.Root.Element(XNames.Commands).Element(XNames.Buttons);

            if (xelement != null && xelement.HasElements)
            {
                foreach (XElement element in xelement.Elements(XNames.Button))
                {
                    string id = element.AttributeValueNull("id");
                    blockSyntax = blockSyntax.AddStatements(new StatementSyntax[1]
                    {
                        VsctHelper.GenerateRegisterCommandStatement(id)
                    });
                }
            }
            return(blockSyntax);
        }
예제 #28
0
 public static BlockSyntax InsertAfter(
     this BlockSyntax blockSyntax,
     ExpressionStatementSyntax statement,
     ExpressionStatementSyntax statementToInsert)
 {
     var idx = blockSyntax.Statements.IndexOf(statement);
     if (idx == -1)
     {
         return blockSyntax;
     }
     else if (idx == blockSyntax.Statements.Count - 1)
     {
         return blockSyntax.AddStatements(statementToInsert);
     }
     else
     {
         return blockSyntax.WithStatements(
             blockSyntax.Statements.Insert(idx + 1, statementToInsert));
     }
 }
예제 #29
0
        private SyntaxNode ImplementConstructorBody(BlockSyntax declaration,
                                                    string sourcename,
                                                    ITypeSymbol targetTypeInfo,
                                                    SemanticModel semanticModel,
                                                    ITypeSymbol sourceType)
        {
            var missingprops = GetMissingProperties(declaration, targetTypeInfo);

            var newproperties =
                sourceType.GetMembers().Where(x => x.Kind == SymbolKind.Property).Cast <IPropertySymbol>().Where(x => x.IsMissing(missingprops));
            var newExpression = declaration.AddStatements(
                newproperties.Select(x =>
                                     SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                        SyntaxFactory.IdentifierName(x.Name),
                                                                        SyntaxFactory.MemberAccessExpression(
                                                                            SyntaxKind.SimpleMemberAccessExpression,
                                                                            SyntaxFactory.IdentifierName(sourcename),
                                                                            SyntaxFactory.IdentifierName(x.Name))))
                .Cast <ExpressionSyntax>().Select(SyntaxFactory.ExpressionStatement).ToArray <StatementSyntax>());

            return(newExpression);
        }
예제 #30
0
        /// <summary> Modify the method found in GetOriginalMethodDeclarationSyntax(). </summary>
        private static MethodDeclarationSyntax GetModifiedMethodDeclarationSyntax(MethodDeclarationSyntax method, MethodModificationData modificationData)
        {
            var nodes = method.DescendantNodes().ToList();

            ParameterListSyntax paramListSyntax = SyntaxFactory.ParameterList();

            foreach (var param in modificationData.m_NewMethodParams)
            {
                paramListSyntax = paramListSyntax.AddParameters(CodeGenerationUtility.CreateParameterSyntax(param.m_ParamName, param.m_ParamType));
            }

            method = modificationData.m_ParamModificationType == MethodParameterModificationType.REPLACE_PARAMS
                ? method.WithParameterList(paramListSyntax)
                : method.AddParameterListParameters(paramListSyntax.Parameters.ToArray());

            BlockSyntax blockSyntax   = SyntaxFactory.Block();
            var         oldStatements = method.Body.Statements.ToList();

            foreach (var statement in modificationData.m_BodyStatements)
            {
                if (modificationData.m_BodyModificationType == MethodBodyModificationType.ADD_OR_REPLACE_BODY)
                {
                    if (oldStatements.Find(x => x.ToFullString().Contains(statement)) != null)
                    {
                        continue;
                    }
                }

                blockSyntax = blockSyntax.AddStatements(SyntaxFactory.ParseStatement(statement));
            }

            // if replacing the body, the statement in the old function with be completely replaced with the new statement
            method = modificationData.m_BodyModificationType == MethodBodyModificationType.REPLACE_BODY
                ? method.WithBody(blockSyntax)
                : method.AddBodyStatements(blockSyntax.Statements.ToArray());

            return(method.NormalizeWhitespace());
        }
예제 #31
0
        public virtual void BuildStack(IStackModel stack, ref BlockSyntax blockNode,
                                       StackExitStrategy exitStrategy = StackExitStrategy.Return)
        {
            if (stack == null || stack.State == ModelState.Disabled)
            {
                return;
            }

            RegisterBuiltStack(stack);

            // JUST in case... until we validate the previous failsafe
            if (m_BuiltStackCounter++ > 10000)
            {
                throw new InvalidOperationException("Infinite loop while building the script, aborting");
            }

            StackExitStrategy origStackExitStrategy = m_StackExitStrategy;

            if (exitStrategy != StackExitStrategy.Inherit)
            {
                m_StackExitStrategy = exitStrategy;
            }

//            Debug.Log($"Build stack {stack}");
            // m_EndStack might get changed by recursive BuildNode() calls
            StackBaseModel origEndStack = EndStack;
            var            statements   = new List <StatementSyntax>();

            foreach (var statement in stack.NodeModels)
            {
                if (statement.State == ModelState.Disabled)
                {
                    continue;
                }
                var syntaxNodes = BuildNode(statement);
                foreach (var syntaxNode in syntaxNodes)
                {
                    switch (syntaxNode)
                    {
                    case StatementSyntax statementNode:
                        statements.Add(statementNode);
                        break;

                    case ExpressionSyntax expressionNode:
                        statements.Add(ExpressionStatement(expressionNode)
                                       .WithAdditionalAnnotations(new SyntaxAnnotation(Annotations.AnnotationKind,
                                                                                       statement.Guid.ToString()))
                                       );
                        break;

                    default:
                        throw new InvalidOperationException($"Expected a statement or expression node, found a {syntaxNode.GetType()} when building {statement}");
                    }
                }
            }

            blockNode = blockNode.AddStatements(statements.ToArray());

            if (stack.DelegatesOutputsToNode(out _))
            {
                var nextStack = EndStack;
                m_StackExitStrategy = origStackExitStrategy;

//                Debug.Log($"Stack {stack} delegates ports. nextStack {nextStack} origEndStack {origEndStack}");

                // if a nested node changed the end stack, but found the same common descendant,
                // let the parent call handle it
                if (EndStack == origEndStack)
                {
                    return;
                }

                EndStack = origEndStack;
                BuildStack(nextStack, ref blockNode, exitStrategy);

                return;
            }

            bool anyConnection = false;

            foreach (var outputPort in stack.OutputPorts)
            {
                foreach (var connectedStack in outputPort.ConnectionPortModels)
                {
                    if (connectedStack.NodeModel is IStackModel nextStack)
                    {
                        anyConnection = true;
                        if (!ReferenceEquals(nextStack, EndStack))
                        {
                            BuildStack(nextStack, ref blockNode, StackExitStrategy.Inherit);
                        }
                    }
                }
            }


            // TODO use function default return value
            StatementSyntax lastStatementSyntax = blockNode.Statements.LastOrDefault();

            if (!anyConnection && !(lastStatementSyntax is ReturnStatementSyntax) && !(lastStatementSyntax is ContinueStatementSyntax))
            {
                //TODO we had that for a reason
//                lastStatementSyntax = StatementFromExitStrategy(m_StackExitStrategy, null);

//                if(lastStatementSyntax != null)
//                    blockNode = blockNode.AddStatements(lastStatementSyntax);
            }

            m_StackExitStrategy = origStackExitStrategy;
        }
            private SyntaxNode ImplementConstructorBody(BlockSyntax declaration,
                                                                                 string sourcename,
                                                                                 ITypeSymbol targetTypeInfo,
                                                                                 ITypeSymbol sourceType)
            {
                var missingprops = GetMissingProperties(declaration, targetTypeInfo);

                var newproperties =
                    sourceType.GetMembers().Where(x => x.Kind == SymbolKind.Property).Cast<IPropertySymbol>().Where(x => x.IsMissing(missingprops));
                var newExpression = declaration.AddStatements(
                    newproperties.Select(x =>
                                             SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                SyntaxFactory.IdentifierName(x.Name),
                                                                                SyntaxFactory.MemberAccessExpression(
                                                                                    SyntaxKind.SimpleMemberAccessExpression,
                                                                                    SyntaxFactory.IdentifierName(sourcename),
                                                                                    SyntaxFactory.IdentifierName(x.Name))))
                        .Cast<ExpressionSyntax>().Select(SyntaxFactory.ExpressionStatement).ToArray<StatementSyntax>());
                return newExpression;
            }
		public UnityInitializationMethodImplementationProvider(IEnumerable<IInitializationExpression> expressions)
		{
			Block = SyntaxFactory.Block();

#if DEBUG || DEBUGBUILD
			if (expressions == null)
				throw new ArgumentNullException(nameof(expressions), "Expressions collection cannot be null in " + typeof(UnityInitializationMethodImplementationProvider) + " as it is required to build the init method.");
#endif

			//Add each expression as a statement to the block
			//WARNING: Do not use foreach. At least not with WithStatements. It'll override the previous Block staterments each time.
			Block = Block.AddStatements(expressions.Select(x => x.Statement).ToArray());

			/*//foreach serialized field in the MonoBehaviour we take a look at it, add a statement for setting it via reflection
			//find an adapter for the source to dest Type and create an instance of it to initialize the EngineScriptComponent
			foreach(InitializationExpressionData data in expressions)
			{
				string fasterFlectMethodName = data.DestinationMemberType == System.Reflection.MemberTypes.Field ?
					@"SetFieldValue" : @"SetPropertyValue"; //can't use nameof with extension method I think. Will

				//genertaed using: http://roslynquoter.azurewebsites.net/ do not attempt to read. Ask Andrew
				Block = Block.WithStatements(SyntaxFactory.SingletonList<StatementSyntax>(SyntaxFactory.ExpressionStatement(
								SyntaxFactory.InvocationExpression(
									SyntaxFactory.MemberAccessExpression(
										SyntaxKind.SimpleMemberAccessExpression,
										SyntaxFactory.IdentifierName(
											targetEngineComponentFieldName),
										SyntaxFactory.IdentifierName(
											fasterFlectMethodName)) //method to call. We're using fasterflect cached reflection
									.WithOperatorToken(
										SyntaxFactory.Token(
											SyntaxKind.DotToken)))
								.WithArgumentList(
									SyntaxFactory.ArgumentList(
										SyntaxFactory.SeparatedList<ArgumentSyntax>(
											new SyntaxNodeOrToken[]{
												SyntaxFactory.Argument(
													SyntaxFactory.IdentifierName(
														data.DestinationFieldName)), //changed to destination field name
												SyntaxFactory.Token(
													SyntaxKind.CommaToken),
												SyntaxFactory.Argument(
													SyntaxFactory.ObjectCreationExpression(
														SyntaxFactory.IdentifierName(
															data.AdapterData.AdapterType.FullName)) //changed to create a new adapter type
													.WithNewKeyword(
														SyntaxFactory.Token(
															SyntaxKind.NewKeyword))
													.WithArgumentList(
														SyntaxFactory.ArgumentList(
															SyntaxFactory.SingletonSeparatedList<ArgumentSyntax>(
																SyntaxFactory.Argument(
																	SyntaxFactory.IdentifierName(
																		data.SourceFieldName)))) //changed to be the source field name
														.WithOpenParenToken(
															SyntaxFactory.Token(
																SyntaxKind.OpenParenToken))
														.WithCloseParenToken(
															SyntaxFactory.Token(
																SyntaxKind.CloseParenToken))))}))
									.WithOpenParenToken(
										SyntaxFactory.Token(
											SyntaxKind.OpenParenToken))
									.WithCloseParenToken(
										SyntaxFactory.Token(
											SyntaxKind.CloseParenToken))))));
											*/
		}
 private static BlockSyntax AddStatement(BlockSyntax statementBlock, string statement)
 {
     return statementBlock.AddStatements(SF.ParseStatement(statement + "\n"));
 }