コード例 #1
0
ファイル: EnumGenerator.cs プロジェクト: seawatts/jsii
        SeparatedSyntaxList <EnumMemberDeclarationSyntax> CreateValues()
        {
            return(SF.SeparatedList(Type.Members.Select(GetMemberDeclaration)));

            EnumMemberDeclarationSyntax GetMemberDeclaration(EnumMember member)
            {
                EnumMemberDeclarationSyntax declaration = SF.EnumMemberDeclaration
                                                          (
                    SF.List(new[] {
                    SF.AttributeList(SF.SeparatedList(new[] {
                        SF.Attribute(
                            SF.ParseName("JsiiEnumMember"),
                            SF.ParseAttributeArgumentList($"(\"{member.Name}\")")
                            )
                    }))
                }),
                    Symbols.GetNameSyntaxToken(Type, member),
                    null
                                                          );

                if (member.Docs != null)
                {
                    DocCommentGeneratorBase <EnumMember> generator = new EnumMemberDocCommentGenerator(member);
                    SyntaxTriviaList trivia = SF.TriviaList(generator.CreateDocComment());

                    declaration = declaration.WithLeadingTrivia(trivia);
                }

                return(declaration);
            }
        }
コード例 #2
0
        private async Task <Document> AddAnnotation(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var highlightedNode = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent;

            var methodDeclaration = CodeFixUtil.GetParentNode(highlightedNode, typeof(MethodDeclarationSyntax)) as MethodDeclarationSyntax;
            var attributesList    = methodDeclaration.AttributeLists[0] as AttributeListSyntax;

            if (methodDeclaration == null)
            {
                return(document);
            }

            var annotationValidate = SF.AttributeList()
                                     .AddAttributes(SF.Attribute(SF.IdentifierName("ValidateAntiForgeryToken")))
                                     .WithLeadingTrivia(CodeFixUtil.KeepLastLine(attributesList.GetLeadingTrivia()));

            var nodes = new List <SyntaxNode>();

            nodes.Add(annotationValidate);

            var newRoot = root.InsertNodesAfter(attributesList, nodes);

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #3
0
        public static (List <AttributeListSyntax>, List <MemberDeclarationSyntax>) GenerateSyntax(
            Assembly targetAssembly,
            List <GrainInterfaceDescription> grainInterfaces,
            List <GrainClassDescription> grainClasses,
            SerializationTypeDescriptions typeDescriptions)
        {
            var attributes = new List <AttributeListSyntax>();
            var members    = new List <MemberDeclarationSyntax>();
            var className  = CodeGeneratorCommon.ClassPrefix + Guid.NewGuid().ToString("N").Substring(0, 10) + ClassSuffix;

            // Generate a class for populating the metadata.
            var classSyntax = SF.ClassDeclaration(className)
                              .AddBaseListTypes(
                SF.SimpleBaseType(typeof(IFeaturePopulator <GrainInterfaceFeature>).GetTypeSyntax()),
                SF.SimpleBaseType(typeof(IFeaturePopulator <GrainClassFeature>).GetTypeSyntax()),
                SF.SimpleBaseType(typeof(IFeaturePopulator <SerializerFeature>).GetTypeSyntax()))
                              .AddModifiers(SF.Token(SyntaxKind.InternalKeyword), SF.Token(SyntaxKind.SealedKeyword))
                              .AddMembers(GeneratePopulateMethod(grainInterfaces), GeneratePopulateMethod(grainClasses), GeneratePopulateMethod(typeDescriptions))
                              .AddAttributeLists(SF.AttributeList(SF.SingletonSeparatedList(CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax())));

            var namespaceSyntax = SF.NamespaceDeclaration(NamespaceName.ToIdentifierName()).AddMembers(classSyntax);

            members.Add(namespaceSyntax);

            // Generate an assembly-level attribute with an instance of that class.
            var attribute = SF.AttributeList(
                SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword)),
                SF.SingletonSeparatedList(
                    SF.Attribute(typeof(FeaturePopulatorAttribute).GetNameSyntax())
                    .AddArgumentListArguments(SF.AttributeArgument(SF.TypeOfExpression(SF.ParseTypeName(NamespaceName + "." + className))))));

            attributes.Add(attribute);

            return(attributes, members);
        }
コード例 #4
0
        protected override MemberDeclarationSyntax CreateType()
        {
            return(SF.ClassDeclaration
                   (
                       SF.List <AttributeListSyntax>(new [] {
                SF.AttributeList(SF.SeparatedList(new [] {
                    SF.Attribute(SF.ParseName("JsiiByValue"))
                }))
            }),
                       SF.TokenList(SF.Token(SyntaxKind.PublicKeyword)),
                       Symbols.GetInterfaceDefaultNameSyntaxToken(Type),
                       null,
                       SF.BaseList(SF.SeparatedList(CreateBaseTypes())),
                       SF.List <TypeParameterConstraintClauseSyntax>(),
                       SF.List(CreateMembers())
                   ));

            IEnumerable <BaseTypeSyntax> CreateBaseTypes()
            {
                yield return(SF.SimpleBaseType(Symbols.GetNameSyntax(Type, disambiguate: true)));
            }

            IEnumerable <MemberDeclarationSyntax> CreateMembers()
            {
                return(CreateProperties());
            }
        }
コード例 #5
0
 public static AttributeListSyntax GenAttribute(string name)
 {
     return(SF.AttributeList(
                SF.SingletonSeparatedList(
                    SF.Attribute(
                        SF.IdentifierName(name)))));
 }
コード例 #6
0
ファイル: EnumGenerator.cs プロジェクト: nicholasgriffen/jsii
        SyntaxList <AttributeListSyntax> CreateAttributes()
        {
            TypeOfExpressionSyntax typeOfExpression          = SF.TypeOfExpression(Symbols.GetNameSyntax(Type));
            SyntaxToken            fullyQualifiedNameLiteral = SF.Literal(Type.FullyQualifiedName);

            return(SF.List(GetAttributeLists()));

            IEnumerable <AttributeListSyntax> GetAttributeLists()
            {
                yield return(SF.AttributeList(SF.SeparatedList(new[] {
                    SF.Attribute(
                        SF.ParseName("JsiiEnum"),
                        SF.ParseAttributeArgumentList($"(nativeType: {typeOfExpression}, fullyQualifiedName: {fullyQualifiedNameLiteral})")
                        )
                })));

                if (Type.Docs?.Stability == Stability.Deprecated)
                {
                    var argument = Type.Docs?.Deprecated != null?SF.Literal(Type.Docs?.Deprecated).ToString() : "";

                    yield return(SF.AttributeList(SF.SeparatedList(new[] {
                        SF.Attribute(
                            SF.ParseName("System.Obsolete"),
                            SF.ParseAttributeArgumentList($"({argument})")
                            )
                    })));
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Generates the class for the provided grain types.
        /// </summary>
        /// <param name="grainType">
        /// The grain interface type.
        /// </param>
        /// <returns>
        /// The generated class.
        /// </returns>
        internal static TypeDeclarationSyntax GenerateClass(Type grainType)
        {
            var baseTypes = new List <BaseTypeSyntax> {
                SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax())
            };

            var grainTypeInfo = grainType.GetTypeInfo();
            var genericTypes  = grainTypeInfo.IsGenericTypeDefinition
                                   ? grainTypeInfo.GetGenericArguments()
                                .Select(_ => SF.TypeParameter(_.ToString()))
                                .ToArray()
                                   : new TypeParameterSyntax[0];

            // Create the special method invoker marker attribute.
            var interfaceId         = GrainInterfaceUtils.GetGrainInterfaceId(grainType);
            var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId));
            var grainTypeArgument   = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false));
            var attributes          = new List <AttributeSyntax>
            {
                CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
                SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax())
                .AddArgumentListArguments(
                    SF.AttributeArgument(grainType.GetParseableName().GetLiteralExpression()),
                    SF.AttributeArgument(interfaceIdArgument),
                    SF.AttributeArgument(grainTypeArgument)),
#if !NETSTANDARD
                SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax())
#endif
            };

            var members = new List <MemberDeclarationSyntax>
            {
                GenerateInvokeMethod(grainType),
                GenerateInterfaceIdProperty(grainType)
            };

            // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker.
            if (typeof(IGrainExtension).IsAssignableFrom(grainType))
            {
                baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax()));
                members.Add(GenerateExtensionInvokeMethod(grainType));
            }

            var classDeclaration =
                SF.ClassDeclaration(
                    CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix)
                .AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
                .AddBaseListTypes(baseTypes.ToArray())
                .AddConstraintClauses(grainType.GetTypeConstraintSyntax())
                .AddMembers(members.ToArray())
                .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()));

            if (genericTypes.Length > 0)
            {
                classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
            }

            return(classDeclaration);
        }
コード例 #8
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()))));
        }
コード例 #9
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()))));
        }
コード例 #10
0
ファイル: SyntaxHelper.cs プロジェクト: alexandrvslv/datawf
        public static AttributeListSyntax GenAttributeList(KeyValuePair <string, string>[] names)
        {
            var list = new List <AttributeSyntax>();

            foreach (var name in names)
            {
                list.Add(GenAttribute(name.Key, name.Value));
            }
            return(SF.AttributeList(SF.SeparatedList(list)));
        }
コード例 #11
0
        private static AttributeListSyntax AttributeList(params AttributeSyntax[] attributes)
        {
            SeparatedSyntaxList <AttributeSyntax> separatedList = SF.SeparatedList <AttributeSyntax>();

            foreach (var attributeSyntax in attributes)
            {
                separatedList = separatedList.Add(attributeSyntax);
            }
            return(SF.AttributeList(separatedList));
        }
コード例 #12
0
        protected override MemberDeclarationSyntax CreateType()
        {
            return(SF.ClassDeclaration
                   (
                       CreateAttributes(),
                       SF.TokenList(
                           SF.Token(SyntaxKind.InternalKeyword),
                           SF.Token(SyntaxKind.SealedKeyword)),
                       GetProxyTypeNameSyntax(),
                       null,
                       CreateBaseList(),
                       SF.List <TypeParameterConstraintClauseSyntax>(),
                       SF.List(CreateMembers())
                   ));

            SyntaxList <AttributeListSyntax> CreateAttributes()
            {
                var typeOfExpression          = SF.TypeOfExpression(Symbols.GetNameSyntax(Type));
                var fullyQualifiedNameLiteral = SF.Literal(Type.FullyQualifiedName);

                return(SF.List(new[]
                {
                    SF.AttributeList(SF.SeparatedList(new[]
                    {
                        SF.Attribute(
                            SF.ParseName("JsiiTypeProxy"),
                            SF.ParseAttributeArgumentList($"({typeOfExpression}, {fullyQualifiedNameLiteral})")
                            )
                    }))
                }));
            }

            BaseListSyntax CreateBaseList()
            {
                return(SF.BaseList(SF.SeparatedList(GetBaseTypes())));

                IEnumerable <BaseTypeSyntax> GetBaseTypes()
                {
                    if (Type is InterfaceType)
                    {
                        yield return(SF.SimpleBaseType(SF.ParseTypeName("DeputyBase")));
                    }

                    Namespaces.Add(Type);
                    yield return(SF.SimpleBaseType(Symbols.GetNameSyntax(Type, disambiguate: true)));
                }
            }

            IEnumerable <MemberDeclarationSyntax> CreateMembers()
            {
                return(CreateConstructors()
                       .Concat(CreateProperties())
                       .Concat(CreateMethods()));
            }
        }
コード例 #13
0
 public static AttributeListSyntax GenAttribute(string name, string args)
 {
     return(SF.AttributeList(
                SF.SingletonSeparatedList(
                    SF.Attribute(
                        SF.IdentifierName(name)).WithArgumentList(
                        SF.AttributeArgumentList(
                            SF.SingletonSeparatedList(
                                SF.AttributeArgument(
                                    SF.ParseExpression(args))))))));
 }
コード例 #14
0
ファイル: MocklisClass.cs プロジェクト: mocklis/mocklis
            AttributeListSyntax FindInList(AttributeListSyntax originalAttributeList, bool add)
            {
                if (found)
                {
                    return(originalAttributeList);
                }

                List <AttributeSyntax> attributes = new List <AttributeSyntax>();

                foreach (var attribute in originalAttributeList.Attributes)
                {
                    if (found)
                    {
                        attributes.Add(attribute);
                        continue;
                    }

                    var p = semanticModel.GetSymbolInfo(attribute);
                    if (p.Symbol.ContainingType.Equals(mocklisSymbols.GeneratedCodeAttribute))
                    {
                        found = true;
                        attributes.Add(typesForSymbols.GeneratedCodeAttribute());
                    }
                    else if (add && p.Symbol.ContainingType.Equals(mocklisSymbols.MocklisClassAttribute))
                    {
                        found = true;
                        attributes.Add(attribute);
                        attributes.Add(typesForSymbols.GeneratedCodeAttribute());
                    }
                    else
                    {
                        attributes.Add(attribute);
                    }
                }

                if (found)
                {
                    var newAttributeList = F.AttributeList(F.SeparatedList(attributes));
                    if (originalAttributeList.HasLeadingTrivia)
                    {
                        newAttributeList = newAttributeList.WithLeadingTrivia(originalAttributeList.GetLeadingTrivia());
                    }

                    if (originalAttributeList.HasTrailingTrivia)
                    {
                        newAttributeList = newAttributeList.WithTrailingTrivia(originalAttributeList.GetTrailingTrivia());
                    }

                    return(newAttributeList);
                }

                return(found ? F.AttributeList(F.SeparatedList(attributes)) : originalAttributeList);
            }
コード例 #15
0
        /// <summary>
        /// Generates the class for the provided grain types.
        /// </summary>
        /// <param name="grainType">
        /// The grain interface type.
        /// </param>
        /// <param name="onEncounteredType">
        /// The callback which is invoked when a type is encountered.
        /// </param>
        /// <returns>
        /// The generated class.
        /// </returns>
        internal static TypeDeclarationSyntax GenerateClass(Type grainType, Action <Type> onEncounteredType)
        {
            var grainTypeInfo = grainType.GetTypeInfo();
            var genericTypes  = grainTypeInfo.IsGenericTypeDefinition
                                   ? grainTypeInfo.GetGenericArguments()
                                .Select(_ => SF.TypeParameter(_.ToString()))
                                .ToArray()
                                   : new TypeParameterSyntax[0];

            // Create the special marker attribute.
            var markerAttribute =
                SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax())
                .AddArgumentListArguments(
                    SF.AttributeArgument(
                        SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false))));
            var attributes = SF.AttributeList()
                             .AddAttributes(
                CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),

                SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()),
#if !NETSTANDARD_TODO
                //ExcludeFromCodeCoverageAttribute became an internal class in netstandard
                SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
#endif

                markerAttribute);

            var className        = CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix;
            var classDeclaration =
                SF.ClassDeclaration(className)
                .AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
                .AddBaseListTypes(
                    SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()),
                    SF.SimpleBaseType(grainType.GetTypeSyntax()))
                .AddConstraintClauses(grainType.GetTypeConstraintSyntax())
                .AddMembers(GenerateConstructors(className))
                .AddMembers(
                    GenerateInterfaceIdProperty(grainType),
                    GenerateInterfaceNameProperty(grainType),
                    GenerateIsCompatibleMethod(grainType),
                    GenerateGetMethodNameMethod(grainType))
                .AddMembers(GenerateInvokeMethods(grainType, onEncounteredType))
                .AddAttributeLists(attributes);

            if (genericTypes.Length > 0)
            {
                classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
            }

            return(classDeclaration);
        }
コード例 #16
0
        public static CompilationUnitSyntax AddGeneratedCodeAttribute(GeneratedSyntax generatedSyntax)
        {
            var codeGenTargetAttributes =
                SF.AttributeList()
                .AddAttributes(
                    generatedSyntax.SourceAssemblies.Select(
                        asm =>
                        SF.Attribute(typeof(OrleansCodeGenerationTargetAttribute).GetNameSyntax())
                        .AddArgumentListArguments(
                            SF.AttributeArgument(asm.GetName().FullName.GetLiteralExpression()))).ToArray())
                .WithTarget(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword)));

            return(generatedSyntax.Syntax.AddAttributeLists(codeGenTargetAttributes));
        }
コード例 #17
0
ファイル: EnumGenerator.cs プロジェクト: seawatts/jsii
        SyntaxList <AttributeListSyntax> CreateAttributes()
        {
            TypeOfExpressionSyntax typeOfExpression          = SF.TypeOfExpression(Symbols.GetNameSyntax(Type));
            SyntaxToken            fullyQualifiedNameLiteral = SF.Literal(Type.FullyQualifiedName);

            return(SF.List(new[] {
                SF.AttributeList(SF.SeparatedList(new[] {
                    SF.Attribute(
                        SF.ParseName("JsiiEnum"),
                        SF.ParseAttributeArgumentList($"({typeOfExpression}, {fullyQualifiedNameLiteral})")
                        )
                }))
            }));
        }
コード例 #18
0
        SyntaxList <AttributeListSyntax> GetAttributeLists()
        {
            return(SF.List(GetAttributeLists()));

            IEnumerable <AttributeListSyntax> GetAttributeLists()
            {
                SyntaxToken nameLiteral = SF.Literal(Method.Name);
                SyntaxToken trueLiteral = SF.Token(SyntaxKind.TrueKeyword);

                string argumentList = $"name: {nameLiteral}";

                if (Method.Returns != null)
                {
                    SyntaxToken returnsJsonLiteral = Method.Returns == null?
                                                     SF.Token(SyntaxKind.NullKeyword) :
                                                         SF.Literal(JsonConvert.SerializeObject(Method.Returns, SerializerSettings));

                    argumentList += $", returnsJson: {returnsJsonLiteral}";
                }

                if (Method.Parameters != null && Method.Parameters.Length > 0)
                {
                    SyntaxToken parametersJsonLiteral = Method.GetParametersJsonSyntaxToken();
                    argumentList += $", parametersJson: {parametersJsonLiteral}";
                }
                if (Method.IsAsync)
                {
                    argumentList += $", isAsync: {trueLiteral}";
                }
                if (Method.Overrides != null)
                {
                    argumentList += $", isOverride: {trueLiteral}";
                }

                yield return(SF.AttributeList(SF.SingletonSeparatedList(SF.Attribute(
                                                                            SF.ParseName("JsiiMethod"),
                                                                            SF.ParseAttributeArgumentList($"({argumentList})")
                                                                            ))));

                if (Method.Docs?.Stability == Stability.Deprecated)
                {
                    var argument = Method.Docs?.Deprecated != null?SF.Literal(Method.Docs?.Deprecated).ToString() : "";

                    yield return(SF.AttributeList(SF.SingletonSeparatedList(SF.Attribute(
                                                                                SF.ParseName("System.Obsolete"),
                                                                                SF.ParseAttributeArgumentList($"({argument})")
                                                                                ))));
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// Generates the class for the provided grain types.
        /// </summary>
        /// <param name="type">The grain interface type.</param>
        /// <param name="onEncounteredType">
        /// The callback invoked when a type is encountered.
        /// </param>
        /// <returns>
        /// The generated class.
        /// </returns>
        internal static TypeDeclarationSyntax GenerateClass(Type type, Action <Type> onEncounteredType)
        {
            var typeInfo     = type.GetTypeInfo();
            var genericTypes = typeInfo.IsGenericTypeDefinition
                                   ? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray()
                                   : new TypeParameterSyntax[0];

            var attributes = new List <AttributeSyntax>
            {
                CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
#if !NETSTANDARD
                SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
#endif
                SF.Attribute(typeof(SerializerAttribute).GetNameSyntax())
                .AddArgumentListArguments(
                    SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))))
            };

            var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions);
            var fields    = GetFields(type);

            // Mark each field type for generation
            foreach (var field in fields)
            {
                var fieldType = field.FieldInfo.FieldType;
                onEncounteredType(fieldType);
            }

            var members = new List <MemberDeclarationSyntax>(GenerateStaticFields(fields))
            {
                GenerateDeepCopierMethod(type, fields),
                GenerateSerializerMethod(type, fields),
                GenerateDeserializerMethod(type, fields),
            };

            var classDeclaration =
                SF.ClassDeclaration(className)
                .AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
                .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()))
                .AddMembers(members.ToArray())
                .AddConstraintClauses(type.GetTypeConstraintSyntax());

            if (genericTypes.Length > 0)
            {
                classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
            }

            return(classDeclaration);
        }
コード例 #20
0
ファイル: InterfaceGenerator.cs プロジェクト: seawatts/jsii
        protected override MemberDeclarationSyntax CreateType()
        {
            return(SF.InterfaceDeclaration
                   (
                       CreateAttributes(),
                       SF.TokenList(SF.Token(SyntaxKind.PublicKeyword)),
                       Symbols.GetNameSyntaxToken(Type),
                       null,
                       CreateBaseList(),
                       SF.List <TypeParameterConstraintClauseSyntax>(),
                       SF.List(CreateMembers())
                   ));

            SyntaxList <AttributeListSyntax> CreateAttributes()
            {
                TypeOfExpressionSyntax typeOfExpression          = SF.TypeOfExpression(Symbols.GetNameSyntax(Type));
                SyntaxToken            fullyQualifiedNameLiteral = SF.Literal(Type.FullyQualifiedName);

                return(SF.List(new[] {
                    SF.AttributeList(SF.SeparatedList(new[] {
                        SF.Attribute(
                            SF.ParseName("JsiiInterface"),
                            SF.ParseAttributeArgumentList($"({typeOfExpression}, {fullyQualifiedNameLiteral})")
                            )
                    }))
                }));
            }

            BaseListSyntax CreateBaseList()
            {
                IEnumerable <BaseTypeSyntax> baseTypes = GetBaseTypes();

                return(baseTypes?.Any() == true?SF.BaseList(SF.SeparatedList(baseTypes)) : null);

                IEnumerable <BaseTypeSyntax> GetBaseTypes()
                {
                    foreach (TypeReference interfaceReference in Type.Interfaces ?? Enumerable.Empty <TypeReference>())
                    {
                        Namespaces.Add(interfaceReference);
                        yield return(SF.SimpleBaseType(Symbols.GetTypeSyntax(interfaceReference)));
                    }
                }
            }

            IEnumerable <MemberDeclarationSyntax> CreateMembers()
            {
                return(CreateProperties().Concat(CreateMethods()));
            }
        }
コード例 #21
0
ファイル: Utils.cs プロジェクト: suzuke/UnityFixedPoint
 public static SyntaxList <AttributeListSyntax> GenerateStructLayoutAttributes()
 {
     return(SF.SingletonList(
                SF.AttributeList(
                    SF.SingletonSeparatedList(
                        SF.Attribute(SF.IdentifierName("StructLayout"))
                        .WithArgumentList(
                            SF.AttributeArgumentList(
                                SF.SingletonSeparatedList(
                                    SF.AttributeArgument(
                                        SF.MemberAccessExpression(
                                            SK.SimpleMemberAccessExpression,
                                            SF.IdentifierName("LayoutKind"),
                                            SF.IdentifierName("Explicit"))))))))));
 }
コード例 #22
0
        private SyntaxList <AttributeListSyntax> CreateSerializationAttribute(SymbolData symbol)
        {
            string requiredValueName;

            if (symbol.IsRequired)
            {
                requiredValueName = (symbol.isNullable) ? "AllowNull" : "Always";
            }
            else
            {
                requiredValueName = "Default";
            }

            Func <string, string, string, AttributeArgumentSyntax> createAttr =
                (lhs, expr, name) =>
            {
                // lhs = expr.name
                return(SF.AttributeArgument(
                           SF.MemberAccessExpression(
                               SyntaxKind.SimpleMemberAccessExpression,
                               SF.IdentifierName(expr),
                               SF.Token(SyntaxKind.DotToken),
                               SF.IdentifierName(name)))
                       .WithNameEquals(
                           SF.NameEquals(SF.IdentifierName(lhs))));
            };

            var attributes = SF.SeparatedList(new[]
            {
                // Required = Required.[requiredValueName]
                createAttr("Required", "Required", requiredValueName),
            });

            if (requiredValueName == "Default" && !symbol.isNullable)
            {
                // NullValueHandling = NullValueHandling.Ignore
                attributes = attributes.Add(
                    createAttr("NullValueHandling", "NullValueHandling", "Ignore"));
            }

            return(SF.SingletonList(
                       SF.AttributeList(
                           SF.SingletonSeparatedList(
                               SF.Attribute(SF.IdentifierName("JsonProperty"))
                               .WithArgumentList(
                                   SF.AttributeArgumentList(attributes))))));
        }
コード例 #23
0
ファイル: EnumGenerator.cs プロジェクト: nicholasgriffen/jsii
        SeparatedSyntaxList <EnumMemberDeclarationSyntax> CreateValues()
        {
            return(SF.SeparatedList(Type.Members.Select(GetMemberDeclaration)));

            EnumMemberDeclarationSyntax GetMemberDeclaration(EnumMember member)
            {
                EnumMemberDeclarationSyntax declaration = SF.EnumMemberDeclaration
                                                          (
                    SF.List(GetAttributeLists()),
                    Symbols.GetNameSyntaxToken(Type, member),
                    null
                                                          );

                if (member.Docs != null)
                {
                    DocCommentGeneratorBase <EnumMember> generator = new EnumMemberDocCommentGenerator(member);
                    SyntaxTriviaList trivia = SF.TriviaList(generator.CreateDocComment());

                    declaration = declaration.WithLeadingTrivia(trivia);
                }

                return(declaration);

                IEnumerable <AttributeListSyntax> GetAttributeLists()
                {
                    yield return(SF.AttributeList(SF.SingletonSeparatedList(
                                                      SF.Attribute(
                                                          SF.ParseName("JsiiEnumMember"),
                                                          SF.ParseAttributeArgumentList($"(name: \"{member.Name}\")")
                                                          )
                                                      )));

                    if (member.Docs?.Stability == Stability.Deprecated)
                    {
                        var argument = member.Docs?.Deprecated != null?SF.Literal(member.Docs?.Deprecated).ToString() : "";

                        yield return(SF.AttributeList(SF.SingletonSeparatedList(
                                                          SF.Attribute(
                                                              SF.ParseName("System.Obsolete"),
                                                              SF.ParseAttributeArgumentList($"({argument})")
                                                              )
                                                          )));
                    }
                }
            }
        }
コード例 #24
0
 /// <summary>
 /// Yields the CompiledHandlebars Class Declaration ClassDeclaration
 /// public static class CompiledHandlebarsTemplate<TViewModel> {}
 /// </summary>
 internal static ClassDeclarationSyntax CompiledHandlebarsClassDeclaration(string templateName, string attribute)
 {
     return
         (SF.ClassDeclaration(
              new SyntaxList <AttributeListSyntax>().Add(
                  SF.AttributeList(new SeparatedSyntaxList <AttributeSyntax>().Add(
                                       SF.Attribute(SF.ParseName(attribute)))
                                   )),
              SF.TokenList(
                  SF.Token(SyntaxKind.PublicKeyword),
                  SF.Token(SyntaxKind.StaticKeyword)),
              SF.Identifier(templateName),
              default(TypeParameterListSyntax),
              default(BaseListSyntax),
              default(SyntaxList <TypeParameterConstraintClauseSyntax>),
              default(SyntaxList <MemberDeclarationSyntax>)
              ));
 }
コード例 #25
0
        private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List <FieldInfoMember> fields)
        {
            Expression <Action> serializeInner =
                () =>
                SerializationManager.SerializeInner(default(object), default(ISerializationContext), default(Type));
            var contextParameter = SF.IdentifierName("context");

            var body = new List <StatementSyntax>
            {
                SF.LocalDeclarationStatement(
                    SF.VariableDeclaration(type.GetTypeSyntax())
                    .AddVariables(
                        SF.VariableDeclarator("input")
                        .WithInitializer(
                            SF.EqualsValueClause(
                                SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput"))))))
            };

            var inputExpression = SF.IdentifierName("input");

            // Serialize all members.
            foreach (var field in fields)
            {
                body.Add(
                    SF.ExpressionStatement(
                        serializeInner.Invoke()
                        .AddArgumentListArguments(
                            SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)),
                            SF.Argument(contextParameter),
                            SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax())))));
            }

            return
                (SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer")
                 .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword))
                 .AddParameterListParameters(
                     SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()),
                     SF.Parameter(SF.Identifier("context")).WithType(typeof(ISerializationContext).GetTypeSyntax()),
                     SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()))
                 .AddBodyStatements(body.ToArray())
                 .AddAttributeLists(
                     SF.AttributeList()
                     .AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax()))));
        }
コード例 #26
0
ファイル: ClassGenerator.cs プロジェクト: bohoffi/xsd2code
 private SyntaxList <MemberDeclarationSyntax> GenerateProperties(List <Property> props)
 {
     return(SF.List(props.Select(p =>
     {
         //return (MemberDeclarationSyntax)SF.PropertyDeclaration(
         //            SF.PredefinedType(
         //                SF.Token(SyntaxKind.StringKeyword)),
         //            SF.Identifier(p.CleanName))
         //       .WithAttributeLists(
         //                SF.SingletonList(
         //                    SF.AttributeList(
         //                        GenerateAttributes(p.Attributes))))
         //       .WithModifiers(
         //            SF.TokenList(
         //                SF.Token(SyntaxKind.PublicKeyword)))
         //       .WithAccessorList(
         //            SF.AccessorList(
         //                SF.List(
         //                    new AccessorDeclarationSyntax[]{
         //                        SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
         //                            .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
         //                        SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
         //                            .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
         //                    })));
         return (MemberDeclarationSyntax)p.ToDeclarationSyntax()
         .WithAttributeLists(
             SF.SingletonList(
                 SF.AttributeList(
                     GenerateAttributes(p.XmlAttributes))))
         .WithModifiers(
             SF.TokenList(
                 SF.Token(SyntaxKind.PublicKeyword)))
         .WithAccessorList(
             SF.AccessorList(
                 SF.List(
                     new AccessorDeclarationSyntax[] {
             SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
             .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)),
             SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
             .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
         })));
     }).ToList()));
 }
コード例 #27
0
        SyntaxList <AttributeListSyntax> GetAttributeLists()
        {
            return(SF.List(new[] { SF.AttributeList(SF.SeparatedList(GetAttributes())) }));

            IEnumerable <AttributeSyntax> GetAttributes()
            {
                SyntaxToken nameLiteral     = SF.Literal(Property.Name);
                SyntaxToken typeJsonLiteral = SF.Literal(JsonConvert.SerializeObject(Property.Type));
                SyntaxToken trueLiteral     = SF.Token(SyntaxKind.TrueKeyword);

                string argumentList = IsOverride ?
                                      $"({nameLiteral}, {typeJsonLiteral}, {trueLiteral})" :
                                      $"({nameLiteral}, {typeJsonLiteral})";

                yield return(SF.Attribute(
                                 SF.ParseName("JsiiProperty"),
                                 SF.ParseAttributeArgumentList(argumentList)
                                 ));
            }
        }
コード例 #28
0
        SyntaxList <AttributeListSyntax> GetAttributeLists()
        {
            return(SF.List(GetAttributesLists()));

            IEnumerable <AttributeListSyntax> GetAttributesLists()
            {
                SyntaxToken nameLiteral     = SF.Literal(Property.Name);
                SyntaxToken typeJsonLiteral = SF.Literal(JsonConvert.SerializeObject(Property.Type, SerializerSettings));
                SyntaxToken trueLiteral     = SF.Token(SyntaxKind.TrueKeyword);

                string argumentList = $"name: {nameLiteral}, typeJson: {typeJsonLiteral}";

                if (Property.IsOptional)
                {
                    argumentList += $", isOptional: {trueLiteral}";
                }
                if (IsOverride)
                {
                    argumentList += $", isOverride: {trueLiteral}";
                }

                yield return(SF.AttributeList(SF.SingletonSeparatedList(SF.Attribute(
                                                                            SF.ParseName("JsiiProperty"),
                                                                            SF.ParseAttributeArgumentList($"({argumentList})")
                                                                            ))));

                if (Property.Docs?.Stability == Stability.Deprecated)
                {
                    var argument = Property.Docs?.Deprecated != null?SF.Literal(Property.Docs?.Deprecated).ToString() : "";

                    yield return(SF.AttributeList(SF.SingletonSeparatedList(SF.Attribute(
                                                                                SF.ParseName("System.Obsolete"),
                                                                                SF.ParseAttributeArgumentList($"({argument})")
                                                                                ))));
                }
            }
        }
コード例 #29
0
        private ClassDeclarationSyntax CreateClass(SymbolData symbol)
        {
            var className = symbol.Name.ToClassName();
            var node      = SF.ClassDeclaration(className)
                            .AddModifiers(SF.Token(SyntaxKind.PublicKeyword));

            if (_options.IsJsonSerializable)
            {
                node = node.WithAttributeLists(
                    SF.SingletonList(
                        SF.AttributeList(
                            SF.SingletonSeparatedList(
                                SF.Attribute(SF.IdentifierName("JsonObject"))))));
            }

            if (!string.IsNullOrEmpty(symbol.Summary))
            {
                var comment = new DocumentComment()
                {
                    Summary = symbol.Summary
                };
                node = node.WithLeadingTrivia(comment.ConstructTriviaList());
            }

            var props = new List <MemberDeclarationSyntax>();

            foreach (var member in symbol.Members)
            {
                props.Add(ConstructImpl(member) as MemberDeclarationSyntax);
                if (member.TypeName == "object")
                {
                    var childSymbol = member.CreateInstanceSymbol();
                    props.Add(CreateProperty(childSymbol));
                }
            }
            return(node.AddMembers(props.ToArray()));
        }
コード例 #30
0
ファイル: MethodGeneratorBase.cs プロジェクト: seawatts/jsii
        SyntaxList <AttributeListSyntax> GetAttributeLists()
        {
            return(SF.List(new[] { SF.AttributeList(SF.SeparatedList(GetAttributes())) }));

            IEnumerable <AttributeSyntax> GetAttributes()
            {
                SyntaxToken nameLiteral        = SF.Literal(Method.Name);
                SyntaxToken returnsJsonLiteral = Method.Returns == null?
                                                 SF.Token(SyntaxKind.NullKeyword) :
                                                     SF.Literal(JsonConvert.SerializeObject(Method.Returns));

                SyntaxToken parametersJsonLiteral = Method.GetParametersJsonSyntaxToken();
                SyntaxToken trueLiteral           = SF.Token(SyntaxKind.TrueKeyword);

                string argumentList = IsOverride ?
                                      $"({nameLiteral}, {returnsJsonLiteral}, {parametersJsonLiteral}, {trueLiteral})" :
                                      $"({nameLiteral}, {returnsJsonLiteral}, {parametersJsonLiteral})";

                yield return(SF.Attribute(
                                 SF.ParseName("JsiiMethod"),
                                 SF.ParseAttributeArgumentList(argumentList)
                                 ));
            }
        }