Beispiel #1
0
        private static MemberDeclarationSyntax[] SetUpGenerate(ClassDeclarationSyntax @class)
        {
            List <MemberDeclarationSyntax> fields = new List <MemberDeclarationSyntax>();
            MethodDeclarationSyntax        SetUp  = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "SetUp")
                                                    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                                    .AddAttributeLists(SyntaxFactory.SingletonList <AttributeListSyntax>(
                                                                           SyntaxFactory.AttributeList(
                                                                               SyntaxFactory.SingletonSeparatedList <AttributeSyntax>(
                                                                                   SyntaxFactory.Attribute(
                                                                                       SyntaxFactory.IdentifierName("SetUp"))))).ToArray()).WithBody(SyntaxFactory.Block());

            if (@class.Modifiers.Any(SyntaxKind.StaticKeyword))
            {
                fields.Add(SetUp);
                return(fields.ToArray());
            }
            fields.Add(GenerateField(SyntaxKind.PrivateKeyword, "_" + @class.Identifier.Text + "UnderTest", @class.Identifier.Text));

            List <ConstructorDeclarationSyntax> constructors = new List <ConstructorDeclarationSyntax>();

            foreach (MemberDeclarationSyntax member in @class.Members.Where(cstr => (cstr is ConstructorDeclarationSyntax)))
            {
                constructors.Add(member as ConstructorDeclarationSyntax);
            }

            string constString = "_" + @class.Identifier.Text + "UnderTest = new " + @class.Identifier.Text + "(";

            if (constructors.Count > 0)
            {
                ConstructorDeclarationSyntax constructor = constructors.OrderBy(x => x.ParameterList.Parameters.Count).First();

                ParameterSyntax[] parametrs = constructor.ParameterList.Parameters.ToArray();

                foreach (ParameterSyntax param in parametrs)
                {
                    if (param.Type.ToString()[0] == 'I')
                    {
                        fields.Add(
                            GenerateField(
                                SyntaxKind.PrivateKeyword,
                                "_" + param.Identifier.Text + "Dependency",
                                "Mock<" + param.Type.ToString() + ">"));
                        SetUp        = SetUp.AddBodyStatements(GenerateMockClass(param.Type.ToString(), "_" + param.Identifier.Text + "Dependency"));
                        constString += "_" + param.Identifier.Text + "Dependency.Object, ";
                    }
                    else
                    {
                        SetUp        = SetUp.AddBodyStatements(GenerateVar(param.Type.ToString(), param.Identifier.Text));
                        constString += param.Identifier.Text + ", ";
                    }
                }
                constString = constString.Remove(constString.Length - 2, 1);
            }
            constString += ");";
            SetUp        = SetUp.AddBodyStatements(SyntaxFactory.ParseStatement(constString));
            fields.Add(SetUp);
            return(fields.ToArray());
        }
Beispiel #2
0
        /// <summary>
        /// Initializing of visitor
        /// </summary>
        public RoslynTreeBuilderVisitor(string libraryModuleName = null)
        {
            //Create unit
            unitNode = CompilationUnit();

            //Create public class "Program" (or library unit's name)
            this.libraryModuleName = libraryModuleName;
            string className = libraryModuleName ?? "$Program";

            programClassNode = ClassDeclaration(className).AddModifiers(Token(SyntaxKind.PublicKeyword));

            //Create method void Main()
            mainMethodNode = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "Main");

            //Set Main method as static
            mainMethodNode = mainMethodNode.AddModifiers(Token(SyntaxKind.StaticKeyword));

            //Add to Main method empty body
            mainMethodNode = mainMethodNode.AddBodyStatements();

            //Set Main method as current block (push to stack)
            blocks.Push(mainMethodNode);

            //initialize dictionary of location annotations
            LocationAnnotations = new List <SyntaxAnnotation>();
        }
        public Type Compile()
        {
            if (expressions.Count != 1)
            {
                throw new Exception("HAML node stack misaligned. Expected only 1 root node.");
            }
            FlushStringRun();
            _renderMethod = _renderMethod.AddBodyStatements(SyntaxFactory.Block(expressions.Peek()));

            _compilationTargetClass = _compilationTargetClass.AddMembers(_renderMethod);
            _compilationUnit        = _compilationUnit
                                      .AddMembers(_compilationTargetClass);
            _compilationUnit = _compilationUnit.NormalizeWhitespace("    ", true);
            _compilation     = _compilation.AddSyntaxTrees(CSharpSyntaxTree.Create(_compilationUnit));
            MemoryStream stream = new MemoryStream();
            EmitResult   result = _compilation.Emit(stream);

            _compilation.Emit("Output.dll");
            if (!result.Success)
            {
                throw new HamlCompilationFailedException(result.Diagnostics);
            }
            stream.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(stream);

            return(assembly.GetType(_compilationTargetClass.Identifier.Text));
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            MethodDeclarationSyntax methodDeclaration,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(methodDeclaration.ReturnType, cancellationToken);

            int         position = -1;
            BlockSyntax body     = methodDeclaration.Body;
            SyntaxList <StatementSyntax> statements = body.Statements;

            if (statements.Any())
            {
                position = statements.Last().FullSpan.End;
            }
            else
            {
                position = body.OpenBraceToken.FullSpan.End;
            }

            MethodDeclarationSyntax newNode = methodDeclaration
                                              .AddBodyStatements(ReturnStatement(typeSymbol.ToDefaultExpression(semanticModel, position)));

            return(await document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken).ConfigureAwait(false));
        }
Beispiel #5
0
        public static MethodDeclarationSyntax CreateMethod(MethodGenerationData data)
        {
            Debug.Assert(!string.IsNullOrEmpty(data.m_MethodName), "Trying to generate a method with null or empty method name!");
            Debug.Assert(!string.IsNullOrEmpty(data.m_MethodReturnType), "Trying to generate a method with null or empty return type!");
            Debug.Assert(data.m_MethodBodyStatements != null && data.m_MethodBodyStatements.Count > 0, "Trying to generate a method with no body!");

            MethodDeclarationSyntax syntax = SyntaxFactory
                                             .MethodDeclaration(SyntaxFactory.ParseTypeName(data.m_MethodReturnType), data.m_MethodName)
                                             .AddModifiers(CodeGenerationUtility.CreateProtectionLevelToken(data.m_ProtectionLevel));

            switch (data.m_InheritanceKeyword)
            {
            case FunctionInheritanceKeyword.STATIC: syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); break;

            case FunctionInheritanceKeyword.OVERRIDE: syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); break;

            case FunctionInheritanceKeyword.VIRTUAL: syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); break;
            }

            if (data.m_IsAsync)
            {
                bool canMakeAsync = false;

                for (int i = 0; i < s_AcceptedAsyncReturnTypes.Length; i++)
                {
                    if (!data.m_MethodReturnType.Contains(s_AcceptedAsyncReturnTypes[i]))
                    {
                        continue;
                    }

                    canMakeAsync = true;
                    break;
                }

                Debug.Assert(canMakeAsync, "Trying to generate async function but the return type is not supported! Please make the return type either void, Task or UniTask");

                if (canMakeAsync)
                {
                    syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword));
                }
            }

            syntax = syntax.AddAttributeLists(AttributeGenerationService.CreateAttributeListSyntaxes(data.m_Attributes));

            foreach (var param in data.m_MethodParams)
            {
                syntax = syntax.AddParameterListParameters(CodeGenerationUtility.CreateParameterSyntax(param.m_ParamName, param.m_ParamType));
            }

            foreach (var statement in data.m_MethodBodyStatements)
            {
                syntax = syntax.AddBodyStatements((SyntaxFactory.ParseStatement(statement)));
            }

            return(syntax);
        }
 private async Task <Document> RemoveThrowAsync(Document document, MethodDeclarationSyntax method, CancellationToken ct)
 {
     return(document
            .WithSyntaxRoot((await document.GetSyntaxRootAsync(ct))
                            .ReplaceNode(method, method.AddBodyStatements(
                                             SyntaxFactory.ExpressionStatement(
                                                 SyntaxFactory.InvocationExpression(
                                                     SyntaxFactory.MemberAccessExpression(
                                                         SyntaxKind.SimpleMemberAccessExpression,
                                                         SyntaxFactory.IdentifierName("GC"),
                                                         SyntaxFactory.IdentifierName("SuppressFinalize")),
                                                     SyntaxFactory.ArgumentList().AddArguments(SyntaxFactory.Argument(SyntaxFactory.ThisExpression())))))
                                         .WithAdditionalAnnotations(Formatter.Annotation))));
 }
            private MethodDeclarationSyntax AddReturnStatement(MethodDeclarationSyntax newMethod, SyntaxGenerator generator)
            {
                var getMethodInvocation =
                    generator.InvocationExpression(
                        generator.MemberAccessExpression(generator.IdentifierName(AdapterParameterName),
                                                         AdapterGetMethodName));

                var returnStatement = generator.ReturnStatement(getMethodInvocation)
                                      ?.WithAdditionalAnnotations(Formatter.Annotation) as StatementSyntax;

                return(returnStatement != null
                                        ? newMethod.AddBodyStatements(returnStatement)
                                        : newMethod);
            }
Beispiel #8
0
        /// <summary>
        /// Добавление выражения в начало тела метода
        /// </summary>
        /// <param name="method"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public MethodDeclarationSyntax AddExpressionToStartMethodsBody(MethodDeclarationSyntax method,
                                                                       ExpressionStatementSyntax expression)
        {
            if (method.Body == null)
            {
                return(method);
            }
            if (method.Body.ChildNodes().Count() == 0)
            {
                return(method.AddBodyStatements(expression).NormalizeWhitespace());
            }
            BlockSyntax newBlock = method.Body.InsertNodesBefore(method.Body
                                                                 .ChildNodes().ElementAt(0),
                                                                 new List <SyntaxNode> {
                expression
            }).NormalizeWhitespace();

            method = method.ReplaceNode(method.Body, newBlock);
            return(method);
        }
Beispiel #9
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());
        }
Beispiel #10
0
        private void ProcessNodes(IEnumerable <MyVisualSyntaxNode> nodes, ref MethodDeclarationSyntax methodDeclaration, IEnumerable <StatementSyntax> statementsToAppend = null)
        {
            m_helperStatementList.Clear();
            m_navigator.ResetNodes();
            m_builderNode.Reset();
            m_builderNode.SequenceOutputs.AddRange(nodes);
            m_builderNode.Navigator = m_navigator;

            foreach (var node in nodes)
            {
                Debug.Assert(node is IMyVisualSyntaxEntryPoint);
                ((IMyVisualSyntaxEntryPoint)node).AddSequenceInput(m_builderNode);
            }

            m_builderNode.Preprocess();
            m_builderNode.CollectSequenceExpressions(m_helperStatementList);

            if (statementsToAppend != null)
            {
                m_helperStatementList.AddRange(statementsToAppend);
            }

            methodDeclaration = methodDeclaration.AddBodyStatements(m_helperStatementList.ToArray());
        }
Beispiel #11
0
        private static MethodDeclarationSyntax[] GenerateMethods(ClassDeclarationSyntax @class)
        {
            List <MethodDeclarationSyntax> testMethods = new List <MethodDeclarationSyntax>();
            var methods = @class.Members.OfType <MethodDeclarationSyntax>();

            foreach (var method in methods.Where(m => m.Modifiers.Any(SyntaxKind.PublicKeyword)))
            {
                MethodDeclarationSyntax testMethod = CreateMethodDeclaration(SyntaxKind.PublicKeyword, "void", method.Identifier.Text + "Test", "Test");
                string invokeArgs = "";

                //Arrange
                foreach (ParameterSyntax paramSyn in method.ParameterList.Parameters)
                {
                    if (!paramSyn.Type.ToString().StartsWith('I'))
                    {
                        testMethod = testMethod.AddBodyStatements(
                            CreateAssignmentStatement(
                                paramSyn.Type.ToString(),
                                paramSyn.Identifier.Text,
                                false,
                                "default"));
                        invokeArgs += paramSyn.Identifier.Text + ", ";
                    }
                    else
                    {
                        invokeArgs += CreateDecoratedName(paramSyn) + ".Object, ";
                    }
                }
                if (invokeArgs.Length > 0)
                {
                    invokeArgs = invokeArgs.Remove(invokeArgs.Length - 2);
                }

                //Act + Assert
                if (method.ReturnType.ToString() == "void")
                {
                    testMethod = testMethod.AddBodyStatements(
                        CreateMethodCallStatement(
                            true,
                            "",
                            "",
                            method.Modifiers.Any(SyntaxKind.StaticKeyword) ?
                            @class.Identifier.Text :
                            $"_{@class.Identifier.Text}UnderTest",
                            method.Identifier.Text,
                            invokeArgs),
                        SyntaxFactory.ParseStatement("Assert.Fail(\"Autogenerated\");"));   //Assert
                }
                else
                {
                    testMethod = testMethod.AddBodyStatements(
                        CreateMethodCallStatement(
                            false,
                            method.ReturnType.ToString(),
                            "actual",
                            method.Modifiers.Any(SyntaxKind.StaticKeyword) ?
                            @class.Identifier.Text :
                            $"_{@class.Identifier.Text}UnderTest",
                            method.Identifier.Text,
                            invokeArgs),
                        CreateAssignmentStatement(                                          //Assert
                            method.ReturnType.ToString(),
                            "expected",
                            false,
                            "default"),
                        SyntaxFactory.ParseStatement("Assert.That(actual, Is.EqualTo(expected));"),
                        SyntaxFactory.ParseStatement("Assert.Fail(\"Autogenerated\");"));
                }


                testMethods.Add(testMethod);
            }

            return(testMethods.ToArray());
        }
Beispiel #12
0
        private static MemberDeclarationSyntax[] GenerateSetUp(ClassDeclarationSyntax @class)
        {
            List <MemberDeclarationSyntax> memberDeclarations = new List <MemberDeclarationSyntax>();
            MethodDeclarationSyntax        setUpMethod        = CreateMethodDeclaration(SyntaxKind.PublicKeyword, "void", "SetUp", "SetUp");

            if (@class.Modifiers.Any(SyntaxKind.StaticKeyword))
            {
                setUpMethod = setUpMethod.AddBodyStatements(new StatementSyntax[0]);
                memberDeclarations.Add(setUpMethod);
                return(memberDeclarations.ToArray());
            }

            memberDeclarations.Add(CreateFieldDeclaration(SyntaxKind.PrivateKeyword, @class.Identifier.Text, $"_{@class.Identifier.Text}UnderTest"));
            ParameterSyntax[] ctorParams = @class.Members.OfType <ConstructorDeclarationSyntax>()
                                           .FirstOrDefault()?.ParameterList.Parameters.ToArray() ?? new ParameterSyntax[0];


            foreach (ParameterSyntax paramSyn in ctorParams?.Where(parameter => !parameter.Type.ToString().StartsWith('I')))
            {
                setUpMethod = setUpMethod.AddBodyStatements(
                    CreateAssignmentStatement(
                        paramSyn.Type.ToString(),
                        paramSyn.Identifier.Text,
                        false,
                        "default"));
            }

            foreach (ParameterSyntax paramSyn in ctorParams?.Where(parameter => parameter.Type.ToString().StartsWith('I')))
            {
                memberDeclarations.Add(
                    CreateFieldDeclaration(
                        SyntaxKind.PrivateKeyword,
                        $"Mock<{paramSyn.Type.ToString()}>",
                        CreateDecoratedName(paramSyn)));

                setUpMethod = setUpMethod.AddBodyStatements(
                    CreateAssignmentStatement(
                        "",
                        CreateDecoratedName(paramSyn),
                        true,
                        $"Mock<{paramSyn.Type.ToString()}>"));
            }

            setUpMethod = setUpMethod.AddBodyStatements(
                CreateAssignmentStatement(
                    "",
                    $"_{@class.Identifier.Text}UnderTest",
                    true,
                    @class.Identifier.Text,
                    string.Join(
                        ", ",
                        ctorParams?
                        .Select(
                            paramSyn => paramSyn.Type.ToString()
                            .StartsWith('I') ?
                            CreateDecoratedName(paramSyn) + ".Object" :
                            paramSyn.Identifier.Text))));

            memberDeclarations.Add(setUpMethod);
            return(memberDeclarations.ToArray());
        }
Beispiel #13
0
        private void CreateMethods()
        {
            // Generate Interface methods
            if (!string.IsNullOrEmpty(m_objectBuilder.Interface))
            {
                var methodNodes = m_navigator.OfType <MyVisualSyntaxInterfaceMethodNode>();
                foreach (var methodNode in methodNodes)
                {
                    var methodSyntax = methodNode.GetMethodDeclaration();
                    ProcessNodes(new[] { methodNode }, ref methodSyntax);
                    m_methodDeclarations.Add(methodSyntax);
                }
            }

            var events = m_navigator.OfType <MyVisualSyntaxEventNode>();

            events.AddRange(m_navigator.OfType <MyVisualSyntaxKeyEventNode>());
            // Generate Event methods
            // Take all events of same name and make a method out of theire bodies.
            while (events.Count > 0)
            {
                var firstEvent         = events[0];
                var eventsWithSameName = events.Where(@event => @event.ObjectBuilder.Name == firstEvent.ObjectBuilder.Name);
                var methodDeclaration  = MySyntaxFactory.PublicMethodDeclaration(
                    firstEvent.EventName,
                    SyntaxKind.VoidKeyword,
                    firstEvent.ObjectBuilder.OutputNames,
                    firstEvent.ObjectBuilder.OuputTypes);

                ProcessNodes(eventsWithSameName, ref methodDeclaration);
                // Bind with VisualScriptingProxy in constructor.
                m_constructor = m_constructor.AddBodyStatements(
                    MySyntaxFactory.DelegateAssignment(
                        firstEvent.ObjectBuilder.Name,
                        methodDeclaration.Identifier.ToString())
                    );
                // unBind from visualScriptingProxy in dispose method
                m_disposeMethod = m_disposeMethod.AddBodyStatements(
                    MySyntaxFactory.DelegateRemoval(
                        firstEvent.ObjectBuilder.Name,
                        methodDeclaration.Identifier.ToString())
                    );

                m_methodDeclarations.Add(methodDeclaration);

                events.RemoveAll(@event => eventsWithSameName.Contains(@event));
            }

            // There can be only one method from single input node.
            // Input nodes are of type Event.
            var inputs  = m_navigator.OfType <MyVisualSyntaxInputNode>();
            var outputs = m_navigator.OfType <MyVisualSyntaxOutputNode>();

            if (inputs.Count > 0)
            {
                Debug.Assert(inputs.Count == 1);

                var input = inputs[0];
                MethodDeclarationSyntax methodDeclaration = null;
                if (outputs.Count > 0)
                {
                    List <string> outputParamNames = new List <string>(outputs[0].ObjectBuilder.Inputs.Count);
                    List <string> outputParamTypes = new List <string>(outputs[0].ObjectBuilder.Inputs.Count);

                    foreach (var outputData in outputs[0].ObjectBuilder.Inputs)
                    {
                        outputParamNames.Add(outputData.Name);
                        outputParamTypes.Add(outputData.Type);
                    }

                    methodDeclaration = MySyntaxFactory.PublicMethodDeclaration("RunScript", SyntaxKind.BoolKeyword, input.ObjectBuilder.OutputNames, input.ObjectBuilder.OuputTypes, outputParamNames, outputParamTypes);
                }
                else
                {
                    methodDeclaration = MySyntaxFactory.PublicMethodDeclaration("RunScript", SyntaxKind.BoolKeyword, input.ObjectBuilder.OutputNames, input.ObjectBuilder.OuputTypes);
                }

                ProcessNodes(new[] { input }, ref methodDeclaration, new[] { SyntaxFactory.ReturnStatement(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)) });
                m_methodDeclarations.Add(methodDeclaration);
            }
        }
Beispiel #14
0
 public static MethodDeclarationSyntax add_Statement(this MethodDeclarationSyntax methodDeclaration, StatementSyntax statement)
 {
     return(methodDeclaration.AddBodyStatements(statement));
 }
Beispiel #15
0
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            node = base.VisitMethodDeclaration(node) as MethodDeclarationSyntax;
            var body = node.Body;

            if (body == null)
            {
                return(node);
            }

            var parentClass = node.Parent as ClassDeclarationSyntax;

            if (parentClass == null)
            {
                return(node);
            }

            var parameterList = node.ParameterList;

            if (parameterList == null)
            {
                return(node);
            }

            var parameters     = parameterList.Parameters;
            var parameterCount = parameters.Count;

            if (parameterCount == 0)
            {
                return(node);
            }

            var methodName         = node.Identifier.Text;
            var firstParameter     = parameterList.Parameters[0];
            var firstParameterName = firstParameter.Identifier.Text;

            if (methodName == k_ConnectSubscriber && parameterCount == 1)
            {
                node = node.WithBody(SyntaxFactory.Block());
                // TODO: share this code with the method for finding subscriber classes below
                var symbol = m_Model.GetDeclaredSymbol(parentClass) as INamedTypeSymbol;
                foreach (var @interface in symbol.AllInterfaces)
                {
                    // TODO: handle provider types with more than one level of inheritence
                    foreach (var baseInterface in @interface.Interfaces)
                    {
                        if (baseInterface.Name != k_IFunctionalityProvider)
                        {
                            continue;
                        }

                        var varName = string.Format(k_VariableNameTemplate, @interface.Name);

                        var castStatement = string.Format(k_CastStatement, varName, firstParameterName, @interface);
                        var assignment    = string.Format(k_SetProviderStatement, varName);
                        node = node.AddBodyStatements(
                            SyntaxFactory.ParseStatement(castStatement),
                            SyntaxFactory.ParseStatement(assignment));

                        wasModified = true;
                    }
                }
            }

            return(node);
        }
        public void Generate()
        {
            // standard using directives
            CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit()
                                       .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")))
                                       .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Collections.Generic")))
                                       .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Linq")))
                                       .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Text")))
                                       .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Threading.Tasks")));

            NamespaceDeclarationSyntax localNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(directoryName));

            ClassDeclarationSyntax localClass = SyntaxFactory.ClassDeclaration(Name);

            foreach (var member in Declarations)
            {
                switch (member.DeclarationType)
                {
                case "method":
                    var currentMethod = member as Method;

                    //currentMethod.Type is a string parsed from the uml diagram
                    MethodDeclarationSyntax method = SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(currentMethod.Type)), currentMethod.Name);

                    List <SyntaxToken> mods = new List <SyntaxToken>();

                    foreach (var modifier in currentMethod.Modifiers)
                    {
                        mods.Add(SyntaxFactory.ParseToken(modifier));
                    }

                    method = method.AddModifiers(mods.ToArray());

                    SeparatedSyntaxList <ParameterSyntax> ssl = SyntaxFactory.SeparatedList <ParameterSyntax>();
                    foreach (var param in currentMethod.Arguments)
                    {
                        ParameterSyntax ps = SyntaxFactory.Parameter(
                            new SyntaxList <AttributeListSyntax>(),
                            new SyntaxTokenList(),
                            SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(param.Type)),
                            SyntaxFactory.Identifier(param.Name), null);

                        ssl = ssl.Add(ps);
                    }

                    method = method.AddParameterListParameters(ssl.ToArray());

                    // we add an exception to the body of an otherwise empty method
                    ThrowStatementSyntax notReady = SyntaxFactory.ThrowStatement(SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName("NotImplementedException"), SyntaxFactory.ArgumentList(), null));

                    method = method.AddBodyStatements(notReady);

                    localClass = localClass.AddMembers(method);
                    break;

                case "field":
                    var currentField = member as Field;

                    SyntaxTokenList stl = new SyntaxTokenList();

                    foreach (var modifier in currentField.Modifiers)
                    {
                        stl = stl.Add(SyntaxFactory.ParseToken(modifier));
                    }

                    SeparatedSyntaxList <VariableDeclaratorSyntax> svd = SyntaxFactory.SeparatedList <VariableDeclaratorSyntax>();

                    svd = svd.Add(SyntaxFactory.VariableDeclarator(currentField.Name));

                    // currentField.Type is a string parsed from the uml diagram
                    VariableDeclarationSyntax variable = SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName(currentField.Type), svd);

                    FieldDeclarationSyntax field = SyntaxFactory.FieldDeclaration(
                        new SyntaxList <AttributeListSyntax>(),
                        stl,
                        variable
                        );

                    localClass = localClass.AddMembers(field);
                    break;
                }
            }

            localNamespace = localNamespace.AddMembers(localClass);
            cu             = cu.AddMembers(localNamespace);

            AdhocWorkspace cw      = new AdhocWorkspace();
            OptionSet      options = cw.Options;

            cw.Options.WithChangedOption(CSharpFormattingOptions.IndentBraces, true);
            SyntaxNode formattedNode = Formatter.Format(cu, cw, options);

            formattedNode.WriteTo(writer);
        }
        /* Update every return statements in the method declaration (if any), to return the specified symbol.*/
        public SyntaxNode ChangeReturnValue(string symbolName)
        {
            // Create a return statement with the given symbol name.
            var returnStatement = Syntax.ReturnStatement
                (Syntax.ParseToken("return").WithTrailingTrivia(Syntax.Whitespace(" ")),
                Syntax.ParseExpression(symbolName), Syntax.ParseToken(";"));

            // Replace every return statements in the method with the created new return statement.
            method = method.ReplaceNodes(
                method.DescendantNodes().Where(n => n.Kind == SyntaxKind.ReturnStatement),
                (n1, n2) => returnStatement);

            // Get all statements in the updated method.
            var statements = GetStatements();

            // If the last statement is not return statement, it needs adding one.
            if (statements.Last().Kind != SyntaxKind.ReturnStatement)
            {
                // Get the leading and trailing white space of the last statement.
                var leading = statements.Last().GetLeadingTrivia();
                var trailing = statements.Last().GetTrailingTrivia();

                // Add a return statement to the end of the body.
                method = method.AddBodyStatements(new StatementSyntax[]
                    {returnStatement.WithLeadingTrivia(leading).WithTrailingTrivia(trailing)});
            }
            return method;
        }
Beispiel #18
0
 /// <summary>
 /// Добавление выражения в тело метода
 /// </summary>
 /// <param name="method">Метод</param>
 /// <param name="expression">Добавляемое выражение</param>
 /// <returns></returns>
 public MethodDeclarationSyntax AddExpressionToMethodsBody(MethodDeclarationSyntax method,
                                                           ExpressionStatementSyntax expression)
 {
     method = method.AddBodyStatements(expression).NormalizeWhitespace();
     return(method);
 }
Beispiel #19
0
 public static MethodDeclarationSyntax AddBodyStatements(this MethodDeclarationSyntax syntax, IEnumerable <StatementSyntax> parameters)
 {
     return(syntax.AddBodyStatements(parameters.ToArray()));
 }
    //访问函数,并且
    public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
        MethodDeclarationSyntax node_raw = node;

        Console.WriteLine("VisitMethodDeclaration: " + node.Identifier);

        SyntaxTree SF = node.SyntaxTree;
        //增加一个body
        BlockSyntax Body = node.Body;

        if (Body == null)
        {
            //处理[DllImport("CSteamworks", CallingConvention = CallingConvention.Cdecl)]
            foreach (AttributeListSyntax attr in node.AttributeLists)
            {
                if (attr.ToString().StartsWith("[DllImport"))
                {
                    var r = node.AttributeLists.Remove(attr);
                    node = node.WithAttributeLists(r);

                    SyntaxTrivia st = SyntaxFactory.PreprocessingMessage("\t\t//" + attr.ToString() + "\r\n");
                    //改为
                    SyntaxTriviaList s = node.GetLeadingTrivia();
                    if (s != null)
                    {
                        s    = s.Add(st);
                        node = node.WithLeadingTrivia(s);
                    }
                    else
                    {
                        node = node.WithLeadingTrivia(st);
                    }
                    break;
                }
            }

            //SyntaxNode
            SyntaxList <StatementSyntax> statements = new SyntaxList <StatementSyntax>();
            BinaryExpressionSyntax       bes        = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName("_a"),
                                                                                     SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("X")));

            //ExpressionSyntax e = SyntaxFactory.ParseExpression(string.Format("Debug.Log(\"{0}: \");", node.Identifier));
            //statements.Add(e);
            // StatementSyntax myStatement = SyntaxFactory.ParseStatement(@"Console.WriteLine();");
            //Body.AddStatements(myStatement);
            //statements.Add(bes);
            //CSharpScript.Create<int>("int x = 1;");
            StatementSyntax myStatement = SyntaxFactory.ParseStatement(string.Format("Debug.Log(\"****call to {0}: \");", node.Identifier));
            node = node.AddBodyStatements(myStatement);

            //处理带有out 修饰的参数:
            SeparatedSyntaxList <ParameterSyntax> Parameters = node.ParameterList.Parameters;
            if (Parameters.Count > 0)
            {
                foreach (ParameterSyntax param in Parameters)
                {
                    foreach (SyntaxToken vv in param.Modifiers)
                    {
                        if (vv.ToString().Contains("out"))
                        {
                            TypeSyntax      t1 = param.Type;
                            string          t2 = param.Identifier.ToString();
                            StatementSyntax ss = SyntaxFactory.ParseStatement(string.Format("{0} = default({1});", t2, t1.ToString()));
                            node = node.AddBodyStatements(ss);
                            break;
                        }
                    }
                    foreach (AttributeListSyntax vv in param.AttributeLists)
                    {
                        if (vv.ToString().Contains("[Out]"))
                        {
                            TypeSyntax      t1 = param.Type;
                            string          t2 = param.Identifier.ToString();
                            StatementSyntax ss = SyntaxFactory.ParseStatement(string.Format("{0} = default({1});", t2, t1.ToString()));
                            node = node.AddBodyStatements(ss);
                            break;
                        }
                    }
                }
                //+		AttributeLists	{[In] [Out]}	Microsoft.CodeAnalysis.SyntaxList<Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax>
            }

            //补充返回值:
            string          sr  = string.Format("return {0};", BuildRetStr(node.ReturnType));
            StatementSyntax ret = SyntaxFactory.ParseStatement(sr);
            node = node.AddBodyStatements(ret).WithSemicolonToken(default(SyntaxToken));

            //处理node的修饰符:
            foreach (SyntaxToken mod in node.Modifiers)
            {
                if (mod.Text == "extern")
                {
                    SyntaxTokenList n = node.Modifiers.Remove(mod);
                    node = node.WithModifiers(n);
                    break;
                }
            }
        }

        // This is new, copies the trivia (indentations, comments, etc.)
        //newVariable = newVariable.WithLeadingTrivia(localDeclarationStatementSyntax.GetLeadingTrivia());
        //newVariable = newVariable.WithTrailingTrivia(localDeclarationStatementSyntax.GetTrailingTrivia());

        //Console.WriteLine(node.AddBodyStatements);
        //StatementSyntax[] items

        //SeparatedSyntaxList<ParameterSyntax> Parameters = node.ParameterListSyntax;
        //if (Parameters.Count > 0)
        //{
        //    for (int i = 0; i < Parameters.Count; ++i)
        //    {
        //        Console.WriteLine(node.Parent);
        //        Console.WriteLine(Parameters[i]);
        //    }
        //}
        node = node.NormalizeWhitespace();
        //Console.WriteLine(node);

        //将新节点替换到旧节点上:
        node_raw.Parent.ReplaceNode(node_raw, node);
        return(node);
    }