Esempio n. 1
0
        private void DoTestAddInsertRemoveOnEmptyList(SeparatedSyntaxList <SyntaxNode> list)
        {
            Assert.Equal(0, list.Count);

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E");

            var newList = list.Add(nodeD);

            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Remove(nodeD);
            Assert.Equal(0, newList.Count);

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(1, nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD }));
            Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws <ArgumentNullException>(() => list.Add(null));
            Assert.Throws <ArgumentNullException>(
                () => list.AddRange((IEnumerable <SyntaxNode>)null)
                );
            Assert.Throws <ArgumentNullException>(() => list.Insert(0, null));
            Assert.Throws <ArgumentNullException>(
                () => list.InsertRange(0, (IEnumerable <SyntaxNode>)null)
                );
        }
Esempio n. 2
0
        public static SeparatedSyntaxList <ParameterSyntax> TransformMultipleComplexTypeParameters(SeparatedSyntaxList <ParameterSyntax> originalParameters, string methodName)
        {
            // handle if parameters have more two or more (i.e. multiple) complex types

            var complexParameters = MultipleComplexTypesGenerator.FindMultipleComplexTypesOrOutKeyword(originalParameters);

            if (!complexParameters.Any())
            {
                return(originalParameters);
            }

            var parameters = new SeparatedSyntaxList <ParameterSyntax>();

            // remove all complex types from parameters
            var complexNames = complexParameters
                               .Select(complex => complex.Identifier.ToFullString());

            var filteredParameters = originalParameters
                                     .Where(parameter =>
            {
                var name = parameter.Identifier.ToFullString();

                return(complexNames.All(complexName => complexName != name));
            });

            parameters = parameters.AddRange(filteredParameters);

            // add single complex class type parameter
            var complexType          = ComplexTypeNamesMapper.MapToServiceComplexClassType(methodName);
            var complexParameterName = ComplexTypeNamesMapper.MapToComplexClassParameterName(methodName);

            var complexTypeClass = SyntaxFactory.Parameter(SyntaxFactory.Identifier(complexParameterName))
                                   .WithType(SyntaxFactory.IdentifierName(complexType));

            // insert complex type before any optional parameters with default values
            // otherwise insert at the end
            var insertIndex = ParametersGenerator.FindIndexBeforeFirstOptionalParam(parameters);

            parameters = parameters.Insert(insertIndex, complexTypeClass);

            return(parameters);
        }
        private void DoTestAddInsertRemoveOnEmptyList(SeparatedSyntaxList<SyntaxNode> list)
        {
            Assert.Equal(0, list.Count);

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E");

            var newList = list.Add(nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Remove(nodeD);
            Assert.Equal(0, newList.Count);

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws<ArgumentNullException>(() => list.Add(null));
            Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNode>)null));
            Assert.Throws<ArgumentNullException>(() => list.Insert(0, null));
            Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNode>)null));
        }
 public SeparatedSyntaxList <TItem> Insert(SeparatedSyntaxList <TItem> list, int index, TItem item)
 {
     return(list.Insert(index, item));
 }
Esempio n. 5
0
        private async Task <Document> CompleteWithItIsAny(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken, ArgumentListSyntax mockedMethod)
        {
            var mockedMethodDeclaration = SymbolFinder.FindDeclarationsAsync(
                document.Project,
                ((IdentifierNameSyntax)((MemberAccessExpressionSyntax)((InvocationExpressionSyntax)mockedMethod.Parent).Expression).Name).Identifier.ValueText,
                false,
                cancellationToken).Result;
            var parameters = ((IMethodSymbol)mockedMethodDeclaration.First()).Parameters;


            var length = parameters.Length;

            SeparatedSyntaxList <ArgumentSyntax> arguments = mockedMethod.Arguments;

            for (int index = 0; index < length; index++)
            {
                var argument  = arguments.ElementAtOrDefault(index);
                var isMissing = argument?.IsMissing ?? true;

                if (isMissing)
                {
                    var parameter = parameters[index];

                    if (argument != null)
                    {
                        arguments = arguments.RemoveAt(index);
                    }

                    var argumentSyntax = SyntaxFactory.Argument(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.IdentifierName("It"),
                                SyntaxFactory.GenericName(SyntaxFactory.Identifier("IsAny"))
                                .WithTypeArgumentList(
                                    SyntaxFactory.TypeArgumentList(
                                        SyntaxFactory.SingletonSeparatedList(
                                            SyntaxFactory.ParseTypeName(parameter.ToDisplayString()))))))
                        .NormalizeWhitespace());
                    arguments = arguments.Insert(index, argumentSyntax);
                }
            }
            var updatedMockedMethod = mockedMethod.WithArguments(arguments);
            var syntaxTree          = await document.GetSyntaxTreeAsync(cancellationToken);

            var updatedSyntaxTree =
                syntaxTree.GetRoot().ReplaceNode(mockedMethod, updatedMockedMethod);

            return(document.WithSyntaxRoot(updatedSyntaxTree));

            return(null);

            // Compute new uppercase name.
            var identifierToken = typeDecl.Identifier;
            var newName         = identifierToken.Text.ToUpperInvariant();

            // Get the symbol representing the type to be renamed.
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

            // Produce a new solution that has all references to that type renamed, including the declaration.
            var originalSolution = document.Project.Solution;
            var optionSet        = originalSolution.Workspace.Options;
            var newSolution      = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

            // Return the new solution with the now-uppercase type name.
            //return newSolution;
        }
 public override SeparatedSyntaxListWrapper <TNode> Insert(int index, TNode node)
 => new AutoWrapSeparatedSyntaxList <TSyntax>(syntaxList.Insert(index, (TSyntax)SyntaxWrapper.Unwrap(node)));
Esempio n. 7
0
        MethodDeclarationSyntax CreateMethod(WaylandProtocol protocol, WaylandProtocolInterface iface,
                                             WaylandProtocolRequest request, int index)
        {
            var newIdArgument = request.Arguments?.FirstOrDefault(a => a.Type == WaylandArgumentTypes.NewId);

            if (newIdArgument != null && newIdArgument.Interface == null)
            {
                return(null);
            }
            var ctorType       = newIdArgument?.Interface;
            var dotNetCtorType = ctorType == null ? "void" : GetWlInterfaceTypeName(ctorType);

            var method = MethodDeclaration(
                ParseTypeName(dotNetCtorType), Pascalize(request.Name));

            var plist             = new SeparatedSyntaxList <ParameterSyntax>();
            var arglist           = new SeparatedSyntaxList <ExpressionSyntax>();
            var statements        = new SeparatedSyntaxList <StatementSyntax>();
            var callStatements    = new SeparatedSyntaxList <StatementSyntax>();
            var fixedDeclarations = new List <VariableDeclarationSyntax>();

            if (request.Since > 0)
            {
                statements = statements.Add(IfStatement(
                                                BinaryExpression(SyntaxKind.LessThanExpression,
                                                                 IdentifierName("Version"), MakeLiteralExpression(request.Since))
                                                ,
                                                request.Type == "destructor"
                        ? (StatementSyntax)ReturnStatement()
                        : ThrowStatement(ObjectCreationExpression(ParseTypeName("System.InvalidOperationException"))
                                         .WithArgumentList(
                                             ArgumentList(SingletonSeparatedList(Argument(MakeLiteralExpression(
                                                                                              $"Request {request.Name} is only supported since version {request.Since}"))))))));
            }

            if (request.Arguments != null)
            {
                foreach (var arg in request.Arguments ?? Array.Empty <WaylandProtocolArgument>())
                {
                    TypeSyntax parameterType = null;
                    var        nullCheck     = false;
                    var        argName       = "@" + Pascalize(arg.Name, true);

                    if (arg.Type == WaylandArgumentTypes.Int32 ||
                        arg.Type == WaylandArgumentTypes.Fixed ||
                        arg.Type == WaylandArgumentTypes.FileDescriptor ||
                        arg.Type == WaylandArgumentTypes.Uint32)
                    {
                        var nativeType = arg.Type == WaylandArgumentTypes.Uint32 ? "uint" : "int";

                        var managedType =
                            TryGetEnumTypeReference(protocol.Name, iface.Name, request.Name, arg.Name, arg.Enum) ??
                            nativeType;

                        parameterType = ParseTypeName(managedType);
                        if (nativeType != managedType)
                        {
                            arglist = arglist.Add(CastExpression(ParseTypeName(nativeType), IdentifierName(argName)));
                        }
                        else
                        {
                            arglist = arglist.Add(IdentifierName(argName));
                        }
                    }
                    else if (arg.Type == WaylandArgumentTypes.NewId)
                    {
                        arglist = arglist.Add(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                     IdentifierName("WlArgument"), IdentifierName("NewId")));
                    }
                    else if (arg.Type == WaylandArgumentTypes.String)
                    {
                        nullCheck     = true;
                        parameterType = ParseTypeName("System.String");
                        var tempName   = "__marshalled__" + argName.TrimStart('@');
                        var bufferType = ParseTypeName("NWayland.Interop.NWaylandMarshalledString");

                        statements = statements.Add(LocalDeclarationStatement(
                                                        new SyntaxTokenList(Token(SyntaxKind.UsingKeyword)),
                                                        VariableDeclaration(ParseTypeName("var"))
                                                        .WithVariables(SingletonSeparatedList(
                                                                           VariableDeclarator(tempName)
                                                                           .WithInitializer(EqualsValueClause(ObjectCreationExpression(bufferType)
                                                                                                              .WithArgumentList(
                                                                                                                  ArgumentList(
                                                                                                                      SingletonSeparatedList(Argument(IdentifierName(argName)))))))
                                                                           ))));
                        arglist = arglist.Add(IdentifierName(tempName));
                    }
                    else if (arg.Type == WaylandArgumentTypes.Object)
                    {
                        nullCheck     = true;
                        parameterType = ParseTypeName(GetWlInterfaceTypeName(arg.Interface));
                        arglist       = arglist.Add(IdentifierName(argName));
                    }
                    else if (arg.Type == WaylandArgumentTypes.Array)
                    {
                        if (arg.AllowNull)
                        {
                            throw new NotSupportedException(
                                      "Wrapping nullable arrays is currently not supported");
                        }
                        var arrayElementType = _hints.GetTypeNameForArray(protocol.Name, iface.Name, request.Name, arg.Name);
                        parameterType = ParseTypeName("ReadOnlySpan<" + arrayElementType + ">");
                        var pointerName = "__pointer__" + argName.TrimStart('@');
                        var tempName    = "__marshalled__" + argName.TrimStart('@');
                        fixedDeclarations.Add(VariableDeclaration(ParseTypeName(arrayElementType + "*"),
                                                                  SingletonSeparatedList(VariableDeclarator(pointerName)
                                                                                         .WithInitializer(EqualsValueClause(IdentifierName(argName))))));

                        callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var"))
                                                                                      .WithVariables(SingletonSeparatedList(VariableDeclarator(tempName)
                                                                                                                            .WithInitializer(EqualsValueClause(
                                                                                                                                                 InvocationExpression(MemberAccess(ParseTypeName("NWayland.Interop.WlArray"),
                                                                                                                                                                                   "FromPointer"), ArgumentList(SeparatedList(new[]
                        {
                            Argument(IdentifierName(pointerName)),
                            Argument(MemberAccess(IdentifierName(argName), "Length"))
                        }
                                                                                                                                                                                                                              ))))

                                                                                                                                             )))));

                        arglist = arglist.Add(PrefixUnaryExpression(SyntaxKind.AddressOfExpression,
                                                                    IdentifierName(tempName)));
                    }

                    if (parameterType != null)
                    {
                        plist = plist.Add(Parameter(Identifier(argName)).WithType(parameterType));
                    }

                    if (nullCheck)
                    {
                        statements = statements.Insert(0, IfStatement(
                                                           BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(argName),
                                                                            MakeNullLiteralExpression()),
                                                           ThrowStatement(ObjectCreationExpression(ParseTypeName("System.ArgumentNullException"))
                                                                          .WithArgumentList(
                                                                              ArgumentList(
                                                                                  SingletonSeparatedList(
                                                                                      Argument(MakeLiteralExpression(argName.TrimStart('@')))))))));
                    }
                }
            }

            callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("WlArgument*"))
                                                                          .WithVariables(SingletonSeparatedList(VariableDeclarator("__args")
                                                                                                                .WithInitializer(EqualsValueClause(StackAllocArrayCreationExpression(
                                                                                                                                                       ArrayType(ParseTypeName("WlArgument[]")),
                                                                                                                                                       InitializerExpression(SyntaxKind.ArrayInitializerExpression, arglist))))))));

            var marshalArgs = SeparatedList(new[]
            {
                Argument(MemberAccess(IdentifierName("this"), "Handle")),
                Argument(MakeLiteralExpression(index)),
                Argument(IdentifierName("__args"))
            });

            if (ctorType != null)
            {
                marshalArgs = marshalArgs.Add(Argument(GetWlInterfaceRefFor(ctorType)));
            }

            var callExpr = InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                       IdentifierName("LibWayland"),
                                                                       IdentifierName(ctorType == null
                        ? "wl_proxy_marshal_array"
                        : "wl_proxy_marshal_array_constructor")),
                                                ArgumentList(marshalArgs));



            if (ctorType == null)
            {
                callStatements = callStatements.Add(ExpressionStatement(callExpr));
            }
            else
            {
                callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var"))
                                                                              .WithVariables(SingletonSeparatedList(
                                                                                                 VariableDeclarator("__ret").WithInitializer(EqualsValueClause(callExpr))))));
                callStatements = callStatements.Add(ReturnStatement(ConditionalExpression(BinaryExpression(
                                                                                              SyntaxKind.EqualsExpression, IdentifierName("__ret"),
                                                                                              MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("IntPtr"),
                                                                                                                     IdentifierName("Zero"))),
                                                                                          MakeNullLiteralExpression(),
                                                                                          ObjectCreationExpression(ParseTypeName(dotNetCtorType)).WithArgumentList(
                                                                                              ArgumentList(SeparatedList(new[]
                {
                    Argument(IdentifierName("__ret")),
                    Argument(IdentifierName("Version")),
                    Argument(IdentifierName("Display"))
                }))))));
            }

            if (fixedDeclarations.Count == 0)
            {
                statements = statements.AddRange(callStatements);
            }
            else
            {
                var callBlock = (StatementSyntax)Block(callStatements);
                fixedDeclarations.Reverse();
                foreach (var fd in fixedDeclarations)
                {
                    callBlock = FixedStatement(fd, callBlock);
                }
                statements = statements.Add(callBlock);
            }

            method = WithSummary(method.WithParameterList(ParameterList(plist))
                                 .WithBody(Block(statements))
                                 .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))),
                                 request.Description);

            if (request.Type == "destructor")
            {
                method = method
                         .WithIdentifier(Identifier("CallWaylandDestructor"))
                         .WithModifiers(TokenList(
                                            Token(SyntaxKind.ProtectedKeyword),
                                            Token(SyntaxKind.SealedKeyword),
                                            Token(SyntaxKind.OverrideKeyword)
                                            ));
            }


            return(method);
        }