/// <summary> /// Generates a default property definition for use in an interface definition. /// </summary> /// <example> /// [property type] [property name] { [get when used]; [set when used]; } /// </example> /// <param name="source">Property model used for generation.</param> /// <param name="manager">Namespace manager used to format type names.</param> /// <returns>Formatted property or null if model data was missing.</returns> public static string CSharpFormatInterfacePropertySignature(this CsProperty source, NamespaceManager manager = null) { if (!source.IsLoaded) { return(null); } string propertyDeclaration = CSharpFormatPropertyDeclaration(source, manager, false, false, false); if (string.IsNullOrEmpty(propertyDeclaration)) { return(null); } StringBuilder propertyDefinition = new StringBuilder($"{propertyDeclaration} {{ "); if (source.HasGet & source.GetSecurity == CsSecurity.Public) { propertyDefinition.Append("get; "); } if (source.HasSet & source.SetSecurity == CsSecurity.Public) { propertyDefinition.Append("set; "); } propertyDefinition.Append("}"); return(propertyDefinition.ToString()); }
public void SetterVisibilityInternal() { CppMethod cppSetMethod = new("SetActive") { Rule = { Property = true } }; var paramType = TypeRegistry.Int32; var setMethod = new CsMethod(cppSetMethod, cppSetMethod.Name) { ReturnValue = new CsReturnValue(null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(null, null) { PublicType = paramType }); var iface = new CsInterface(null, null); iface.Add(setMethod); var prop = new CsProperty(null, "Active", null, setMethod); PropertyBuilder.AttachPropertyToParent(prop); Assert.Equal(Visibility.Internal, setMethod.Visibility); }
public void PropertyNotAttachedWhenSetterAllowPropertyIsFalse() { CppMethod cppSetMethod = new("SetActive") { Rule = { Property = false } }; var paramType = TypeRegistry.Int32; var setMethod = new CsMethod(cppSetMethod, cppSetMethod.Name) { ReturnValue = new CsReturnValue(null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(null, null) { PublicType = paramType }); var iface = new CsInterface(null, null); iface.Add(setMethod); var prop = new CsProperty(null, "Active", null, setMethod); PropertyBuilder.AttachPropertyToParent(prop); Assert.Null(prop.Parent); }
public void PersistentGetterGeneratesPersistentProperty() { CppMethod cppGetMethod = new("GetActive") { Rule = { Property = true, Persist = true } }; var paramType = TypeRegistry.Int32; var getMethod = new CsMethod(cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); var prop = new CsProperty(null, "Active", getMethod, null); PropertyBuilder.AttachPropertyToParent(prop); Assert.True(prop.IsPersistent); }
public void GetterVisibiltyInternal() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider("SharpGen.Runtime")); var paramType = new CsFundamentalType(typeof(int)); var getMethod = new CsMethod { Name = "GetActive", ReturnValue = new CsReturnValue { PublicType = paramType, MarshalType = paramType }, AllowProperty = true }; var iface = new CsInterface(); iface.Add(getMethod); var prop = new CsProperty("Active") { Getter = getMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(Visibility.Internal, getMethod.Visibility); }
public void PropertyAttachedToGetterType() { var paramType = TypeRegistry.Int32; CppMethod cppGetMethod = new("GetActive") { Rule = { Property = true } }; var getMethod = new CsMethod(cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); var prop = new CsProperty(null, "Active", getMethod, null); PropertyBuilder.AttachPropertyToParent(prop); Assert.Equal(iface, prop.Parent); }
public void SetOnlyPropertyAttachedToSetterType() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider("SharpGen.Runtime")); var paramType = new CsFundamentalType(typeof(int)); var setMethod = new CsMethod { Name = "SetActive", ReturnValue = new CsReturnValue { PublicType = new CsFundamentalType(typeof(void)) }, AllowProperty = true }; setMethod.Add(new CsParameter { PublicType = paramType }); var iface = new CsInterface(); iface.Add(setMethod); var prop = new CsProperty("Active") { Setter = setMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(iface, prop.Parent); }
public void PropertyNotAttachedWhenGetterAllowPropertyIsFalse() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider("SharpGen.Runtime")); var paramType = new CsFundamentalType(typeof(int)); var getMethod = new CsMethod { Name = "GetActive", ReturnValue = new CsReturnValue { PublicType = paramType, MarshalType = paramType }, AllowProperty = false }; var iface = new CsInterface(); iface.Add(getMethod); var prop = new CsProperty("Active") { Getter = getMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.Null(prop.Parent); }
public void PropertyNotAttachedWhenSetterAllowPropertyIsFalse() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider()); var paramType = new CsFundamentalType(typeof(int)); var setMethod = new CsMethod { Name = "SetActive", ReturnValue = new CsReturnValue { PublicType = new CsFundamentalType(typeof(void)) }, AllowProperty = false }; setMethod.Add(new CsParameter { PublicType = paramType }); var iface = new CsInterface(); iface.Add(setMethod); var prop = new CsProperty("Active") { Setter = setMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.Null(prop.Parent); }
public void PersistentGetterGeneratesPersistentProperty() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider()); var paramType = new CsFundamentalType(typeof(int)); var getMethod = new CsMethod { Name = "GetActive", ReturnValue = new CsReturnValue { PublicType = paramType, MarshalType = paramType }, AllowProperty = true, IsPersistent = true }; var iface = new CsInterface(); iface.Add(getMethod); var prop = new CsProperty("Active") { Getter = getMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.True(prop.IsPersistent); }
public void SetterVisibilityInternal() { var propertyBuilder = new PropertyBuilder(new GlobalNamespaceProvider()); var paramType = new CsFundamentalType(typeof(int)); var setMethod = new CsMethod { Name = "SetActive", ReturnValue = new CsReturnValue { PublicType = new CsFundamentalType(typeof(void)) }, AllowProperty = true }; setMethod.Add(new CsParameter { PublicType = paramType }); var iface = new CsInterface(); iface.Add(setMethod); var prop = new CsProperty("Active") { Setter = setMethod }; propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(Visibility.Internal, setMethod.Visibility); }
/// <summary> /// Implements a default property implementation for a missing member. /// </summary> /// <param name="memberData">Property data to be loaded.</param> /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param> /// <returns>The fully formatted property source code or null if the member could not be implemented.</returns> public static string FormatMemberProperty(CsProperty memberData, NamespaceManager manager) { //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null. if (memberData == null) { return(null); } if (!memberData.IsLoaded) { return(null); } if (manager == null) { return(null); } //C# helper used to format output syntax. var formatter = new CodeFactory.SourceFormatter(); //Using the formatter helper to generate a default property signature. string propertySyntax = memberData.CSharpFormatDefaultPropertySignature(manager); //If the property syntax was not created return. if (string.IsNullOrEmpty(propertySyntax)) { return(null); } //If the member has document then will build the documentation. if (memberData.HasDocumentation) { //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member. foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator()) { //Appending each xml document line to the being of the member definition. formatter.AppendCodeLine(0, documentation); } } //The member has attributes assigned to it, append the attributes. if (memberData.HasAttributes) { //Using a documentation helper that will generate an enumerator that will output each attribute definition. foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager)) { //Appending each attribute definition before the member definition. formatter.AppendCodeLine(0, attributeSyntax); } } //Adding the property declaration formatter.AppendCodeLine(0, propertySyntax); //Adding a extra line feed at the end of the declaration. formatter.AppendCodeLine(0); //The source formatter returning the final results. return(formatter.ReturnSource()); }
public TheProperty(CsProperty pCsProperty, TheClass pTheClass, FactoryExpressionCreator pCreator) { MyClass = pTheClass; Modifiers.AddRange(Helpers.GetModifiers(pCsProperty.modifiers)); Name = pCsProperty.identifier.identifier; FullName = MyClass.FullName + "." + Name; ReturnType = Helpers.GetType(pCsProperty.type); if (pCsProperty.getter != null) Getter = new Property(pCsProperty.getter, this); if (pCsProperty.setter != null) Setter = new Property(pCsProperty.setter, this); }
/// <summary> /// Generates a default property definition with a backing properties. Will determine security modifiers and append to get and set statements when needed. /// </summary> /// <example> /// With Keywords [security] [keywords] [property type] [property name] { [get when used]{return [backingField];} [set when used]{ [backingField] = value;} } /// Without Keywords [security] [property type] [property name] { [get when used]{return [backingField];} [set when used]{ [backingField] = value;} } /// </example> /// <param name="source">Property model used for generation.</param> /// <param name="backingFieldName">the name of the backing field to be managed by the property.</param> /// <param name="manager">Namespace manager used to format type names.</param> /// <param name="includeKeyword">Optional parameter that determines if the keywords will be appended. Default is false.</param> /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param> /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param> /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param> /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param> /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param> /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param> /// <param name="propertySecurity">Optional parameter that overrides the models property security and sets a new security access level.</param> /// <param name="setSecurity">Optional parameter that overrides the models set security level with a new access level. Will also define a set statement even if it is not defined.</param> /// <param name="getSecurity">Optional parameter that overrides the models get security level with a new access level. Will also define a get statement even if it is not defined.</param> /// <returns>Formatted property or null if model data was missing.</returns> public static string CSharpFormatDefaultPropertySignatureWithBackingField(this CsProperty source, string backingFieldName, NamespaceManager manager = null, bool includeKeyword = false, bool includeAbstractKeyword = false, bool requireStaticKeyword = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false, bool requireOverrideKeyword = false, bool requireVirtualKeyword = false, CsSecurity propertySecurity = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown, CsSecurity getSecurity = CsSecurity.Unknown) { if (!source.IsLoaded) { return(null); } if (string.IsNullOrEmpty(backingFieldName)) { return(null); } string propertyDeclaration = CSharpFormatPropertyDeclaration(source, manager, true, includeKeyword, includeAbstractKeyword, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword, requireOverrideKeyword, requireVirtualKeyword, propertySecurity); if (string.IsNullOrEmpty(propertyDeclaration)) { return(null); } StringBuilder propertyDefinition = new StringBuilder($"{propertyDeclaration} {{ "); if (source.HasGet | getSecurity != CsSecurity.Unknown) { var getStatement = source.CSharpFormatGetStatement(propertySecurity, getSecurity); if (getStatement == null) { return(null); } propertyDefinition.Append($"{getStatement} {{ return {backingFieldName}; }} "); } if (source.HasSet | setSecurity != CsSecurity.Unknown) { var setStatement = source.CSharpFormatSetStatement(propertySecurity, setSecurity); if (setStatement == null) { return(null); } propertyDefinition.Append($"{setStatement} {{ {backingFieldName} = value; }} "); } propertyDefinition.Append("}"); return(propertyDefinition.ToString()); }
/// <summary> /// Generates the initial definition portion of a property. /// </summary> /// <example> /// Format with Keywords [Security] [Keywords*] [ReturnType] [PropertyName] = public static string FirstName /// Format without Keywords [Security] [ReturnType] [PropertyName] = public string FirstName /// </example> /// <param name="manager">Namespace manager used to format type names.</param> /// <param name="source">The source property to use for formatting.</param> /// <param name="includeSecurity">Optional flag that determines if the security scope will be applied to the property definition. Default is true.</param> /// <param name="includeKeyWords">Optional flag that determines if keywords assigned to the property should be included in the signature. Default is false.</param> /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param> /// <param name="propertySecurity">Optional parameter to override the models security and set your own security.</param> /// <returns>The formatted signature or null if the model data was not loaded.</returns> public static string CSharpFormatPropertyDeclaration(this CsProperty source, NamespaceManager manager = null, bool includeSecurity = true, bool includeKeyWords = false, bool includeAbstractKeyword = false, CsSecurity propertySecurity = CsSecurity.Unknown) { if (!source.IsLoaded) { return(null); } StringBuilder propertyBuilder = new StringBuilder(); if (includeKeyWords & source.IsSealed) { propertyBuilder.Append($"{Keywords.Sealed} "); } if (includeSecurity) { propertyBuilder.Append(propertySecurity == CsSecurity.Unknown ? source.Security.CSharpFormatKeyword() : propertySecurity.CSharpFormatKeyword()); } if (includeKeyWords) { if (source.IsStatic) { propertyBuilder.Append($" {Keywords.Static}"); } if (source.IsOverride) { propertyBuilder.Append($" {Keywords.Override}"); } if (source.IsAbstract & !source.IsOverride & includeAbstractKeyword) { propertyBuilder.Append($" {Keywords.Abstract}"); } if (source.IsVirtual & !source.IsOverride) { propertyBuilder.Append($" {Keywords.Virtual}"); } } propertyBuilder.Append($" {source.PropertyType.CSharpFormatTypeName(manager)}"); propertyBuilder.Append($" {source.Name}"); return(propertyBuilder.ToString()); }
/// <summary> /// Extension method that formats the set statement of a property definition. /// </summary> /// <example> /// With the same security [set] will return example: set /// With different security [security] [set] will return example: public set /// </example> /// <param name="source">the source property definition</param> /// <param name="propertySecurity">Optional parameter that defined the security used by the implementing property.</param> /// <param name="setSecurity">Optional parameter that allows you to set the set security level.</param> /// <returns>Will return the formatted set statement or null if the property model is empty or the property does not support set.</returns> public static string CSharpFormatSetStatement(this CsProperty source, CsSecurity propertySecurity = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown) { if (!source.IsLoaded) { return(null); } if (!source.HasSet & setSecurity == CsSecurity.Unknown) { return(null); } CsSecurity security = propertySecurity == CsSecurity.Unknown ? source.Security : propertySecurity; CsSecurity accessSecurity = setSecurity == CsSecurity.Unknown ? source.SetSecurity : setSecurity; return(security == accessSecurity ? "set" : $"{accessSecurity.CSharpFormatKeyword()} set"); }
public void Retrieves_type_properties() { CsSolution solution = SolutionParser.ParseSolution(_testSolutionFilePath); CsProject project = solution.Projects.ElementAt(0); CsClass csClass = project.GetClass(nameof(Class2)); var csProps = csClass.Properties; Assert.AreEqual(2, csProps.Count(), "Unexpected number of properties."); CsProperty csProp = csProps.First(); Assert.AreEqual(nameof(Class2.RefToClass1), csProp.Name, "Unexpected property name."); Assert.AreEqual(typeof(Class1).Name, csProp.Type, "Unexpected property type."); //TODO: retrieve property access //Assert.AreEqual("public", csProp.Access, "Unexpected property access."); }
public TheProperty(CsProperty pCsProperty, TheClass pTheClass, FactoryExpressionCreator pCreator) { MyClass = pTheClass; Modifiers.AddRange(Helpers.GetModifiers(pCsProperty.modifiers)); Name = pCsProperty.identifier.identifier; FullName = MyClass.FullName + "." + Name; ReturnType = Helpers.GetType(pCsProperty.type); if (pCsProperty.getter != null) { Getter = new Property(pCsProperty.getter, this); } if (pCsProperty.setter != null) { Setter = new Property(pCsProperty.setter, this); } }
/// <summary> /// Generates a default property definition with no backing properties. Will determine security modifiers and append to get and set statements when needed. /// </summary> /// <example> /// With Keywords [security] [keywords] [property type] [property name] { [get when used]; [set when used]; } /// No Keywords [security] [property type] [property name] { [get when used]; [set when used]; } /// </example> /// <param name="source">Property model used for generation.</param> /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param> /// <param name="includeKeyword">Optional parameter that determines if the keywords will be appended. Default is false.</param> /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param> /// <param name="propertySecurity">Optional parameter that overrides the models property security and sets a new security access level.</param> /// <param name="setSecurity">Optional parameter that overrides the models set security level with a new access level. Will also define a set statement even if it is not defined.</param> /// <param name="getSecurity">Optional parameter that overrides the models get security level with a new access level. Will also define a get statement even if it is not defined.</param> /// <returns>Formatted property or null if model data was missing.</returns> public static string CSharpFormatDefaultPropertySignature(this CsProperty source, NamespaceManager manager = null, bool includeKeyword = false, bool includeAbstractKeyword = false, CsSecurity propertySecurity = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown, CsSecurity getSecurity = CsSecurity.Unknown) { if (!source.IsLoaded) { return(null); } string propertyDeclaration = CSharpFormatPropertyDeclaration(source, manager, true, includeKeyword, includeAbstractKeyword, propertySecurity); if (string.IsNullOrEmpty(propertyDeclaration)) { return(null); } StringBuilder propertyDefinition = new StringBuilder($"{propertyDeclaration} {{ "); if (source.HasGet | getSecurity != CsSecurity.Unknown) { var getStatement = source.CSharpFormatGetStatement(propertySecurity, getSecurity); if (getStatement == null) { return(null); } propertyDefinition.Append($"{getStatement}; "); } if (source.HasSet | setSecurity != CsSecurity.Unknown) { var setStatement = source.CSharpFormatSetStatement(propertySecurity, setSecurity); if (setStatement == null) { return(null); } propertyDefinition.Append($"{setStatement}; "); } propertyDefinition.Append("}"); return(propertyDefinition.ToString()); }
private async Task <CsSource> AddProperty(CsClass targetClass, CsProperty member, string targetFilePath, NamespaceManager manager) { CsSource result = null; string sourceCode = CSharpSourceGenerationCommon.GenerateStandardPropertySourceCode(member, manager); if (string.IsNullOrEmpty(sourceCode)) { throw new CodeFactoryException("Was not able to generate the source code for the member property."); } result = await targetClass.AddToEndAsync(targetFilePath, CsSourceFormatter.IndentCodeBlock(2, sourceCode)); if (result == null) { throw new CodeFactoryException("Could not load the source code after adding the member."); } return(result); }
public void AttachPropertyToParent(CsProperty property) { var underlyingMethod = property.Getter ?? property.Setter; // Associate the property with the underlying method's C++ element. property.CppElement = underlyingMethod.CppElement; // If We have a getter, then we need to modify the documentation in order to print that we have Gets and Sets. if (property.Getter != null && property.Setter != null && !string.IsNullOrEmpty(property.Description)) { property.Description = MatchGet.Replace(property.Description, "$1$2 or sets"); } var parent = underlyingMethod.Parent; // If mapping rule disallows properties, don't attach the property to the model. if ((property.Getter?.AllowProperty == false) || (property.Setter?.AllowProperty == false)) { return; } // Update visibility for getter and setter (set to internal) if (property.Getter != null) { property.Getter.Visibility = Visibility.Internal; property.IsPersistent = property.Getter.IsPersistent; } if (property.Setter != null) { property.Setter.Visibility = Visibility.Internal; } if (property.Getter != null && property.Name.StartsWith("Is")) { property.Getter.Name += "_"; } parent.Add(property); }
/// <summary> /// Creates C# properties for method that respect the following convention: /// TODO describe the convention to create properties from methods here. /// </summary> /// <param name="methods">The methods.</param> private static void CreateProperties(IEnumerable <CsMethod> methods) { var cSharpProperties = new Dictionary <string, CsProperty>(); foreach (var cSharpMethod in methods) { bool isIs = cSharpMethod.Name.StartsWith("Is"); bool isGet = cSharpMethod.Name.StartsWith("Get") || isIs; bool isSet = cSharpMethod.Name.StartsWith("Set"); if (!(isGet || isSet)) { continue; } string propertyName = isIs ? cSharpMethod.Name : cSharpMethod.Name.Substring("Get".Length); int parameterCount = cSharpMethod.ParameterCount; var parameterList = cSharpMethod.Parameters; CsProperty csProperty; bool isPropertyToAdd = false; if (!cSharpProperties.TryGetValue(propertyName, out csProperty)) { csProperty = new CsProperty(propertyName); isPropertyToAdd = true; } // If the property has already a getter and a setter, this must be an error, remove the property // (Should never happen, unless there are some polymorphism on the interface's methods) if (csProperty.Getter != null && csProperty.Setter != null) { cSharpProperties.Remove(propertyName); continue; } // Check Getter if (isGet) { if ((cSharpMethod.IsHResult || !cSharpMethod.HasReturnType) && parameterCount == 1 && parameterList[0].IsOut && !parameterList[0].IsArray) { csProperty.Getter = cSharpMethod; csProperty.PublicType = parameterList[0].PublicType; csProperty.IsPropertyParam = true; } else if (parameterCount == 0 && cSharpMethod.HasReturnType) { csProperty.Getter = cSharpMethod; csProperty.PublicType = csProperty.Getter.ReturnType.PublicType; } else { // If there is a getter, but the setter is not valid, then remove the getter if (csProperty.Setter != null) { cSharpProperties.Remove(propertyName); } continue; } } else { // Check Setter if ((cSharpMethod.IsHResult || !cSharpMethod.HasReturnType) && parameterCount == 1 && (parameterList[0].IsRefIn || parameterList[0].IsIn || parameterList[0].IsRef) && !parameterList[0].IsArray) { csProperty.Setter = cSharpMethod; csProperty.PublicType = parameterList[0].PublicType; } else if (parameterCount == 1 && !cSharpMethod.HasReturnType) { csProperty.Setter = cSharpMethod; csProperty.PublicType = csProperty.Setter.ReturnType.PublicType; } else { // If there is a getter, but the setter is not valid, then remove the getter if (csProperty.Getter != null) { cSharpProperties.Remove(propertyName); } continue; } } // Check when Setter and Getter together that they have the same return type if (csProperty.Setter != null && csProperty.Getter != null) { bool removeProperty = false; //// Don't add property that doesn't match with return type //if (property.Setter != property.Getter.IsHResult) // continue; if (csProperty.IsPropertyParam) { var getterParameter = csProperty.Getter.Parameters.First(); var setterParameter = csProperty.Setter.Parameters.First(); if (getterParameter.PublicType.QualifiedName != setterParameter.PublicType.QualifiedName) { removeProperty = true; } } else { var getterType = csProperty.Getter.ReturnType; var setterType = csProperty.Setter.Parameters.First(); if (getterType.PublicType.QualifiedName != setterType.PublicType.QualifiedName) { removeProperty = true; } } if (removeProperty) { cSharpProperties.Remove(propertyName); } } if (isPropertyToAdd) { cSharpProperties.Add(propertyName, csProperty); } } // Add the property to the parentContainer foreach (var cSharpProperty in cSharpProperties) { var property = cSharpProperty.Value; var getterOrSetter = property.Getter ?? property.Setter; // Associate the property with the Getter element property.CppElement = getterOrSetter.CppElement; // If We have a getter, then we need to modify the documentation in order to print that we have Gets and Sets. if (property.Getter != null && property.Setter != null && !string.IsNullOrEmpty(property.Description)) { property.Description = MatchGet.Replace(property.Description, "$1$2 or sets"); } var parent = getterOrSetter.Parent; // If Getter has no property, if ((property.Getter != null && !property.Getter.AllowProperty) || (property.Setter != null && !property.Setter.AllowProperty)) { continue; } // Update visibility for getter and setter (set to internal) if (property.Getter != null) { property.Getter.Visibility = Visibility.Internal; property.IsPersistent = property.Getter.IsPersistent; if (property.IsPersistent) { parent.HasPersistent = true; } } if (property.Setter != null) { property.Setter.Visibility = Visibility.Internal; } if (property.Getter != null && property.Name.StartsWith("Is")) { property.Getter.Name = property.Getter.Name + "_"; } parent.Add(property); } }
public TheProperty GetProperty(CsProperty pMemberDeclaration) { TheProperty c; return _properties.TryGetValue(pMemberDeclaration, out c) ? c : null; }
private async Task <CsSource> UpdateMembersAsync(CsClass targetClass, IEnumerable <CsMember> members, bool logging, bool cdf, bool cdfAspnet, string targetFilePath, bool isContract, NamespaceManager manager) { if (targetClass == null) { return(null); } if (members == null) { return(null); } if (!members.Any()) { return(null); } if (string.IsNullOrEmpty(targetFilePath)) { return(null); } CsSource updatedSource = null; CsClass updatedClass = targetClass; foreach (var csMember in members) { switch (csMember.MemberType) { case CsMemberType.Event: CsEvent eventData = csMember as CsEvent; if (eventData == null) { throw new CodeFactoryException("Cannot load event data, cannot process members."); } updatedSource = await AddEvent(updatedClass, eventData, isContract, targetFilePath, manager); updatedClass = updatedSource.GetModel(updatedClass.LookupPath) as CsClass; if (updatedClass == null) { throw new CodeFactoryException("Could not load class data cannot add members."); } break; case CsMemberType.Method: CsMethod methodData = csMember as CsMethod; if (methodData == null) { throw new CodeFactoryException("Cannot load method data, cannot process members."); } updatedSource = await AddMethodMember(updatedClass, methodData, logging, cdf, cdfAspnet, targetFilePath, manager); updatedClass = updatedSource.GetModel(updatedClass.LookupPath) as CsClass; if (updatedClass == null) { throw new CodeFactoryException("Could not load class data cannot add members."); } break; case CsMemberType.Property: CsProperty propertyData = csMember as CsProperty; if (propertyData == null) { throw new CodeFactoryException("Cannot load property data, cannot process members."); } updatedSource = await AddProperty(updatedClass, propertyData, targetFilePath, manager); updatedClass = updatedSource.GetModel(updatedClass.LookupPath) as CsClass; if (updatedClass == null) { throw new CodeFactoryException("Could not load class data cannot add members."); } break; default: continue; } } return(updatedSource); }
public TheProperty GetProperty(CsProperty pMemberDeclaration) { TheProperty c; return(_properties.TryGetValue(pMemberDeclaration, out c) ? c : null); }
public TheClass(CsInterface pCsInterface, FactoryExpressionCreator pCreator) { IsInterface = true; List <string> name = new List <string>(); CsNamespace parent = pCsInterface.parent as CsNamespace; if (parent != null) { name.AddRange(parent.qualified_identifier.Select(pArt => pArt.identifier.identifier)); } NameSpace = string.Join(".", name.ToArray()); Name = pCsInterface.identifier.identifier; FullName = NameSpace + "." + Name; if (pCsInterface.type_base != null && pCsInterface.type_base.base_list.Count != 0) { foreach (CsTypeRef typeRef in pCsInterface.type_base.base_list) { object u = typeRef.entity_typeref.u; if (u == null) { continue; } if (u is CsEntityClass) { Extends.Add(Helpers.GetType(typeRef.type_name)); _baseTyperef = typeRef; } else if (u is CsEntityInterface) { Implements.Add(Helpers.GetType(typeRef.type_name)); } else if (u is CsEntityInstanceSpecifier) { Implements.Add(Helpers.GetType(typeRef.type_name)); } else { throw new NotSupportedException(); } } } Dictionary <string, int> methodNames = new Dictionary <string, int>(); bool methodsDone = false; if (pCsInterface.member_declarations != null) { foreach (CsNode memberDeclaration in pCsInterface.member_declarations) { CsMethod m = memberDeclaration as CsMethod; if (m != null) { if (m.interface_type != null) { continue; } TheMethod tm = new TheMethod(m, this, pCreator); if (methodNames.ContainsKey(tm.Name)) { methodNames[tm.Name]++; int index = tm._index = methodNames[tm.Name]; if (!methodsDone) { methodsDone = true; foreach (KeyValuePair <CsMethod, TheMethod> method in _methods) { method.Value._isUnique = false; method.Value._index = --index; } } tm._isUnique = false; } else { methodNames[tm.Name] = tm._index = 1; } _methods.Add(m, tm); continue; } CsIndexer i = memberDeclaration as CsIndexer; if (i != null) { _indexers.Add(i, new TheIndexer(i, this, pCreator)); continue; } CsVariableDeclaration v = memberDeclaration as CsVariableDeclaration; if (v != null) { _variables.Add(v, new TheVariable(v, this, pCreator)); continue; } CsProperty p = memberDeclaration as CsProperty; if (p != null) { if (p.interface_type == null) { _properties.Add(p, new TheProperty(p, this, pCreator)); } continue; } throw new NotImplementedException("Unknown type not implemented"); } } Modifiers.AddRange(Helpers.GetModifiers(pCsInterface.modifiers)); }
public TheClass(CsClassStruct pCsClass, FactoryExpressionCreator pCreator) { CsNamespace csNamespace; _creator = pCreator; List <string> name = new List <string>(); if (pCsClass.parent is CsClass) { IsPrivate = true; csNamespace = (CsNamespace)pCsClass.parent.parent; } else { csNamespace = (CsNamespace)pCsClass.parent; } CsQualifiedIdentifier list = csNamespace.qualified_identifier; name.AddRange(list.Select(pIdentifier => pIdentifier.identifier.identifier)); if (IsPrivate) { name.Add(((CsClass)pCsClass.parent).identifier.identifier); } NameSpace = string.Join(".", name.ToArray()); //RealName = pCsClass.identifier.identifier; //Name = Helpers.GetRealName(pCsClass, RealName); Name = pCsClass.identifier.identifier; FullName = NameSpace + "." + Name; //FullRealName = NameSpace + "." + RealName; if (pCsClass.type_base != null && pCsClass.type_base.base_list.Count != 0) { foreach (CsTypeRef typeRef in pCsClass.type_base.base_list) { object u = typeRef.entity_typeref.u; if (u == null) { continue; } if (u is CsEntityClass) { Extends.Add(Helpers.GetType(typeRef.type_name)); _baseTyperef = typeRef; } else if (u is CsEntityInterface) { Implements.Add(Helpers.GetType(typeRef.type_name)); } else if (u is CsEntityInstanceSpecifier) { Implements.Add(Helpers.GetType(typeRef.type_name)); //CsEntityInstanceSpecifier specifier = (CsEntityInstanceSpecifier)typeRef.entity_typeref.u; } else { throw new NotSupportedException(); } } } Dictionary <string, int> methodNames = new Dictionary <string, int>(); bool constructorsDone = false; bool methodsDone = false; if (pCsClass.member_declarations != null) { foreach (CsNode memberDeclaration in pCsClass.member_declarations) { CsConstructor c = memberDeclaration as CsConstructor; if (c != null) { TheConstructor tm = new TheConstructor(c, this, pCreator); if (methodNames.ContainsKey(tm.Name)) { methodNames[tm.Name]++; int index = tm._index = methodNames[tm.Name]; if (!constructorsDone) { constructorsDone = true; foreach (KeyValuePair <CsConstructor, TheConstructor> constructor in _constructors) { constructor.Value._isUnique = false; constructor.Value._index = --index; } } tm._isUnique = false; } else { methodNames[tm.Name] = tm._index = 1; } _constructors.Add(c, tm); continue; } CsMethod m = memberDeclaration as CsMethod; if (m != null) { if (m.interface_type != null) { continue; } TheMethod tm = new TheMethod(m, this, pCreator); if (methodNames.ContainsKey(tm.Name)) { methodNames[tm.Name]++; int index = tm._index = methodNames[tm.Name]; if (!methodsDone) { methodsDone = true; foreach (KeyValuePair <CsMethod, TheMethod> method in _methods) { method.Value._isUnique = false; method.Value._index = --index; } } tm._isUnique = false; } else { methodNames[tm.Name] = tm._index = 1; } _methods.Add(m, tm); continue; } CsIndexer i = memberDeclaration as CsIndexer; if (i != null) { _indexers.Add(i, new TheIndexer(i, this, pCreator)); continue; } CsVariableDeclaration v = memberDeclaration as CsVariableDeclaration; if (v != null) { _variables.Add(v, new TheVariable(v, this, pCreator)); continue; } CsConstantDeclaration k = memberDeclaration as CsConstantDeclaration; if (k != null) { _constants.Add(k, new TheConstant(k, this, pCreator)); continue; } CsProperty p = memberDeclaration as CsProperty; if (p != null) { if (p.interface_type == null) { _properties.Add(p, new TheProperty(p, this, pCreator)); } continue; } CsDelegate d = memberDeclaration as CsDelegate; if (d != null) { _delegates.Add(d, new TheDelegate(d, this, pCreator)); continue; } CsEvent e = memberDeclaration as CsEvent; if (e != null) { TheEvent theEvent = new TheEvent(e, this, pCreator); _events.Add(theEvent.Name, theEvent); continue; } CsClass csClass = memberDeclaration as CsClass; if (csClass != null) { continue; } throw new NotImplementedException("Unknown type not implemented"); } } Modifiers.AddRange(Helpers.GetModifiers(pCsClass.modifiers)); }
/// <summary> /// Generates the source code for a standard property definition. That uses a standard getter and setter. /// </summary> /// <param name="memberData">property data to be loaded.</param> /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param> /// <param name="security">The security level to set the source event source code to. Will default to public if not provided.</param> /// <param name="getSecurity">Set the security level of the get accessor if defined for the property, will default to unknown</param> /// <param name="setSecurity">Set the security level of the set accessor if defined for the property, will default to unknown</param> /// <param name="useKeywords">Include the keywords currently assigned to the event model. Default value is to not include them.</param> /// <param name="includeAbstractKeyword">Optional parameter that determines if it will include the definition for the abstract keyword in the definition if it is defined. default is false.</param> /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param> /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param> /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param> /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param> /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param> /// <returns>The fully formatted event source code or null if the member could not be implemented.</returns> public static string GenerateStandardPropertySourceCode(CsProperty memberData, NamespaceManager manager, bool useKeywords = false, bool includeAbstractKeyword = false, bool requireStaticKeyword = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false, bool requireOverrideKeyword = false, bool requireVirtualKeyword = false, CsSecurity security = CsSecurity.Public, CsSecurity getSecurity = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown) { //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null. if (memberData == null) { return(null); } if (!memberData.IsLoaded) { return(null); } if (manager == null) { return(null); } //C# helper used to format output syntax. var formatter = new CodeFactory.SourceFormatter(); //Using the formatter helper to generate a default event signature. string propertySyntax = memberData.CSharpFormatDefaultPropertySignature(manager, useKeywords, includeAbstractKeyword, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword, requireOverrideKeyword, requireVirtualKeyword, security, setSecurity, getSecurity); //If the property syntax was not created return. if (string.IsNullOrEmpty(propertySyntax)) { return(null); } //If the member has document then will build the documentation. if (memberData.HasDocumentation) { //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member. foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator()) { //Appending each xml document line to the being of the member definition. formatter.AppendCodeLine(0, documentation); } } //The member has attributes assigned to it, append the attributes. if (memberData.HasAttributes) { //Using a documentation helper that will generate an enumerator that will output each attribute definition. foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager)) { //Appending each attribute definition before the member definition. formatter.AppendCodeLine(0, attributeSyntax); } } //Adding the event declaration formatter.AppendCodeBlock(0, propertySyntax); //Adding a extra line feed at the end of the declaration. formatter.AppendCodeLine(0); //The source formatter returning the final results. return(formatter.ReturnSource()); }
/// <summary> /// Generates the initial definition portion of a property. /// </summary> /// <example> /// Format with Keywords [Security] [Keywords*] [ReturnType] [PropertyName] = public static string FirstName /// Format without Keywords [Security] [ReturnType] [PropertyName] = public string FirstName /// </example> /// <param name="manager">Namespace manager used to format type names.</param> /// <param name="source">The source property to use for formatting.</param> /// <param name="includeSecurity">Optional flag that determines if the security scope will be applied to the property definition. Default is true.</param> /// <param name="includeKeyWords">Optional flag that determines if keywords assigned to the property should be included in the signature. Default is false.</param> /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param> /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param> /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param> /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param> /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param> /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param> /// <param name="propertySecurity">Optional parameter to override the models security and set your own security.</param> /// <returns>The formatted signature or null if the model data was not loaded.</returns> public static string CSharpFormatPropertyDeclaration(this CsProperty source, NamespaceManager manager = null, bool includeSecurity = true, bool includeKeyWords = false, bool includeAbstractKeyword = false, bool requireStaticKeyword = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false, bool requireOverrideKeyword = false, bool requireVirtualKeyword = false, CsSecurity propertySecurity = CsSecurity.Unknown) { if (!source.IsLoaded) { return(null); } StringBuilder propertyBuilder = new StringBuilder(); if (includeKeyWords & source.IsSealed) { propertyBuilder.Append($"{Keywords.Sealed} "); } if (includeSecurity) { propertyBuilder.Append(propertySecurity == CsSecurity.Unknown ? source.Security.CSharpFormatKeyword() : propertySecurity.CSharpFormatKeyword()); } bool staticKeyword = false; bool sealedKeyword = false; bool abstractKeyword = false; bool overrideKeyword = false; bool virtualKeyword = false; if (includeKeyWords) { if (source.IsStatic) { staticKeyword = true; } if (source.IsSealed) { sealedKeyword = true; } if (includeAbstractKeyword & source.IsAbstract) { abstractKeyword = true; } if (source.IsOverride) { overrideKeyword = true; } if (source.IsVirtual) { virtualKeyword = true; } } if (!staticKeyword) { staticKeyword = requireStaticKeyword; } if (!sealedKeyword) { sealedKeyword = requireSealedKeyword; } if (!abstractKeyword) { abstractKeyword = requireAbstractKeyword; } if (!overrideKeyword) { overrideKeyword = requireOverrideKeyword; } if (!virtualKeyword) { virtualKeyword = requireVirtualKeyword; } if (staticKeyword) { propertyBuilder.Append($"{Keywords.Static} "); } if (sealedKeyword) { propertyBuilder.Append($"{Keywords.Sealed} "); } if (abstractKeyword) { propertyBuilder.Append($"{Keywords.Abstract} "); } if (overrideKeyword) { propertyBuilder.Append($"{Keywords.Override} "); } if (virtualKeyword) { propertyBuilder.Append($"{Keywords.Virtual} "); } propertyBuilder.Append($" {source.PropertyType.CSharpFormatTypeName(manager)}"); propertyBuilder.Append($" {source.Name}"); return(propertyBuilder.ToString()); }