Exemplo n.º 1
0
    public void BeforeCompile(IBeforeCompileContext context)
    {
        // Firstly, I need to resolve the namespace of the ModuleProvider instance in this current compilation.
        string ns = GetModuleProviderNamespace(context.Compilation.SyntaxTrees);
        // Next, get all the available modules in assembly and compilation references.
        var modules = GetAvailableModules(context.Compilation).ToList();
        // Map them to a collection of statements
        var statements = modules.Select(m => F.ParseStatement("AddModule<" + module + ">();")).ToList();
        // Now, I'll create the dynamic implementation as a private class.
        var cu = F.CompilationUnit()
                 .AddMembers(
            F.NamespaceDeclaration(F.IdentifierName(ns))
            .AddMembers(
                F.ClassDeclaration("ModuleProvider")
                .WithModifiers(F.TokenList(F.Token(K.PartialKeyword)))
                .AddMembers(
                    F.MethodDeclaration(F.PredefinedType(F.Token(K.VoidKeyword)), "Setup")
                    .WithModifiers(
                        F.TokenList(
                            F.Token(K.ProtectedKeyword),
                            F.Token(K.OverrideKeyword)))
                    .WithBody(F.Block(statements))
                    )
                )
            )
                 .NormalizeWhitespace(indentation("\t"));
        var tree = T.Create(cu);

        context.Compilation = context.Compilation.AddSyntaxTrees(tree);
    }
        public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
        {
            var stmt = node.ForStatement;
            ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(_expressionVisitor);
            VariableDeclarationSyntax declaration = null;
            ExpressionSyntax          id;

            if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
            {
                var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                declaration = CommonConversions.SplitVariableDeclarations(v).Values.Single();
                declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
            }
            else
            {
                id = (ExpressionSyntax)stmt.ControlVariable.Accept(_expressionVisitor);
                var symbol = _semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol;
                if (symbol != null && !_semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any())
                {
                    declaration = CommonConversions.CreateVariableDeclarationAndAssignment(symbol.Name, startValue);
                }
                else
                {
                    startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue);
                }
            }

            var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(_expressionVisitor);
            PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
            ExpressionSyntax            condition;

            // In Visual Basic, the To expression is only evaluated once, but in C# will be evaluated every loop.
            // If it could evaluate differently or has side effects, it must be extracted as a variable
            var preLoopStatements = new List <SyntaxNode>();
            var csToValue         = (ExpressionSyntax)stmt.ToValue.Accept(_expressionVisitor);

            if (!_semanticModel.GetConstantValue(stmt.ToValue).HasValue)
            {
                var loopToVariableName = GetUniqueVariableNameInScope(node, "loopTo");
                var loopEndDeclaration = SyntaxFactory.LocalDeclarationStatement(CommonConversions.CreateVariableDeclarationAndAssignment(loopToVariableName, csToValue));
                // Does not do anything about porting newline trivia upwards to maintain spacing above the loop
                preLoopStatements.Add(loopEndDeclaration);
                csToValue = SyntaxFactory.IdentifierName(loopToVariableName);
            }
            ;

            if (value == null)
            {
                condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, csToValue);
            }
            else
            {
                condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, csToValue);
            }
            if (step == null)
            {
                step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
            }
            else
            {
                step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
            }
            var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)));
            var forStatementSyntax = SyntaxFactory.ForStatement(
                declaration,
                declaration != null
                    ? SyntaxFactory.SeparatedList <ExpressionSyntax>()
                    : SyntaxFactory.SingletonSeparatedList(startValue),
                condition,
                SyntaxFactory.SingletonSeparatedList(step),
                block.UnpackNonNestedBlock());

            return(SyntaxFactory.List(preLoopStatements.Concat(new[] { forStatementSyntax })));
        }
        public override SyntaxList <StatementSyntax> VisitSelectBlock(VBSyntax.SelectBlockSyntax node)
        {
            var expr = (ExpressionSyntax)node.SelectStatement.Expression.Accept(_expressionVisitor);
            var exprWithoutTrivia = expr.WithoutTrivia().WithoutAnnotations();
            var sections          = new List <SwitchSectionSyntax>();

            foreach (var block in node.CaseBlocks)
            {
                var labels = new List <SwitchLabelSyntax>();
                foreach (var c in block.CaseStatement.Cases)
                {
                    if (c is VBSyntax.SimpleCaseClauseSyntax s)
                    {
                        var originalExpressionSyntax = (ExpressionSyntax)s.Value.Accept(_expressionVisitor);
                        // CSharp allows an implicit cast from the base type (e.g. int) in the special case of switching on an enum
                        var expressionSyntax = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(s.Value, originalExpressionSyntax, implicitCastFromIntToEnum: true);
                        SwitchLabelSyntax caseSwitchLabelSyntax = SyntaxFactory.CaseSwitchLabel(expressionSyntax);
                        if (!_semanticModel.GetConstantValue(s.Value).HasValue || originalExpressionSyntax != expressionSyntax)
                        {
                            caseSwitchLabelSyntax =
                                WrapInCasePatternSwitchLabelSyntax(node, expressionSyntax);
                        }

                        labels.Add(caseSwitchLabelSyntax);
                    }
                    else if (c is VBSyntax.ElseCaseClauseSyntax)
                    {
                        labels.Add(SyntaxFactory.DefaultSwitchLabel());
                    }
                    else if (c is VBSyntax.RelationalCaseClauseSyntax relational)
                    {
                        var operatorKind     = VBasic.VisualBasicExtensions.Kind(relational);
                        var cSharpSyntaxNode = SyntaxFactory.BinaryExpression(operatorKind.ConvertToken(TokenContext.Local), exprWithoutTrivia, (ExpressionSyntax)relational.Value.Accept(_expressionVisitor));
                        labels.Add(WrapInCasePatternSwitchLabelSyntax(node, cSharpSyntaxNode, treatAsBoolean: true));
                    }
                    else if (c is VBSyntax.RangeCaseClauseSyntax range)
                    {
                        var lowerBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, (ExpressionSyntax)range.LowerBound.Accept(_expressionVisitor), exprWithoutTrivia);
                        var upperBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, exprWithoutTrivia, (ExpressionSyntax)range.UpperBound.Accept(_expressionVisitor));
                        var withinBounds    = SyntaxFactory.BinaryExpression(SyntaxKind.LogicalAndExpression, lowerBoundCheck, upperBoundCheck);
                        labels.Add(WrapInCasePatternSwitchLabelSyntax(node, withinBounds, treatAsBoolean: true));
                    }
                    else
                    {
                        throw new NotSupportedException(c.Kind().ToString());
                    }
                }

                var csBlockStatements = block.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)).ToList();
                if (csBlockStatements.LastOrDefault()
                    ?.IsKind(SyntaxKind.ReturnStatement) != true)
                {
                    csBlockStatements.Add(SyntaxFactory.BreakStatement());
                }
                var list = SingleStatement(SyntaxFactory.Block(csBlockStatements));
                sections.Add(SyntaxFactory.SwitchSection(SyntaxFactory.List(labels), list));
            }

            var switchStatementSyntax = ValidSyntaxFactory.SwitchStatement(expr, sections);

            return(SingleStatement(switchStatementSyntax));
        }
Exemplo n.º 4
0
        public static byte[] CreateControllerCode(IService service)
        {
            var @file      = SF.CompilationUnit();
            var @namespace = SF.NamespaceDeclaration(SF.ParseName("MBase.ServiceHost.Controllers")).NormalizeWhitespace();

            @file = @file
                    .AddUsings(SF.UsingDirective(SF.IdentifierName("System")));
            @file = @file
                    .AddUsings(SF.UsingDirective(SF.IdentifierName("Microsoft.AspNetCore.Mvc")));
            @file = @file
                    .AddUsings(SF.UsingDirective(SF.IdentifierName("System.Threading.Tasks")));

            @file = @file.AddUsings(SF.UsingDirective(SF.IdentifierName(service.GetType().Namespace)));
            @file = @file.AddUsings(SF.UsingDirective(SF.IdentifierName(service.GetType().Namespace + ".Models")));

            foreach (var item in service.Commands.Where(m => typeof(ICommand).IsAssignableFrom(m.GetType())))
            {
                @file = @file.AddUsings(SF.UsingDirective(SF.IdentifierName(item.GetType().Namespace)));
            }



            var classDeclaration = SF.ClassDeclaration(service.GetType().Name.ToString() + "Controller")
                                   .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                                   .AddBaseListTypes(SF.SimpleBaseType(SF.ParseTypeName("ControllerBase")))
                                   .WithAttributeLists(
                SF.List(
                    new AttributeListSyntax[] {
                SF.AttributeList(
                    SF.SingletonSeparatedList(
                        SF.Attribute(SF.IdentifierName("Route"))
                        .WithArgumentList(
                            SF.AttributeArgumentList(
                                SF.SingletonSeparatedList(
                                    SF.AttributeArgument(
                                        SF.LiteralExpression(SyntaxKind.StringLiteralExpression, SF.Literal($"api/[controller]")))))))),
                SF.AttributeList(
                    SF.SingletonSeparatedList(
                        SF.Attribute(SF.IdentifierName("ApiController"))))
            }));

            List <MemberDeclarationSyntax> controllerMembers = new List <MemberDeclarationSyntax>();

            controllerMembers.Add(
                SF.FieldDeclaration(
                    SF.VariableDeclaration(
                        SF.ParseTypeName(service.GetType().Name))
                    .AddVariables(SF.VariableDeclarator("_service")))
                .AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)));

            controllerMembers.Add(
                SF.ConstructorDeclaration(service.GetType().Name.ToString() + "Controller")
                .WithParameterList(
                    SF.ParameterList(
                        SF.SingletonSeparatedList(
                            SF.Parameter(
                                SF.Identifier("service"))
                            .WithType(
                                SF.IdentifierName("IService")))

                        ))
                .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                .WithBody(SF.Block(SF.ParseStatement($"this._service = ({service.GetType().Name})service;"))));

            foreach (var item in service.Commands.Where(m => typeof(ICommand).IsAssignableFrom(m.GetType())))
            {
                var syntax = @$ "

            var response = await CommandHelper.ExecuteMethod<{item.Name}>(new {item.Name}(),new Request<{item.Name}>(request, new MessageEnvelope()));
Exemplo n.º 5
0
        private static MethodDeclarationSyntax AddDeclarationAssignementLogging(MethodDeclarationSyntax methodDecl)
        {
            var declarations = methodDecl
                               .Body
                               .DescendantNodes()
                               .OfType <VariableDeclarationSyntax>()
                               .Where(methodDecl.DirectlyContains)
                               .Where(declaration =>
                                      declaration
                                      .ChildNodes().OfType <VariableDeclaratorSyntax>()
                                      .SelectMany(node => node.ChildNodes().OfType <EqualsValueClauseSyntax>())
                                      .SelectMany(node => node.DescendantNodes().Where(methodDecl.DirectlyContains))
                                      .Any(node => node.Kind().Fits(
#if PCL
#else
                                               SyntaxKind.DefaultLiteralExpression,
#endif
                                               SyntaxKind.NumericLiteralToken,
                                               SyntaxKind.CharacterLiteralToken,
                                               SyntaxKind.StringLiteralToken,
                                               SyntaxKind.NumericLiteralExpression,
                                               SyntaxKind.StringLiteralExpression,
                                               SyntaxKind.CharacterLiteralExpression,
                                               SyntaxKind.TrueLiteralExpression,
                                               SyntaxKind.FalseLiteralExpression,
                                               SyntaxKind.NullLiteralExpression) == false))
                               .ToArray();

            var newMethod = methodDecl.TrackNodes(declarations);

            foreach (var declaration in declarations)
            {
                var assignemntCurrent = newMethod.GetCurrentNode(declaration);
                var declarationSyntax = assignemntCurrent.Parent as LocalDeclarationStatementSyntax;
                if (declarationSyntax == null)
                {
                    continue;
                }

                var block      = assignemntCurrent.FirstAncestorOrSelf <BlockSyntax>();
                var statements = block.Statements;

                var declarator = declaration
                                 .DescendantNodes()
                                 .OfType <VariableDeclaratorSyntax>()
                                 .Single();

                var logExpression = GetLoggingStatementWithSingleStateWithName(
                    methodDecl,
                    LogAssignmentName,
                    declarator.Identifier);

                logExpression = logExpression.WithTrailingTrivia(SF.LineFeed);

                var declarationIndex = statements.IndexOf(declarationSyntax);

                statements = statements.Insert(declarationIndex + 1, logExpression);

                newMethod = newMethod.ReplaceNode(block, SF.Block(statements));
            }

            return(newMethod);
        }
Exemplo n.º 6
0
            public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
            {
                var stmt = node.ForStatement;
                ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(nodesVisitor);
                VariableDeclarationSyntax declaration = null;
                ExpressionSyntax          id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    declaration = SplitVariableDeclarations(v, nodesVisitor, semanticModel).Values.Single();
                    declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                    id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
                }
                else
                {
                    id = (ExpressionSyntax)stmt.ControlVariable.Accept(nodesVisitor);
                    var symbol = semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol;
                    if (!semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any())
                    {
                        var variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(symbol.Name), null,
                                                                                        SyntaxFactory.EqualsValueClause(startValue));
                        declaration = SyntaxFactory.VariableDeclaration(
                            SyntaxFactory.IdentifierName("var"),
                            SyntaxFactory.SingletonSeparatedList(variableDeclaratorSyntax));
                    }
                    else
                    {
                        startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue);
                    }
                }

                var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(nodesVisitor);
                PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
                ExpressionSyntax            condition;

                if (value == null)
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                else
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                if (step == null)
                {
                    step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
                }
                else
                {
                    step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
                }
                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(this)));

                return(SingleStatement(SyntaxFactory.ForStatement(
                                           declaration,
                                           declaration != null ? SyntaxFactory.SeparatedList <ExpressionSyntax>() : SyntaxFactory.SingletonSeparatedList(startValue),
                                           condition,
                                           SyntaxFactory.SingletonSeparatedList(step),
                                           block.UnpackBlock())));
            }
Exemplo n.º 7
0
        public MethodDeclarationSyntax ToMethodDeclaration()
        {
            bool       isMain           = false;
            TypeSyntax mainReturnSyntax = null;

            TypeSyntax returnType = SF.PredefinedType(
                SF.Token(SyntaxKind.VoidKeyword));

            var procedureName = canonicalName.value;

            if (procedureName == "main")
            {
                isMain = true;
            }
            if (procedureName != name.name.value || name.library != null)
            {
                Console.WriteLine($"Take a look at this! {name.library?.canonicalName?.value}.{name.name.value}");
            }

            if (function.TryGetValue(out var functionNode))
            {
                returnType = functionNode.returnType.ToTypeSyntax();
            }

            var method = SF.MethodDeclaration(returnType, SF.Identifier(procedureName));

            var modifiers = new List <SyntaxToken>();

            if (flags.HasFlag(Flag.isConst))
            {
                modifiers.Add(SF.Token(SyntaxKind.ConstKeyword));
            }
            if (flags.HasFlag(Flag.isStatic))
            {
                modifiers.Add(SF.Token(SyntaxKind.StaticKeyword));
            }
            // if (isMain) modifiers.Add(SF.Token(SyntaxKind.PublicKeyword));
            if (!procedureName.StartsWith('_'))
            {
                modifiers.Add(SF.Token(SyntaxKind.PublicKeyword));
            }

            if (flags.HasFlag(Flag.isAbstract))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isExternal))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isForwardingStub))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isForwardingSemiStub))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isRedirectingFactoryConstructor))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isNoSuchMethodForwarder))
            {
                throw new NotImplementedException();
            }

            if (modifiers.Count == 1)
            {
                method = method.WithModifiers(SF.TokenList(modifiers.First()));
            }
            else if (modifiers.Count != 0)
            {
                method = method.WithModifiers(SF.TokenList(modifiers.ToArray()));
            }

            // todo: in our test cases this is a dart Block which goes to BlockSyntax ~ is this always the case?
            // --> I'm guessing it's not for arrow functions???
            if (functionNode.body.TryGetValue(out var body))
            {
                // if 'isMain' we need to rewrite all return blocks
                var blockSyntax = body.ToStatementSyntax() as BlockSyntax;
                blockSyntax = SF.Block(blockSyntax.Statements.Add(SF.ReturnStatement(SF.LiteralExpression(
                                                                                         SyntaxKind.DefaultLiteralExpression,
                                                                                         SF.Token(SyntaxKind.DefaultKeyword)))));
                method = method.WithBody(blockSyntax);
            }

            return(method);
        }
 /// <summary>Creates a new AnonymousMethodExpressionSyntax instance.</summary>
 public static AnonymousMethodExpressionSyntax AnonymousMethodExpression()
 {
     return(SyntaxFactory.AnonymousMethodExpression(default(SyntaxToken), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), default(ParameterListSyntax), SyntaxFactory.Block()));
 }