private static string GenerateCodeBehindClass(string className, string contents, RazorCodeDocument razorCodeDocument) { var namespaceNode = (NamespaceDeclarationIntermediateNode)razorCodeDocument .GetDocumentIntermediateNode() .FindDescendantNodes <IntermediateNode>() .FirstOrDefault(n => n is NamespaceDeclarationIntermediateNode); var mock = (ClassDeclarationSyntax)CSharpSyntaxFactory.ParseMemberDeclaration($"class Class {contents}"); var @class = CSharpSyntaxFactory .ClassDeclaration(className) .AddModifiers(CSharpSyntaxFactory.Token(CSharpSyntaxKind.PublicKeyword), CSharpSyntaxFactory.Token(CSharpSyntaxKind.PartialKeyword)) .AddMembers(mock.Members.ToArray()); var @namespace = CSharpSyntaxFactory .NamespaceDeclaration(CSharpSyntaxFactory.ParseName(namespaceNode.Content)) .AddMembers(@class); var usings = FindUsings(razorCodeDocument) .Select(u => CSharpSyntaxFactory.UsingDirective(CSharpSyntaxFactory.ParseName(u))) .ToArray(); var compilationUnit = CSharpSyntaxFactory .CompilationUnit() .AddUsings(usings) .AddMembers(@namespace); return(compilationUnit.NormalizeWhitespace().ToFullString()); }
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); }
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); }
public static TypeDeclarationSyntax TypeDeclaration( SyntaxKind kind, SyntaxList <AttributeListSyntax> attributes, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax?typeParameterList, BaseListSyntax?baseList, SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList <MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { switch (kind) { case SyntaxKind.ClassDeclaration: return(SyntaxFactory.ClassDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken)); case SyntaxKind.StructDeclaration: return(SyntaxFactory.StructDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken)); case SyntaxKind.InterfaceDeclaration: return(SyntaxFactory.InterfaceDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken)); case SyntaxKind.RecordDeclaration: return(SyntaxFactory.RecordDeclaration(attributes, modifiers, keyword, identifier, typeParameterList, parameterList: null, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken)); default: throw new ArgumentException("kind"); } }
public void BeforeCompile(IBeforeCompileContext context) { // Firstly, I need to resolve the namespace of the ModuleProvider instance in this current compilation. string ns = GetModuleProviderNamespace(context.Compilation.SyntaxTrees); // Next, get all the available modules in assembly and compilation references. var modules = GetAvailableModules(context.Compilation).ToList(); // Map them to a collection of statements var statements = modules.Select(m => F.ParseStatement("AddModule<" + module + ">();")).ToList(); // Now, I'll create the dynamic implementation as a private class. var cu = F.CompilationUnit() .AddMembers( F.NamespaceDeclaration(F.IdentifierName(ns)) .AddMembers( F.ClassDeclaration("ModuleProvider") .WithModifiers(F.TokenList(F.Token(K.PartialKeyword))) .AddMembers( F.MethodDeclaration(F.PredefinedType(F.Token(K.VoidKeyword)), "Setup") .WithModifiers( F.TokenList( F.Token(K.ProtectedKeyword), F.Token(K.OverrideKeyword))) .WithBody(F.Block(statements)) ) ) ) .NormalizeWhitespace(indentation("\t")); var tree = T.Create(cu); context.Compilation = context.Compilation.AddSyntaxTrees(tree); }
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); }
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); }
protected override MemberDeclarationSyntax CreateType() { return(SF.ClassDeclaration ( SF.List <AttributeListSyntax>(), 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(SF.ParseTypeName("DeputyBase"))); yield return(SF.SimpleBaseType(Symbols.GetNameSyntax(Type, disambiguate: true))); } IEnumerable <MemberDeclarationSyntax> CreateMembers() { return(CreateProperties()); } }
// We might want to combine all the libraries together into a single CompilationUnit, we could combine all the usings public object ToLibrary() { if (name.index != 0) { Console.WriteLine($"Warning, Library has a Name => {name.value};"); } var safeLibraryName = SafeLibraryName(); var library = SF.ClassDeclaration(safeLibraryName) .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.StaticKeyword))); // todo: annotations // todo: libraryDependencies ~ static usings? // todo: additionalExports ~ I'm unsure how to handle this ~ I may not need to // todo: libraryParts ~ hmm.... will this happen? // todo: typedefs // todo: classes <-- sub-classes to my static classing // fields var fieldDeclarationList = fields.Select(field => field.ToFieldDeclaration()); // procedures var methodDeclarationList = procedures.Select(procedure => procedure.ToMethodDeclaration()); library = library.WithMembers(SF.List(fieldDeclarationList.Concat <MemberDeclarationSyntax>(methodDeclarationList))); // I assume we can remove this during production for increased efficiency? return(library.NormalizeWhitespace()); }
/// <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); }
public ClassDeclarationSyntax GenerateHelper() { if (!HasImports) { return(null); } var xAttributeList = SyntaxFactory.FieldDeclaration( SyntaxFactory.List <AttributeListSyntax>(), SyntaxFactory.TokenList(SyntaxFactory.Token(CSSyntaxKind.PrivateKeyword), SyntaxFactory.Token(CSSyntaxKind.StaticKeyword)), CommonConversions.CreateVariableDeclarationAndAssignment( "namespaceAttributes", SyntaxFactory.InitializerExpression( CSSyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( from x in _xNamespaceFields let fieldIdentifierName = SyntaxFactory.IdentifierName(x.Declaration.Variables.Single().Identifier) let namespaceNameExpression = SyntaxFactory.MemberAccessExpression(CSSyntaxKind.SimpleMemberAccessExpression, fieldIdentifierName, SyntaxFactory.IdentifierName("NamespaceName")) let attributeNameExpression = fieldIdentifierName.IsEquivalentTo(DefaultIdentifierName) ? CommonConversions.Literal("xmlns") : BuildXmlnsAttributeName(fieldIdentifierName) let arguments = SyntaxFactory.Argument(attributeNameExpression).Yield().Concat(SyntaxFactory.Argument(namespaceNameExpression)) select SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName("XAttribute")).WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))))), SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName("XAttribute"), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList <ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression())))))); var boilerplate = SyntaxFactory.ParseStatement(@" TContainer Apply<TContainer>(TContainer x) where TContainer : XContainer { foreach (var d in x.Descendants()) { foreach (var n in namespaceAttributes) { var a = d.Attribute(n.Name); if (a != null && a.Value == n.Value) { a.Remove(); } } } x.Add(namespaceAttributes); return x; }") as LocalFunctionStatementSyntax; var applyMethod = SyntaxFactory.MethodDeclaration( SyntaxFactory.List <AttributeListSyntax>(), SyntaxFactory.TokenList(SyntaxFactory.Token(CSSyntaxKind.InternalKeyword), SyntaxFactory.Token(CSSyntaxKind.StaticKeyword)), boilerplate.ReturnType, null, boilerplate.Identifier, boilerplate.TypeParameterList, boilerplate.ParameterList, boilerplate.ConstraintClauses, boilerplate.Body, boilerplate.ExpressionBody); return(SyntaxFactory.ClassDeclaration( SyntaxFactory.List <AttributeListSyntax>(), SyntaxFactory.TokenList(SyntaxFactory.Token(CSSyntaxKind.InternalKeyword), SyntaxFactory.Token(CSSyntaxKind.StaticKeyword)), HelperClassUniqueIdentifierName.Identifier, null, null, SyntaxFactory.List <TypeParameterConstraintClauseSyntax>(), SyntaxFactory.List(_xNamespaceFields.Concat <MemberDeclarationSyntax>(xAttributeList).Concat(applyMethod)) )); }
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); }
/// <summary> /// Returns class syntax for dispatching events to the provided <paramref name="actors"/>. /// </summary> /// <param name="actors"> /// The actor descriptions. /// </param> /// <returns> /// Class syntax for dispatching events to the provided <paramref name="actors"/>. /// </returns> private static TypeDeclarationSyntax GenerateClass(IEnumerable <ActorDescription> actors) { var eventDispatcher = SF.SimpleBaseType(typeof(IEventDispatcher).GetTypeSyntax(false)); return (SF.ClassDeclaration(ClassSuffix) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(eventDispatcher) .AddMembers(GenerateMethod(actors))); }
public override void Exit() { var classDeclaration = SF.ClassDeclaration(_className) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SF.SimpleBaseType(SF.ParseTypeName(GetTypeName(_baseType)))) .AddMembers(_memberDeclarations.ToArray()) ; _exitHandler(classDeclaration); }
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())); } }
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); }
private static TypeDeclarationSyntax GenerateClass(ActorDescription actor) { var producerType = SF.SimpleBaseType(actor.Type.GetTypeSyntax()); var helperType = SF.SimpleBaseType(typeof(EventProducerBase <>).MakeGenericType(actor.Type).GetTypeSyntax()); return (SF.ClassDeclaration(GetClassName(actor)) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(helperType, producerType) .AddMembers(GenerateMethods(actor).ToArray())); }
/// <summary> /// Generates the class for the provided actor. /// </summary> /// <param name="actor"> /// The actor. /// </param> /// <returns> /// The generated class. /// </returns> private static TypeDeclarationSyntax GenerateClass(ActorDescription actor) { var replayType = SF.SimpleBaseType(typeof(IEventInvoker <>).MakeGenericType(actor.Type).GetTypeSyntax()); return (SF.ClassDeclaration(GetClassName(actor)) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(replayType) .AddMembers(GenerateInvokeMethod(actor)) .AddMembers(GenerateGetTypeArgumentsMethod(actor))); }
/// <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); }
/// <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); }
private ClassDeclarationSyntax GetClassForInfo(WebElementInfo info) { var infoMembers = new List <MemberDeclarationSyntax>(); var infoMembersList = new List <(string type, string fName, string value)> { ("string", nameof(info.ElementType), info.ElementType), ("string", nameof(info.Name), info.Name), ("string", nameof(info.Description), info.Description), ("bool", nameof(info.IsKey), $"{info.IsKey}"), ("string", nameof(info.InnerKey), $"{info.InnerKey ?? "null"}"), (LocatorClassName, LocatorClassName, "Element Locator values") }; var newLineToken = SF.Token(default(SyntaxTriviaList), SyntaxKind.XmlTextLiteralNewLineToken, Environment.NewLine, Environment.NewLine, default(SyntaxTriviaList)); var docCommentToken = SF.Token(SF.TriviaList( SF.SyntaxTrivia(SyntaxKind.DocumentationCommentExteriorTrivia, "///")), SyntaxKind.XmlTextLiteralToken, " ", " ", default(SyntaxTriviaList)); var endNode = SF.XmlText( SF.TokenList(SF.Token(default(SyntaxTriviaList), SyntaxKind.XmlTextLiteralNewLineToken, Environment.NewLine, Environment.NewLine, default(SyntaxTriviaList)))); 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(InfoClassName) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddMembers(infoMembers.ToArray()); return(infoCD); }
/// <summary> /// private class CompiledHandlebarsTemplateAttribute : Attribute /// </summary> /// <returns></returns> internal static ClassDeclarationSyntax CompiledHandlebarsLayoutAttributeClass() { return (SF.ClassDeclaration( default(SyntaxList <AttributeListSyntax>), SF.TokenList( SF.Token(SyntaxKind.PrivateKeyword)), SF.Identifier(StringConstants.LAYOUTATTRIBUTEFULL), default(TypeParameterListSyntax), SF.BaseList(new SeparatedSyntaxList <BaseTypeSyntax>().Add( SF.SimpleBaseType(SF.ParseTypeName("Attribute")))), default(SyntaxList <TypeParameterConstraintClauseSyntax>), default(SyntaxList <MemberDeclarationSyntax>) )); }
public static string GenerateClass() { var @consoleWriteLine = Syntax.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, Syntax.IdentifierName("Console"), name: Syntax.IdentifierName("WriteLine")); var @arguments = Syntax.ArgumentList(Syntax.SeparatedList(new[] { Syntax.Argument( Syntax.LiteralExpression( SyntaxKind.StringLiteralExpression, Syntax.Literal(@"$""{this.Name} -> {this.counter}""", "${this.Name} -> {this.counter}"))) })); var @consoleWriteLineStatement = Syntax.ExpressionStatement(Syntax.InvocationExpression(@consoleWriteLine, @arguments)); var @voidType = Syntax.ParseTypeName("void"); var @stringType = Syntax.ParseTypeName("string"); var @field = Syntax.FieldDeclaration(Syntax.VariableDeclaration(Syntax.ParseTypeName("int"), Syntax.SeparatedList(new[] { Syntax.VariableDeclarator(Syntax.Identifier("counter")) }))).AddModifiers(Syntax.Token(SyntaxKind.PrivateKeyword)).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)); var @property = Syntax.PropertyDeclaration(stringType, "Name").AddAccessorListAccessors(Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken) )).AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)); @property = @property.AddAccessorListAccessors(Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken))); var @printMethod = Syntax.MethodDeclaration(voidType, "Print").AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).WithBody(Syntax.Block(consoleWriteLineStatement)); List <ParameterSyntax> @parameterList = new List <ParameterSyntax> { Syntax.Parameter(Syntax.Identifier("x")).WithType(Syntax.ParseTypeName("int")) }; var @methodBody = Syntax.ParseStatement("counter += x;"); var @incrementMethod = Syntax.MethodDeclaration(voidType, "Increment").AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).WithBody(Syntax.Block(methodBody)).AddParameterListParameters(parameterList.ToArray()); var @class = Syntax.ClassDeclaration("MyClass").WithMembers(Syntax.List(new MemberDeclarationSyntax[] { @property, @field, @incrementMethod, @printMethod })).AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)).AddModifiers(Syntax.Token(SyntaxKind.SealedKeyword)); var adhocWorkSpace = new AdhocWorkspace(); adhocWorkSpace.Options.WithChangedOption(CSharpFormattingOptions.IndentBraces, true); var formattedCode = Formatter.Format(@class, adhocWorkSpace); return(formattedCode.ToFullString()); }
/// <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>) )); }
private static SyntaxNode MoveToApplication(SyntaxNode root, IEnumerable <SyntaxNode> members, Scope scope) { var appClass = root .DescendantNodes() .OfType <ClassDeclarationSyntax>() .Where(@class => @class.Identifier.ToString() == "application") .FirstOrDefault(); if (appClass == null) { appClass = CSharp.ClassDeclaration("application"); } return(CSharp.CompilationUnit() .WithMembers(CSharp.List(new[] { (MemberDeclarationSyntax)appClass .WithMembers(CSharp.List(members)) }))); }
public static void Generate() { // Make a namespace var nspaceDecl = SF.NamespaceDeclaration(SF.ParseName("ExampleNamespace")); // Make a class var classDecl = SF.ClassDeclaration("Order"); // Class inherits base type and implements interface classDecl = classDecl.AddBaseListTypes( SF.SimpleBaseType(SF.ParseTypeName("BaseEntity<Order>")), SF.SimpleBaseType(SF.ParseTypeName("IHaveIdentity")) ); var varDecl = SF.VariableDeclaration(SF.ParseTypeName("bool")).AddVariables(SF.VariableDeclarator("canceled")); var fieldDecl = SF.FieldDeclaration(varDecl).AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)); var propDecl = SF.PropertyDeclaration(SF.ParseTypeName("int"), "Quantity") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)), SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)) ); var methodBody = SF.ParseStatement("canceled = true"); var methodDecl = SF.MethodDeclaration(SF.ParseTypeName("void"), "MarkAsCanceled") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .WithBody(SF.Block(methodBody)); classDecl = classDecl.AddMembers( fieldDecl, propDecl, methodDecl); nspaceDecl = nspaceDecl.AddMembers(classDecl); var code = nspaceDecl.NormalizeWhitespace().ToFullString(); Console.WriteLine(code); }
private static SyntaxNode MoveToMain(SyntaxNode root, IEnumerable <SyntaxNode> statements, Scope scope) { var appClass = root .DescendantNodes() .OfType <ClassDeclarationSyntax>() .Where(@class => @class.Identifier.ToString() == "application") .FirstOrDefault(); if (appClass == null) { appClass = CSharp.ClassDeclaration("application"); } return(CSharp.CompilationUnit() .WithMembers(CSharp.List(new MemberDeclarationSyntax[] { appClass.AddMembers( CSharp.MethodDeclaration(CSharp.ParseTypeName("int"), "main") .WithModifiers(CSharp.TokenList(CSharp.Token(SyntaxKind.PrivateKeyword))) .WithBody(CSharp.Block() .WithStatements(CSharp.List(statements .Union(new [] { CSharp.ParseStatement("return 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())); }
/// <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 IEnumerable <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(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), 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), }; if (typeInfo.IsConstructedGenericType || !typeInfo.IsGenericTypeDefinition) { members.Add(GenerateRegisterMethod(type)); members.Add(GenerateConstructor(className)); attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())); } 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); } var classes = new List <TypeDeclarationSyntax> { classDeclaration }; if (typeInfo.IsGenericTypeDefinition) { // Create a generic representation of the serializer type. var serializerType = SF.GenericName(classDeclaration.Identifier) .WithTypeArgumentList( SF.TypeArgumentList() .AddArguments( type.GetGenericArguments() .Select(_ => SF.OmittedTypeArgument()) .Cast <TypeSyntax>() .ToArray())); var registererClassName = className + "_" + string.Join("_", type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" + RegistererClassSuffix; classes.Add( SF.ClassDeclaration(registererClassName) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists( SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()))) .AddMembers( GenerateMasterRegisterMethod(type, serializerType), GenerateConstructor(registererClassName))); } return(classes); }
/// <summary> /// Create a class that implements <see cref="ICommand"/>. /// /// The implementation will execute the given <see cref="method"/>. /// </summary> /// <param name="id">The unique identifier of the command for <see cref="ICommand.Id"/>.</param> /// <param name="className">The new class name.</param> /// <param name="moduleType">The type that contains the <see cref="method"/>.</param> /// <param name="method">The method that should be executed when <see cref="ICommand.ExecuteAsync"/> is called.</param> /// <returns>The <see cref="ClassDeclarationSyntax"/>.</returns> private ClassDeclarationSyntax CreateCommandClass( string id, IReadOnlyList <string> aliases, string className, Type moduleType, MethodInfo method) { var permission = ModuleUtils.GetPermissionName(moduleType, method); var moduleName = ModuleUtils.GetModuleName(moduleType); var attr = method.GetCustomAttribute <CommandAttribute>(); var guildOnly = attr.GuildOnly; var permissionGroup = attr.PermissionGroup.ToString(); return(S.ClassDeclaration(className) .AddBaseListTypes(S.SimpleBaseType(CommandType)) .AddMembers( // ICommand.Id S.PropertyDeclaration(StringType, nameof(ICommand.Id)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(id)))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.Aliases S.PropertyDeclaration(ReadOnlyStringList, nameof(ICommand.Aliases)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.ArrayCreationExpression( S.ArrayType(StringType) .WithRankSpecifiers(S.SingletonList(S.ArrayRankSpecifier(S.SingletonSeparatedList <ExpressionSyntax>(S.OmittedArraySizeExpression())))), S.InitializerExpression(SyntaxKind.ArrayInitializerExpression, new SeparatedSyntaxList <ExpressionSyntax>() .AddRange(aliases.Select(s => S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(s)))))))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.Module S.PropertyDeclaration(StringType, nameof(ICommand.Module)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(moduleName)))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.Permission S.PropertyDeclaration(StringType, nameof(ICommand.Permission)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(SyntaxKind.StringLiteralExpression, S.Literal(permission)))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.PermissionGroup S.PropertyDeclaration(S.ParseName(nameof(PermissionGroup)), nameof(ICommand.PermissionGroup)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, S.IdentifierName(nameof(PermissionGroup)), S.IdentifierName(permissionGroup)))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.GuildOnly S.PropertyDeclaration(BoolType, nameof(ICommand.GuildOnly)) .AddAccessorListAccessors( S.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(S.ReturnStatement(S.LiteralExpression(guildOnly ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression))) .WithSemicolonToken(S.Token(SyntaxKind.SemicolonToken)) ) .AddModifiers(S.Token(SyntaxKind.PublicKeyword)), // ICommand.ExecuteAsync S.MethodDeclaration(TaskType, nameof(ICommand.ExecuteAsync)) .AddModifiers(S.Token(SyntaxKind.PublicKeyword), S.Token(SyntaxKind.AsyncKeyword)) .AddParameterListParameters(Parameter(ArgumentContext, MessageContextType)) .AddBodyStatements( S.ExpressionStatement(InvokeCommand(moduleType, method)) ) )); }