public IClassBuilder AppendExamplaryMethod() { var statements = new List<StatementSyntax> { SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.Comment("// Arrange")), SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed), SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.Comment("// Act")), SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed), SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.Comment("// Assert")), SyntaxFactory.ParseStatement(string.Empty).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed) }; var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "UnitOfWork_InitialCondition_ExpectedOutcome") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithBody(SyntaxFactory.Block(statements)); if (_testFramework.TestMethodAttribute.ShouldBeApplied) { var attributes = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(_testFramework.TestMethodAttribute.Value)) ) ); method = method.AddAttributeLists(attributes); } _classDeclaration = _classDeclaration.AddMembers(method); return this; }
private ClassDeclarationSyntax GenerateReadReplicaGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface) { string readReplicaGrainName = SwmrUtils.GetReadReplicaGrainName(grainClass.Identifier.Text); string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name); ClassDeclarationSyntax readReplicaGrain = GenerateClassSqueleton(readReplicaGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", readReplicaInterfaceName })); string grainStateTypeName = FindGrainStateTypeName(grainClass); readReplicaGrain = readReplicaGrain.AddMembers(SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(grainStateTypeName), SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier("State")) }))).AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))); readReplicaGrain = readReplicaGrain.AddMembers(GenerateReadReplicaOnActivateAsync(swmrInterface)); foreach (ISymbol member in swmrInterface.GetMembers()) { IMethodSymbol methodSymbol = member as IMethodSymbol; if (methodSymbol == null || !IsReadOnlyMethod(methodSymbol)) { continue; } MethodDeclarationSyntax methodImpl = RoslynUtils.FindImplementation(methodSymbol, grainClass); readReplicaGrain = readReplicaGrain.AddMembers(methodImpl.WithLeadingTrivia(SF.EndOfLine(""))); } readReplicaGrain = readReplicaGrain.AddMembers(GenerateSetStateMethod(grainStateTypeName)); return(readReplicaGrain); }
public override IEnumerable <MemberDeclarationSyntax> Generate() { string className = ((QualifiedNameSyntax)TypeInfo.Name).Right.Identifier.ValueText; ClassDeclarationSyntax declaration = ClassDeclaration(className) .AddElementAnnotation(Element, Context.ElementRegistry) .AddGeneratorAnnotation(this) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SimpleBaseType(RequestTypeGenerator.TypeInfo.Name)) .AddMembers(ConstructorDeclaration(className) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .WithBody(Block())); var schema = Element.GetSchemaOrDefault(); declaration = declaration.AddMembers(CreateBodyPropertyDeclaration(schema)); if (schema.Element.Reference == null) { ITypeGenerator schemaGenerator = Context.TypeGeneratorRegistry.Get(schema); MemberDeclarationSyntax[] childMembers = schemaGenerator.Generate().ToArray(); if (childMembers.Length > 0) { declaration = declaration.AddMembers(childMembers); } } yield return(declaration.AddMembers( BuildContentMethodGenerator.Generate(RequestTypeGenerator.Element, Element))); }
public static ClassDeclarationSyntax GeneratePackageGuidsClass(XDocument vsctDocument) { VisualStudioWorkspace componentModelService = Services.GetComponentModelService <VisualStudioWorkspace>(); ClassDeclarationSyntax declarationSyntax = SyntaxFactory.ClassDeclaration("GuidSymbols").WithModifiers(Modifiers.InternalStaticPartial); XElement xelement = vsctDocument.Root.Element(XNames.Symbols); SyntaxList <FieldDeclarationSyntax> syntaxList = SyntaxFactory.List <FieldDeclarationSyntax>(); foreach (XElement element in xelement.Elements(XNames.GuidSymbol)) { string str = element.Attribute("name").Value; string guid = element.Attribute("value").Value.TrimStart('{').TrimEnd('}'); declarationSyntax = declarationSyntax.AddMembers(new MemberDeclarationSyntax[1] { FieldGenerator.GenerateStaticGuidField(str) }); syntaxList = @syntaxList.Add(FieldGenerator.GenerateConstantGuidStringField(str, guid)); } SyntaxList <FieldDeclarationSyntax> .Enumerator enumerator = @syntaxList.GetEnumerator(); while (@enumerator.MoveNext()) { FieldDeclarationSyntax current = @enumerator.Current; declarationSyntax = declarationSyntax.AddMembers(new MemberDeclarationSyntax[1] { current }); } return((ClassDeclarationSyntax)Formatter.Format(declarationSyntax, componentModelService, null, new CancellationToken())); }
protected override CSharpSyntaxGeneratorResult Generate( OperationDescriptor descriptor, CSharpSyntaxGeneratorSettings settings) { string componentName = descriptor.Name.Value + "Renderer"; string resultType = descriptor.ResultTypeReference.GetRuntimeType().ToString(); ClassDeclarationSyntax classDeclaration = ClassDeclaration(componentName) .AddImplements(TypeNames.QueryBase.WithGeneric(resultType)) .AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.PartialKeyword)) .AddGeneratedAttribute() .AddMembers(CreateOperationProperty(descriptor.RuntimeType.ToString())); foreach (var argument in descriptor.Arguments) { classDeclaration = classDeclaration.AddMembers( CreateArgumentProperty(argument)); } classDeclaration = classDeclaration.AddMembers( CreateLifecycleMethodMethod("OnInitialized", descriptor.Arguments)); classDeclaration = classDeclaration.AddMembers( CreateLifecycleMethodMethod("OnParametersSet", descriptor.Arguments)); return(new CSharpSyntaxGeneratorResult( componentName, Components, $"{descriptor.RuntimeType.NamespaceWithoutGlobal}.{Components}", classDeclaration, isRazorComponent: true)); }
public ClassDeclarationSyntax CreateClass(ClassDeclarationSyntax classDeclaration, IEnumerable <MemberDeclarationSyntax> members) { if (members == null || !members.Any()) { return(classDeclaration); } members = members.Distinct(); var properties = members.Where(m => m is PropertyDeclarationSyntax).Select(m => m as PropertyDeclarationSyntax).OrderBy(m => m.Identifier.ValueText); foreach (var property in properties) { classDeclaration = classDeclaration.AddMembers(WithFormatter(property)); } var constructors = members.Where(m => m is ConstructorDeclarationSyntax).Select(m => m as ConstructorDeclarationSyntax).OrderBy(m => m.ParameterList.Parameters.Count); foreach (var constructor in constructors) { classDeclaration = classDeclaration.AddMembers(WithFormatter(constructor)); } var methods = members.Where(m => m is MethodDeclarationSyntax) .Select(m => m as MethodDeclarationSyntax) .OrderBy(m => m.Identifier.ValueText) .ThenBy(m => m.ParameterList.Parameters.Count); foreach (var method in methods) { classDeclaration = classDeclaration.AddMembers(WithFormatter(method)); } return(classDeclaration); }
private async Task <Document> AutogenerateMethodsAsync(Document document, ClassDeclarationSyntax serializableClass, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync().ConfigureAwait(false); ClassDeclarationSyntax newClass = null; if (!serializableClass.Members.Where(m => m is MethodDeclarationSyntax).Any(m => ((MethodDeclarationSyntax)m).Identifier.Text == "Serialize")) { var serializeMethod = GetMethodDeclarationSyntax(returnTypeName: "void", methodName: "Serialize", parameterTypes: new[] { "SerializeEvent" }, paramterNames: new[] { "e" }); foreach (var member in serializableClass.Members.Where(m => m is PropertyDeclarationSyntax).Select(m => (PropertyDeclarationSyntax)m)) { serializeMethod = serializeMethod.AddBodyStatements(this.GetInvocationExpression(member.Identifier.Text)); } foreach (var field in serializableClass.Members.Where(m => m is FieldDeclarationSyntax).Select(f => (FieldDeclarationSyntax)f)) { serializeMethod = serializeMethod.AddBodyStatements(this.GetInvocationExpression(field.Declaration.Variables.First().Identifier.Text)); } newClass = serializableClass.AddMembers(serializeMethod); } if (!serializableClass.Members.Where(m => m is MethodDeclarationSyntax).Any(m => ((MethodDeclarationSyntax)m).Identifier.Text == "Deserialize")) { var semanticModel = await document.GetSemanticModelAsync(); var deserializeMethod = GetMethodDeclarationSyntax(returnTypeName: "void", methodName: "Deserialize", parameterTypes: new[] { "DeserializeEvent" }, paramterNames: new[] { "e" }); foreach (var member in serializableClass.Members) { if (member is FieldDeclarationSyntax field) { var readMethod = this.GetReadMethod(field.Declaration.Type, semanticModel); deserializeMethod = deserializeMethod.AddBodyStatements(this.GetReadExpression(field.Declaration.Variables.First().Identifier.Text, readMethod)); } else if (member is PropertyDeclarationSyntax property) { var readMethod = this.GetReadMethod(property.Type, semanticModel); deserializeMethod = deserializeMethod.AddBodyStatements(this.GetReadExpression(property.Identifier.Text, readMethod)); } } if (newClass != null) { newClass = newClass.AddMembers(deserializeMethod); } else { newClass = serializableClass.AddMembers(deserializeMethod); } } if (newClass != null) { root = root.ReplaceNode(serializableClass, newClass); root = Formatter.Format(root, Formatter.Annotation, document.Project.Solution.Workspace); } return(document.WithSyntaxRoot(root)); }
public ClassDeclarationSyntax StubMethod(ClassDeclarationSyntax classDclr, IMethodSymbol methodSymbol, INamedTypeSymbol stubbedInterface) { // only handle EventAdd and ignore EventRemove because we only need to stub the event once if (!methodSymbol.IsEventAdd()) { return(classDclr); } // add the event implementation to the stub IEventSymbol eventSymbol = (IEventSymbol)methodSymbol.AssociatedSymbol; EventFieldDeclarationSyntax eventDclr = ToEventDclr(eventSymbol); classDclr = classDclr.AddMembers(eventDclr); string eventName = eventSymbol.Name; ParameterSyntax[] parameters = GetEventParameters(eventSymbol); string onEventArgs = "sender"; string eventTriggerArgs = "sender"; if (parameters.Count() == 2) { onEventArgs += ", args"; eventTriggerArgs += ", args"; } else if (parameters.Count() == 1) { onEventArgs += ", null"; } string eventType = GetEventType(eventSymbol); string onEventMethodName = "On_" + eventName; // Create OnEvent method MethodDeclarationSyntax onEventMethodDclr = SF.MethodDeclaration(SF.ParseTypeName("void"), onEventMethodName) .AddModifiers(SF.Token(SyntaxKind.ProtectedKeyword)) .AddParameterListParameters(parameters) .WithBody(SF.Block( SF.ParseStatement($"{eventType} handler = {eventName};\n"), SF.ParseStatement($"if (handler != null) {{ handler({onEventArgs}); }}\n") )); classDclr = classDclr.AddMembers(onEventMethodDclr); // Create event trigger method string eventTriggerMethodName = eventName + "_Raise"; MethodDeclarationSyntax eventTriggerMethod = SF.MethodDeclaration(SF.ParseTypeName("void"), eventTriggerMethodName) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .WithBody(SF.Block( SF.ParseStatement($"{onEventMethodName}({eventTriggerArgs});\n") )); classDclr = classDclr.AddMembers(eventTriggerMethod); return(classDclr); }
private static void FindMethod(SyntaxNode namespac, CompilationUnitSyntax root, ref List <Tests> Tests) { var classes = namespac.ChildNodes().Where(@class => @class is ClassDeclarationSyntax); foreach (ClassDeclarationSyntax @class in classes) { if (!(@class.Modifiers.Any(SyntaxKind.AbstractKeyword))) { var members = @class.Members; var methods = members.Where(mem => mem is MethodDeclarationSyntax); methods = methods.Where(method => method.Modifiers.Where(modifier => modifier.Kind() == SyntaxKind.PublicKeyword).Any()); if (methods.Count() > 0) { var usings = root.Usings; var syntaxFactory = SyntaxFactory.CompilationUnit(); syntaxFactory = syntaxFactory.AddUsings(usings.ToArray()); syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("NUnit.Framework"))); syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("Moq"))); syntaxFactory = syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(GetFullNameSpace(@class)))); var namespaceName = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(GetFullNameSpace(@class) + ".Test")); ClassDeclarationSyntax TestClass = SyntaxFactory.ClassDeclaration(@class.Identifier.Text + "Tests") .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))); TestClass = TestClass.AddAttributeLists(SyntaxFactory.SingletonList <AttributeListSyntax>( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList <AttributeSyntax>( SyntaxFactory.Attribute( SyntaxFactory.IdentifierName("TestFixture"))))).ToArray()); TestClass = TestClass.AddMembers(SetUpGenerate(@class)); TestClass = TestClass.AddMembers(TestMethodsGenerate(@class)); namespaceName = namespaceName.AddMembers(TestClass); syntaxFactory = syntaxFactory.AddMembers(namespaceName); string fileName = GetFullNameSpace(@class) + "." + @class.Identifier.Text + ".Test.cs"; Tests.Add(new Tests(fileName, syntaxFactory.NormalizeWhitespace().ToFullString())); } foreach (MemberDeclarationSyntax member in members) { if (member is ClassDeclarationSyntax) { FindMethod(@class, root, ref Tests); } } } } var namespaces = namespac.ChildNodes().Where(@class => @class is NamespaceDeclarationSyntax); foreach (NamespaceDeclarationSyntax @namespace in namespaces) { FindMethod(@namespace, root, ref Tests); } }
private void ParseXmlSchemaComplexType(XmlSchemaComplexType type, [CallerLineNumber] int callerLine = -1) { if (type.ContentModel != null) { var model = type.ContentModel; XmlSchemaObjectCollection attributes = new XmlSchemaObjectCollection(); if (model.Content is XmlSchemaComplexContentExtension ceContent) { attributes = ceContent.Attributes; } else if (model.Content is XmlSchemaComplexContentRestriction crContent) { attributes = crContent.Attributes; } else if (model.Content is XmlSchemaSimpleContentExtension seContent) { attributes = seContent.Attributes; } else if (model.Content is XmlSchemaSimpleContentRestriction srContent) { attributes = srContent.Attributes; } foreach (XmlSchemaAttribute attr in attributes) { ParseXmlSchemaAttribute(attr); } if (type.ContentType == XmlSchemaContentType.TextOnly) { var typeName = GetAliasedType(type.Datatype.ValueType.FullName); var field = FieldDeclaration(VariableDeclaration(ParseTypeName(typeName), new SeparatedSyntaxList <VariableDeclaratorSyntax>())); field = field.AddDeclarationVariables(new[] { VariableDeclarator("valueField") }).WithModifiers(TokenList(Token(SyntaxKind.PrivateKeyword))); currentClass = currentClass.AddMembers(field); var property = PropertyDeclaration( ParseTypeName(typeName), "Value").WithAccessorList(AccessorList(new SyntaxList <AccessorDeclarationSyntax>().AddRange(new AccessorDeclarationSyntax[] { AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, Block(SingletonList <StatementSyntax>(ReturnStatement(IdentifierName("valueField"))))), AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, Block(SingletonList <StatementSyntax>(ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName("valueField"), IdentifierName("value")))))) }))).WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))); currentClass = currentClass.AddMembers(property); } return; } var contentParticle = type.ContentTypeParticle; if (contentParticle is XmlSchemaSequence) { foreach (XmlSchemaElement particle in (type.ContentTypeParticle as XmlSchemaSequence).Items) { //ParseXmlSchemaElement(particle); } } }
private static ClassDeclarationSyntax GenerateWriteGrain(ClassDeclarationSyntax grainClass, ITypeSymbol swmrInterface, int readReplicaCount) { string grainName = grainClass.Identifier.Text; string writerGrainName = SwmrUtils.GetWriteInterfaceName(grainName); string writerInterfaceName = SwmrUtils.GetWriteInterfaceName(swmrInterface.Name); ClassDeclarationSyntax writerGrain = GenerateClassSqueleton(writerGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", writerInterfaceName })); writerGrain = RoslynUtils.AddField(writerGrain, "ITopology<string>", "_topology"); writerGrain = writerGrain.AddMembers(GenerateOnActivateAsyncMethod(readReplicaCount)); string readReplicaInterfaceName = SwmrUtils.GetReadReplicaInterfaceName(swmrInterface.Name); foreach (ISymbol member in swmrInterface.GetMembers()) { IMethodSymbol methodSymbol = member as IMethodSymbol; if (methodSymbol == null || IsReadOnlyMethod(methodSymbol) || new MethodInspector(methodSymbol).MethodName == "GetState") { continue; } MethodInspector methodInspector = new MethodInspector(methodSymbol); MethodDeclarationSyntax methodImpl = GenerateMethodDeclaration(methodInspector); methodImpl = SwmrUtils.AddSessionIdParameter(methodImpl).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.AsyncKeyword)).WithSemicolonToken(SF.Token(SyntaxKind.None)); BlockSyntax statmentBlock = SF.Block(); statmentBlock = AddStatement(statmentBlock, "string grainId = this.GetPrimaryKeyString();"); statmentBlock = AddStatement(statmentBlock, string.Format("{0} grain = GrainFactory.GetGrain<{0}>(grainId);", swmrInterface.Name)); statmentBlock = AddStatement(statmentBlock, String.Format("{0} await grain.{1}({2});", methodInspector.ReturnType != "Task"? "var result =" : "", methodInspector.MethodName, string.Join(", ", methodInspector.MethodParams.Keys))); statmentBlock = AddStatement(statmentBlock, "GrainState state = await grain.GetState();"); statmentBlock = AddStatement(statmentBlock, "string sessionNode = _topology.GetNode(sessionId);"); statmentBlock = AddStatement(statmentBlock, "IEnumerable<string> otherNodes = _topology.Nodes.Where(node => node != sessionNode);"); ForEachStatementSyntax forEachStatement = SF.ForEachStatement( SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword)), SF.Identifier("node"), SF.IdentifierName("otherNodes"), SF.Block(SF.ParseStatement(GenerateSetStateStmt(readReplicaInterfaceName, @"node"))) ); statmentBlock = statmentBlock.AddStatements(forEachStatement); statmentBlock = AddStatement(statmentBlock, (string.Format("{0} {1}", "await", GenerateSetStateStmt(readReplicaInterfaceName, @"sessionNode")))); if (methodInspector.ReturnType != "Task") { statmentBlock = AddStatement(statmentBlock, "return result;"); } methodImpl = methodImpl.WithBody(statmentBlock); writerGrain = writerGrain.AddMembers(methodImpl); } return(writerGrain); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); MethodDeclarationSyntax prector = Syntax.MethodDeclaration(Syntax.PredefinedType(Syntax.Token(SyntaxKind.VoidKeyword)), ".prector"); List<StatementSyntax> Initializers = new List<StatementSyntax>(); foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind == SyntaxKind.FieldDeclaration) { FieldDeclarationSyntax fds = (FieldDeclarationSyntax)member; foreach (VariableDeclaratorSyntax vds in fds.Declaration.Variables) { if (vds.Initializer != null) { Initializers.Add(Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName(vds.Identifier), vds.Initializer.Value))); } } } } if (Initializers.Count == 0) return node; int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax)); prector = prector.AddBodyStatements(Initializers.ToArray()); node = node.AddMembers(prector); if (constructors == 0) { ConstructorDeclarationSyntax ctor = Syntax.ConstructorDeclaration(node.Identifier); ctor = ctor.AddBodyStatements(Syntax.ExpressionStatement(Syntax.InvocationExpression(Syntax.IdentifierName(".prector")))); ctor = ctor.AddModifiers(Syntax.Token(SyntaxKind.PublicKeyword)); return node.AddMembers(ctor); } SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>(); foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind == SyntaxKind.ConstructorDeclaration) { newMembers = newMembers.Add((MemberDeclarationSyntax)ConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member)); } else { newMembers = newMembers.Add(member); } } return node.WithMembers(newMembers); }
public string NewCodeBlock(string content, TypeSyntax returnType) { var methodName = string.Format("_{0:x}", content.GetHashCode()); var body = SyntaxFactory.ParseExpression(content); var method = SyntaxFactory.MethodDeclaration(returnType, methodName) .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(body))) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))); _compilationTargetClass = _compilationTargetClass.AddMembers(method); return(methodName); }
private static ClassDeclarationSyntax HandleClearMethod(ClassDeclarationSyntax node, string parentName, string propertyName, string clearMethodName, string removeMethodName) { node = node.AddMembers(MethodDeclaration( PredefinedType( Token(SyntaxKind.VoidKeyword)), Identifier(clearMethodName)) .WithModifiers( TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.VirtualKeyword))) .WithBody( Block( SingletonList <StatementSyntax>( ForEachStatement( IdentifierName("var"), Identifier("item"), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName(propertyName), IdentifierName("ToList"))), Block( SingletonList <StatementSyntax>( ExpressionStatement( InvocationExpression( IdentifierName(removeMethodName)) .WithArgumentList( ArgumentList( SingletonSeparatedList <ArgumentSyntax>( Argument( IdentifierName("item"))))))))))))); return(node); }
private static void GenerateQueryType( CodeGenerationResult result, DataGeneratorContext dataContext, CodeGeneratorContext generatorContext, IReadOnlyList <IObjectType> objectTypes) { ClassDeclarationSyntax queryDeclaration = ClassDeclaration("Query") // todo : we need to read the name from the config .AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.PartialKeyword)) .AddGeneratedAttribute() .AddExtendObjectTypeAttribute("Query"); foreach (IObjectType?objectType in objectTypes) { queryDeclaration = queryDeclaration.AddMembers( CreateQueryResolver(dataContext, generatorContext, objectType)); GenerateObjectType(result, generatorContext.Namespace !, objectType); } NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(IdentifierName(generatorContext.Namespace !)) .AddMembers(queryDeclaration); CompilationUnitSyntax compilationUnit = CompilationUnit() .AddMembers(namespaceDeclaration); compilationUnit = compilationUnit.NormalizeWhitespace(elasticTrivia: true); result.AddSource(generatorContext.Namespace !+".Query.cs", compilationUnit.ToFullString()); }
private static string GenerateTest(IEnumerable <UsingDirectiveSyntax> usings, NamespaceDeclarationSyntax ns, ClassDeclarationSyntax @class) { usings = usings.Append(CreateUsingDirective("NUnit.Framework")); usings = usings.Append(CreateUsingDirective("Moq")); usings = usings.Append(CreateUsingDirective(FindFullNamespace(@class))); CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit().AddUsings(usings.ToArray()); NamespaceDeclarationSyntax testNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName($"{usings.Last().Name}.Tests")); ClassDeclarationSyntax testClass = SyntaxFactory.ClassDeclaration(@class.Identifier.Text + "Tests").AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); testClass = testClass.AddMembers(GenerateSetUp(@class)); testClass = testClass.AddMembers(GenerateMethods(@class)); cu = cu.AddMembers(testNamespace.AddMembers(testClass)); return(cu.NormalizeWhitespace().ToFullString()); }
public ClassDeclarationSyntax StubMethod(ClassDeclarationSyntax classDclr, IMethodSymbol methodSymbol, INamedTypeSymbol stubbedInterface, SemanticModel semanticModel) { if (!methodSymbol.IsOrdinaryMethod()) { return(classDclr); } MethodDeclarationSyntax methodDclr = SF.MethodDeclaration( SF.ParseTypeName(methodSymbol.ReturnType.GetFullyQualifiedName()), methodSymbol.GetGenericName()); methodDclr = methodDclr.WithParameterList(methodDclr.ParameterList.AddParameters( RoslynUtils.GetMethodParameterSyntaxList(methodSymbol).ToArray())); methodDclr = methodDclr.WithSemicolonToken(SF.Token(SyntaxKind.None)) .WithExplicitInterfaceSpecifier( SF.ExplicitInterfaceSpecifier( SF.IdentifierName(methodSymbol.GetContainingInterfaceGenericQualifiedName()))); string delegateTypeName = NamingUtils.GetDelegateTypeName(methodSymbol, stubbedInterface); string parameters = StubbingUtils.FormatParameters(methodSymbol); var outParameters = methodSymbol.Parameters.Where(p => p.RefKind == RefKind.Out); var methodBlock = StubbingUtils.GetInvocationBlockSyntax(delegateTypeName, methodSymbol.GetGenericName(), parameters, outParameters, methodSymbol.ReturnType, semanticModel); classDclr = classDclr.AddMembers(methodDclr.WithBody(methodBlock)); return(classDclr); }
private ClassDeclarationSyntax GenerateClass(ClassDeclarationSyntax context) { ClassDeclarationSyntax generatedClass = SyntaxFactory.ClassDeclaration(context.Identifier). AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); return(generatedClass.AddMembers(GenerateMethods(context))); }
public static ClassDeclarationSyntax WithMethods(this ClassDeclarationSyntax node, ITypeSymbol mvcSymbol) { return(node); // TODO fix member generation return(node.AddMembers(mvcSymbol.CreateMethods().ToArray())); }
static ClassDeclarationSyntax AddImplicitEvents(this ClassDeclarationSyntax proxyClass, ProxySyntaxInfo proxyInfo) { // Events proxyClass = proxyClass .AddMembers(proxyInfo.ImplicitEvents.Select(e => EventDeclaration( ToSyntax(e.Type), Identifier(e.Name)) .WithPublicModifier() .WithAccessorList( AccessorList( List(new AccessorDeclarationSyntax[] { AccessorDeclaration( SyntaxKind.AddAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause(InvokePipeline(e.AddMethod.ReturnType, e.AddMethod.Parameters))) .WithSemicolon(), AccessorDeclaration( SyntaxKind.RemoveAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause(InvokePipeline(e.RemoveMethod.ReturnType, e.RemoveMethod.Parameters))) .WithSemicolon() })))).ToArray()); return(proxyClass); }
private static ClassDeclarationSyntax WithViewTemplateMembers(this ClassDeclarationSyntax node, string templateKind, IEnumerable <View> viewFiles) { var className = $"_{templateKind}Class"; var templateClass = SyntaxFactory.ClassDeclaration(className) .WithModifiers(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword) .WithGeneratedNonUserCodeAttributes(); if (templateKind == "DisplayTemplates" || templateKind == "EditorTemplates") { templateClass = templateClass.AddMembers(viewFiles .Select(t => CreateStringFieldDeclaration(t.ViewName.SanitiseFieldName(), t.ViewName, SyntaxKind.PublicKeyword, SyntaxKind.ReadOnlyKeyword)) .ToArray()); } else { templateClass = templateClass .WithViewNamesClassNode(viewFiles) .WithStaticFieldBackedProperty("ViewNames", ViewNamesClassName, SyntaxKind.PublicKeyword); var viewFields = viewFiles .Select(x => CreateStringFieldDeclaration(x.ViewName.SanitiseFieldName(), x.RelativePath.ToString(), SyntaxKind.PublicKeyword, SyntaxKind.ReadOnlyKeyword)) .ToArray <MemberDeclarationSyntax>(); templateClass = templateClass.AddMembers(viewFields); } node = node .AddMembers(templateClass) .WithStaticFieldBackedProperty(templateKind, className, SyntaxKind.PublicKeyword); return(node); }
private async Task <Document> CreateSetupMethod(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var setupMethodDeclaration = SetupMethod(generator); var root = await document.GetSyntaxRootAsync(cancellationToken); var existingSetupMethod = root.DescendantNodes().OfType <MethodDeclarationSyntax>() .FirstOrDefault(_ => _.Identifier.Text == "Setup"); SyntaxNode newRoot; if (existingSetupMethod != null) { newRoot = root.ReplaceNode(existingSetupMethod, setupMethodDeclaration); } else { var newClassDecl = classDecl.AddMembers(setupMethodDeclaration as MemberDeclarationSyntax); newRoot = root.ReplaceNode(classDecl, newClassDecl); } var newDocument = document.WithSyntaxRoot(newRoot); return(newDocument); }
public static ClassDeclarationSyntax AddField(ClassDeclarationSyntax classDeclaration, string type, string name) { return(classDeclaration.AddMembers( SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(type), SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier(name)) }))) .AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)))); }
internal static ClassDeclarationSyntax GetCollectible(ClassDeclarationSyntax classDecl) { foreach (var c in ClassNames) { var anyCards = false; var className = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(c.ToLower()); var cCard = ClassDeclaration(className).AddModifiers(Token(PublicKeyword)); foreach (var card in Cards.All.Values.Where(x => x.Collectible && x.Class.ToString().Equals(c))) { var name = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(card.Name.ToLower()); name = Regex.Replace(name, @"[^\w\d]", ""); if (card.Id.StartsWith("HERO")) { name += "Hero"; } cCard = cCard.AddMembers(GenerateConst(name, card.Id)); anyCards = true; } if (anyCards) { classDecl = classDecl.AddMembers(cCard); } } return(classDecl); }
internal static ClassDeclarationSyntax StripTestInitializerAttribute(this ClassDeclarationSyntax type, SyntaxAnnotation annotation) { var target = type.Members.OfType <MethodDeclarationSyntax>().SingleOrDefault(m => m.GetTargetAttribute("TestInitialize") != null); if (target == null) { return(type); } var ctor = type.Members.OfType <ConstructorDeclarationSyntax>().SingleOrDefault(c => c.ParameterList.Parameters.Count == 0); var initializeStatement = ParseStatement($"{target.Identifier}();").WithAdditionalAnnotations(annotation); var replacementBody = ctor == null?Block(initializeStatement) : Block(ctor.Body.Statements.Add(initializeStatement)); var replacementCtor = ConstructorDeclaration(type.Identifier.WithoutTrivia()).WithBody(replacementBody).WithAdditionalAnnotations(annotation); type = ctor == null?type.AddMembers(replacementCtor) : type.ReplaceNode(ctor, replacementCtor); //Refresh reference target = type.Members.OfType <MethodDeclarationSyntax>().SingleOrDefault(m => m.GetTargetAttribute("TestInitialize") != null); var cleanedTarget = target.RemoveNode(target.GetTargetAttribute("TestInitialize"), SyntaxRemoveOptions.KeepExteriorTrivia) .WithAdditionalAnnotations(annotation); type = type.ReplaceNode(target, cleanedTarget); return(type.Cleanup()); }
private async Task <Solution> MakeUppercaseAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var props = root.DescendantNodes().Where(x => x is PropertyDeclarationSyntax); StringBuilder sb = new StringBuilder(@" StringBuilder resultSb = new StringBuilder(""""); "); foreach (SyntaxNode currentProp in props) { var currentSyntax = currentProp as PropertyDeclarationSyntax; sb.Append("resultSb.AppendFormat(\"{0}: {1}, \", nameof(" + currentSyntax.Identifier.Value + "), " + currentSyntax.Identifier.Value + ");"); sb.Append(Environment.NewLine); } // The new ToString method to add var methodToInsert = GetMethodDeclarationSyntax(returnTypeName: "string ", methodName: "ToString", body: sb.ToString()); var newClassDecl = classDecl.AddMembers(methodToInsert); // Replace to node and done! return(document.WithSyntaxRoot( root.ReplaceNode(classDecl, newClassDecl) ).Project.Solution); }
public override IEnumerable <MemberDeclarationSyntax> Generate() { string className = ((QualifiedNameSyntax)TypeInfo.Name).Right.Identifier.ValueText; ClassDeclarationSyntax declaration = ClassDeclaration(className) .AddElementAnnotation(Element, Context.ElementRegistry) .AddGeneratorAnnotation(this) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SimpleBaseType(RequestsNamespace.OperationRequest)); declaration = declaration.AddMembers( GenerateParameterProperties(className) .Concat(MemberGenerators .Select(p => p.Generate(Element, null))) .ToArray()); yield return(declaration); if (Element.GetRequestBody()?.GetMediaTypes().Any(p => SerializerSelector.Select(p) == null) ?? false) { var buildContentMethod = declaration.Members .OfType <MethodDeclarationSyntax>() .First(p => p.Identifier.Text == BuildContentMethodGenerator.BuildContentMethodName); var httpContentGenerator = new HttpContentRequestTypeGenerator(Element, Context, this, buildContentMethod); foreach (var otherMember in httpContentGenerator.Generate()) { yield return(otherMember); } } }
public static ClassDeclarationSyntax WithViewsClass(this ClassDeclarationSyntax node, IEnumerable <View> viewFiles) { // create subclass called ViewsClass // create ViewNames get property returning static instance of _ViewNamesClass subclass // create subclass in ViewsClass called _ViewNamesClass // create string field per view const string viewNamesClass = "_ViewNamesClass"; var viewClassNode = CreateClass("ViewsClass", null, SyntaxKind.PublicKeyword) .WithAttributes(CreateGeneratedCodeAttribute(), CreateDebugNonUserCodeAttribute()) .WithField("s_ViewNames", viewNamesClass, SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword); var viewNamesClassNode = CreateClass(viewNamesClass, null, SyntaxKind.PublicKeyword); var controllerViews = viewFiles.Where(x => x.ControllerName.Equals(node.Identifier.ToString(), StringComparison.CurrentCultureIgnoreCase)) .ToImmutableArray(); var viewNameFields = controllerViews.Select( x => CreateStringFieldDeclaration(x.ViewName, x.ViewName, SyntaxKind.PublicKeyword, SyntaxKind.ReadOnlyKeyword)) .Cast <MemberDeclarationSyntax>() .ToArray(); viewNamesClassNode = viewNamesClassNode.AddMembers(viewNameFields); viewClassNode = viewClassNode.AddMembers(viewNamesClassNode); var viewFields = controllerViews.Select( x => CreateStringFieldDeclaration(x.ViewName, "~/" + x.RelativePath, SyntaxKind.PublicKeyword)) .Cast <MemberDeclarationSyntax>() .ToArray(); viewClassNode = viewClassNode.AddMembers(viewFields); return(node.AddMembers(viewClassNode)); }
private SyntaxNode GenerateTestMethods(SyntaxNode root, IEnumerable <MethodDeclarationSyntax> methods) { Dictionary <string, int> OverridedMethods = new Dictionary <string, int>(); ClassDeclarationSyntax oldClassDeclaration = root.DescendantNodes().OfType <ClassDeclarationSyntax>().FirstOrDefault(); ClassDeclarationSyntax newClassDeclaration = oldClassDeclaration; foreach (MethodDeclarationSyntax method in methods) { string substr = ""; if (methods.Any(Method => (method != Method) && (method.Identifier.ValueText == Method.Identifier.ValueText))) { if (OverridedMethods.ContainsKey(method.Identifier.ValueText)) { OverridedMethods[method.Identifier.ValueText] += 1; } else { OverridedMethods[method.Identifier.ValueText] = 1; } substr = OverridedMethods[method.Identifier.ValueText].ToString(); } newClassDeclaration = newClassDeclaration.AddMembers(GenerateTestMethod(method, substr)); } return(root.ReplaceNode(oldClassDeclaration, newClassDeclaration)); }
private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic, ClassDeclarationSyntax classNode) { // Generated from http://roslynquoter.azurewebsites.net/ var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithParameterList(SyntaxFactory.ParameterList() .WithOpenParenToken( SyntaxFactory.Token(SyntaxKind.OpenParenToken)) .WithCloseParenToken( SyntaxFactory.Token( SyntaxKind.CloseParenToken))) .WithBody(SyntaxFactory.Block() .WithOpenBraceToken( SyntaxFactory.Token( SyntaxKind.OpenBraceToken)) .WithCloseBraceToken( SyntaxFactory.Token( SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation); var newClassNode = classNode.AddMembers(constructor); var newRoot = root.ReplaceNode(classNode, newClassNode); context.RegisterCodeFix( CodeAction.Create( CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription, _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)), CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic); }
private void ParseOperationBindingExtensions(ServiceDescriptionFormatExtensionCollection extensions, [CallerLineNumber] int callerLine = -1) { foreach (ServiceDescriptionFormatExtension extension in extensions) { if (extension is SoapBodyBinding body) { var message = messages[(body.Parent as MessageBinding).Name]; //var part = body.Parts[] foreach (MessagePart part in message.Parts) { string typeName = GetAliasedType("object"); if (DiscoveryClientReferencesElements.ContainsKey(part.Element.Name)) { var elements = DiscoveryClientReferencesElements[part.Element.Name]; var xmlObject = elements.Find(e => e is XmlSchemaElement); if ((xmlObject is XmlSchemaElement element)) { typeName = GetAliasedType(element.SchemaTypeName.Name); } else if ((xmlObject is XmlSchemaComplexType type)) { //typeName = GetAliasedType(type); } else if ((xmlObject is XmlSchemaSimpleType simpleType)) { //typeName = GetAliasedType(simpleType.SchemaTypeName.Name); } } var propertyName = part.Element.Name; var escapedPropertyName = FixupIdentifier(propertyName); var fieldName = string.Format("{0}Field", propertyName); var field = FieldDeclaration(VariableDeclaration(ParseTypeName(typeName), new SeparatedSyntaxList <VariableDeclaratorSyntax>())).AddAttributeLists(new AttributeListSyntax[] { AttributeList( SingletonSeparatedList <AttributeSyntax>( Attribute(IdentifierName("System.Xml.XmlElement")).WithArgumentList( AttributeArgumentList( SingletonSeparatedList <AttributeArgumentSyntax>( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(propertyName))) ) ) ) ) ) }); field = field.AddDeclarationVariables(new[] { VariableDeclarator(fieldName) }).WithModifiers(TokenList(Token(SyntaxKind.PrivateKeyword))); currentClass = currentClass.AddMembers(field); var property = PropertyDeclaration(ParseTypeName(typeName), escapedPropertyName).WithAccessorList(AccessorList(new SyntaxList <AccessorDeclarationSyntax>().AddRange(new AccessorDeclarationSyntax[] { AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, Block(SingletonList <StatementSyntax>(ReturnStatement(IdentifierName(fieldName))))), AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, Block(SingletonList <StatementSyntax>(ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(fieldName), IdentifierName("value")))))) }))).WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))); currentClass = currentClass.AddMembers(property); }