Exemplo n.º 1
0
        public SyntaxToken ConvertIdentifier(SyntaxToken id, bool isAttribute = false)
        {
            string text        = id.ValueText;
            var    keywordKind = SyntaxFacts.GetKeywordKind(text);

            if (keywordKind != Microsoft.CodeAnalysis.CSharp.SyntaxKind.None)
            {
                return(SyntaxFactory.Identifier("@" + text));
            }
            if (id.SyntaxTree == _semanticModel.SyntaxTree)
            {
                var symbol = _semanticModel.GetSymbolInfo(id.Parent).Symbol;
                if (symbol != null && !String.IsNullOrWhiteSpace(symbol.Name))
                {
                    if (symbol.IsConstructor() && isAttribute)
                    {
                        text = symbol.ContainingType.Name;
                        if (text.EndsWith("Attribute", StringComparison.Ordinal))
                        {
                            text = text.Remove(text.Length - "Attribute".Length);
                        }
                    }
                    else if (text.StartsWith("_", StringComparison.Ordinal) && symbol is IFieldSymbol fieldSymbol && fieldSymbol.AssociatedSymbol?.IsKind(SymbolKind.Property) == true)
                    {
                        text = fieldSymbol.AssociatedSymbol.Name;
                    }
                }
            }
            return(SyntaxFactory.Identifier(text));
        }
Exemplo n.º 2
0
 /// <summary>
 ///   public static bool IsTruthy(int i)
 /// </summary>
 /// <returns></returns>
 internal static MethodDeclarationSyntax IsTruthyMethodInt()
 {
     return
         (SF.MethodDeclaration(
              new SyntaxList <AttributeListSyntax>(),
              SF.TokenList(
                  SF.Token(SyntaxKind.PrivateKeyword),
                  SF.Token(SyntaxKind.StaticKeyword)),
              SF.PredefinedType(SF.Token(SyntaxKind.BoolKeyword)),
              default(ExplicitInterfaceSpecifierSyntax),
              SF.Identifier("IsTruthy"),
              default(TypeParameterListSyntax),
              SF.ParameterList(new SeparatedSyntaxList <ParameterSyntax>().Add(SyntaxFactory.Parameter(
                                                                                   default(SyntaxList <AttributeListSyntax>),
                                                                                   default(SyntaxTokenList),
                                                                                   SF.PredefinedType(SF.Token(SyntaxKind.IntKeyword)),
                                                                                   SF.Identifier("i"),
                                                                                   default(EqualsValueClauseSyntax)))
                               ),
              default(SyntaxList <TypeParameterConstraintClauseSyntax>),
              SF.Block(
                  SF.ReturnStatement(SF.ParseExpression("i!=0"))
                  ),
              default(SyntaxToken)
              ));
 }
Exemplo n.º 3
0
        private static MethodDeclarationSyntax MakeWithMethod(
            TypeDeclarationSyntax type, IEnumerable <Field> fields, MethodDeclarationSyntax maybePreviousWithMethod)
        {
            var fieldsList = fields.ToList();

            var withMethodParameters = SF.ParameterList(
                SF.SeparatedList(
                    fieldsList.Select(
                        field => SF.Parameter(SF.Identifier(field.Name))
                        .WithType(field.IsNonNullable ? SF.NullableType(field.Type) : field.Type)
                        .WithDefault(
                            SF.EqualsValueClause(
                                SF.Token(SyntaxKind.EqualsToken),
                                SF.LiteralExpression(SyntaxKind.NullLiteralExpression)
                                )
                            )
                        .WithAttributeLists(field.Attributes)
                        )
                    )
                );

            var withMethodBodyStatements = fieldsList.Select(
                field => SF.Argument(
                    SF.BinaryExpression(
                        SyntaxKind.CoalesceExpression, SF.IdentifierName(field.Name),
                        SF.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression, SF.ThisExpression(), SF.IdentifierName(field.Name)
                            )
                        )
                    )
                );

            var previousAttributes = maybePreviousWithMethod?.AttributeLists ?? new SyntaxList <AttributeListSyntax>();

            var typeSyntax = TypeSyntaxFactory.GetTypeSyntax(
                type.Identifier.Text, type.TypeParameterList?.Parameters.Select(x => x.Identifier.Text).ToArray()
                );

            var res = SF.MethodDeclaration(typeSyntax, "With")
                      .WithAttributeLists(previousAttributes)
                      .WithModifiers(SF.TokenList(new[] { SF.Token(SyntaxKind.PublicKeyword) }))
                      .WithParameterList(withMethodParameters)
                      .WithBody(
                SF.Block(
                    SF.ReturnStatement(
                        SF.ObjectCreationExpression(
                            typeSyntax, SF.ArgumentList(SF.SeparatedList(withMethodBodyStatements)), null
                            )
                        )
                    )
                );

            res = fieldsList.Any(x => x.StructuredTrivia != null) ? res.WithLeadingTrivia(
                MakeXmlDocComments(maybePreviousWithMethod, fieldsList, Constants.DefaultModifierSummary)
                ) :
                  maybePreviousWithMethod?.HasLeadingTrivia ?? false?
                  res.WithLeadingTrivia(maybePreviousWithMethod.GetLeadingTrivia()) : res;

            return(res);
        }
        private MemberDeclarationSyntax MockVirtualMethod()
        {
            var parameters = F.SeparatedList(Symbol.Parameters.Select(ps => TypesForSymbols.AsParameterSyntax(ps)));

            if (ArglistParameterName != null && TypesForSymbols.RuntimeArgumentHandle() != null)
            {
                parameters = parameters.Add(F.Parameter(F.Identifier(ArglistParameterName)).WithType(TypesForSymbols.RuntimeArgumentHandle()));
            }

            var method = F.MethodDeclaration(ReturnTypeWithoutReadonly, F.Identifier(MemberMockName))
                         .WithModifiers(F.TokenList(F.Token(SyntaxKind.ProtectedKeyword), F.Token(SyntaxKind.VirtualKeyword)))
                         .WithParameterList(F.ParameterList(parameters))
                         .WithBody(F.Block(ThrowMockMissingStatement("VirtualMethod")));

            if (Symbol.TypeParameters.Any())
            {
                method = method.WithTypeParameterList(TypeParameterList());

                var constraints = TypesForSymbols.AsConstraintClauses(Symbol.TypeParameters);

                if (constraints.Any())
                {
                    method = method.AddConstraintClauses(constraints);
                }
            }

            return(method);
        }
Exemplo n.º 5
0
        private ClassDeclarationSyntax GetClassForConstLocatorInInfo(WebLocatorInfo locatorInfo)
        {
            var infoMembers     = new List <MemberDeclarationSyntax>();
            var infoMembersList = new List <(string type, string fName, ExpressionSyntax expr)>
            {
                (nameof(WebLocatorType), nameof(locatorInfo.LocatorType), GetESForValue(locatorInfo.LocatorType)),
                ("string", nameof(locatorInfo.LocatorValue), GetESForValue(locatorInfo.LocatorValue)),
                ("bool", nameof(locatorInfo.IsRelative), GetESForValue(locatorInfo.IsRelative))
            };

            foreach (var infoMemberItem in infoMembersList)
            {
                var fd = SF.FieldDeclaration(
                    SF.VariableDeclaration(SF.ParseTypeName(infoMemberItem.type))
                    .AddVariables(SF.VariableDeclarator(SF.Identifier(infoMemberItem.fName))
                                  .WithInitializer(SF.EqualsValueClause(infoMemberItem.expr))
                                  )
                    )
                         .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.ConstKeyword));
                infoMembers.Add(fd);
            }



            var infoCD = SF.ClassDeclaration(LocatorStaticClassName)
                         .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
                         .AddMembers(infoMembers.ToArray());

            return(infoCD);
        }
Exemplo n.º 6
0
        public static ConstructorDeclarationSyntax MakeConstructor(string className, IEnumerable <Field> fields)
        {
            var constructorParameters =
                SF.ParameterList(
                    SF.SeparatedList(
                        fields.Select(field =>
                                      SF.Parameter(SF.Identifier(field.Name))
                                      .WithType(field.Type))));

            var constructorBodyStatements =
                fields.Select(
                    field =>
                    SF.ExpressionStatement(
                        SF.AssignmentExpression(
                            SyntaxKind.SimpleAssignmentExpression,
                            SF.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SF.ThisExpression(),
                                SF.IdentifierName(field.Name)
                                ),
                            SF.IdentifierName(field.Name))));

            return
                (SF.ConstructorDeclaration(className)
                 .WithModifiers(SF.TokenList(new[] { SF.Token(SyntaxKind.PublicKeyword) }))
                 .WithParameterList(constructorParameters)
                 .WithBody(SF.Block(constructorBodyStatements)));
        }
Exemplo n.º 7
0
        private ClassDeclarationSyntax GetClassForLocatorInInfo(WebLocatorInfo locatorInfo)
        {
            var infoMembers     = new List <MemberDeclarationSyntax>();
            var infoMembersList = new List <(string type, string fName, string value)>
            {
                (nameof(WebLocatorType), nameof(locatorInfo.LocatorType), $"{nameof(WebLocatorType)}.{locatorInfo.LocatorType}"),
                ("string", nameof(locatorInfo.LocatorValue), locatorInfo.LocatorValue),
                ("bool", nameof(locatorInfo.IsRelative), $"{locatorInfo.IsRelative}"),
            };

            foreach (var infoMemberItem in infoMembersList)
            {
                var docComment = GetDocCommentWithText(infoMemberItem.value);

                var fd = SF.FieldDeclaration(
                    SF.VariableDeclaration(SF.ParseTypeName(infoMemberItem.type))
                    .AddVariables(SF.VariableDeclarator(SF.Identifier(infoMemberItem.fName))
                                  )
                    )
                         .AddModifiers(
                    SF.Token(SF.TriviaList(), SyntaxKind.PublicKeyword, SF.TriviaList())
                    .WithLeadingTrivia(SF.Trivia(docComment))
                    );
                infoMembers.Add(fd);
            }

            var infoCD = SF.ClassDeclaration(LocatorClassName)
                         .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                         .AddMembers(infoMembers.ToArray());

            return(infoCD);
        }
Exemplo n.º 8
0
        public CompilationUnitSyntax StubInterface(CompilationUnitSyntax cu, InterfaceDeclarationSyntax interfaceDclr,
                                                   SemanticModel semanticModel)
        {
            INamedTypeSymbol           interfaceType = semanticModel.GetDeclaredSymbol(interfaceDclr);
            NamespaceDeclarationSyntax namespaceNode = GetNamespaceNode(interfaceDclr);
            string interfaceName             = interfaceType.GetGenericName();
            string stubName                  = NamingUtils.GetStubName(interfaceName);
            ClassDeclarationSyntax classDclr = SF.ClassDeclaration(SF.Identifier(stubName))
                                               .AddModifiers(SF.Token(RoslynUtils.GetVisibilityKeyword(interfaceType)))
                                               .WithBaseList(RoslynUtils.BaseList(interfaceName))
                                               .AddAttributeLists(AttributeListList(Attribute("CompilerGenerated")).ToArray());

            classDclr = RoslynUtils.CopyGenericConstraints(interfaceType, classDclr);
            classDclr = AddStubContainerField(classDclr, stubName);
            classDclr = StubProperties(interfaceType, classDclr);
            classDclr = StubMethods(interfaceType, classDclr);

            string fullNameSpace = semanticModel.GetDeclaredSymbol(namespaceNode).ToString();
            NamespaceDeclarationSyntax namespaceDclr = SF.NamespaceDeclaration(SF.IdentifierName(fullNameSpace))
                                                       .WithUsings(namespaceNode.Usings);

            namespaceDclr = namespaceDclr.AddMembers(classDclr);
            cu            = cu.AddMembers(namespaceDclr);
            return(cu);
        }
 private static ParameterSyntax CreateFileSystemParameterDeclaration()
 {
     return(SF.Parameter(SF.Identifier("fileSystem"))
            .WithType(CreateFileSystemType())
            .WithAdditionalAnnotations(Formatter.Annotation, Simplifier.SpecialTypeAnnotation)
            .NormalizeWhitespace());
 }
Exemplo n.º 10
0
        private MethodDeclarationSyntax GetGetInstanceMethod(string className)
        {
            var comment = GetDocCommentWithText("Get new element instance");

            var md = SF.MethodDeclaration(
                SF.IdentifierName(className),
                SF.Identifier("GetInstance")
                )
                     .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(comment)), SF.Token(SyntaxKind.StaticKeyword))
                     .AddParameterListParameters(
                SF.Parameter(SF.Identifier("parentElement"))
                .WithType(SF.IdentifierName(nameof(CombinedWebElementInfo)))
                )
                     .WithExpressionBody(
                SF.ArrowExpressionClause(
                    SF.ObjectCreationExpression(SF.IdentifierName(className))
                    .WithInitializer(
                        SF.InitializerExpression(
                            SyntaxKind.ObjectInitializerExpression
                            )
                        .AddExpressions(
                            SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SF.IdentifierName(nameof(WebElementInfo.Parent)), SF.IdentifierName("parentElement"))
                            )
                        )
                    )
                )
                     .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken));

            return(md);
        }
Exemplo n.º 11
0
            private CasePatternSwitchLabelSyntax WrapInCasePatternSwitchLabelSyntax(VBSyntax.SelectBlockSyntax node, ExpressionSyntax cSharpSyntaxNode, bool treatAsBoolean = false)
            {
                var typeInfo = _semanticModel.GetTypeInfo(node.SelectStatement.Expression);

                DeclarationPatternSyntax patternMatch;

                if (typeInfo.ConvertedType.SpecialType == SpecialType.System_Boolean || treatAsBoolean)
                {
                    patternMatch = SyntaxFactory.DeclarationPattern(
                        SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)),
                        SyntaxFactory.DiscardDesignation());
                }
                else
                {
                    var varName = CommonConversions.ConvertIdentifier(SyntaxFactory.Identifier(GetUniqueVariableNameInScope(node, "case"))).ValueText;
                    patternMatch = SyntaxFactory.DeclarationPattern(
                        SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(varName)));
                    cSharpSyntaxNode = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), cSharpSyntaxNode);
                }

                var casePatternSwitchLabelSyntax = SyntaxFactory.CasePatternSwitchLabel(patternMatch,
                                                                                        SyntaxFactory.WhenClause(cSharpSyntaxNode), SyntaxFactory.Token(SyntaxKind.ColonToken));

                return(casePatternSwitchLabelSyntax);
            }
Exemplo n.º 12
0
    //*/

    //*
    public static NameSyntax OptionalOf(TypeSyntax type)
    {
        return
            (SF.GenericName(
                 SF.Identifier(nameof(Option)),
                 SF.TypeArgumentList(SF.SingletonSeparatedList(type))));
    }
Exemplo n.º 13
0
        public static ParameterListSyntax AsParameterList(this IEnumerable <IParameterSymbol> parameters, MocklisTypesForSymbols typesForSymbols)
        {
            var args = parameters.Select(p =>
            {
                var syntax = F.Parameter(F.Identifier(p.Name)).WithType(typesForSymbols.ParseTypeName(p.Type, p.NullableOrOblivious()));

                switch (p.RefKind)
                {
                case RefKind.In:
                    {
                        syntax = syntax.WithModifiers(F.TokenList(F.Token(SyntaxKind.InKeyword)));
                        break;
                    }

                case RefKind.Out:
                    {
                        syntax = syntax.WithModifiers(F.TokenList(F.Token(SyntaxKind.OutKeyword)));
                        break;
                    }

                case RefKind.Ref:
                    {
                        syntax = syntax.WithModifiers(F.TokenList(F.Token(SyntaxKind.RefKeyword)));
                        break;
                    }
                }

                return(syntax);
            });

            return(F.ParameterList(F.SeparatedList(args)));
        }
Exemplo n.º 14
0
        private static string CreateClass_ColorNames(List <ColorEntity> entities, ProgressBar progress)
        {
            string classDeclaration;

            using (var child = progress.Spawn(entities.Count, "enum items added", childOptions))
            {
                var members = entities.Select((entity, index) =>
                {
                    //double prog = (double)index / entities.Count / STEPS;
                    //progress.Report(PROGRESS_STEP * lastStep + prog);

                    child.Tick();

                    // Console.WriteLine($"Converted {index} of {entities.Count} entities!");
                    return(Syntax.EnumMemberDeclaration(identifier:
                                                        Syntax.Identifier(entity.Name.SanitizeEnum())));
                });

                // TODO
                // Console.WriteLine("Declaring enum!");
                var declaration = Syntax.EnumDeclaration(
                    new SyntaxList <AttributeListSyntax>(),
                    identifier: Syntax.Identifier("ColorNames"),
                    modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword)),
                    baseList: null,
                    members: Syntax.SeparatedList(members))
                                  .NormalizeWhitespace();

                classDeclaration = declaration.ToFullString();
            }

            return(classDeclaration);
        }
Exemplo n.º 15
0
 public static NameSyntax IEquatableOf(TypeSyntax typeSyntax)
 {
     return(SF.QualifiedName(
                SF.IdentifierName(nameof(System)),
                SF.GenericName(
                    SF.Identifier(nameof(IEquatable <int>)),
                    SF.TypeArgumentList(SF.SingletonSeparatedList(typeSyntax)))));
 }
 private MemberDeclarationSyntax MockGetVirtualMethod()
 {
     return(F.MethodDeclaration(ValueTypeSyntax, F.Identifier(MemberMockName))
            .WithModifiers(F.TokenList(F.Token(SyntaxKind.ProtectedKeyword), F.Token(SyntaxKind.VirtualKeyword)))
            .WithParameterList(F.ParameterList(F.SeparatedList(Symbol.Parameters.Select(a =>
                                                                                        F.Parameter(F.Identifier(a.Name)).WithType(TypesForSymbols.ParseTypeName(a.Type, a.NullableOrOblivious()))))))
            .WithBody(F.Block(ThrowMockMissingStatement("VirtualIndexerGet"))));
 }
Exemplo n.º 17
0
        public FieldDeclarationSyntax ToFieldDeclaration()
        {
            if (canonicalName.value != name.name.value)
            {
                Console.WriteLine($"Warning!!! '{canonicalName.value}' != '{name.name.value}';");
            }

            if (annotations.Count != 0)
            {
                Console.WriteLine($"Warning!!! Annotations!;");
            }

            var declaratorSyntax = SF.VariableDeclarator(SF.Identifier(name.name.value));

            if (initializer.TryGetValue(out var initializerExpression))
            {
                declaratorSyntax = declaratorSyntax.WithInitializer(
                    // todo: I think this might not work ... a lot!
                    SF.EqualsValueClause(initializerExpression.ToLiteralExpressionSyntax()));
            }

            var fieldDeclaration = SF.FieldDeclaration(
                SF.VariableDeclaration(type.ToTypeSyntax())
                .WithVariables(SF.SingletonSeparatedList <VariableDeclaratorSyntax>(declaratorSyntax)));

            if (flags.HasFlag(Flag.isConst))
            {
                fieldDeclaration = fieldDeclaration.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.ConstKeyword)));
            }
            if (flags.HasFlag(Flag.isFinal))
            {
                fieldDeclaration = fieldDeclaration.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.ReadOnlyKeyword)));
            }
            if (flags.HasFlag(Flag.isStatic))
            {
                fieldDeclaration = fieldDeclaration.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.StaticKeyword)));
            }

            if (flags.HasFlag(Flag.isCovariant))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.isGenericCovariantImpl))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.hasImplicitSetter))
            {
                throw new NotImplementedException();
            }
            if (flags.HasFlag(Flag.hasImplicitGetter))
            {
                throw new NotImplementedException();
            }

            return(fieldDeclaration);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Returns syntax for the deserializer method.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="fields">The fields.</param>
        /// <returns>Syntax for the deserializer method.</returns>
        private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List <FieldInfoMember> fields)
        {
            Expression <Action> deserializeInner =
                () => SerializationManager.DeserializeInner(default(Type), default(IDeserializationContext));
            var contextParameter = SF.IdentifierName("context");

            var resultDeclaration =
                SF.LocalDeclarationStatement(
                    SF.VariableDeclaration(type.GetTypeSyntax())
                    .AddVariables(
                        SF.VariableDeclarator("result")
                        .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))));
            var resultVariable = SF.IdentifierName("result");

            var body = new List <StatementSyntax> {
                resultDeclaration
            };

            // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types.
            if (!type.GetTypeInfo().IsValueType)
            {
                // Record the result for cyclic deserialization.
                Expression <Action <IDeserializationContext> > recordObject = ctx => ctx.RecordObject(default(object));
                var currentSerializationContext = contextParameter;
                body.Add(
                    SF.ExpressionStatement(
                        recordObject.Invoke(currentSerializationContext)
                        .AddArgumentListArguments(SF.Argument(resultVariable))));
            }

            // Deserialize all fields.
            foreach (var field in fields)
            {
                var deserialized =
                    deserializeInner.Invoke()
                    .AddArgumentListArguments(
                        SF.Argument(SF.TypeOfExpression(field.Type)),
                        SF.Argument(contextParameter));
                body.Add(
                    SF.ExpressionStatement(
                        field.GetSetter(
                            resultVariable,
                            SF.CastExpression(field.Type, deserialized))));
            }

            body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable)));
            return
                (SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer")
                 .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
                 .AddParameterListParameters(
                     SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()),
                     SF.Parameter(SF.Identifier("context")).WithType(typeof(IDeserializationContext).GetTypeSyntax()))
                 .AddBodyStatements(body.ToArray())
                 .AddAttributeLists(
                     SF.AttributeList()
                     .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Generates syntax for an invoke method.
        /// </summary>
        /// <param name="grainType">
        /// The grain type.
        /// </param>
        /// <param name="invokeMethod">
        /// The invoke method to generate.
        /// </param>
        /// <returns>
        /// Syntax for an invoke method.
        /// </returns>
        private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod)
        {
            var methodDeclaration = invokeMethod.GetDeclarationSyntax();
            var parameters        = invokeMethod.GetParameters();

            var grainArgument       = parameters[0].Name.ToIdentifierName();
            var interfaceIdArgument = parameters[1].Name.ToIdentifierName();
            var methodIdArgument    = parameters[2].Name.ToIdentifierName();
            var argumentsArgument   = parameters[3].Name.ToIdentifierName();

            var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch(
                grainType,
                methodIdArgument,
                methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsArgument));

            // Generate the default case, which will throw a NotImplementedException.
            var errorMessage = SF.BinaryExpression(
                SyntaxKind.AddExpression,
                "interfaceId=".GetLiteralExpression(),
                interfaceIdArgument);
            var throwStatement =
                SF.ThrowStatement(
                    SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax())
                    .AddArgumentListArguments(SF.Argument(errorMessage)));
            var defaultCase       = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement);
            var interfaceIdSwitch =
                SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase);

            // If the provided grain is null, throw an argument exception.
            var argumentNullException =
                SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax())
                .AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression()));
            var grainArgumentCheck =
                SF.IfStatement(
                    SF.BinaryExpression(
                        SyntaxKind.EqualsExpression,
                        grainArgument,
                        SF.LiteralExpression(SyntaxKind.NullLiteralExpression)),
                    SF.ThrowStatement(argumentNullException));

            // Wrap everything in a try-catch block.
            var          faulted   = (Expression <Func <Task <object> > >)(() => TaskUtility.Faulted(null));
            const string Exception = "exception";
            var          exception = SF.Identifier(Exception);
            var          body      =
                SF.TryStatement()
                .AddBlockStatements(grainArgumentCheck, interfaceIdSwitch)
                .AddCatches(
                    SF.CatchClause()
                    .WithDeclaration(
                        SF.CatchDeclaration(typeof(Exception).GetTypeSyntax()).WithIdentifier(exception))
                    .AddBlockStatements(
                        SF.ReturnStatement(
                            faulted.Invoke().AddArgumentListArguments(SF.Argument(SF.IdentifierName(Exception))))));

            return(methodDeclaration.AddBodyStatements(body));
        }
Exemplo n.º 20
0
        private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List <FieldInfoMember> fields)
        {
            Expression <Action> deserializeInner =
                () => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader));
            var streamParameter = SF.IdentifierName("stream");

            var resultDeclaration =
                SF.LocalDeclarationStatement(
                    SF.VariableDeclaration(type.GetTypeSyntax())
                    .AddVariables(
                        SF.VariableDeclarator("result")
                        .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))));
            var resultVariable      = SF.IdentifierName("result");
            var boxedResultVariable = resultVariable;

            var body = new List <StatementSyntax> {
                resultDeclaration
            };

            if (type.IsValueType)
            {
                // For value types, we need to box the result for reflection-based setters to work.
                body.Add(SF.LocalDeclarationStatement(
                             SF.VariableDeclaration(typeof(object).GetTypeSyntax())
                             .AddVariables(
                                 SF.VariableDeclarator("boxedResult").WithInitializer(SF.EqualsValueClause(resultVariable)))));
                boxedResultVariable = SF.IdentifierName("boxedResult");
            }

            // Deserialize all fields.
            foreach (var field in fields)
            {
                var deserialized =
                    deserializeInner.Invoke()
                    .AddArgumentListArguments(
                        SF.Argument(SF.TypeOfExpression(field.Type)),
                        SF.Argument(streamParameter));
                body.Add(
                    SF.ExpressionStatement(
                        field.GetSetter(
                            resultVariable,
                            SF.CastExpression(field.Type, deserialized),
                            boxedResultVariable)));
            }

            body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), boxedResultVariable)));
            return
                (SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer")
                 .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
                 .AddParameterListParameters(
                     SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()),
                     SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax()))
                 .AddBodyStatements(body.ToArray())
                 .AddAttributeLists(
                     SF.AttributeList()
                     .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))));
        }
Exemplo n.º 21
0
        private SyntaxTree CreateSyntaxTree()
        {
            var compilationUnit = SF
                                  .CompilationUnit()
                                  .AddUsings
                                  (
                SF.UsingDirective
                    (SF.ParseName("System"))
                                  );

            var ns = SF
                     .NamespaceDeclaration(SF.IdentifierName("SynTreeFred"));

            var cls = SF
                      .ClassDeclaration("Henry")
                      .AddModifiers(SF.Token(SyntaxKind.PublicKeyword));

            // How to define base class and interfaces, with/without generics
            //
            //cls = cls.AddBaseListTypes(
            //    SF.SimpleBaseType(SF.ParseTypeName("Object")),
            //    SF.SimpleBaseType(SF.ParseTypeName("IEnumerable<string>")));

            var inti = SF
                       .VariableDeclaration(SF.ParseTypeName("int"))
                       .AddVariables
                       (
                SF.VariableDeclarator
                (
                    SF.Identifier("i"),
                    null,
                    SF.EqualsValueClause
                    (
                        SF.LiteralExpression
                        (
                            SyntaxKind.NumericLiteralExpression,
                            SF.Literal(12)
                        )
                    )
                )
                       );

            var field = SF.FieldDeclaration(inti)
                        .AddModifiers(SF.Token(SyntaxKind.PrivateKeyword));

            var syntax            = SF.ParseStatement("return ++i;");
            var methodDeclaration = SF
                                    .MethodDeclaration(SF.ParseTypeName("int"), "GetNextInt")
                                    .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
                                    .WithBody(SF.Block(syntax));

            cls             = cls.AddMembers(field, methodDeclaration);
            ns              = ns.AddMembers(cls);
            compilationUnit = compilationUnit.AddMembers(ns);
            return(compilationUnit.SyntaxTree);
        }
Exemplo n.º 22
0
 public PropertyDeclarationSyntax GenerateListProperty(string propertyName, PrimitiveType type)
 {
     return(SF.PropertyDeclaration(
                SF.GenericName(SF.Identifier("List"))
                .WithTypeArgumentList(
                    SF.TypeArgumentList(
                        SF.SingletonSeparatedList <TypeSyntax>(
                            SF.PredefinedType(SF.Token(FromPrimitive(type)))))),
                SF.Identifier(propertyName)));
 }
Exemplo n.º 23
0
 public PropertyDeclarationSyntax GenerateListProperty(string propertyName, string typeName)
 {
     return(SF.PropertyDeclaration(
                SF.GenericName(SF.Identifier("List"))
                .WithTypeArgumentList(
                    SF.TypeArgumentList(
                        SF.SingletonSeparatedList <TypeSyntax>(
                            SF.IdentifierName(typeName)))),
                SF.Identifier(propertyName)));
 }
 private MemberDeclarationSyntax MockSetVirtualMethod()
 {
     return(F.MethodDeclaration(F.PredefinedType(F.Token(SyntaxKind.VoidKeyword)), F.Identifier(MemberMockName))
            .WithParameterList(F.ParameterList(F.SeparatedList(new[]
     {
         F.Parameter(F.Identifier("value")).WithType(ValueTypeSyntax)
     })))
            .WithModifiers(F.TokenList(F.Token(SyntaxKind.ProtectedKeyword), F.Token(SyntaxKind.VirtualKeyword)))
            .WithBody(F.Block(ThrowMockMissingStatement("VirtualPropertySet"))));
 }
Exemplo n.º 25
0
        public WebInfoGenerationData GetClassForWebElement(WebElementInfo info)
        {
            var className   = GetClassNameFromElementName(info.Name);
            var propName    = className.Substring(1);
            var constInfoCD = GetClassForConstInfo(info);

            var baseClassName = info.GetType().Name;
            var docComment    = GetDocCommentWithText(info.Description);

            var infoComment = GetDocCommentWithText("Information about element");

            var infoProperty = SF.PropertyDeclaration(
                SF.ParseTypeName($"{InfoStaticClassName}.{InfoClassName}"),
                SF.Identifier(InfoClassName)
                )
                               .WithAccessorList(
                SF.AccessorList(
                    SF.List(
                        new List <AccessorDeclarationSyntax>
            {
                SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
                SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
            }
                        )
                    )
                .WithOpenBraceToken(SF.Token(SyntaxKind.OpenBraceToken))
                .WithCloseBraceToken(SF.Token(SyntaxKind.CloseBraceToken))
                )
                               .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(infoComment)));

            var getInstMd = GetGetInstanceMethod(className);

            var cd = SF.ClassDeclaration(className)
                     .AddModifiers(SF.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(SF.Trivia(docComment)))
                     .AddBaseListTypes(SF.SimpleBaseType(SF.IdentifierName(baseClassName)))
                     .AddMembers(infoProperty, getInstMd, constInfoCD);

            var genData = new WebInfoGenerationData
            {
                ClassName    = className,
                PropertyName = propName,
                ClassSyntax  = cd,
                Element      = info
            };

            FillWithChildrenElementsProperties(genData, out List <WebInfoGenerationData> childrenGens);

            AddCtor(genData, childrenGens);

            FillWithChildrenElementsClasses(genData, childrenGens);

            return(genData);
        }
Exemplo n.º 26
0
            private static VariableDeclarationSyntax CreateVariableDeclaration(string variableName,
                                                                               ExpressionSyntax variableValue)
            {
                var variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variableName), null,
                                                                                SyntaxFactory.EqualsValueClause(variableValue));
                var declaration = SyntaxFactory.VariableDeclaration(
                    SyntaxFactory.IdentifierName("var"),
                    SyntaxFactory.SingletonSeparatedList(variableDeclaratorSyntax));

                return(declaration);
            }
Exemplo n.º 27
0
 public static NameSyntax IReadOnlyListOf(TypeSyntax elementType)
 {
     return(SF.QualifiedName(
                SF.QualifiedName(
                    SF.QualifiedName(
                        SF.IdentifierName(nameof(System)),
                        SF.IdentifierName(nameof(System.Collections))),
                    SF.IdentifierName(nameof(System.Collections.Generic))),
                SF.GenericName(
                    SF.Identifier(nameof(IReadOnlyList <int>)),
                    SF.TypeArgumentList(SF.SingletonSeparatedList(elementType)))));
 }
Exemplo n.º 28
0
 public static NameSyntax KeyValuePairOf(TypeSyntax keyType, TypeSyntax valueType)
 {
     return(SF.QualifiedName(
                SF.QualifiedName(
                    SF.QualifiedName(
                        SF.IdentifierName(nameof(System)),
                        SF.IdentifierName(nameof(System.Collections))),
                    SF.IdentifierName(nameof(System.Collections.Generic))),
                SF.GenericName(
                    SF.Identifier(nameof(KeyValuePair <int, int>)),
                    SF.TypeArgumentList(JoinSyntaxNodes(SyntaxKind.CommaToken, keyType, valueType)))));
 }
Exemplo n.º 29
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            FieldDeclarationSyntax aField = SF.FieldDeclaration(
                SF.VariableDeclaration(
                    SF.ParseTypeName(" string "),
                    SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier("bopin=\"Hi bopin\"")) })
                    ))
                                            .AddModifiers(SF.Token(SyntaxKind.StaticKeyword)); //SyntaxKind.PublicKeyword),

            node = node.AddMembers(aField);
            return(base.VisitClassDeclaration(node));
        }
Exemplo n.º 30
0
        static SyntaxToken?ConvertModifier(SyntaxToken m, TokenContext context = SyntaxKindExtensions.TokenContext.Global)
        {
            VBasic.SyntaxKind vbSyntaxKind = VBasic.VisualBasicExtensions.Kind(m);
            switch (vbSyntaxKind)
            {
            case VBasic.SyntaxKind.DateKeyword:
                return(SyntaxFactory.Identifier("DateTime"));
            }
            var token = SyntaxKindExtensions.ConvertToken(vbSyntaxKind, context);

            return(token == SyntaxKind.None ? null : new SyntaxToken?(SyntaxFactory.Token(token)));
        }