private void CreateEnum(Type t) { bool flags = TypeHelper.HasCustomAttribute(t, typeof(FlagsAttribute)); EnumDeclaration e = this.ns.AddEnum(this.conformer.ToCapitalized(t.Name), flags); this.types.Add(t, e); }
private void GenerateEnumType(Type t) { EnumDeclaration e = this.ns.Enums[this.conformer.ToCapitalized(t.Name)]; if (e == null) { throw new Exception(); } // generate fields and properties foreach (FieldInfo f in t.GetFields()) { if (f.Name == "Value__") { continue; } var field = e.AddField(f.Name); // add XmlEnum attribute var xmlEnum = new CodeAttributeDeclaration("XmlEnum"); var arg = new CodeAttributeArgument( "Name", new CodePrimitiveExpression(f.Name) ); xmlEnum.Arguments.Add(arg); field.CustomAttributes.Add(xmlEnum); } }
private void GenerateEnumType(Type t) { EnumDeclaration e = this.ns.Enums[this.conformer.ToCapitalized(t.Name)]; e.CustomAttributes.Add(typeof(SerializableAttribute)); if (e == null) { throw new Exception(); } // generate fields and properties foreach (FieldInfo f in t.GetFields()) { if (f.Name == "Value__") { continue; } FieldDeclaration field = e.AddField(f.Name); // add XmlEnum attribute AttributeDeclaration xmlEnum = field.CustomAttributes.Add(typeof(XmlEnumAttribute)); AttributeArgument arg = xmlEnum.Arguments.Add( "Name", Expr.Prim(f.Name) ); } }
public void RoundTripEnum() { ModuleDeclaration module = ReflectToModules("public enum Foo {\ncase a, b, c\n } ", "SomeModule").Find(m => m.Name == "SomeModule"); EnumDeclaration fooClass = module.AllEnums.Where(cl => cl.Name == "Foo").FirstOrDefault(); Assert.IsNotNull(fooClass); EnumDeclaration unrootedFoo = fooClass.MakeUnrooted() as EnumDeclaration; Entity entity = new Entity { SharpNamespace = "SomeModule", SharpTypeName = "Foo", Type = unrootedFoo }; TypeDatabase db = new TypeDatabase(); db.Add(entity); MemoryStream ostm = new MemoryStream(); db.Write(ostm, "SomeModule"); ostm.Seek(0, SeekOrigin.Begin); TypeDatabase dbread = new TypeDatabase(); var errors = dbread.Read(ostm); Utils.CheckErrors(errors); Entity entityRead = dbread.EntityForSwiftName("SomeModule.Foo"); Assert.IsNotNull(entityRead); Assert.AreEqual(entity.SharpNamespace, entityRead.SharpNamespace); Assert.AreEqual(entity.SharpTypeName, entityRead.SharpTypeName); Assert.IsTrue(entity.Type is EnumDeclaration); }
EnumDeclaration ToEnumDeclaration(TypeDefinition definition) { var name = definition.Name; var moduleName = definition.Namespace; TypeAggregator.RemapModuleAndName(platform, ref moduleName, ref name, TypeType.Enum); var module = ToModuleDeclaration(moduleName); var enumDeclaration = new EnumDeclaration { Name = name, Access = ToAccessibility(definition), Module = module, ParentExtension = null, Kind = TypeKind.Enum, Members = new List <Member> (), IsObjC = true, IsDeprecated = false, IsUnavailable = false, }; foreach (var field in definition.Fields) { if (field.Name == "value__") { continue; } enumDeclaration.Elements.Add(ToEnumElement(field)); } return(enumDeclaration.MakeUnrooted() as EnumDeclaration); }
protected override IEnumerable <object> EnumerateReferences(EnumDeclaration record) { yield return(record.AttributeListCollection); yield return(record.BaseList); yield return(record.ConstraintClauseList); yield return(record.ConstructorList); yield return(record.DocumentationCommentList); yield return(record.EnumMemberList); yield return(record.FieldList); yield return(record.Identifier); yield return(record.MethodList); yield return(record.ModifierList); yield return(record.Namespace); yield return(record.PropertyList); yield return(record.TypeParameterList); yield return(record.UsingDirectiveList); }
public void can_create_enum() { var @enum = new EnumDeclaration("TransactionLineTypes"); @enum.AddField("Pending", 1); var builder = new CodeBuilder(); builder.GenerateCode(Console.Out, "Awish.Lars.Core.Enums", @enum); }
public EnumInfo(EnumDeclaration @enum, OutputOption outputOption, ProtoFile proto) { Enum = @enum; Name = @enum.Name.Pascal(); Fields = @enum.Members.ToDictionary(x => x.Name, x => new EnumMemberInfo(x)); Namespace = $"{proto.Option.Namespace}.{outputOption.Namespace ?? "Models"}"; }
protected override object VisitEnumDeclaration(EnumDeclarationSyntax node) { var name = _Name(node.Identifier); var ed = new EnumDeclaration(name); return(ed); }
private CodeCompileUnit CompileOnOffStateEnum() { var declaration = new EnumDeclaration("State", new[] { "On", "Off" }); var model = CreateSemanticModelWith(declaration); return(CodeDomCompiler.Compile(model)); }
private string GenerateEnum(EnumDeclaration e) { var writer = new CodeWriter(); writer.AppendLine(2); if (e.Option.Description != null) { writer.Append($"/** {e.Option.Description} */") .AppendLine(); } writer.Append($"export enum {e.GetTypeName()} {{").AppendLine(); foreach (var field in e.Members) { if (field.Option.Description != null) { writer.Append(' ', 2). Append($"/** {field.Option.Description} */") .AppendLine(); } writer.Append(' ', 2) .Append($"{field.Name.Camel()} = {field.Value},") .AppendLine(); } writer.Append("}"); writer.AppendLine(2); return(writer.ToString()); }
public virtual void Visit(EnumDeclaration enumDeclaration) { Visit(enumDeclaration.Identifier); foreach (var enumValueDeclaration in enumDeclaration.Values) { Visit(enumValueDeclaration); } }
/// <summary> /// Creates a <see cref="EnumTranslationUnitFactory"/>. /// </summary> /// <returns>A <see cref="EnumTranslationUnitFactory"/>.</returns> public ITranslationUnit Create() { EnumDeclaration helper = new EnumDeclaration(this.Node as EnumDeclarationSyntax, this.SemanticModel); var enumDeclaration = this.CreateTranslationUnit(helper.Visibility, IdentifierTranslationUnit.Create(helper.Name)) as EnumTranslationUnit; return(enumDeclaration); }
/// <summary> /// Processes an XmlSchemaSimpleType into corresponding code. /// </summary> /// <param name="typeName">Type name to use.</param> /// <param name="simpleType">XmlSchemaSimpleType to be processed.</param> /// <param name="codeNamespace">CodeNamespace to be used when outputting code.</param> private static void ProcessSimpleType(string typeName, XmlSchemaSimpleType simpleType, CodeNamespace codeNamespace) { XmlSchemaSimpleTypeRestriction simpleTypeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeRestriction != null) { CodeTypeDeclaration typeDeclaration = null; EnumDeclaration enumDeclaration = null; foreach (XmlSchemaFacet facet in simpleTypeRestriction.Facets) { XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet; if (enumFacet != null) { if (enumDeclaration == null) { typeDeclaration = new CodeTypeDeclaration(typeName); typeDeclaration.Attributes = MemberAttributes.Public; typeDeclaration.IsEnum = true; enumDeclaration = new EnumDeclaration(typeName, typeDeclaration); typeNamesToEnumDeclarations.Add(typeName, enumDeclaration); codeNamespace.Types.Add(typeDeclaration); simpleTypeNamesToClrTypeNames.Add(typeName, typeName); string typeDocumentation = GetDocumentation(simpleType.Annotation); if (typeDocumentation != null) { GenerateSummaryComment(typeDeclaration.Comments, typeDocumentation); } } string enumValue = MakeEnumValue(enumFacet.Value); enumDeclaration.AddValue(enumFacet.Value); CodeMemberField memberField = new CodeMemberField(typeof(int), enumValue); typeDeclaration.Members.Add(memberField); string documentation = GetDocumentation(enumFacet.Annotation); if (documentation != null) { GenerateSummaryComment(memberField.Comments, documentation); } } } if (typeDeclaration == null) { string baseTypeName = simpleTypeRestriction.BaseTypeName.Name; if (baseTypeName == "nonNegativeInteger" || baseTypeName == "integer") { simpleTypeNamesToClrTypeNames.Add(typeName, "int"); } else if (baseTypeName == "string" || baseTypeName == "NMTOKEN") { simpleTypeNamesToClrTypeNames.Add(typeName, "string"); } } } }
private IodineEnum CompileEnum(EnumDeclaration enumDecl) { IodineEnum ienum = new IodineEnum(enumDecl.Name); foreach (string name in enumDecl.Items.Keys) { ienum.AddItem(name, enumDecl.Items [name]); } return(ienum); }
/// <summary> /// Determines whether this StringEnumDeclarationDictionary contains a specific value. /// </summary> /// <param name="value"> /// The EnumDeclaration value to locate in this StringEnumDeclarationDictionary. /// </param> /// <returns> /// true if this StringEnumDeclarationDictionary contains an element with the specified value; /// otherwise, false. /// </returns> public virtual bool ContainsValue(EnumDeclaration value) { foreach (EnumDeclaration item in this.Dictionary.Values) { if (item == value) { return(true); } } return(false); }
public override void Accept(EnumDeclaration enumDecl) { IodineEnum ienum = new IodineEnum(enumDecl.Name); foreach (string name in enumDecl.Items.Keys) { ienum.AddItem(name, enumDecl.Items [name]); } methodBuilder.EmitInstruction(enumDecl.Location, Opcode.LoadConst, methodBuilder.Module.DefineConstant(ienum)); methodBuilder.EmitInstruction(enumDecl.Location, Opcode.StoreLocal, symbolTable.GetSymbol(enumDecl.Name).Index); }
public void TestEnumDeclaration() { EnumDeclaration node = new EnumDeclaration( GetSymbolAtom(), new List <EnumMemberDeclaration> { new EnumMemberDeclaration(GetSymbolAtom(), GetExpression1(), Declaration.DeclarationFlags.Export, GetExpressionList(), DefaultLineInfo), new EnumMemberDeclaration(GetSymbolAtom(), GetExpression2(), Declaration.DeclarationFlags.Export, GetExpressionList(), DefaultLineInfo) }, GetExpressionList(), Declaration.DeclarationFlags.Export, DefaultLineInfo); CheckSerializationRoundTrip(node); }
public CSharpSyntaxNode Convert(EnumDeclaration node) { EnumDeclarationSyntax csEnum = SyntaxFactory.EnumDeclaration(node.Name.Text); csEnum = csEnum.AddModifiers(node.Modifiers.ToCsNodes <SyntaxToken>()); csEnum = csEnum.AddMembers(node.Members.ToCsNodes <EnumMemberDeclarationSyntax>()); if (node.JsDoc.Count > 0) { csEnum = csEnum.WithLeadingTrivia(SyntaxFactory.Trivia(node.JsDoc[0].ToCsNode <DocumentationCommentTriviaSyntax>())); } return(csEnum); }
public override int GetHashCode() { unchecked { var hashCode = (ColumnInfo != null ? ColumnInfo.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (NewColumnName != null ? NewColumnName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ IsRowVersion.GetHashCode(); hashCode = (hashCode * 397) ^ PrimaryKey.GetHashCode(); hashCode = (hashCode * 397) ^ InsertIgnore.GetHashCode(); hashCode = (hashCode * 397) ^ (EnumDeclaration != null ? EnumDeclaration.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Exclude.GetHashCode(); hashCode = (hashCode * 397) ^ (ForgeinKeyDeclarations != null ? ForgeinKeyDeclarations.GetHashCode() : 0); return(hashCode); } }
public void DtoDeclaration_WithNestedDto_Enum_ShouldCompile() { var enumDeclaration = new EnumDeclaration("Role", new[] { "Tester", "Developer" }); var employeeInfoDto = new DtoDeclaration( "EmployeeInfo", new[] { new PropertyDeclaration("EmployeeRole", new TypeName("Role")) } ); var source = CompileToSource(CodeDomCompiler .Compile(CreateSemanticModelWith(enumDeclaration, employeeInfoDto))); Assert.That(source, Is.StringMatching(@"public\s+Role\s+EmployeeRole")); }
public void EnumSmokeTest1() { string code = "public enum foo { case a, b, c, d }"; ModuleDeclaration module = ReflectToModules(code, "SomeModule").Find(m => m.Name == "SomeModule"); Assert.IsNotNull(module); Assert.AreEqual(1, module.AllEnums.Count); EnumDeclaration edecl = module.AllEnums.First(); Assert.AreEqual(edecl.Name, "foo"); Assert.AreEqual(4, edecl.Elements.Count); Assert.IsTrue(edecl.IsTrivial); Assert.IsTrue(edecl.IsHomogenous); Assert.IsFalse(edecl.HasRawType); }
private static void __Execute(atom.Trace context, int level, EnumDeclaration data, string file, bool isShowPrivate) { if (__IsEnabled(data, isShowPrivate)) { context. SetComment(__GetType(data, "enum"), "[[[Data Type]]]"). SetUrl(file, __GetLine(data, data.Name.Pos.Value), __GetPosition(data, data.Name.Pos.Value)). Send(NAME.SOURCE.PREVIEW, NAME.TYPE.CLASS, level, __GetName(data.Name, true)); foreach (var a_Context in data.Members.OfType <EnumMember>()) { context. SetComment("int", "[[[Data Type]]]"). SetUrl(file, __GetLine(a_Context, a_Context.Name.Pos.Value), __GetPosition(a_Context, a_Context.Name.Pos.Value)). Send(NAME.SOURCE.PREVIEW, NAME.TYPE.PARAMETER, level + 1, __GetName(a_Context.Name, false)); } } }
protected override async Task <EnumDeclaration> AssignUpsertedReferences(EnumDeclaration record) { record.AttributeListCollection = await _attributeLists.UpsertAsync(record.AttributeListCollection); record.AttributeListCollectionId = record.AttributeListCollection?.AttributeListCollectionId ?? record.AttributeListCollectionId; record.BaseList = await _baseLists.UpsertAsync(record.BaseList); record.BaseListId = record.BaseList?.BaseListId ?? record.BaseListId; record.ConstraintClauseList = await _constraintClauseLists.UpsertAsync(record.ConstraintClauseList); record.ConstraintClauseListId = record.ConstraintClauseList?.ConstraintClauseListId ?? record.ConstraintClauseListId; record.ConstructorList = await _constuctorLists.UpsertAsync(record.ConstructorList); record.ConstructorListId = record.ConstructorList?.ConstructorListId ?? record.ConstructorListId; record.DocumentationCommentList = await _documentationCommentLists.UpsertAsync(record.DocumentationCommentList); record.DocumentationCommentListId = record.DocumentationCommentList?.DocumentationCommentListId ?? record.DocumentationCommentListId; record.EnumMemberList = await _enumMemberLists.UpsertAsync(record.EnumMemberList); record.EnumMemberListId = record.EnumMemberList?.EnumMemberListId ?? record.EnumMemberListId; record.FieldList = await _fieldLists.UpsertAsync(record.FieldList); record.FieldListId = record.FieldList?.FieldListId ?? record.FieldListId; record.Identifier = await _identifiers.UpsertAsync(record.Identifier); record.IdentifierId = record.Identifier?.IdentifierId ?? record.IdentifierId; record.MethodList = await _methodLists.UpsertAsync(record.MethodList); record.MethodListId = record.MethodList?.MethodListId ?? record.MethodListId; record.ModifierList = await _modifierLists.UpsertAsync(record.ModifierList); record.ModifierListId = record.ModifierList?.ModifierListId ?? record.ModifierListId; record.Namespace = await _namespaces.UpsertAsync(record.Namespace); record.NamespaceId = record.Namespace?.NamespaceId ?? record.NamespaceId; record.PropertyList = await _propertyLists.UpsertAsync(record.PropertyList); record.PropertyListId = record.PropertyList?.PropertyListId ?? record.PropertyListId; record.TypeParameterList = await _typeParameterLists.UpsertAsync(record.TypeParameterList); record.TypeParameterListId = record.TypeParameterList?.TypeParameterListId ?? record.TypeParameterListId; record.UsingDirectiveList = await _usingDirectiveLists.UpsertAsync(record.UsingDirectiveList); record.UsingDirectiveListId = record.UsingDirectiveList?.UsingDirectiveListId ?? record.UsingDirectiveListId; return(record); }
public void CommandDeclaration_WithNestedDto_Enum_ShouldCompile() { var enumDeclaration = new EnumDeclaration("Role", new[] { "Tester", "Developer" }); var commandDeclaration = new CommandDeclaration("ImportEmployeeCommand", new[] { new PropertyDeclaration("EmployeeNumber", new SimpleType(typeof(int))), new PropertyDeclaration("Role", new TypeName("Role")), }); var model = CreateSemanticModelWith(enumDeclaration, commandDeclaration); var actual = CodeDomCompiler.Compile(model); Assert.That(actual, Is.Not.Null); var source = CompileToSource(actual); Assert.That(source, Is.StringContaining("class ImportEmployeeCommand")); Assert.That(source, Is.StringMatching(@"public.*Role\s+Role")); }
public void DomainEventDeclaration_WithNestedDto_Enum_ShouldCompile() { var enumDeclaration = new EnumDeclaration("Role", new[] { "Tester", "Developer" }); var eventDeclaration = new DomainEventDeclaration( "EmployeeImported", new[] { new PropertyDeclaration( "EmployeeNumber", new SimpleType(typeof(int))), new PropertyDeclaration( "EmployeeRole", new TypeName("Role")) }); var model = CreateSemanticModelWith(enumDeclaration, eventDeclaration); var actual = CodeDomCompiler.Compile(model); var source = CompileToSource(actual); Assert.That(source, Is.StringMatching(@"Role\s+EmployeeRole")); }
protected override async Task <EnumDeclaration> AssignUpsertedReferences(EnumDeclaration record) { record.DocumentationComment = await _documentationComments.UpsertAsync(record.DocumentationComment); record.DocumentationCommentId = record.DocumentationComment?.DocumentationCommentId ?? record.DocumentationCommentId; record.EnumMemberList = await _enumMemberLists.UpsertAsync(record.EnumMemberList); record.EnumMemberListId = record.EnumMemberList?.EnumMemberListId ?? record.EnumMemberListId; record.Identifier = await _identifiers.UpsertAsync(record.Identifier); record.IdentifierId = record.Identifier?.IdentifierId ?? record.IdentifierId; record.ImportStatementList = await _importStatementLists.UpsertAsync(record.ImportStatementList); record.ImportStatementListId = record.ImportStatementList?.ImportStatementListId ?? record.ImportStatementListId; record.Namespace = await _namespaces.UpsertAsync(record.Namespace); record.NamespaceId = record.Namespace?.NamespaceId ?? record.NamespaceId; return(record); }
public bool TryDeclareEnum(EnumDeclaration declaration) { if (TryGetEnum(declaration.Identifier.Text, out _)) { return(false); } var enumType = new Enum { Declaration = declaration, Members = declaration.Values.ToDictionary(x => x.Identifier.Text, y => y.Value) }; int nextMemberValue = 0; bool anyImplicitValues = false; for (int i = 0; i < enumType.Members.Count; i++) { var key = enumType.Members.Keys.ElementAt(i); var value = enumType.Members[key]; if (value == null) { enumType.Members[key] = new IntLiteral(nextMemberValue++); anyImplicitValues = true; } else { if (!TryGetNextMemberValue(enumType.Members, value, out nextMemberValue)) { // Only error if there are any implicit values if (anyImplicitValues) { return(false); } } } } Enums[declaration.Identifier.Text] = enumType; return(true); }
public override bool TryParse(TokenStack tokens, out GraphNode node) { if (tokens.ExpectSequence(TokenType.EnumKeyword, TokenType.Identifier, TokenType.OpenCurlyBraceSymbol)) { var source = new Queue <Token>(); var enumKeyword = tokens.Pop(); var identifier = tokens.Pop(); var openBrace = tokens.Pop(); source.Enqueue(enumKeyword); source.Enqueue(identifier); source.Enqueue(openBrace); var enumValues = new List <EnumValue>(); var enumBodySyntax = new EnumValueSyntax(); while (tokens.Peek().TokenType != TokenType.CloseCurlyBraceSymbol) { if (enumBodySyntax.TryParse(tokens, out GraphNode enumValue)) { enumValues.Add((EnumValue)enumValue); } else { // TODO: Set error message node = null; return(false); } } var closeBrace = tokens.Pop(); source.Enqueue(closeBrace); node = new EnumDeclaration(source, identifier.Value, enumValues); return(true); } // TODO: Set error message node = null; return(false); }
/// <summary> /// Génère le code d'une enum. /// </summary> /// <param name="decl"></param> /// <returns></returns> string GenerateEnumInstruction(EnumDeclaration decl) { StringBuilder builder = new StringBuilder(); builder.Append("public enum " + decl.Name + "\n{\n"); foreach (var kvp in decl.Members) { string member = kvp.Key; int value = kvp.Value; builder.Append(Tools.StringUtils.Indent(member, 1)); builder.Append(" = " + value.ToString()); if (kvp.Key != decl.Members.Last().Key) { builder.Append(','); } builder.Append("\n"); } builder.Append("}\n"); return(builder.ToString()); }
public void EnumSmokeTest3() { string code = "public enum foo { case a(UInt), b(Int), c(Int), d(Int) }"; ModuleDeclaration module = ReflectToModules(code, "SomeModule").Find(m => m.Name == "SomeModule"); Assert.IsNotNull(module); Assert.AreEqual(1, module.AllEnums.Count); EnumDeclaration edecl = module.AllEnums.First(); Assert.AreEqual(edecl.Name, "foo"); Assert.AreEqual(4, edecl.Elements.Count); foreach (EnumElement elem in edecl.Elements) { Assert.IsTrue(elem.HasType); } Assert.IsFalse(edecl.IsTrivial); Assert.IsTrue(edecl.IsIntegral); Assert.IsFalse(edecl.IsHomogenous); Assert.IsFalse(edecl.HasRawType); }
/// <summary> /// Generates the specified writer. /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="nameField">The name field.</param> /// <param name="valueField">The value field.</param> public virtual ICodeDom<CodeTypeDeclaration> Generate(string tableName, string nameField, string valueField) { if (String.IsNullOrEmpty(tableName)) { throw new ArgumentException("tableName is null or empty.", "tableName"); } var tableSchema = _dbProvider.GetTableSchema(tableName); if (tableSchema == null) { throw new HyperActiveException("Table {0} was not found in the database. Check your spelling and make sure that's the table you wanted.", tableName); } string internalNameField = GetNameField(nameField, tableSchema); if (String.IsNullOrEmpty(internalNameField)) { return null; } string internalValueField = GetValueField(valueField, tableSchema); if (String.IsNullOrEmpty(internalValueField)) { return null; } var data = _dbProvider.GetTableEnumData(tableName, internalNameField, internalValueField); if (data.Count == 0) { return null; } var @enum = new EnumDeclaration(_nameProvider.GetEnumName(tableName)); foreach (var kvp in data) { var field = @enum.AddField(_nameProvider.GetEnumFieldName(kvp.Key), kvp.Value); field.AddComment("{0} has the value of {1}", field.Name, kvp.Value); } return @enum; }
/// <summary> /// Processes an XmlSchemaSimpleType into corresponding code. /// </summary> /// <param name="simpleTypeName">Name for the type.</param> /// <param name="simpleType">XmlSchemaSimpleType to be processed.</param> /// <param name="codeNamespace">CodeNamespace to be used when outputting code for global types.</param> /// <param name="parentTypeDeclaration">CodeTypeDeclaration to be used when outputting code for nested types.</param> /// <param name="outputXmlMethod">Member method for the OutputXml method for nested types.</param> /// <param name="setAttributeMethod">Member method for the SetAttribute method for nested types.</param> private static void ProcessSimpleType(string simpleTypeName, XmlSchemaSimpleType simpleType, bool nestedType, out EnumDeclaration enumDeclaration, out string baseTypeName) { enumDeclaration = null; baseTypeName = null; // XSD supports simpleTypes derived by union, list, or restriction; restrictions can have any // combination of pattern, enumeration, length, and more; lists can contain any other simpleType. // XsdGen, in contrast, only supports a limited set of values... // Unions are weakly supported by just using the first member type // restrictions must either be all enumeration or a single pattern, a list must be of a // single simpleType which itself is only a restriction of enumeration. if (simpleType.Content is XmlSchemaSimpleTypeUnion) { XmlSchemaSimpleTypeUnion union = simpleType.Content as XmlSchemaSimpleTypeUnion; if (union.MemberTypes.Length > 0) { baseTypeName = union.MemberTypes[0].Name; return; } else { baseTypeName = "string"; return; } } bool listType = false; // XSD lists become [Flag]enums in C#... XmlSchemaSimpleTypeList simpleTypeList = simpleType.Content as XmlSchemaSimpleTypeList; XmlSchemaSimpleTypeRestriction simpleTypeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeList != null) { baseTypeName = simpleTypeList.ItemTypeName.Name; if (String.IsNullOrEmpty(baseTypeName)) { simpleTypeRestriction = simpleTypeList.ItemType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeRestriction == null) { string appName = typeof(XsdGen).Assembly.GetName().Name; throw new NotImplementedException(string.Format("{0} does not support a <list> that does not contain a <simpleType>/<restriction>.", appName)); } listType = true; } else { // We expect to find an existing enum already declared! EnumDeclaration existingEnumDeclaration = typeNamesToEnumDeclarations[baseTypeName]; // TODO: do we need to further alter the Flags setter code because of the helper stuff? // As far as I can tell, this code is never exercised by our existing XSDs! existingEnumDeclaration.SetFlags(); } } if (simpleTypeRestriction == null) { string appName = typeof(XsdGen).Assembly.GetName().Name; throw new NotImplementedException(string.Format("{0} does not understand this simpleType!", appName)); } bool foundPattern = false; foreach (XmlSchemaFacet facet in simpleTypeRestriction.Facets) { XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet; XmlSchemaPatternFacet patternFacet = facet as XmlSchemaPatternFacet; if (enumFacet != null) { if (foundPattern) { string appName = typeof(XsdGen).Assembly.GetName().Name; throw new NotImplementedException(string.Format("{0} does not support restrictions containing both <pattern> and <enumeration>.", appName)); } if (enumDeclaration == null) { // For nested types, the simple name comes from the attribute name, with "Type" appended // to prevent name collision with the attribute member itself. if (nestedType) { simpleTypeName = String.Concat(simpleTypeName, "Type"); } baseTypeName = simpleTypeName; string typeDocumentation = GetDocumentation(simpleType.Annotation); enumDeclaration = new EnumDeclaration(simpleTypeName, typeDocumentation); } string documentation = GetDocumentation(enumFacet.Annotation); enumDeclaration.AddValue(enumFacet.Value, documentation); } if (patternFacet != null) { if (enumDeclaration != null) { string appName = typeof(XsdGen).Assembly.GetName().Name; throw new NotImplementedException(string.Format("{0} does not support restrictions containing both <pattern> and <enumeration>.", appName)); } if (foundPattern) { string appName = typeof(XsdGen).Assembly.GetName().Name; throw new NotImplementedException(string.Format("{0} does not support restrictions multiple <pattern> elements.", appName)); } foundPattern = true; } } if (enumDeclaration != null && listType) { enumDeclaration.SetFlags(); } if (String.IsNullOrEmpty(baseTypeName)) { baseTypeName = (string)simpleTypeNamesToClrTypeNames[simpleTypeRestriction.BaseTypeName.Name]; } }
private static void AddEnumHelperMethods(EnumDeclaration enumDeclaration, CodeTypeDeclaration parentType) { CodeTypeReference stringType = new CodeTypeReference(typeof(string)); CodeTypeReference boolType = new CodeTypeReference(typeof(bool)); CodeTypeReference enumType = new CodeTypeReference(typeof(Enum)); CodeTypeReference newEnumType = new CodeTypeReference(enumDeclaration.Name); CodePrimitiveExpression falseValue = new CodePrimitiveExpression(false); CodePrimitiveExpression trueValue = new CodePrimitiveExpression(true); CodeMethodReturnStatement returnFalse = new CodeMethodReturnStatement(falseValue); CodeMethodReturnStatement returnTrue = new CodeMethodReturnStatement(trueValue); string parseMethodName = String.Concat("Parse", enumDeclaration.Name); string tryParseMethodName = String.Concat("TryParse", enumDeclaration.Name); CodeFieldReferenceExpression defaultEnumValue = null; CodeFieldReferenceExpression illegalEnumValue = null; bool addParse = true; if (enumDeclaration.Flags) { defaultEnumValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(newEnumType), "None"); illegalEnumValue = defaultEnumValue; // Because there's no "IllegalValue" for [Flags] enums, we can't create the Parse() // method. We can still create the TryParse() method, though! addParse = false; } else { defaultEnumValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(newEnumType), "NotSet"); illegalEnumValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(newEnumType), "IllegalValue"); } if (addParse) { CodeMemberMethod parseNewEnum = new CodeMemberMethod(); GenerateSummaryComment(parseNewEnum.Comments, String.Format("Parses a {0} from a string.", enumDeclaration.Name)); parseNewEnum.Attributes = MemberAttributes.Public | MemberAttributes.Static; parseNewEnum.Name = parseMethodName; parseNewEnum.ReturnType = newEnumType; parseNewEnum.Parameters.Add(new CodeParameterDeclarationExpression(stringType, "value")); parseNewEnum.Statements.Add(new CodeVariableDeclarationStatement(newEnumType, "parsedValue")); // Just delegate to the TryParse version... parseNewEnum.Statements.Add(new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(parentType.Name), tryParseMethodName), new CodeArgumentReferenceExpression("value"), new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("parsedValue")))); parseNewEnum.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("parsedValue"))); parentType.Members.Add(parseNewEnum); } CodeMemberMethod tryParseNewEnum = new CodeMemberMethod(); GenerateSummaryComment(tryParseNewEnum.Comments, String.Format("Tries to parse a {0} from a string.", enumDeclaration.Name)); tryParseNewEnum.Attributes = MemberAttributes.Public | MemberAttributes.Static; tryParseNewEnum.Name = tryParseMethodName; tryParseNewEnum.ReturnType = boolType; CodeParameterDeclarationExpression valueDeclaration = new CodeParameterDeclarationExpression(stringType, "value"); CodeParameterDeclarationExpression parsedValueDeclaration = new CodeParameterDeclarationExpression(newEnumType, "parsedValue"); parsedValueDeclaration.Direction = FieldDirection.Out; tryParseNewEnum.Parameters.Add(valueDeclaration); tryParseNewEnum.Parameters.Add(parsedValueDeclaration); CodeArgumentReferenceExpression value = new CodeArgumentReferenceExpression(valueDeclaration.Name); CodeArgumentReferenceExpression parsedValue = new CodeArgumentReferenceExpression(parsedValueDeclaration.Name); tryParseNewEnum.Statements.Add(new CodeAssignStatement(parsedValue, defaultEnumValue)); tryParseNewEnum.Statements.Add(new CodeConditionStatement( new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(stringType), "IsNullOrEmpty"), value), returnFalse)); // The structure is similar, but distinct, for regular and flag-style enums. In particular, // for a flags-style enum we have to be able to parse multiple values, separated by // spaces, and each value is bitwise-OR'd together. CodeStatementCollection nestedIfParent = tryParseNewEnum.Statements; CodeExpression valueToTest = value; // For Flags-style enums, we need to loop over the space-separated values... if (enumDeclaration.Flags) { CodeVariableDeclarationStatement split = new CodeVariableDeclarationStatement(typeof(string[]), "splitValue", new CodeMethodInvokeExpression(value, "Split", new CodeMethodInvokeExpression(new CodePrimitiveExpression(" \t\r\n"), "ToCharArray"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(StringSplitOptions)), "RemoveEmptyEntries"))); tryParseNewEnum.Statements.Add(split); CodeIterationStatement flagLoop = new CodeIterationStatement( new CodeVariableDeclarationStatement(typeof(IEnumerator), "enumerator", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(split.Name), "GetEnumerator")), new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("enumerator"), "MoveNext"), new CodeSnippetStatement("")); tryParseNewEnum.Statements.Add(flagLoop); CodeVariableDeclarationStatement currentValue = new CodeVariableDeclarationStatement(typeof(string), "currentValue", new CodeCastExpression(stringType, new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("enumerator"), "Current"))); flagLoop.Statements.Add(currentValue); valueToTest = new CodeVariableReferenceExpression(currentValue.Name); nestedIfParent = flagLoop.Statements; } // We can't just Enum.Parse, because some values are also keywords (like 'string', 'int', 'default'), // and these get generated as '@'-prefixed values. Instead, we 'switch' on the value and do it manually. // Actually, we if/else, because CodeDom doesn't support 'switch'! Also, we nest the successive 'if's // in order to short-circuit the parsing as soon as there's a match. foreach (string enumValue in enumDeclaration.Values) { CodeFieldReferenceExpression enumValueReference = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(newEnumType), MakeEnumValue(enumValue)); CodeConditionStatement ifStatement = new CodeConditionStatement( new CodeBinaryOperatorExpression(new CodePrimitiveExpression(enumValue), CodeBinaryOperatorType.ValueEquality, valueToTest)); if (enumDeclaration.Flags) { ifStatement.TrueStatements.Add(new CodeAssignStatement(parsedValue, new CodeBinaryOperatorExpression(parsedValue, CodeBinaryOperatorType.BitwiseOr, enumValueReference))); } else { ifStatement.TrueStatements.Add(new CodeAssignStatement(parsedValue, enumValueReference)); } nestedIfParent.Add(ifStatement); nestedIfParent = ifStatement.FalseStatements; } // Finally, if we didn't find a match, it's illegal (or none, for flags)! nestedIfParent.Add(new CodeAssignStatement(parsedValue, illegalEnumValue)); nestedIfParent.Add(returnFalse); tryParseNewEnum.Statements.Add(returnTrue); parentType.Members.Add(tryParseNewEnum); enumsToParseMethodClasses.Add(enumDeclaration, parentType); }
private static void AddEnumHelperMethods(EnumDeclaration enumDeclaration, CodeNamespace codeNamespace) { if (enumHelperClass == null) { enumHelperClass = new CodeTypeDeclaration("Enums"); enumHelperClass.CustomAttributes.Add(GetGeneratedCodeAttribute()); // The static and final attributes don't seem to get applied, but we'd prefer if they were. enumHelperClass.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final; codeNamespace.Types.Add(enumHelperClass); } AddEnumHelperMethods(enumDeclaration, enumHelperClass); }
/// <summary> /// Generates the private field and public property for a piece of data. /// </summary> /// <param name="propertyName">Name of the property being generated.</param> /// <param name="typeName">Name of the type for the property.</param> /// <param name="typeDeclaration">Type declaration into which the field and property should be placed.</param> /// <param name="outputXmlMethod">Member method for the OutputXml method.</param> /// <param name="enumDeclaration">EnumDeclaration, which is null unless called from a locally defined enum attribute.</param> /// <param name="documentation">Comment string to be placed on the property.</param> /// <param name="nestedContent">If true, the field will be placed in nested content when outputting to XML.</param> /// <param name="requiredField">If true, the generated serialization code will throw if the field is not set.</param> private static void GenerateFieldAndProperty(string propertyName, string typeName, CodeTypeDeclaration typeDeclaration, CodeMemberMethod outputXmlMethod, EnumDeclaration enumDeclaration, string documentation, bool nestedContent, bool requiredField) { string fieldName = String.Concat(propertyName.Substring(0, 1).ToLower(), propertyName.Substring(1), "Field"); string fieldNameSet = String.Concat(fieldName, "Set"); Type type = GetClrTypeByXmlName(typeName); CodeMemberField fieldMember; if (type == null) { fieldMember = new CodeMemberField(typeName, fieldName); } else { fieldMember = new CodeMemberField(type, fieldName); } fieldMember.Attributes = MemberAttributes.Private; typeDeclaration.Members.Add(fieldMember); typeDeclaration.Members.Add(new CodeMemberField(typeof(bool), fieldNameSet)); CodeMemberProperty propertyMember = new CodeMemberProperty(); propertyMember.Attributes = MemberAttributes.Public | MemberAttributes.Final; if (documentation != null) { GenerateSummaryComment(propertyMember.Comments, documentation); } propertyMember.Name = propertyName; if (type == null) { propertyMember.Type = new CodeTypeReference(typeName); } else { propertyMember.Type = new CodeTypeReference(type); } CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(); returnStatement.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); propertyMember.GetStatements.Add(returnStatement); CodeAssignStatement assignmentStatement = new CodeAssignStatement(); propertyMember.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldNameSet), new CodePrimitiveExpression(true))); assignmentStatement.Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); assignmentStatement.Right = new CodePropertySetValueReferenceExpression(); propertyMember.SetStatements.Add(assignmentStatement); CodeConditionStatement fieldSetStatement = new CodeConditionStatement(); fieldSetStatement.Condition = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldNameSet); string clrTypeName = (string)simpleTypeNamesToClrTypeNames[typeName]; switch (clrTypeName) { case "string": if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); } break; case "int": case "uint": if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString"))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString"))); } break; default: if (typeName == "DateTime") { if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString"))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString"))); } break; } if (enumDeclaration == null) { GenerateOutputForEnum(fieldSetStatement, (EnumDeclaration)typeNamesToEnumDeclarations[typeName], fieldName, propertyName); } else { GenerateOutputForEnum(fieldSetStatement, enumDeclaration, fieldName, propertyName); } break; } // TODO: Add throw to falseStatements if required field not set. outputXmlMethod.Statements.Add(fieldSetStatement); typeDeclaration.Members.Add(propertyMember); }
/// <summary> /// Generates the private field and public property for a piece of data. /// </summary> /// <param name="propertyName">Name of the property being generated.</param> /// <param name="typeName">Name of the type for the property.</param> /// <param name="typeDeclaration">Type declaration into which the field and property should be placed.</param> /// <param name="outputXmlMethod">Member method for the OutputXml method.</param> /// <param name="setAttributeMethod">Member method for the SetAttribute method.</param> /// <param name="enumDeclaration">EnumDeclaration, which is null unless called from a locally defined enum attribute.</param> /// <param name="documentation">Comment string to be placed on the property.</param> /// <param name="nestedContent">If true, the field will be placed in nested content when outputting to XML.</param> /// <param name="requiredField">If true, the generated serialization code will throw if the field is not set.</param> private static void GenerateFieldAndProperty(string propertyName, string typeName, CodeTypeDeclaration typeDeclaration, CodeMemberMethod outputXmlMethod, CodeMemberMethod setAttributeMethod, EnumDeclaration enumDeclaration, string documentation, bool nestedContent, bool requiredField) { string fieldName = String.Concat(propertyName.Substring(0, 1).ToLower(), propertyName.Substring(1), "Field"); string fieldNameSet = String.Concat(fieldName, "Set"); Type type = GetClrTypeByXmlName(typeName); CodeMemberField fieldMember; if (type == null) { fieldMember = new CodeMemberField(typeName, fieldName); } else { fieldMember = new CodeMemberField(type, fieldName); } fieldMember.Attributes = MemberAttributes.Private; typeDeclaration.Members.Add(fieldMember); typeDeclaration.Members.Add(new CodeMemberField(typeof(bool), fieldNameSet)); CodeMemberProperty propertyMember = new CodeMemberProperty(); propertyMember.Attributes = MemberAttributes.Public | MemberAttributes.Final; if (documentation != null) { GenerateSummaryComment(propertyMember.Comments, documentation); } propertyMember.Name = propertyName; if (type == null) { propertyMember.Type = new CodeTypeReference(typeName); } else { propertyMember.Type = new CodeTypeReference(type); } if (propertyMember.Name.StartsWith("src")) { propertyMember.CustomAttributes.Add(GetCodeAnalysisSuppressionAttribute("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")); } else if (StronglyTypedClasses.multiUppercaseNameRegex.Match(propertyMember.Name).Success) { propertyMember.CustomAttributes.Add(GetCodeAnalysisSuppressionAttribute("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased")); } CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(); returnStatement.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); propertyMember.GetStatements.Add(returnStatement); CodeAssignStatement assignmentStatement = new CodeAssignStatement(); propertyMember.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldNameSet), new CodePrimitiveExpression(true))); assignmentStatement.Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); assignmentStatement.Right = new CodePropertySetValueReferenceExpression(); propertyMember.SetStatements.Add(assignmentStatement); CodeConditionStatement fieldSetStatement = new CodeConditionStatement(); fieldSetStatement.Condition = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldNameSet); CodeAssignStatement fieldSetAttrStatement = new CodeAssignStatement(); fieldSetAttrStatement.Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldNameSet); fieldSetAttrStatement.Right = new CodePrimitiveExpression(true); CodeConditionStatement attributeNameMatchStatement = new CodeConditionStatement(); attributeNameMatchStatement.Condition = new CodeBinaryOperatorExpression(new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), CodeBinaryOperatorType.IdentityEquality, new CodeVariableReferenceExpression("name")); string clrTypeName = (string)simpleTypeNamesToClrTypeNames[typeName]; switch (clrTypeName) { case "string": if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); attributeNameMatchStatement.TrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeVariableReferenceExpression("value"))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); attributeNameMatchStatement.TrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeVariableReferenceExpression("value"))); } break; case "bool": if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); } attributeNameMatchStatement.TrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Convert"), "ToBoolean", new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); break; case "int": case "long": if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); } attributeNameMatchStatement.TrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Convert"), "ToInt32", new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); break; default: if (typeName == "DateTime") { if (nestedContent) { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteString", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); } else { fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), "ToString", new CodePrimitiveExpression("yyyy-MM-ddTHH:mm:ss"), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture"), "DateTimeFormat")))); } attributeNameMatchStatement.TrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Convert"), "ToDateTime", new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("CultureInfo"), "InvariantCulture")))); break; } if (enumDeclaration == null) { GenerateOutputForEnum(fieldSetStatement, attributeNameMatchStatement, typeNamesToEnumDeclarations[typeName], fieldName, propertyName); } else { GenerateOutputForEnum(fieldSetStatement, attributeNameMatchStatement, enumDeclaration, fieldName, propertyName); } break; } attributeNameMatchStatement.TrueStatements.Add(fieldSetAttrStatement); // TODO: Add throw to falseStatements if required field not set. outputXmlMethod.Statements.Add(fieldSetStatement); setAttributeMethod.Statements.Add(attributeNameMatchStatement); typeDeclaration.Members.Add(propertyMember); }
/** * Call back method that must be called as soon as the given <code> * EnumDeclaration</code> object has been traversed. * * @param pEnumDeclaration The <code>EnumDeclaration</code> object that has * just been traversed. */ public void actionPerformed( EnumDeclaration pEnumDeclaration) { // Nothing to do. }
/// <summary> /// Generates output for an enum type. Will generate a switch statement for normal enums, and if statements /// for a flags enum. /// </summary> /// <param name="fieldSetStatement">If statement to add statements to.</param> /// <param name="enumDeclaration">Enum declaration for this field. Could be locally defined enum or global.</param> /// <param name="fieldName">Name of the private field.</param> /// <param name="propertyName">Name of the property (and XML attribute).</param> private static void GenerateOutputForEnum(CodeConditionStatement fieldSetStatement, EnumDeclaration enumDeclaration, string fieldName, string propertyName) { if (enumDeclaration.Flags) { CodeVariableDeclarationStatement outputValueVariable = new CodeVariableDeclarationStatement(typeof(string), "outputValue", new CodeSnippetExpression("\"\"")); fieldSetStatement.TrueStatements.Add(outputValueVariable); foreach (string key in enumDeclaration.Values) { CodeConditionStatement enumIfStatement = new CodeConditionStatement(); enumIfStatement.Condition = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), CodeBinaryOperatorType.BitwiseAnd, new CodePropertyReferenceExpression(new CodeSnippetExpression(enumDeclaration.Name), MakeEnumValue(key))), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression("0")); CodeConditionStatement lengthIfStatement = new CodeConditionStatement(); lengthIfStatement.Condition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("outputValue"), "Length"), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression("0")); lengthIfStatement.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("outputValue"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("outputValue"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("\" \"")))); enumIfStatement.TrueStatements.Add(lengthIfStatement); enumIfStatement.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("outputValue"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("outputValue"), CodeBinaryOperatorType.Add, new CodeSnippetExpression(String.Concat("\"", key, "\""))))); fieldSetStatement.TrueStatements.Add(enumIfStatement); } fieldSetStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeSnippetExpression(String.Concat("outputValue")))); } else { foreach (string key in enumDeclaration.Values) { CodeConditionStatement enumIfStatement = new CodeConditionStatement(); enumIfStatement.Condition = new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), CodeBinaryOperatorType.ValueEquality, new CodePropertyReferenceExpression(new CodeSnippetExpression(enumDeclaration.Name), MakeEnumValue(key))); enumIfStatement.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteAttributeString", new CodeSnippetExpression(String.Concat("\"", propertyName, "\"")), new CodeSnippetExpression(String.Concat("\"", key, "\"")))); fieldSetStatement.TrueStatements.Add(enumIfStatement); } } }
/** * Call back method that must be called when the given <code>EnumDeclaration * </code> will become the next <i>traverse candidate</i>. * * @param pEnumDeclaration The <code>EnumDeclaration</code> object that will * become the next <i>traverse candidate</i>. */ public void performAction( EnumDeclaration pEnumDeclaration) { // Nothing to do. }
/// <summary> /// Processes an attribute, generating the required field and property. Potentially generates /// an enum for an attribute restriction. /// </summary> /// <param name="attribute">Attribute element being processed.</param> /// <param name="typeDeclaration">CodeTypeDeclaration to be used when outputting code.</param> /// <param name="outputXmlMethod">Member method for the OutputXml method.</param> private static void ProcessAttribute(XmlSchemaAttribute attribute, CodeTypeDeclaration typeDeclaration, CodeMemberMethod outputXmlMethod) { string attributeName = attribute.Name; string rawAttributeType = attribute.SchemaTypeName.Name; string attributeType = null; EnumDeclaration enumDeclaration = null; if (rawAttributeType == null || rawAttributeType.Length == 0) { XmlSchemaSimpleTypeRestriction simpleTypeRestriction = attribute.SchemaType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeRestriction != null) { attributeType = String.Concat(attributeName, "Type"); bool enumRestriction = false; CodeTypeDeclaration enumTypeDeclaration = new CodeTypeDeclaration(attributeType); enumTypeDeclaration.Attributes = MemberAttributes.Public; enumTypeDeclaration.IsEnum = true; enumDeclaration = new EnumDeclaration(attributeType, enumTypeDeclaration); foreach (XmlSchemaFacet facet in simpleTypeRestriction.Facets) { XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet; if (enumFacet != null) { enumRestriction = true; string enumValue = MakeEnumValue(enumFacet.Value); enumDeclaration.AddValue(enumFacet.Value); CodeMemberField memberField = new CodeMemberField(typeof(int), enumValue); enumTypeDeclaration.Members.Add(memberField); string enumItemDocumentation = GetDocumentation(enumFacet.Annotation); if (enumItemDocumentation != null) { GenerateSummaryComment(memberField.Comments, enumItemDocumentation); } } XmlSchemaPatternFacet patternFacet = facet as XmlSchemaPatternFacet; if (patternFacet != null) { attributeType = (string)simpleTypeNamesToClrTypeNames[simpleTypeRestriction.BaseTypeName.Name]; } } if (enumRestriction) { typeDeclaration.Members.Add(enumTypeDeclaration); } else { enumDeclaration = null; } } XmlSchemaSimpleTypeList simpleTypeList = attribute.SchemaType.Content as XmlSchemaSimpleTypeList; if (simpleTypeList != null) { attributeType = simpleTypeList.ItemTypeName.Name; EnumDeclaration declaration = (EnumDeclaration)typeNamesToEnumDeclarations[attributeType]; declaration.Flags = true; } } else { attributeType = (string)simpleTypeNamesToClrTypeNames[rawAttributeType]; } string documentation = GetDocumentation(attribute.Annotation); // TODO: Handle required fields. GenerateFieldAndProperty(attributeName, attributeType, typeDeclaration, outputXmlMethod, enumDeclaration, documentation, false, false); }
/// <summary> /// Processes an XmlSchemaSimpleType into corresponding code. /// </summary> /// <param name="typeName">Type name to use.</param> /// <param name="simpleType">XmlSchemaSimpleType to be processed.</param> /// <param name="codeNamespace">CodeNamespace to be used when outputting code.</param> private static void ProcessSimpleType(string typeName, XmlSchemaSimpleType simpleType, CodeNamespace codeNamespace) { XmlSchemaSimpleTypeRestriction simpleTypeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeRestriction != null) { CodeTypeDeclaration typeDeclaration = null; EnumDeclaration enumDeclaration = null; foreach (XmlSchemaFacet facet in simpleTypeRestriction.Facets) { XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet; if (enumFacet != null) { if (enumDeclaration == null) { typeDeclaration = new CodeTypeDeclaration(typeName); typeDeclaration.Attributes = MemberAttributes.Public; typeDeclaration.IsEnum = true; enumDeclaration = new EnumDeclaration(typeName, typeDeclaration); typeNamesToEnumDeclarations.Add(typeName, enumDeclaration); codeNamespace.Types.Add(typeDeclaration); simpleTypeNamesToClrTypeNames.Add(typeName, typeName); string typeDocumentation = GetDocumentation(simpleType.Annotation); if (typeDocumentation != null) { GenerateSummaryComment(typeDeclaration.Comments, typeDocumentation); } } string enumValue = MakeEnumValue(enumFacet.Value); enumDeclaration.AddValue(enumFacet.Value); CodeMemberField memberField = new CodeMemberField(typeof(int), enumValue); typeDeclaration.Members.Add(memberField); string documentation = GetDocumentation(enumFacet.Annotation); if (documentation != null) { GenerateSummaryComment(memberField.Comments, documentation); } } } if (typeDeclaration == null) { string baseTypeName = simpleTypeRestriction.BaseTypeName.Name; if (baseTypeName == "nonNegativeInteger" || baseTypeName == "integer") { simpleTypeNamesToClrTypeNames.Add(typeName, "int"); } else if (baseTypeName == "string" || baseTypeName == "NMTOKEN") { simpleTypeNamesToClrTypeNames.Add(typeName, "string"); } } } }
/// <summary> /// Determines whether this StringEnumDeclarationDictionary contains a specific value. /// </summary> /// <param name="value"> /// The EnumDeclaration value to locate in this StringEnumDeclarationDictionary. /// </param> /// <returns> /// true if this StringEnumDeclarationDictionary contains an element with the specified value; /// otherwise, false. /// </returns> public virtual bool ContainsValue(EnumDeclaration value) { foreach (EnumDeclaration item in this.Dictionary.Values) { if (item == value) return true; } return false; }
/// <summary> /// Adds an element with the specified key and value to this StringEnumDeclarationDictionary. /// </summary> /// <param name="key"> /// The String key of the element to add. /// </param> /// <param name="value"> /// The EnumDeclaration value of the element to add. /// </param> public virtual void Add(EnumDeclaration value) { this.Dictionary.Add(value.Name,value); }