public void GenerateHandler() { _namespace = _namespace.AddMembers(_class); _syntaxFactory = _syntaxFactory.AddMembers(_namespace); var data = _syntaxFactory .NormalizeWhitespace() .ToFullString(); var patternAbsolutePath = _settings.GroupingStrategy switch { GroupByType.Concern => FileSystemUtility.CreateDirectory(new[] { _settings.DomainAbsolutePath, _settings.Concern, _settings.PatternType.ToString() }), GroupByType.Operation => FileSystemUtility.CreateDirectory(new[] { _settings.DomainAbsolutePath, _settings.PatternType.ToString() }) }; //LogUtility.Info($"patternAbsolutePath: ${patternAbsolutePath}"); var concernAbsolutePath = _settings.GroupingStrategy switch { GroupByType.Concern => FileSystemUtility.CreateDirectory(new[] { _settings.DomainAbsolutePath, _settings.Concern, _settings.PatternType.ToString() }), GroupByType.Operation => FileSystemUtility.CreateDirectory(new[] { patternAbsolutePath, _settings.Concern }) }; //LogUtility.Info($"concernAbsolutePath: ${concernAbsolutePath}"); var absoluteFilePath = FileSystemUtility.CreateFile(new[] { concernAbsolutePath, _settings.ClassName }, data); //LogUtility.Info($"absoluteFilePath: ${absoluteFilePath}"); CleanUp(); }
public string Generate() { IEnumerable <MemberDeclarationSyntax> CollectionSelector(StructModel s) { if (s.InitNode == null) { yield break; } yield return(s.InitNode); if (s.MatchingProxy != null) { yield return(s.MatchingProxy); } } CompilationUnitSyntax replaced = Tree.GetCompilationUnitRoot().ReplaceNodes( Structs.SelectMany(CollectionSelector), (initial, updated) => { if (initial is StructDeclarationSyntax structDecl) { var str = Structs.Single(s => s.InitNode == structDecl); return(str.Generate().NormalizeWhitespace()); } if (initial is ClassDeclarationSyntax proxyDecl) { var str = Structs.Single(s => s.MatchingProxy == proxyDecl); return(str.GenerateProxy()); } throw new InvalidOperationException(); }); replaced = replaced.AddMembers(Structs .Where(s => s.InitNode != null && s.MatchingProxy == null) .Select(s => (MemberDeclarationSyntax)s.GenerateProxy()) .Where(proxy => proxy != null) .ToArray()); replaced = replaced.AddMembers(Structs .Where(s => s.InitNode == null) .SelectMany(s => s.GenerateStructAndProxy()).ToArray()); var adHocWorkspace = new AdhocWorkspace(); var options = adHocWorkspace.Options .WithChangedOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, true) .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false) .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false) .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, true) ; return(Formatter.Format(replaced.SyntaxTree.GetCompilationUnitRoot(), adHocWorkspace, options).GetText().ToString()); }
public static async Task <CompilationUnitSyntax> Generate(Document sourceDocument, CancellationToken cancellationToken) { Compilation compilation = await sourceDocument.Project.GetCompilationAsync(cancellationToken); CompilationUnitSyntax compilationUnit = await sourceDocument.GetSyntaxRootAsync() as CompilationUnitSyntax; ClientProxyGenerator generator = new ClientProxyGenerator(); CompilationUnitSyntax targetCompilationUnit = SyntaxFactory.CompilationUnit(compilationUnit.Externs, compilationUnit.Usings, SyntaxFactory.List <AttributeListSyntax>(), SyntaxFactory.List <MemberDeclarationSyntax>()); targetCompilationUnit = targetCompilationUnit.AddMembers((await GenerateProxyInterfaces(sourceDocument, generator, cancellationToken)).ToArray()); sourceDocument = AddCompilationUnitToProject(sourceDocument, targetCompilationUnit); targetCompilationUnit = targetCompilationUnit.AddMembers((await GenerateProxyClasses(sourceDocument, generator, cancellationToken)).ToArray()); return(targetCompilationUnit); }
/// <summary> /// Causes the structure if the SAT to change. It can cause leftovers (empty structures) to be present. /// </summary> private void ProcessOverridenNamespaceNames() { CompilationUnitSyntax newNode = this.node; CSharpSyntaxTree newTree = this.tree; // Removing classes var removableNodes = new List <BaseTypeDeclarationSyntax>(); foreach (var info in this.transformationInfos) { removableNodes.Add(info.OriginalNode); } // Removing the classes in the array // These classes will have another namespace assigned, this will work in case the program defines a namespace or not newNode = newNode.RemoveNodes(removableNodes, SyntaxRemoveOptions.KeepNoTrivia); // Adding classes in new namespaces foreach (var info in this.transformationInfos) { var namespaceSyntax = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(info.OverridenNamespace)); namespaceSyntax = namespaceSyntax.AddMembers(info.TransformedNode); // TODO: Use the cache here to feed values, the new node should be provided newNode = newNode.AddMembers(namespaceSyntax); } this.newNode = newNode; }
/// <summary> /// Start code generation /// </summary> public void GenerateIntermediateCode() { if (Module == null) { throw new DataException("Please set Module before calling GenerateIntermediateCode()"); } StandardFunctionRepository.Initialize(Module); _compiledCode = SyntaxFactory.CompilationUnit(); MainClassNamespace = "Oberon0." + Module.Name; MainClassName = Module.Name + "__Impl"; // Create a namespace: (namespace CodeGenerationSample) _namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(MainClassNamespace)) .NormalizeWhitespace(); // Add System using statement: (using System) _namespace = _namespace.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("AnyClone"))); GenerateClass(); _namespace = _namespace.AddMembers(_classDeclaration); _compiledCode = _compiledCode.AddMembers(_namespace).NormalizeWhitespace(); }
public Type Compile() { if (expressions.Count != 1) { throw new Exception("HAML node stack misaligned. Expected only 1 root node."); } FlushStringRun(); _renderMethod = _renderMethod.AddBodyStatements(SyntaxFactory.Block(expressions.Peek())); _compilationTargetClass = _compilationTargetClass.AddMembers(_renderMethod); _compilationUnit = _compilationUnit .AddMembers(_compilationTargetClass); _compilationUnit = _compilationUnit.NormalizeWhitespace(" ", true); _compilation = _compilation.AddSyntaxTrees(CSharpSyntaxTree.Create(_compilationUnit)); MemoryStream stream = new MemoryStream(); EmitResult result = _compilation.Emit(stream); _compilation.Emit("Output.dll"); if (!result.Success) { throw new HamlCompilationFailedException(result.Diagnostics); } stream.Flush(); stream.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(stream); return(assembly.GetType(_compilationTargetClass.Identifier.Text)); }
private string GenerateRepositoryBaseClass() { string className = String.Join("", configuration.OperationClassPrefixName, configuration.OperationClassBaseName, CSharpLanguageSettings.BaseKeyWord); string fileName = $"{className}.cs"; string fileLocation = Path.Combine(configuration.OperationsBaseFolderLocation, fileName); if (!File.Exists(fileLocation)) { CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit(); NamespaceDeclarationSyntax @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName( String.Join(".", configuration.ProjectName, configuration.OperationsFolderName, configuration.OperationsGeneratedFolderName)).NormalizeWhitespace()); ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration(className) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); @namespace = @namespace.AddMembers(classDeclaration); compilationUnit = compilationUnit.AddMembers(@namespace); string fileContent = compilationUnit.NormalizeWhitespace().ToFullString(); File.WriteAllText(fileLocation, fileContent); } return(className); }
private async Task <Document> AddOperatorType( Document document, CompilationUnitSyntax root, ImmutableDictionary <string, ImmutableArray <ITypeSymbol> > constraintDic) { bool hasMethod = false; var usings = root.Usings.ToNamespaceHashSet(); MemberDeclarationSyntax[] newMembers = new MemberDeclarationSyntax[constraintDic.Count]; foreach (var(p, i) in constraintDic.Select((p, i) => (p, i))) { bool m; (newMembers[i], m) = CreateOperatorTypeSyntax(p.Key, p.Value, usings); hasMethod |= m; } root = root.AddMembers(newMembers); if (hasMethod && !usings.Contains(System_Runtime_CompilerServices)) { root = SyntaxHelpers.AddSystem_Runtime_CompilerServicesSyntax(root); } return(document.WithSyntaxRoot(root)); }
CompilationUnitSyntax Generate(CompilationUnitSyntax code, WaylandProtocol protocol) { code = code.AddUsings(UsingDirective(IdentifierName("System"))) .AddUsings(UsingDirective(IdentifierName("System.Collections.Generic"))) .AddUsings(UsingDirective(IdentifierName("System.Linq"))) .AddUsings(UsingDirective(IdentifierName("System.Text"))) .AddUsings(UsingDirective(IdentifierName("NWayland.Protocols.Wayland"))) .AddUsings(UsingDirective(IdentifierName("NWayland.Interop"))) .AddUsings(UsingDirective(IdentifierName("System.Threading.Tasks"))); var ns = NamespaceDeclaration(ProtocolNamespaceSyntax(protocol.Name)); foreach (var iface in protocol.Interfaces) { var cl = ClassDeclaration(Pascalize(iface.Name)) .WithModifiers(new SyntaxTokenList( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.SealedKeyword), Token(SyntaxKind.UnsafeKeyword), Token(SyntaxKind.PartialKeyword))) .AddBaseListTypes( SimpleBaseType(SyntaxFactory.ParseTypeName("NWayland.Protocols.Wayland.WlProxy"))); cl = WithSummary(cl, iface.Description); cl = WithSignature(cl, iface); cl = WithRequests(cl, protocol, iface); cl = WithEvents(cl, protocol, iface); cl = WithEnums(cl, protocol, iface); cl = WithFactory(cl, iface) .AddMembers(DeclareConstant("string", "InterfaceName", MakeLiteralExpression(iface.Name))) .AddMembers(DeclareConstant("int", "InterfaceVersion", MakeLiteralExpression(iface.Version))); if (iface.Name != "wl_display") { var ctor = ConstructorDeclaration(cl.Identifier) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .WithParameterList(ParameterList( SeparatedList(new[] { Parameter(Identifier("handle")).WithType(ParseTypeName("IntPtr")), Parameter(Identifier("version")).WithType(ParseTypeName("int")), Parameter(Identifier("display")) .WithType(ParseTypeName("NWayland.Protocols.Wayland.WlDisplay")), }))).WithBody(Block()) .WithInitializer(ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, ArgumentList(SeparatedList(new[] { Argument(IdentifierName("handle")), Argument(IdentifierName("version")), Argument(IdentifierName("display")) })))); cl = cl.AddMembers(ctor); } ns = ns.AddMembers(cl); } return(code.AddMembers(ns)); }
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 CompilationUnitSyntax GenerateGlobalPropertiesProviderCompilationUnit(Workspace workspace, string targetNamespace, string className) { CompilationUnitSyntax unit = SyntaxFactory.CompilationUnit(); SyntaxList <UsingDirectiveSyntax> usings = SyntaxFactory.List( new[] { Using("System.Collections.Immutable"), Using("System.ComponentModel.Composition"), Using("System.Threading"), Using("System.Threading.Tasks"), Using("Microsoft.VisualStudio.ProjectSystem"), Using("Microsoft.VisualStudio.ProjectSystem.Build") } ); unit = unit.WithUsings(usings); unit = unit.WithLeadingTrivia(GenerateLicenseHeader($"{className}.cs")); NamespaceDeclarationSyntax ns = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(targetNamespace)); ClassDeclarationSyntax cd = GenerateGlobalPropertiesProviderClass(className); cd = cd.WithAttributeLists(GenerateExportBuildGlobalPropertiesProviderAttribute()); ns = ns.AddMembers(cd); unit = unit.AddMembers(ns); unit = (CompilationUnitSyntax)Formatter.Format(unit, workspace); return(unit); }
CompilationUnitSyntax FixupSubmissionWithTrailingFieldDeclarationForEmission( CompilationUnitSyntax compilationUnit, FieldDeclarationSyntax trailingField) { var vars = trailingField.Declaration.Variables; if (vars.Count != 1) { return(compilationUnit); } // FIXME: The public SyntaxFactory API enforces ExpressionStatementSyntax having // a semicolon token. For interactive/scripting, this is optional, but we have // no way of generating a tree by hand that makes it so. The parser uses the // internal SyntaxFactory, which does not do argument checking. Ideally we could // use this: // // var exprStatement = SyntaxFactory.ExpressionStatement ( // SyntaxFactory.IdentifierName (vars [0].Identifier), // SyntaxFactory.Token (SyntaxKind.None) // ); // // instead of this hack: var exprStatement = SyntaxFactory.ParseStatement( vars [0].Identifier.Text, options: parseOptions); return(compilationUnit.AddMembers( SyntaxFactory.GlobalStatement(exprStatement))); }
private void GenerateOperationClass(OperationGroupContext operationGroupContext, string generatedClassName) { try { string className = String.Join("", configuration.OperationClassPrefixName, operationGroupContext.Name, configuration.OperationClassBaseName); string fileName = $"{className}.cs"; string fileLocation = Path.Combine(configuration.OperationsFolderLocation, fileName); if (!File.Exists(fileLocation)) { CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit(); NamespaceDeclarationSyntax @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName( String.Join(".", configuration.ProjectName, configuration.OperationsFolderName)).NormalizeWhitespace()); ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration(className) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(generatedClassName))); @namespace = @namespace.AddMembers(classDeclaration); compilationUnit = compilationUnit.AddMembers(@namespace); string fileContent = compilationUnit.NormalizeWhitespace().ToFullString(); File.WriteAllText(fileLocation, fileContent); } } catch (Exception e) { Console.WriteLine(e); } }
public static void CreateUnit(string unitName, Func <string, NamespaceDeclarationSyntax> nsFactory, string filePathFactory, params string[] usings) { unitName = NamingConventions.Normalize(unitName); CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit(); cu = cu.AddUsings(usings.OrderBy(s => s) .Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(u))) .ToArray()); var cw = new AdhocWorkspace(); cw.Options.WithChangedOption(CSharpFormattingOptions.IndentBlock, true); SyntaxNode formattedNode = Formatter.Format(cu.AddMembers(nsFactory(unitName)), cw, cw.Options); var file = new FileInfo(filePathFactory); DirectoryInfo dir = file.Directory; if (!dir !.Exists) { dir.Create(); } using FileStream fileStream = file.Exists ? file.Open(FileMode.Truncate) : file.Create(); using var sw = new StreamWriter(fileStream); formattedNode.WriteTo(sw); }
public CompileContext(Type baseType, Type modelType, string templateNamespace = null, string templateName = null, string templatePath = null, LogHandler logHandler = null) { _templateBaseType = baseType; _location = new TemplateLocation(templatePath); _macroManager = new MacroManager(baseType); _modelTypeName = ClassContext.GetTypeName(modelType); _stateTypeName = $"TxMark.Template.IState<{_modelTypeName}>"; _nameTagManager = new NameTagManager(); _bagsByReference = new Bag <object>(); _variableTypeByName = new Dictionary <string, VariableTypes>(); if (templateNamespace == null) { templateNamespace = DEFAULT_NAMESPACE; } if (templateName == null) { templateName = "Template_" + Guid.NewGuid().ToString().Replace('-', '_'); } _logHandler = logHandler ?? DefaultLogHandler; _codeContextStack = new Stack <ICodeContext>(); _metadataReferenceManager = new MetadataReferenceManager(); AddNamespaceFor(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)); AddNamespaceFor(typeof(DynamicObject)); AddNamespaceFor(typeof(string)); AddNamespaceFor(baseType); AddNamespaceFor(modelType); AddNamespaceFor(typeof(TemplateState <object>)); AddNamespaceFor(typeof(Dictionary <string, object>)); _namespace = SF.NamespaceDeclaration(SF.IdentifierName(templateNamespace)); _codeContext = new ClassContext(templateName, baseType, modelType, (classDeclaration) => { _namespace = _namespace.AddMembers(classDeclaration); List <UsingDirectiveSyntax> usingDirectives = new List <UsingDirectiveSyntax>(); foreach (var namespaceName in _usingNamespaces) { //usingDirectives.Add(SF.UsingDirective(SF.IdentifierName(namespaceName))); } _compilationUnit = SF.CompilationUnit(); //.AddUsings(usingDirectives.ToArray()); _compilationUnit = _compilationUnit.AddMembers(_namespace); }); }
public string Compile() { CompilationUnitSyntax compileUnit = null; lock (syncObj) //don't mutate the class fields //We should do it without changing them compileUnit = rosylnCompilationUnit.AddMembers(rosylnClassUnit.AddMembers(memberSyntax.ToArray())); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { Formatter.Format(compileUnit, new AdhocWorkspace()).WriteTo(writer); } return(sb.ToString()); }
public void ConstructorThrowsArgumentException_When_DeclarationDoesNotRepresentAnySymbol() { CompilationUnitSyntax unit = CompilationUnit(); ClassDeclarationSyntax decl = ClassDeclaration("Test"); FieldDeclarationSyntax field = FieldDeclaration(VariableDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), SingletonSeparatedList(VariableDeclarator("field")))); unit = unit.AddMembers(decl.AddMembers(field)); Assert.Throws <ArgumentException>(() => new Data.MemberData(decl, CreateValidCompilationData(unit.SyntaxTree))); }
public void AddOneExpression(string name, string type, ExpressionSyntax objectInitializationSyntax) { _compilationUnitSyntax = _compilationUnitSyntax.AddMembers(SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration( SyntaxFactory.IdentifierName(_variableDeclarationManager.GetDeclarationType(type))) .WithVariables( SyntaxFactory.SingletonSeparatedList < VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier(name)) .WithInitializer( SyntaxFactory.EqualsValueClause(objectInitializationSyntax))))) .WithSemicolonToken( SyntaxFactory.Token( SyntaxFactory.TriviaList(), SyntaxKind.SemicolonToken, SyntaxFactory.TriviaList( SyntaxFactory.LineFeed)))); }
public CSharpSyntaxNode Convert(SourceFile sourceFile) { CompilationUnitSyntax csCompilationUnit = SyntaxFactory.CompilationUnit(); foreach (string us in this.Context.Config.Usings) { csCompilationUnit = csCompilationUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(us))); } csCompilationUnit = csCompilationUnit.AddMembers(sourceFile.MouduleDeclarations.ToCsNodes <MemberDeclarationSyntax>()); foreach (Node import in sourceFile.ImportDeclarations) { foreach (UsingDirectiveSyntax usingSyntax in import.ToCsNode <SyntaxList <UsingDirectiveSyntax> >()) { csCompilationUnit = csCompilationUnit.AddUsings(usingSyntax); } } List <Node> typeAliases = sourceFile.TypeAliases; List <Node> typeDefinitions = this.FilterTypes(sourceFile.TypeDefinitions); if (typeAliases.Count > 0 || typeDefinitions.Count > 0) { string ns = sourceFile.Document.GetPackageName(); if (!string.IsNullOrEmpty(ns)) { NamespaceDeclarationSyntax nsSyntaxNode = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)); nsSyntaxNode = nsSyntaxNode .AddUsings(typeAliases.ToCsNodes <UsingDirectiveSyntax>()) .AddMembers(typeDefinitions.ToCsNodes <MemberDeclarationSyntax>()); csCompilationUnit = csCompilationUnit.AddMembers(nsSyntaxNode); } else { csCompilationUnit = csCompilationUnit .AddUsings(typeAliases.ToCsNodes <UsingDirectiveSyntax>()) .AddMembers(typeDefinitions.ToCsNodes <MemberDeclarationSyntax>()); } } return(csCompilationUnit); }
internal string GetTest() { _test = _test.AddUsings(_unit.Usings.Select(us => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(us))).ToArray()); _test = _test.AddUsings( SyntaxFactory.UsingDirective( SyntaxFactory.IdentifierName("NUnit.Framework")), SyntaxFactory.UsingDirective( SyntaxFactory.IdentifierName("Moq"))); _test = _test.AddMembers(_unit.Namespaces.Select(nm => CreateNamespace(nm)).ToArray()); return(_test.NormalizeWhitespace().ToFullString()); }
/// <summary> /// Generates the source code graph for the specified resource property dictionary. /// </summary> /// <param name="properties">The property dictionary for which to generate the code.</param> /// <param name="resxFile">The full path of the input XML resource file.</param> /// <param name="defaultNamespace">The namespace into which the generated code will be placed.</param> /// <returns>The generated source code.</returns> private string GenerateCode(Dictionary <string, ResXData> properties, string resxFile, string defaultNamespace) { CompilationUnitSyntax unit = SyntaxFactory.CompilationUnit(); if (properties.Count > 0) { string fileName = Path.GetFileNameWithoutExtension(resxFile); string className = CreateIdentifier(fileName); if (className == null) { GenerateError(string.Format(Strings.InvalidClassIdentifier, Path.GetFileName(resxFile))); return(unit.ToFileString()); } NameSyntax ns = SyntaxFactory.ParseName(defaultNamespace); unit = unit.AddMembers( SyntaxFactory.NamespaceDeclaration(ns).AddMembers( SyntaxFactory.ClassDeclaration(className).AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)).AddMembers( SyntaxFactory.ClassDeclaration(ClassName).AddModifiers( SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PartialKeyword) ).AddAttributes( SyntaxFactory.Attribute(SyntaxFactory.ParseName(typeof(DebuggerNonUserCodeAttribute).FullName)), SyntaxFactory.Attribute(SyntaxFactory.ParseName(typeof(CompilerGeneratedAttribute).FullName)) ).AddMembers( SyntaxFactory.FieldDeclaration( SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseName(typeof(ResourceManager).FullName)).AddVariables( SyntaxFactory.VariableDeclarator(FieldName).WithInitializer( SyntaxFactory.EqualsValueClause( SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseName(typeof(ResourceManager).FullName)).AddArgumentListArguments( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(SyntaxFactory.QualifiedName(ns, SyntaxFactory.IdentifierName(fileName)).ToString()))), SyntaxFactory.Argument(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.TypeOfExpression(SyntaxFactory.IdentifierName(className)), SyntaxFactory.IdentifierName(nameof(Type.Assembly)))) ) ) ) ) ).AddModifiers( SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword) ) ).AddMembers(GenerateProperties(properties).ToArray()).AddSummary(Strings.ResourcesClassSummary) ) ) ); } return(unit.ToFileString(new Formatter())); }
public CompilationUnitSyntax Generate(CompilationUnitSyntax compilationUnitSyntax, ClassToGenerate classToGenerate) { var classDeclarationSyntax = _syntaxGeneratorFacade.GetClassSyntax(classToGenerate.ClassName); classDeclarationSyntax = _classDeclarationGenerators .Aggregate(classDeclarationSyntax, (current, classDeclarationGenerator) => classDeclarationGenerator.Generate(current, classToGenerate)); var @namespace = _syntaxGeneratorFacade.GetNamespace(_namespace); @namespace = @namespace.AddMembers(classDeclarationSyntax); return(compilationUnitSyntax.AddMembers(@namespace)); }
private static CompilationUnitSyntax AddTargetNamespaceToCompilation(NamespaceDeclarationSyntax originalTargetNamespace, CompilationUnitSyntax compilation, NamespaceDeclarationSyntax targetNamespace) { if (originalTargetNamespace == null) { compilation = compilation.AddMembers(targetNamespace); } else { compilation = compilation.RemoveNode(originalTargetNamespace, SyntaxRemoveOptions.KeepNoTrivia).AddMembers(targetNamespace); } return(compilation); }
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()); }
private static void GenerateSingleCSharpDocument( IEnumerable <GeneratorResult> results, SourceDocumentKind kind, string fileName, ICollection <SourceDocument> documents) { var code = new StringBuilder(); // marker for style cop to ignore this code code.AppendLine("// <auto-generated/>"); // enable nullability settings code.AppendLine("#nullable enable"); CompilationUnitSyntax compilationUnit = CompilationUnit(); foreach (var group in results.GroupBy(t => t.Result.Namespace).OrderBy(t => t.Key)) { NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(IdentifierName(group.Key)); foreach (var item in group) { BaseTypeDeclarationSyntax typeDeclaration = item.Result.TypeDeclaration; #if DEBUG SyntaxTriviaList trivia = typeDeclaration .GetLeadingTrivia() .Insert(0, Comment("// " + item.Generator.FullName)); typeDeclaration = typeDeclaration.WithLeadingTrivia(trivia); #endif namespaceDeclaration = namespaceDeclaration.AddMembers(typeDeclaration); } compilationUnit = compilationUnit.AddMembers(namespaceDeclaration); } compilationUnit = compilationUnit.NormalizeWhitespace(elasticTrivia: true); code.AppendLine(); code.AppendLine(compilationUnit.ToFullString()); documents.Add(new( fileName, code.ToString(), kind)); }
public async Task <CodeGenResult> CodeGen(Workspace workspace, Project project) { var usings = new HashSet <string>(); usings.UnionWith(GetCommonUsings()); CompilationUnitSyntax cu = SF.CompilationUnit(); foreach (Document document in project.Documents) { SyntaxTree syntaxTree = await document.GetSyntaxTreeAsync(); SemanticModel semanticModel = await document.GetSemanticModelAsync(); IEnumerable <InterfaceDeclarationSyntax> interfaces = syntaxTree.GetRoot().DescendantNodes().OfType <InterfaceDeclarationSyntax>(); bool copyDocumentUsings = false; foreach (var interfaceNode in interfaces) { ClassDeclarationSyntax classDclr = GenerateApiControllerForInterface(interfaceNode, semanticModel); if (classDclr == null) { continue; } // only copy the usings in the document if at least one ApiController is generated copyDocumentUsings = true; var namespaceNode = interfaceNode.Parent as NamespaceDeclarationSyntax; // ReSharper disable once PossibleNullReferenceException usings.UnionWith(namespaceNode.Usings.Select(@using => @using.Name.ToString())); // use the same namespace in the generated class string fullNameSpace = semanticModel.GetDeclaredSymbol(namespaceNode).ToString(); NamespaceDeclarationSyntax namespaceDclr = SF.NamespaceDeclaration(SF.IdentifierName(fullNameSpace)).WithUsings(namespaceNode.Usings); namespaceDclr = namespaceDclr.AddMembers(classDclr); cu = cu.AddMembers(namespaceDclr); } if (copyDocumentUsings) { usings.UnionWith(syntaxTree.GetRoot().DescendantNodes().OfType <UsingDirectiveSyntax>().Select(@using => @using.Name.ToString())); } } return(new CodeGenResult(Formatter.Format(cu, workspace).ToString(), usings)); }
public async Task <Document> AddOperatorType( Document document, CompilationUnitSyntax root, ImmutableDictionary <string, ImmutableArray <ITypeSymbol> > constraintDic) { bool hasMethod = false; var usings = root.Usings.ToNamespaceHashSet(); MemberDeclarationSyntax[] newMembers = new MemberDeclarationSyntax[constraintDic.Count]; foreach (var(p, i) in constraintDic.Select((p, i) => (p, i))) { bool m; (newMembers[i], m) = Build(p.Key, p.Value); hasMethod |= m; } return(document.WithSyntaxRoot(root.AddMembers(newMembers))); }
private string GenerateOperationGenClass(OperationGroupContext operationGroupContext, string baseClassName) { string className = String.Join("", configuration.OperationClassPrefixName, operationGroupContext.Name, CSharpLanguageSettings.GeneratedKeyWord, configuration.OperationClassBaseName); string fileName = $"{className}.generated.cs"; string fileLocation = Path.Combine(configuration.OperationsGeneratedFolderLocation, fileName); CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit(); compilationUnit = compilationUnit .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Net.Http"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Threading.Tasks"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName($"{configuration.ProjectName}.{configuration.ModelFolderName}"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(String.Join(".", configuration.ProjectName, configuration.OperationsFolderName, configuration.OperationsBaseFolderName)))); NamespaceDeclarationSyntax @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName( String.Join(".", configuration.ProjectName, configuration.OperationsFolderName, configuration.OperationsGeneratedFolderName)).NormalizeWhitespace()); //ConstructorDeclarationSyntax constructor = GenerateConstructor(className); ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration(className) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(baseClassName))); //.AddMembers(constructor); foreach (OperationContext operationContext in operationGroupContext.Operations) { MethodDeclarationSyntax methodDeclaration = GenerateMethod(operationContext); classDeclaration = classDeclaration.AddMembers(methodDeclaration); } @namespace = @namespace.AddMembers(classDeclaration); compilationUnit = compilationUnit.AddMembers(@namespace); string fileContent = compilationUnit.NormalizeWhitespace().ToFullString(); File.WriteAllText(fileLocation, fileContent); return(className); }
public static string GenerateTestCode(List <NamespaceData> namespaces, string fileName) { CompilationUnitSyntax tree = SyntaxFactory.CompilationUnit() .AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("NUnit.Framework")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(fileName.Replace(".cs", "")))); foreach (NamespaceData namespaceData in namespaces) { NamespaceDeclarationSyntax ns = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(namespaceData.Name + ".Tests")); foreach (ClassData classData in namespaceData.ClassList) { ClassDeclarationSyntax classNode = SyntaxFactory .ClassDeclaration(classData.Name + "TestClass") .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("TestFixture")))).NormalizeWhitespace()); foreach (MethodData methodData in classData.MethodList) { MethodDeclarationSyntax method = SyntaxFactory .MethodDeclaration(SyntaxFactory.ParseTypeName("void"), methodData.Name + "TestMethod") .AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Test")))).NormalizeWhitespace()) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) .AddBodyStatements( SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Assert"), SyntaxFactory.IdentifierName("Fail")), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("autogenerated")))))))); classNode = classNode .AddMembers(method); } ns = ns .AddMembers(classNode); } tree = tree .AddMembers(ns); } AdhocWorkspace cw = new AdhocWorkspace(); return(Formatter.Format(tree.SyntaxTree.GetRoot(), cw, null).ToFullString()); }
public SyntaxNode Build() { CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit(); var namespaceDecleration = SyntaxFactory.NamespaceDeclaration(this.NamespaceName.ParseCSharpName()); var orderedNamespaceDeclerations = this.UsingNamespaces.OrderBy(x => x).Select(x => SyntaxFactory.UsingDirective(x.ParseCSharpName())); compilationUnit = compilationUnit.AddUsings(orderedNamespaceDeclerations.ToArray()); if (0 < this.ClassBuilderList.Count) { var classDeclerations = this.ClassBuilderList.Select(x => x.Build()).OfType <ClassDeclarationSyntax>().ToArray(); namespaceDecleration = namespaceDecleration.AddMembers(classDeclerations); } compilationUnit = compilationUnit.AddMembers(namespaceDecleration); return(compilationUnit); }