public override string ImportSchemaType( string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (ns != "http://www.w3.org/2001/XMLSchema") return null; switch (name) { case "anyURI": return "System.Uri"; case "gDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay"; case "gMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth"; case "gMonthDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonthDay"; case "gYear": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear"; case "gYearMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYearMonth"; case "duration": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration"; default: return null; } }
//public override string ImportSchemaType( // string name, // string ns, // XmlSchemaObject context, // XmlSchemas schemas, // XmlSchemaImporter importer, // CodeCompileUnit compileUnit, // CodeNamespace mainNamespace, // CodeGenerationOptions options, // CodeDomProvider codeProvider) //{ // XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType) schemas.Find(new XmlQualifiedName(name, ns), typeof(XmlSchemaSimpleType)); // return ImportSchemaType( // simpleType, // context, // schemas, // importer, // compileUnit, // mainNamespace, // options, // codeProvider); //} public override string ImportSchemaType( XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { XmlSchemaAnnotated annotatedType = type as XmlSchemaAnnotated; if (annotatedType == null) return null; if (annotatedType.Annotation == null) return null; // create the comments and add them to the hash table under the namespace of the object CreateComments(annotatedType); //mainNamespace.Types. return null; }
public override string ImportSchemaType(XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (type == null) { return null; } if (importedTypes[type] != null) { mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return (string)importedTypes[type]; } if (!(context is XmlSchemaElement)) return null; if (type is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)type; if (ct.Particle is XmlSchemaSequence) { XmlSchemaObjectCollection items = ((XmlSchemaSequence)ct.Particle).Items; if (items.Count == 2 && items[0] is XmlSchemaAny && items[1] is XmlSchemaAny) { XmlSchemaAny any0 = (XmlSchemaAny)items[0]; XmlSchemaAny any1 = (XmlSchemaAny)items[1]; if (any0.Namespace == XmlSchema.Namespace && any1.Namespace == "urn:schemas-microsoft-com:xml-diffgram-v1") { string typeName = typeof(DataTable).FullName; importedTypes.Add(type, typeName); mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataTable).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return typeName; } } } } return null; }
public MapCodeGenerator (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options) { // this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; this.options = options; this.identifiers = new CodeIdentifiers (); }
internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, System.Xml.Serialization.ImportContext context) { if (!schemas.Contains("http://www.w3.org/2001/XMLSchema")) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains("http://www.w3.org/XML/1998/namespace")) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } this.schemas = schemas; this.options = options; this.codeProvider = codeProvider; this.context = context; this.Schemas.SetCache(this.Context.Cache, this.Context.ShareTypes); SchemaImporterExtensionsSection section = System.Configuration.PrivilegedConfigurationManager.GetSection(ConfigurationStrings.SchemaImporterExtensionsSectionPath) as SchemaImporterExtensionsSection; if (section != null) { this.extensions = section.SchemaImporterExtensionsInternal; } else { this.extensions = new SchemaImporterExtensionCollection(); } }
public override string ImportSchemaType( string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace codeNamespace, CodeGenerationOptions options, CodeDomProvider codeGenerator) { if (IsBaseType(name, ns)) { return base.ImportSchemaType(name, ns, context, schemas, importer, compileUnit, codeNamespace, options, codeGenerator); } // Add the Namespace, except the first for (int i = 1; i < ImportNamespaces.Length; i++) { string _Import = ImportNamespaces[i]; codeNamespace.Imports.Add(new CodeNamespaceImport(_Import)); } return name; }
public XmlCodeExporter (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options, Hashtable mappings) : this (codeNamespace, codeCompileUnit, null, options, mappings) { }
[MonoTODO]// FIXME: mappings? public SoapCodeExporter (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) { codeGenerator = new SoapMapCodeGenerator (codeNamespace, codeCompileUnit, codeProvider, options, mappings); }
public MapCodeGenerator (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) { // this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; this.options = options; this.codeProvider = codeProvider; this.identifiers = new CodeIdentifiers ((codeProvider.LanguageOptions & LanguageOptions.CaseInsensitive) == 0); // this.mappings = mappings; }
/// <summary> /// Constructs a instance of the uglification options /// </summary> public UglificationOptions() { ParsingOptions = new ParsingOptions(); CompressionOptions = new CompressionOptions(); ManglingOptions = new ManglingOptions(); CodeGenerationOptions = new CodeGenerationOptions(); ScrewIe8 = false; KeepFunctionNames = false; Severity = 0; }
public override string ImportSchemaType(string name, string xmlNamespace, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if ((this.m_direct && (context is XmlSchemaElement)) && ((string.CompareOrdinal(this.m_name, name) == 0) && (string.CompareOrdinal(this.m_targetNamespace, xmlNamespace) == 0))) { compileUnit.ReferencedAssemblies.AddRange(this.m_references); mainNamespace.Imports.AddRange(this.m_namespaceImports); return this.m_destinationType; } return null; }
public override string ImportSchemaType(string name, string schemaNamespace, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { IList values = schemas.GetSchemas(schemaNamespace); if (values.Count != 1) { return null; } XmlSchema schema = values[0] as XmlSchema; if (schema == null) return null; XmlSchemaType type = (XmlSchemaType)schema.SchemaTypes[new XmlQualifiedName(name, schemaNamespace)]; return ImportSchemaType(type, context, schemas, importer, compileUnit, mainNamespace, options, codeProvider); }
public override string ImportSchemaType (XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (type == null) return null; var xe = context as XmlSchemaElement; if (xe == null) return null; return null; }
public override string ImportSchemaType (string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (ns == "http://monkeywrench.novell.com/") { if (name != "ArrayOfString" && name != "ArrayOfInt1") { mainNamespace.Imports.Add (new CodeNamespaceImport ("MonkeyWrench.DataClasses")); mainNamespace.Imports.Add (new CodeNamespaceImport ("MonkeyWrench.DataClasses.Logic")); return name; } } return base.ImportSchemaType (name, ns, context, schemas, importer, compileUnit, mainNamespace, options, codeProvider); }
public void Test_Generate_CSharp_To_Console() { var options = new CodeGenerationOptions { GenerateClasses = true, Namespace = "Io.Fickle.Test.Servicemodel" }; var serviceModel = FicklefileParserTests.GetTestServiceModel(); var serviceModelcodeGenerator = ServiceModelCodeGenerator.GetCodeGenerator("csharp", TextWriter.Null, options); serviceModelcodeGenerator.Generate(serviceModel); }
public void Test_Generate_Javascript_To_Console() { var options = new CodeGenerationOptions { GenerateClasses = false, TypeNamePrefix = "TN" }; var serviceModel = FicklefileParserTests.GetTestServiceModel(); var serviceModelcodeGenerator = ServiceModelCodeGenerator.GetCodeGenerator("javascript", Console.Out, options); serviceModelcodeGenerator.Generate(serviceModel); }
public virtual string ImportAnyElement ( XmlSchemaAny any, bool mixed, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider ) { return null; }
public virtual string ImportSchemaType ( XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider ) { return null; }
public override string ImportSchemaType(XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if ((!this.m_direct && (type is XmlSchemaSimpleType)) && (context is XmlSchemaElement)) { XmlQualifiedName qualifiedName = ((XmlSchemaSimpleType) type).BaseXmlSchemaType.QualifiedName; if ((string.CompareOrdinal(this.m_name, qualifiedName.Name) == 0) && (string.CompareOrdinal(this.m_targetNamespace, qualifiedName.Namespace) == 0)) { compileUnit.ReferencedAssemblies.AddRange(this.m_references); mainNamespace.Imports.AddRange(this.m_namespaceImports); return this.m_destinationType; } } return null; }
internal CodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable exportedMappings) { if (codeNamespace != null) CodeGenerator.ValidateIdentifiers(codeNamespace); this.codeNamespace = codeNamespace; if (codeCompileUnit != null) { if (!codeCompileUnit.ReferencedAssemblies.Contains("System.dll")) codeCompileUnit.ReferencedAssemblies.Add("System.dll"); if (!codeCompileUnit.ReferencedAssemblies.Contains("System.Xml.dll")) codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); } this.codeCompileUnit = codeCompileUnit; this.options = options; this.exportedMappings = exportedMappings; this.codeProvider = codeProvider; }
public override string ImportSchemaType(string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (XmlSchema.Namespace == ns) { switch (name) { case "dateTime": string codeTypeName = typeof(DateTimeOffset).FullName; return codeTypeName; default: return null; } } else { return null; } }
public void Test_Generate_Javascript_Files() { var options = new CodeGenerationOptions { GenerateClasses = false, TypeNamePrefix = "TN" }; var outputDir = FileSystemManager.Default.ResolveDirectory("./" + new StackTrace().GetFrame(0).GetMethod().Name); var serviceModel = FicklefileParserTests.GetTestServiceModel(); outputDir.Create(true); var serviceModelcodeGenerator = ServiceModelCodeGenerator.GetCodeGenerator("javascript", outputDir, options); serviceModelcodeGenerator.Generate(serviceModel); }
internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) { if (!schemas.Contains(XmlSchema.Namespace)) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains(XmlReservedNs.NsXml)) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } _schemas = schemas; _options = options; _context = context; Schemas.SetCache(Context.Cache, Context.ShareTypes); }
public void Test_Generate_CSharp_Files() { var options = new CodeGenerationOptions { GenerateClasses = true, Namespace = "Io.Fickle.Test.Servicemodel" }; var outputDir = FileSystemManager.Default.ResolveDirectory("./" + new StackTrace().GetFrame(0).GetMethod().Name); var serviceModel = FicklefileParserTests.GetTestServiceModel(); outputDir.Create(true); var serviceModelcodeGenerator = ServiceModelCodeGenerator.GetCodeGenerator("csharp", outputDir, options); serviceModelcodeGenerator.Generate(serviceModel); }
public override string ImportSchemaType( XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { XmlSchemaSimpleType simpleType = type as XmlSchemaSimpleType; if (simpleType == null) return null; string typeName = null; if (generatedTypes.TryGetValue(simpleType, out typeName)) return typeName; XmlSchemaSimpleTypeRestriction restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (restriction == null) return null; // genetate type only for xs:string restrictions if (restriction.BaseTypeName.Name != "string" || restriction.BaseTypeName.Namespace != XmlSchema.Namespace) return null; // does not generate custom type if it has any enumeration facets foreach (object o in restriction.Facets) { if (o is XmlSchemaEnumerationFacet) return null; } typeName = GenerateSimpleType(simpleType, compileUnit, mainNamespace, options, codeProvider); // add generated type information to the cache to avoid generating type al the time if (typeName != null) { generatedTypes[simpleType] = typeName; clrTypes.Add(typeName, typeName); } return typeName; }
public override string ImportSchemaType(string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { // Uncomment these lines for debugging. // (Messages are displayed when you run wsdl.exe // and this schema importer is called.) //Console.WriteLine("ImportSchemaType"); //Console.WriteLine(name); //Console.WriteLine(ns); //Console.WriteLine(); if (name.Equals("FileData") && ns.Equals("http://www.apress.com/ProASP.NET/FileData")) { mainNamespace.Imports.Add(new CodeNamespaceImport("FileDataComponent")); return "FileData"; } return null; }
public void Test_Generate_CSharp_Files_With_Mapped_Type_Assembly() { var options = new CodeGenerationOptions { GenerateClasses = false, GenerateEnums = false, Namespace = "Io.Fickle.Test.Servicemodel", MappedTypeAssemblies = new []{ typeof(Person).Assembly.Location } }; var outputDir = FileSystemManager.Default.ResolveDirectory("./" + new StackTrace().GetFrame(0).GetMethod().Name); var serviceModel = FicklefileParserTests.GetTestServiceModel(); outputDir.Create(true); var serviceModelcodeGenerator = ServiceModelCodeGenerator.GetCodeGenerator("csharp", outputDir, options); serviceModelcodeGenerator.Generate(serviceModel); }
public override string ImportSchemaType(string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (discoveredTypes == null) DiscoverTypes(); string key = ns + name; Type type; if (!discoveredTypes.TryGetValue(key, out type)) return base.ImportSchemaType(name, ns, context, schemas, importer, compileUnit, mainNamespace, options, codeProvider); compileUnit.ReferencedAssemblies.Add(type.Assembly.FullName); XmlSchemaElement schemaElement = context as XmlSchemaElement; if ((schemaElement != null) && schemaElement.IsNillable && (schemaElement.ElementSchemaType is XmlSchemaSimpleType)) return String.Format("System.Nullable<{0}>", type.FullName); return type.FullName; }
private string Write1_CodeGenerationOptions(CodeGenerationOptions v) { switch (v) { case CodeGenerationOptions.GenerateProperties: return "properties"; case CodeGenerationOptions.GenerateNewAsync: return "newAsync"; case CodeGenerationOptions.GenerateOldAsync: return "oldAsync"; case CodeGenerationOptions.GenerateOrder: return "order"; case CodeGenerationOptions.EnableDataBinding: return "enableDataBinding"; } return XmlSerializationWriter.FromEnum((long) v, new string[] { "properties", "newAsync", "oldAsync", "order", "enableDataBinding" }, new long[] { 1L, 2L, 4L, 8L, 0x10L }, "System.Xml.Serialization.CodeGenerationOptions"); }
internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) { if (!schemas.Contains(XmlSchema.Namespace)) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains(XmlReservedNs.NsXml)) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } this.schemas = schemas; this.options = options; this.codeProvider = codeProvider; this.context = context; Schemas.SetCache(Context.Cache, Context.ShareTypes); SchemaImporterExtensionsSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.SchemaImporterExtensionsSectionPath) as SchemaImporterExtensionsSection; if (section != null) extensions = section.SchemaImporterExtensionsInternal; else extensions = new SchemaImporterExtensionCollection(); }
static void Validate(List <GenBase> gens, CodeGenerationOptions opt, CodeGeneratorContext context) { //int cycle = 1; List <GenBase> removed = new List <GenBase> (); var nested_removes = new List <GenBase> (); // This loop is required because we cannot really split type validation and member // validation apart (unlike C# compiler), because invalidated members will result // in the entire interface invalidation (since we cannot implement it), and use of // those invalidated interfaces must be eliminated in members in turn again. do { //Console.WriteLine ("Validation cycle " + cycle++); removed.Clear(); foreach (GenBase gen in gens) { gen.ResetValidation(); } foreach (GenBase gen in gens) { gen.FixupAccessModifiers(opt); } foreach (GenBase gen in gens) { if ((opt.IgnoreNonPublicType && (gen.RawVisibility != "public" && gen.RawVisibility != "internal")) || !gen.Validate(opt, null, context)) { foreach (GenBase nest in gen.NestedTypes) { foreach (var nt in nest.Invalidate()) { removed.Add(nt); } } removed.Add(gen); } } // Remove any nested types that are package-private foreach (var gen in gens) { foreach (var nest in gen.NestedTypes) { if (opt.IgnoreNonPublicType && (nest.RawVisibility != "public" && nest.RawVisibility != "internal" && nest.RawVisibility != "protected internal")) { // We still add it to "removed" even though the removal // code later won't work, so that it triggers a new cycle removed.Add(nest); nested_removes.Add(nest); } } foreach (var nest in nested_removes) { gen.NestedTypes.Remove(nest); } nested_removes.Clear(); } foreach (GenBase gen in removed) { gens.Remove(gen); } } while (removed.Count > 0); }
public override string ImportSchemaType(string name, string namespaceName, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { throw new NotImplementedException(); }
public BusinessLayerInterfaceGenerator(CodeGenerationOptions options) { this._options = options; }
void AddMethodInvokers(InterfaceGen iface, IEnumerable <Method> methods, HashSet <string> members, CodeGenerationOptions opt, CodeGeneratorContext context) { foreach (var m in methods) { var sig = m.GetSignature(); if (members.Contains(sig)) { continue; } members.Add(sig); Methods.Add(new InterfaceInvokerMethod(iface, m, opt, context)); } }
protected override TDeclarationNode AddNamedType <TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList <bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode <TypeDeclarationSyntax, NamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax) { return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <TypeDeclarationSyntax>(destination), namedType, options, availableIndices, cancellationToken))); } else if (destination is NamespaceDeclarationSyntax) { return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <NamespaceDeclarationSyntax>(destination), namedType, options, availableIndices, cancellationToken))); } else { return(Cast <TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast <CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken))); } }
protected override TDeclarationNode AddNamespace <TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList <bool> availableIndices) { CheckDeclarationNode <CompilationUnitSyntax, PackageDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax) { return(Cast <TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast <CompilationUnitSyntax>(destination), @namespace, options, availableIndices))); } else { return(Cast <TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast <PackageDeclarationSyntax>(destination), @namespace, options, availableIndices))); } }
protected override TDeclarationNode AddEvent <TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList <bool> availableIndices) { CheckDeclarationNode <TypeDeclarationSyntax>(destination); return(Cast <TDeclarationNode>(EventGenerator.AddEventTo(Cast <TypeDeclarationSyntax>(destination), @event, options, availableIndices))); }
public BoundClass(ClassGen klass, CodeGenerationOptions opt, CodeGeneratorContext context, GenerationInfo generationInfo) { context.ContextTypes.Push(klass); context.ContextGeneratedMethods = new List <Method> (); generationInfo.TypeRegistrations.Add(new KeyValuePair <string, string> (klass.RawJniName, klass.AssemblyQualifiedName)); var is_enum = klass.base_symbol != null && klass.base_symbol.FullName == "Java.Lang.Enum"; if (is_enum) { generationInfo.Enums.Add(klass.RawJniName.Replace('/', '.') + ":" + klass.Namespace + ":" + klass.JavaSimpleName); } this.opt = opt; Name = klass.Name; SetVisibility(klass.Visibility); IsShadow = klass.NeedsNew; IsAbstract = klass.IsAbstract; IsSealed = klass.IsFinal; IsPartial = true; UsePriorityOrder = true; AddImplementedInterfaces(klass); klass.JavadocInfo?.AddJavadocs(Comments); Comments.Add($"// Metadata.xml XPath class reference: path=\"{klass.MetadataXPathReference}\""); if (klass.IsDeprecated) { Attributes.Add(new ObsoleteAttr(klass.DeprecatedComment) { WriteAttributeSuffix = true }); } SourceWriterExtensions.AddSupportedOSPlatform(Attributes, klass, opt); Attributes.Add(new RegisterAttr(klass.RawJniName, null, null, true, klass.AdditionalAttributeString()) { UseGlobal = true, UseShortForm = true }); if (klass.TypeParameters != null && klass.TypeParameters.Any()) { Attributes.Add(new CustomAttr(klass.TypeParameters.ToGeneratedAttributeString())); } // Figure out our base class string obj_type = null; if (klass.base_symbol != null) { obj_type = klass.base_symbol is GenericSymbol gs && gs.IsConcrete ? gs.GetGenericType(null) : opt.GetOutputName(klass.base_symbol.FullName); } if (klass.InheritsObject && obj_type != null) { Inherits = obj_type; } // Handle fields var seen = new HashSet <string> (); SourceWriterExtensions.AddFields(this, klass, klass.Fields, seen, opt, context); var ic = new InterfaceConstsClass(klass, seen, opt, context); if (ic.ShouldGenerate) { NestedTypes.Add(ic); } // Sibling classes if (!klass.AssemblyQualifiedName.Contains('/')) { foreach (InterfaceExtensionInfo nestedIface in klass.GetNestedInterfaceTypes()) { if (nestedIface.Type.Methods.Any(m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any(m => m.Asyncify)) { sibling_types.Add(new InterfaceExtensionsClass(nestedIface.Type, nestedIface.DeclaringType, opt)); } } } if (klass.IsAbstract) { sibling_types.Add(new ClassInvokerClass(klass, opt)); } AddNestedTypes(klass, opt, context, generationInfo); AddBindingInfrastructure(klass); AddConstructors(klass, opt, context); AddProperties(klass, opt); AddMethods(klass, opt, context); AddAbstractMembers(klass, opt, context); AddExplicitGenericInterfaceMembers(klass, opt); AddCharSequenceEnumerator(klass); context.ContextGeneratedMethods.Clear(); context.ContextTypes.Pop(); }
public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options) { return(NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options)); }
private static TDeclarationNode UpdateDeclarationModifiers <TDeclarationNode>(TDeclarationNode declaration, Func <SyntaxTokenList, SyntaxTokenList> computeNewModifiersList, CodeGenerationOptions options, CancellationToken cancellationToken) { // Handle type declarations. var typeDeclaration = declaration as BaseTypeDeclarationSyntax; if (typeDeclaration != null) { return(Cast <TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers)))); } // Handle field declarations. var fieldDeclaration = declaration as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { return(Cast <TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers)))); } // Handle method declarations. var methodDeclaration = declaration as BaseMethodDeclarationSyntax; if (methodDeclaration != null) { return(Cast <TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers)))); } // Handle properties. var propertyDeclaration = declaration as BasePropertyDeclarationSyntax; if (propertyDeclaration != null) { return(Cast <TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers)))); } return(declaration); }
public override TDeclarationNode UpdateDeclarationModifiers <TDeclarationNode>(TDeclarationNode declaration, IEnumerable <SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { Func <SyntaxTokenList, SyntaxTokenList> computeNewModifiersList = (SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return(UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)); }
private static SyntaxList <AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return(default);
public override TDeclarationNode UpdateDeclarationAccessibility <TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccesibility, CodeGenerationOptions options, CancellationToken cancellationToken) { Func <SyntaxTokenList, SyntaxTokenList> computeNewModifiersList = (SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccesibility, options); return(UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)); }
public override TDeclarationNode UpdateDeclarationMembers <TDeclarationNode>(TDeclarationNode declaration, IList <ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { var memberDeclaration = declaration as MemberDeclarationSyntax; if (memberDeclaration != null) { return(Cast <TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken))); } var syntaxNode = declaration as CSharpSyntaxNode; if (syntaxNode != null) { switch (syntaxNode.CSharpKind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: return(Cast <TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken))); } } return(declaration); }
protected override TDeclarationNode AddField <TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList <bool> availableIndices) { CheckDeclarationNode <EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return(Cast <TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast <EnumDeclarationSyntax>(destination), field, options))); } else if (destination is TypeDeclarationSyntax) { return(Cast <TDeclarationNode>(FieldGenerator.AddFieldTo(Cast <TypeDeclarationSyntax>(destination), field, options, availableIndices))); } else { return(Cast <TDeclarationNode>(FieldGenerator.AddFieldTo(Cast <CompilationUnitSyntax>(destination), field, options, availableIndices))); } }
public static int GetInsertionIndex <TDeclaration>( SyntaxList <TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList <bool> availableIndices, Func <SyntaxList <TDeclaration>, TDeclaration> after = null, Func <SyntaxList <TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { Contract.ThrowIfTrue(availableIndices != null && availableIndices.Count != declarationList.Count + 1); if (options != null) { // Try to strictly obey the after option by inserting immediately after the member containing the location if (options.AfterThisLocation != null) { var afterMember = declarationList.LastOrDefault(m => m.SpanStart <= options.AfterThisLocation.SourceSpan.Start); if (afterMember != null) { var index = declarationList.IndexOf(afterMember); index = GetPreferredIndex(index + 1, availableIndices, forward: true); if (index != -1) { return(index); } } } // Try to strictly obey the before option by inserting immediately before the member containing the location if (options.BeforeThisLocation != null) { var beforeMember = declarationList.FirstOrDefault(m => m.Span.End >= options.BeforeThisLocation.SourceSpan.End); if (beforeMember != null) { var index = declarationList.IndexOf(beforeMember); index = GetPreferredIndex(index, availableIndices, forward: false); if (index != -1) { return(index); } } } if (options.AutoInsertionLocation) { if (declarationList.IsEmpty()) { return(0); } else if (declarationList.IsSorted(CSharpDeclarationComparer.Instance)) { var result = Array.BinarySearch(declarationList.ToArray(), declaration, CSharpDeclarationComparer.Instance); var index = GetPreferredIndex(result < 0 ? ~result : result, availableIndices, forward: true); if (index != -1) { return(index); } } if (after != null) { var member = after(declarationList); if (member != null) { var index = declarationList.IndexOf(member); if (index >= 0) { index = GetPreferredIndex(index + 1, availableIndices, forward: true); if (index != -1) { return(index); } } } } if (before != null) { var member = before(declarationList); if (member != null) { var index = declarationList.IndexOf(member); if (index >= 0) { index = GetPreferredIndex(index, availableIndices, forward: false); if (index != -1) { return(index); } } } } } } // Otherwise, add the declaration to the end. { var index = GetPreferredIndex(declarationList.Count, availableIndices, forward: false); if (index != -1) { return(index); } } return(declarationList.Count); }
public override TDeclarationNode RemoveAttribute <TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; // Handle all members including types. var member = destination as MemberDeclarationSyntax; if (member != null) { var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return(Cast <TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))); } // Handle accessors var accessor = destination as AccessorDeclarationSyntax; if (accessor != null) { var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return(Cast <TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))); } // Handle global attributes var compilationUnit = destination as CompilationUnitSyntax; if (compilationUnit != null) { var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return(Cast <TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))); } // Handle parameters var parameter = destination as ParameterSyntax; if (parameter != null) { var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return(Cast <TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))); } var typeParameter = destination as TypeParameterSyntax; if (typeParameter != null) { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return(Cast <TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))); } return(destination); }
static void Run(CodeGeneratorOptions options, DirectoryAssemblyResolver resolver) { string assemblyQN = options.AssemblyQualifiedName; string api_level = options.ApiLevel; int product_version = options.ProductVersion; bool preserve_enums = options.PreserveEnums; string csdir = options.ManagedCallableWrapperSourceOutputDirectory ?? "cs"; string javadir = "java"; string enumdir = options.EnumOutputDirectory ?? "enum"; string enum_metadata = options.EnumMetadataOutputFile ?? "enummetadata"; var references = options.AssemblyReferences; string enum_fields_map = options.EnumFieldsMapFile; string enum_flags = options.EnumFlagsFile; string enum_methods_map = options.EnumMethodsMapFile; var fixups = options.FixupFiles; var annotations_zips = options.AnnotationsZipFiles; string filename = options.ApiDescriptionFile; string mapping_file = options.MappingReportFile; bool only_xml_adjuster = options.OnlyRunApiXmlAdjuster; string api_xml_adjuster_output = options.ApiXmlAdjusterOutput; var apiSource = ""; var opt = new CodeGenerationOptions() { ApiXmlFile = options.ApiDescriptionFile, CodeGenerationTarget = options.CodeGenerationTarget, UseGlobal = options.GlobalTypeNames, IgnoreNonPublicType = true, UseShortFileNames = options.UseShortFileNames, ProductVersion = options.ProductVersion, SupportInterfaceConstants = options.SupportInterfaceConstants, SupportDefaultInterfaceMethods = options.SupportDefaultInterfaceMethods, SupportNestedInterfaceTypes = options.SupportNestedInterfaceTypes, SupportNullableReferenceTypes = options.SupportNullableReferenceTypes, }; var resolverCache = new TypeDefinitionCache(); // Load reference libraries foreach (var lib in options.LibraryPaths) { resolver.SearchDirectories.Add(lib); } foreach (var reference in references) { resolver.SearchDirectories.Add(Path.GetDirectoryName(reference)); } // Figure out if this is class-parse string apiXmlFile = filename; string apiSourceAttr = null; using (var xr = XmlReader.Create(filename, new XmlReaderSettings { XmlResolver = null })) { xr.MoveToContent(); apiSourceAttr = xr.GetAttribute("api-source"); } // We don't use shallow referenced types with class-parse because the Adjuster process // enumerates every ctor/method/property/field to build its model, so we will need // every type to be fully populated. opt.UseShallowReferencedTypes = apiSourceAttr != "class-parse"; foreach (var reference in references.Distinct()) { try { Report.Verbose(0, "resolving assembly {0}.", reference); var assembly = resolver.Load(reference); foreach (var md in assembly.Modules) { foreach (var td in md.Types) { // FIXME: at some stage we want to import generic types. // For now generator fails to load generic types that have conflicting type e.g. // AdapterView`1 and AdapterView cannot co-exist. // It is mostly because generator primarily targets jar (no real generics land). var nonGenericOverload = td.HasGenericParameters ? md.GetType(td.FullName.Substring(0, td.FullName.IndexOf('`'))) : null; if (BindSameType(td, nonGenericOverload, resolverCache)) { continue; } ProcessReferencedType(td, opt); } } } catch (Exception ex) { Report.LogCodedWarning(0, Report.WarningAssemblyParseFailure, ex, reference, ex.Message); } } // For class-parse API description, transform it to jar2xml style. if (apiSourceAttr == "class-parse") { apiXmlFile = api_xml_adjuster_output ?? Path.Combine(Path.GetDirectoryName(filename), Path.GetFileName(filename) + ".adjusted"); new Adjuster().Process(filename, opt, opt.SymbolTable.AllRegisteredSymbols(opt).OfType <GenBase> ().ToArray(), apiXmlFile, Report.Verbosity ?? 0); } if (only_xml_adjuster) { return; } // load XML API definition with fixups. Dictionary <string, EnumMappings.EnumDescription> enums = null; EnumMappings enummap = null; if (enum_fields_map != null || enum_methods_map != null) { enummap = new EnumMappings(enumdir, enum_metadata, api_level, preserve_enums); enums = enummap.Process(enum_fields_map, enum_flags, enum_methods_map); fixups.Add(enum_metadata); } Parser p = new Parser(opt); List <GenBase> gens = p.Parse(apiXmlFile, fixups, api_level, product_version); if (gens == null) { return; } apiSource = p.ApiSource; // disable interface default methods here, especially before validation. gens = gens.Where(g => !g.IsObfuscated && g.Visibility != "private").ToList(); foreach (var gen in gens) { gen.StripNonBindables(opt); if (gen.IsGeneratable) { AddTypeToTable(opt, gen); } } // Apply fixups KotlinFixups.Fixup(gens); Validate(gens, opt, new CodeGeneratorContext()); foreach (var api_versions_xml in options.ApiVersionsXmlFiles) { ApiVersionsSupport.AssignApiLevels(gens, api_versions_xml); } foreach (GenBase gen in gens) { gen.FillProperties(); } var cache = new AncestorDescendantCache(gens); foreach (var gen in gens) { gen.UpdateEnums(opt, cache); } foreach (GenBase gen in gens) { gen.FixupMethodOverrides(opt); } foreach (GenBase gen in gens) { gen.FixupExplicitImplementation(); } SealedProtectedFixups.Fixup(gens); GenerateAnnotationAttributes(gens, annotations_zips); //SymbolTable.Dump (); GenerationInfo gen_info = new GenerationInfo(csdir, javadir, assemblyQN); opt.AssemblyName = gen_info.Assembly; if (mapping_file != null) { GenerateMappingReportFile(gens, mapping_file); } foreach (IGeneratable gen in gens) { if (gen.IsGeneratable) { gen.Generate(opt, gen_info); } } new NamespaceMapping(gens).Generate(opt, gen_info); ClassGen.GenerateTypeRegistrations(opt, gen_info); ClassGen.GenerateEnumList(gen_info); // Create the .cs files for the enums var enumFiles = enums == null ? null : enummap.WriteEnumerations(enumdir, enums, FlattenNestedTypes(gens).ToArray(), opt.UseShortFileNames); gen_info.GenerateLibraryProjectFile(options, enumFiles); }
protected override TDeclarationNode AddProperty <TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList <bool> availableIndices) { CheckDeclarationNode <TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List <ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol) { foreach (var annotation in ((CodeGenerationSymbol)property).GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol) { foreach (var annotation in ((CodeGenerationSymbol)property).GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return(AddMembers(destination, members, availableIndices, options)); } if (destination is TypeDeclarationSyntax) { return(Cast <TDeclarationNode>(PropertyGenerator.AddPropertyTo(Cast <TypeDeclarationSyntax>(destination), property, options, availableIndices))); } else { return(Cast <TDeclarationNode>(PropertyGenerator.AddPropertyTo(Cast <CompilationUnitSyntax>(destination), property, options, availableIndices))); } }
public override TDeclarationNode UpdateDeclarationType <TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { var syntaxNode = declaration as CSharpSyntaxNode; if (syntaxNode == null) { return(declaration); } TypeSyntax newTypeSyntax; switch (syntaxNode.CSharpKind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return(Cast <TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax))); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return(Cast <TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax))); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return(Cast <TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax))); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax))); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax))); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax))); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax))); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax))); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax))); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return(Cast <TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax))); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return(Cast <TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax))); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax))); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return(Cast <TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax))); default: return(declaration); } }
void AddPropertyInvokers(InterfaceGen iface, IEnumerable <Property> properties, HashSet <string> members, CodeGenerationOptions opt, CodeGeneratorContext context) { foreach (var prop in properties) { if (members.Contains(prop.Name)) { continue; } members.Add(prop.Name); Properties.Add(new InterfaceInvokerProperty(iface, prop, opt, context)); } }
public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return(destination == CodeGenerationDestination.EnumType ? (SyntaxNode)EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, destination, options)); }
protected override TDeclarationNode AddMethod <TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList <bool> availableIndices) { CheckDeclarationNode <TypeDeclarationSyntax, CompilationUnitSyntax, PackageDeclarationSyntax>(destination); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return(destination); } if (method.AssociatedSymbol is IPropertySymbol) { // we will ignore the method if the associated property can be generated. var property = (IPropertySymbol)method.AssociatedSymbol; if (PropertyGenerator.CanBeGenerated(property)) { return(destination); } } var typeDeclaration = destination as TypeDeclarationSyntax; if (typeDeclaration != null) { if (method.IsConstructor()) { return(Cast <TDeclarationNode>(ConstructorGenerator.AddConstructorTo(typeDeclaration, method, options, availableIndices))); } if (method.IsDestructor()) { return(Cast <TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices))); } if (method.MethodKind == MethodKind.Conversion) { return(Cast <TDeclarationNode>(ConversionGenerator.AddConversionTo(typeDeclaration, method, options, availableIndices))); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return(Cast <TDeclarationNode>(OperatorGenerator.AddOperatorTo(typeDeclaration, method, options, availableIndices))); } return(Cast <TDeclarationNode>(MethodGenerator.AddMethodTo(typeDeclaration, method, options, availableIndices))); } if (method.IsConstructor() || method.IsDestructor()) { return(destination); } var compilationUnit = destination as CompilationUnitSyntax; if (compilationUnit != null) { return(Cast <TDeclarationNode>(MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices))); } var ns = Cast <PackageDeclarationSyntax>(destination); return(Cast <TDeclarationNode>(MethodGenerator.AddMethodTo(ns, method, options, availableIndices))); }
public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return(EventGenerator.GenerateEventDeclaration(@event, destination, options)); }
public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { return(NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options)); }
private static async Task <Solution> PullMembersIntoClassAsync( Document document, PullMembersUpOptions result, Solution solution, CancellationToken cancellationToken) { var solutionEditor = new SolutionEditor(solution); var codeGenerationService = document.Project.LanguageServices.GetRequiredService <ICodeGenerationService>(); var destinationSyntaxNode = await codeGenerationService.FindMostRelevantNameSpaceOrTypeDeclarationAsync( solution, result.Destination, options : null, cancellationToken).ConfigureAwait(false); var symbolToDeclarations = await InitializeSymbolToDeclarationsMapAsync(result, cancellationToken).ConfigureAwait(false); // Add members to destination var pullUpMembersSymbols = result.MemberAnalysisResults.SelectAsArray( memberResult => { if (memberResult.MakeMemberDeclarationAbstract && !memberResult.Member.IsKind(SymbolKind.Field)) { // Change the member to abstract if user choose to make them abstract return(MakeAbstractVersion(memberResult.Member)); } else { return(memberResult.Member); } }); var options = new CodeGenerationOptions(reuseSyntax: true, generateMethodBodies: false); var newDestination = codeGenerationService.AddMembers(destinationSyntaxNode, pullUpMembersSymbols, options: options, cancellationToken: cancellationToken); // Remove some original members since we are pulling members into class. // Note: If the user chooses to make the member abstract, then the original member will be changed to an override, // and it will pull an abstract declaration up to the destination. // But if the member is abstract itself, it will still be removed. foreach (var analysisResult in result.MemberAnalysisResults) { foreach (var syntax in symbolToDeclarations[analysisResult.Member]) { var originalMemberEditor = await solutionEditor.GetDocumentEditorAsync( solution.GetDocumentId(syntax.SyntaxTree), cancellationToken).ConfigureAwait(false); if (!analysisResult.MakeMemberDeclarationAbstract || analysisResult.Member.IsAbstract) { originalMemberEditor.RemoveNode(originalMemberEditor.Generator.GetDeclaration(syntax)); } else { var declarationSyntax = originalMemberEditor.Generator.GetDeclaration(syntax); originalMemberEditor.ReplaceNode(declarationSyntax, (node, generator) => generator.WithModifiers(node, DeclarationModifiers.Override)); } } } // Change the destination to abstract class if needed. var destinationEditor = await solutionEditor.GetDocumentEditorAsync( solution.GetDocumentId(destinationSyntaxNode.SyntaxTree), cancellationToken).ConfigureAwait(false); if (!result.Destination.IsAbstract && result.MemberAnalysisResults.Any(analysis => analysis.Member.IsAbstract || analysis.MakeMemberDeclarationAbstract)) { var modifiers = DeclarationModifiers.From(result.Destination).WithIsAbstract(true); newDestination = destinationEditor.Generator.WithModifiers(newDestination, modifiers); } destinationEditor.ReplaceNode(destinationSyntaxNode, (syntaxNode, generator) => newDestination); return(solutionEditor.GetChangedSolution()); }
public RobSharperMessagePackageGenerator(CodeGenerationPackageContext package, CodeGenerationOptions options, ProjectCodeGenerationDirectoryContext directories, IKeyedTemplateFormatter templateEngine) : base(package, options, directories, templateEngine) { }
public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return(PropertyGenerator.GeneratePropertyDeclaration(property, destination, options)); }
public string ImportSchemasAsClasses(string[] DocXsds, string ns, CodeGenerationOptions options, StringCollection schemaImporterExtensions) { CodeDomProvider _CodeDomProvider = new CSharpCodeProvider(); string xsdOut = string.Empty; for (int i = 0; i < DocXsds.Length; i++) { pseudoFileStreams[string.Format("urn:rudine.progablab.com/pseudoFile_{0}.xsd", i).ToLower()] = DocXsds[i]; } string[] fileNames = pseudoFileStreams.Keys.ToArray(); string uri = string.Empty; string[] elements = { }; XmlSchemas userSchemas = new XmlSchemas(); Hashtable filePath_xmlSchema = new Hashtable(); Hashtable xmlSchema_uri = new Hashtable(); foreach (string filename in fileNames) { if (!string.IsNullOrEmpty(filename)) { string filePath = filename.ToLower(CultureInfo.InvariantCulture); if (filePath_xmlSchema[filePath] == null) { XmlSchema xmlSchema = ReadSchema(filePath, true); filePath_xmlSchema.Add(filePath, xmlSchema); Uri uri2 = new Uri(filePath); xmlSchema_uri.Add(xmlSchema, uri2); userSchemas.Add(xmlSchema, uri2); } } } Hashtable includeSchemas = new Hashtable(); Compile(userSchemas, xmlSchema_uri, includeSchemas); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); //GenerateVersionComment(codeNamespace); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit, _CodeDomProvider, options, null); XmlSchemaImporter xmlSchemaImporter = new XmlSchemaImporter(userSchemas, options, _CodeDomProvider, new ImportContext(new CodeIdentifiers(), false)); xmlSchemaImporter.Extensions.Add(new DataSetSchemaImporterExtension()); foreach (string current in schemaImporterExtensions) { Type type = Type.GetType(current.Trim(), true, false); xmlSchemaImporter.Extensions.Add(type.FullName, type); } AddImports(codeNamespace, GetNamespacesForTypes(new[] { typeof(XmlAttributeAttribute) })); for (int i = 0; i < userSchemas.Count; i++) { ImportSchemaAsClasses(userSchemas[i], uri, elements, xmlSchemaImporter, codeExporter); } foreach (XmlSchema schema in includeSchemas.Values) { ImportSchemaAsClasses(schema, uri, elements, xmlSchemaImporter, codeExporter); } CodeGenerator.ValidateIdentifiers(codeNamespace); StringBuilder _StringBuilder = new StringBuilder(); using (StringWriter _StringWriter = new StringWriter(_StringBuilder)) _CodeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, _StringWriter, new CodeGeneratorOptions { IndentString = " " }); return(_StringBuilder.ToString()); }
private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccesibility, CodeGenerationOptions options) { var newModifierTokens = new List <SyntaxToken>(); AbstractCSharpCodeGenerator.AddAccessibilityModifiers(newAccesibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return(modifiersList); } return(GetUpdatedDeclarationAccessibilityModifiers(newModifierTokens, modifiersList, (SyntaxToken modifier) => SyntaxFacts.IsAccessibilityModifier(modifier.CSharpKind())) .ToSyntaxTokenList()); }