Beispiel #1
0
        private void AddConstuctor(StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (type.IsInterface())
            {
                return;
            }
            var initCollections = feature.ShouldInitializeCollections(type, Config.InitializeCollections);

            if (Config.AddImplicitVersion == null && !initCollections)
            {
                return;
            }

            var collectionProps = new List <MetadataPropertyType>();

            if (type.Properties != null && initCollections)
            {
                collectionProps = type.Properties.Where(x => x.IsCollection()).ToList();
            }

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;

            if (!addVersionInfo && collectionProps.Count <= 0)
            {
                return;
            }

            if (addVersionInfo)
            {
                var @virtual = Config.MakeVirtual ? "Overridable " : "";
                sb.AppendLine("Public {0}Property Version As Integer".Fmt(@virtual));
                sb.AppendLine();
            }

            sb.AppendLine("Public Sub New()".Fmt(NameOnly(type.Name)));
            //sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
            {
                sb.AppendLine("Version = {0}".Fmt(Config.AddImplicitVersion));
            }

            foreach (var prop in collectionProps)
            {
                var suffix = prop.IsArray() ? "{}" : "";
                sb.AppendLine("{0} = New {1}{2}".Fmt(
                                  prop.Name.SafeToken(),
                                  Type(prop.Type, prop.GenericArgs, includeNested: true),
                                  suffix));
            }

            sb = sb.UnIndent();
            sb.AppendLine("End Sub");
            sb.AppendLine();
        }
Beispiel #2
0
        private void AddConstuctor(StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (type.IsInterface())
            {
                return;
            }

            var initCollections = feature.ShouldInitializeCollections(type, Config.InitializeCollections);

            if (Config.AddImplicitVersion == null && !initCollections)
            {
                return;
            }

            var collectionProps = new List <MetadataPropertyType>();

            if (type.Properties != null && initCollections)
            {
                collectionProps = type.Properties.Where(x => x.IsCollection()).ToList();
            }

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;

            if (!addVersionInfo && collectionProps.Count <= 0)
            {
                return;
            }

            if (addVersionInfo)
            {
                var virt = Config.MakeVirtual ? "virtual " : "";
                sb.AppendLine($"public {virt}int Version {{ get; set; }}");
                sb.AppendLine();
            }

            sb.AppendLine($"public {NameOnly(type.Name)}()");
            sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
            {
                sb.AppendLine($"Version = {Config.AddImplicitVersion};");
            }

            foreach (var prop in collectionProps)
            {
                sb.AppendLine($"{prop.Name.SafeToken()} = new {Type(prop.GetTypeName(Config, allTypes), prop.GenericArgs,includeNested:true)}{{}};");
            }

            sb = sb.UnIndent();
            sb.AppendLine("}");
            sb.AppendLine();
        }
Beispiel #3
0
        private void AddConstuctor(StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (type.IsInterface())
            {
                return;
            }
            if (Config.AddImplicitVersion == null && !Config.InitializeCollections)
            {
                return;
            }

            var collectionProps = new List <MetadataPropertyType>();

            if (type.Properties != null && Config.InitializeCollections)
            {
                collectionProps = type.Properties.Where(x => x.IsCollection()).ToList();
            }

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;

            if (!addVersionInfo && collectionProps.Count <= 0)
            {
                return;
            }

            if (addVersionInfo)
            {
                var @virtual = Config.MakeVirtual ? "virtual " : "";
                sb.AppendLine("public {0}int Version {{ get; set; }}".Fmt(@virtual));
                sb.AppendLine();
            }

            sb.AppendLine("public {0}()".Fmt(NameOnly(type.Name)));
            sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
            {
                sb.AppendLine("Version = {0};".Fmt(Config.AddImplicitVersion));
            }

            foreach (var prop in collectionProps)
            {
                sb.AppendLine("{0} = new {1}{{}};".Fmt(
                                  prop.Name.SafeToken(),
                                  Type(prop.Type, prop.GenericArgs, includeNested: true)));
            }

            sb = sb.UnIndent();
            sb.AppendLine("}");
            sb.AppendLine();
        }
Beispiel #4
0
        private void ExtractTypeAliases(CreateTypeOptions options, List <string> typeAliases, List <string> extends, ref StringBuilderWrapper sbExt)
        {
            var implStr = options.ImplementsFn();

            if (!string.IsNullOrEmpty(implStr))
            {
                var interfaceParts = implStr.SplitOnFirst('<');
                if (interfaceParts.Length > 1)
                {
                    implStr = interfaceParts[0];

                    //Strip 'I' prefix for interfaces and use as typealias for protocol
                    var alias = implStr.StartsWith("I")
                        ? implStr.Substring(1)
                        : implStr;

                    var genericType = interfaceParts[1].Substring(0, interfaceParts[1].Length - 1);
                    typeAliases.Add("public typealias {0} = {1}".Fmt(alias, genericType));
                }

                extends.Add(implStr);
            }
        }
        private void ExtractTypeAliases(CreateTypeOptions options, List<string> typeAliases, List<string> extends, ref StringBuilderWrapper sbExt)
        {
            var implStr = options.ImplementsFn();
            if (!string.IsNullOrEmpty(implStr))
            {
                var interfaceParts = implStr.SplitOnFirst('<');
                if (interfaceParts.Length > 1)
                {
                    implStr = interfaceParts[0];

                    //Strip 'I' prefix for interfaces and use as typealias for protocol
                    var alias = implStr.StartsWith("I")
                        ? implStr.Substring(1)
                        : implStr;

                    var genericType = interfaceParts[1].Substring(0, interfaceParts[1].Length - 1);
                    typeAliases.Add("public typealias {0} = {1}".Fmt(alias, genericType));
                }

                extends.Add(implStr);
            }
        }
Beispiel #6
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List <MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
            {
                return(lastNS);
            }

            var ns = Config.GlobalNamespace ?? type.Namespace;

            if (ns != lastNS)
            {
                if (lastNS != null)
                {
                    sb.AppendLine("}");
                }

                lastNS = ns;

                sb.AppendLine();
                sb.AppendLine("namespace {0}".Fmt(ns.SafeToken()));
                sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name)
                            : "{0} = {1},".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var partial = Config.MakePartial ? "partial " : "";
                var defType = type.IsInterface() ? "interface" : "class";
                sb.AppendLine("public {0}{1} {2}".Fmt(partial, defType, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                var inheritsList = new List <string>();
                if (type.Inherits != null)
                {
                    inheritsList.Add(Type(type.Inherits, includeNested: true));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        inheritsList.Add(implStr);
                    }
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                {
                    inheritsList.Add("IExtensibleDataObject");
                }
                if (inheritsList.Count > 0)
                {
                    sb.AppendLine("    : {0}".Fmt(string.Join(", ", inheritsList.ToArray())));
                }

                sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                    {
                        continue;
                    }

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                               new CreateTypeOptions {
                        IsNestedType = true
                    });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();
            return(lastNS);
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List<MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
                return lastNS;

            var ns = Config.GlobalNamespace ?? type.Namespace;
            if (ns != lastNS)
            {
                if (lastNS != null)
                    sb.AppendLine("}");

                lastNS = ns;

                sb.AppendLine();
                sb.AppendLine("namespace {0}".Fmt(ns.SafeToken()));
                sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
                sb.AppendLine("[GeneratedCode(\"AddServiceStackReference\", \"{0}\")]".Fmt(Env.VersionString));

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null 
                            ? "{0},".Fmt(name) 
                            : "{0} = {1},".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var partial = Config.MakePartial ? "partial " : "";
                var defType = type.IsInterface() ? "interface" : "class";
                sb.AppendLine("public {0}{1} {2}".Fmt(partial, defType, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                var inheritsList = new List<string>();
                if (type.Inherits != null)
                {
                    inheritsList.Add(Type(type.Inherits, includeNested:true));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        inheritsList.Add(implStr);
                    if (!type.Implements.IsEmpty())
                        type.Implements.Each(x => inheritsList.Add(Type(x)));
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                    inheritsList.Add("IExtensibleDataObject");
                if (inheritsList.Count > 0)
                    sb.AppendLine("    : {0}".Fmt(string.Join(", ", inheritsList.ToArray())));

                sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                        continue;

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                        new CreateTypeOptions { IsNestedType = true });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();
            return lastNS;
        }
Beispiel #8
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public static enum {0}".Fmt(typeName));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    var hasIntValue = false;
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues?[i];

                        var delim       = i == type.EnumNames.Count - 1 ? ";" : ",";
                        var serializeAs = JsConfig.TreatEnumAsInteger || (type.Attributes.Safe().Any(x => x.Name == "Flags"))
                            ? "@SerializedName(\"{0}\") ".Fmt(value)
                            : "";

                        sb.AppendLine(value == null
                            ? "{0}{1}".Fmt(name.ToPascalCase(), delim)
                            : serializeAs + "{0}({1}){2}".Fmt(name.ToPascalCase(), value, delim));

                        hasIntValue = hasIntValue || value != null;
                    }

                    if (hasIntValue)
                    {
                        sb.AppendLine();
                        sb.AppendLine("private final int value;");
                        sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                        sb.AppendLine("public int getValue() { return value; }");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types      = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? "new TypeToken<{0}>(){{}}.getType()".Fmt(returnType)
                                : "{0}.class".Fmt(returnType);
                        }
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var extend = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    extend += " implements " + string.Join(", ", interfaces.ToArray());
                }

                var addPropertyAccessors = Config.AddPropertyAccessors && !type.IsInterface();
                var settersReturnType    = addPropertyAccessors && Config.SettersReturnThis ? typeName : null;

                sb.AppendLine("public static {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public Integer {0} = {1};".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));

                    if (addPropertyAccessors)
                    {
                        sb.AppendPropertyAccessor("Integer", "Version", settersReturnType);
                    }
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name),
                              addPropertyAccessors: addPropertyAccessors,
                              settersReturnType: settersReturnType);

                if (responseTypeExpression != null)
                {
                    sb.AppendLine("private static Object responseType = {0};".Fmt(responseTypeExpression));
                    sb.AppendLine("public Object getResponseType() { return responseType; }");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            sb = sb.UnIndent();

            return(lastNS);
        }
Beispiel #9
0
        private static string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            if (type == null || (type.Namespace != null && type.Namespace.StartsWith("System")))
                return lastNS;

            if (type.Namespace != lastNS)
            {
                if (lastNS != null)
                    sb.AppendLine("}");

                lastNS = type.Namespace;

                sb.AppendLine();
                sb.AppendLine("namespace {0}".Fmt(type.Namespace.SafeToken()));
                sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            sb.AppendComments(type.Description);
            sb.AppendDataContract(type.DataContract);

            var partial = Config.MakePartial ? "partial " : "";
            sb.AppendLine("public {0}class {1}".Fmt(partial, type.Name.SafeToken()));

            //: BaseClass, Interfaces
            var inheritsList = new List<string>();
            if (type.Inherits != null)
                inheritsList.Add(Type(type.Inherits, type.InheritsGenericArgs));
            if (options.ImplementsFn != null)
            {
                var implStr = options.ImplementsFn();
                if (!string.IsNullOrEmpty(implStr))
                    inheritsList.Add(implStr);
            }

            var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
            if (makeExtensible)
                inheritsList.Add("IExtensibleDataObject");
            if (inheritsList.Count > 0)
                sb.AppendLine("    : {0}".Fmt(string.Join(", ", inheritsList.ToArray())));

            sb.AppendLine("{");
            sb = sb.Indent();

            sb.AddConstuctor(type, options);
            sb.AddProperties(type);

            sb = sb.UnIndent();
            sb.AppendLine("}");

            sb = sb.UnIndent();
            return lastNS;
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List <MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
            {
                return(lastNS);
            }

            if (!Config.ExcludeNamespace)
            {
                var ns = Config.GlobalNamespace ?? type.Namespace;
                if (ns != lastNS)
                {
                    if (lastNS != null)
                    {
                        sb.AppendLine("}");
                    }

                    lastNS = ns;

                    sb.AppendLine();
                    sb.AppendLine($"namespace {ns.SafeToken()}");
                    sb.AppendLine("{");
                }

                sb = sb.Indent();
            }

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine($"[GeneratedCode(\"AddServiceStackReference\", \"{Env.VersionString}\")]");
            }

            var typeAccessor = !Config.MakeInternal ? "public" : "internal";

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine($"{typeAccessor} enum {Type(type.Name, type.GenericArgs)}");
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues?[i];
                        sb.AppendLine(value == null
                            ? $"{name},"
                            : $"{name} = {value},");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var partial = Config.MakePartial ? "partial " : "";
                var defType = type.IsInterface() ? "interface" : "class";
                sb.AppendLine($"{typeAccessor} {partial}{defType} {Type(type.Name, type.GenericArgs)}");

                //: BaseClass, Interfaces
                var inheritsList = new List <string>();
                if (type.Inherits != null)
                {
                    inheritsList.Add(Type(type.GetInherits(), includeNested: true));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        inheritsList.Add(implStr);
                    }
                }

                type.Implements.Each(x => inheritsList.Add(Type(x)));

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                {
                    inheritsList.Add("IExtensibleDataObject");
                }
                if (inheritsList.Count > 0)
                {
                    sb.AppendLine($"    : {string.Join(", ", inheritsList.ToArray())}");
                }

                sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                    {
                        continue;
                    }

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                               new CreateTypeOptions {
                        IsNestedType = true
                    });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            if (!Config.ExcludeNamespace)
            {
                sb = sb.UnIndent();
            }

            return(lastNS);
        }
Beispiel #11
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                var typeDeclaration = !Config.ExportAsTypes
                    ? "enum"
                    : "export const enum";

                sb.AppendLine("{0} {1}".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name.PropertyStyle())
                            : "{0} = {1},".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                var interfaces = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);
                    }
                }

                var isClass = Config.ExportAsTypes && !type.IsInterface.GetValueOrDefault();
                var extend  = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    extend += " implements " + string.Join(", ", interfaces.ToArray());
                }

                var typeDeclaration = !Config.ExportAsTypes
                    ? "interface"
                    : "export {0}".Fmt(isClass ? "class" : "interface");

                sb.AppendLine("{0} {1}{2}".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}{1}: number; //{2}".Fmt(
                                      "Version".PropertyStyle(), isClass ? "" : "?", Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return(lastNS);
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List<MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
                return lastNS;

            var ns = Config.GlobalNamespace ?? type.Namespace;
            if (ns != lastNS)
            {
                if (lastNS != null)
                    sb.AppendLine("End Namespace");

                lastNS = ns;

                sb.AppendLine();
                sb.AppendLine("Namespace {0}".Fmt(ns.SafeToken()));
                //sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("Public Enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                //sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0}".Fmt(name)
                            : "{0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("End Enum");
            }
            else
            {
                var partial = Config.MakePartial && !type.IsInterface() ? "Partial " : "";
                var defType = type.IsInterface() ? "Interface" : "Class";
                sb.AppendLine("Public {0}{1} {2}".Fmt(partial, defType, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    sb.AppendLine("    Inherits {0}".Fmt(Type(type.Inherits, includeNested: true)));
                }

                var implements = new List<string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        implements.Add(implStr);
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                    implements.Add("IExtensibleDataObject");

                if (implements.Count > 0)
                {
                    foreach (var x in implements)
                    {
                        sb.AppendLine("    Implements {0}".Fmt(x));
                    }
                }

                //sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type);

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                        continue;

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                        new CreateTypeOptions { IsNestedType = true });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine(type.IsInterface() ? "End Interface" : "End Class");
            }

            sb = sb.UnIndent();
            return lastNS;
        }
Beispiel #13
0
        private void ExtractTypeAliases(CreateTypeOptions options, List <string> typeAliases, List <string> extends, ref StringBuilderWrapper sbExt)
        {
            var implStr = options.ImplementsFn();

            if (!string.IsNullOrEmpty(implStr))
            {
                var interfaceParts = implStr.SplitOnFirst('<');
                if (interfaceParts.Length > 1)
                {
                    implStr = interfaceParts[0];

                    //Strip 'I' prefix for interfaces and use as typealias for protocol
                    var alias = implStr.StartsWith("I")
                        ? implStr.Substring(1)
                        : implStr;

                    var genericType = interfaceParts[1].Substring(0, interfaceParts[1].Length - 1);


                    //Workaround segfault for adding JsonSerializable extension to String and
                    //segfault when NSString extension is not declared in same file as DTO's
                    if (alias == "Return" && genericType == "String")
                    {
                        typeAliases.Add("typealias {0} = {1}".Fmt(alias, "NSString"));
                        if (!emittedNSStringExtension)
                        {
                            emittedNSStringExtension = true;
                            sbExt.AppendLine(@"
extension NSString : JsonSerializable
{
    public static var typeName:String { return ""NSString"" }
    
    public static func reflect() -> Type<NSString> {
        return Type<NSString>(properties:[])
    }
    
    public func toString() -> String {
        return self as String
    }
    
    public func toJson() -> String {
        return jsonString(self as String)
    }
    
    public static func fromJson(json:String) -> NSString? {
        return parseJson(json) as? NSString
    }
    
    public static func fromString(string: String) -> NSString? {
        return string
    }
    
    public static func fromObject(any:AnyObject) -> NSString?
    {
        switch any {
        case let s as NSString: return s
        default:return nil
        }
    }
}");
                        }
                    }
                    else
                    {
                        typeAliases.Add("typealias {0} = {1}".Fmt(alias, genericType));
                    }
                }

                extends.Add(implStr);
            }
        }
Beispiel #14
0
        private string AppendType(ref StringBuilderWrapper sb, ref StringBuilderWrapper sbExt, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            if (type.IgnoreSystemType())
            {
                return(lastNS);
            }

            //sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0} : Int".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "case {0}".Fmt(name.PropertyStyle())
                            : "case {0} = {1}".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");

                AddEnumExtension(ref sbExt, type);
            }
            else
            {
                var defType  = "class";
                var typeName = Type(type.Name, type.GenericArgs);
                var extends  = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    var baseType = Type(type.Inherits).InheritedType();

                    //Swift requires re-declaring base type generics definition on super type
                    var genericDefPos = baseType.IndexOf("<");
                    if (genericDefPos >= 0)
                    {
                        typeName += baseType.Substring(genericDefPos);
                    }

                    extends.Add(baseType);
                }

                var typeAliases = new List <string>();

                if (options.ImplementsFn != null)
                {
                    //Swift doesn't support Generic Interfaces like IReturn<T>
                    //Converting them into protocols with typealiases instead
                    ExtractTypeAliases(options, typeAliases, extends);
                }

                if (type.IsInterface())
                {
                    defType = "protocol";

                    //Extract Protocol Arguments into different typealiases
                    if (!type.GenericArgs.IsEmpty())
                    {
                        typeName = Type(type.Name, null);
                        foreach (var arg in type.GenericArgs)
                        {
                            typeAliases.Add("typealias {0} = {0}".Fmt(arg));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " : " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("public {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                if (typeAliases.Count > 0)
                {
                    foreach (var typeAlias in typeAliases)
                    {
                        sb.AppendLine(typeAlias);
                    }
                    sb.AppendLine();
                }

                if (!type.IsInterface())
                {
                    sb.AppendLine("required public init(){}");
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                if (addVersionInfo)
                {
                    sb.AppendLine("public var {0}:Int = {1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                              initCollections: !type.IsInterface() && Config.InitializeCollections);

                sb = sb.UnIndent();
                sb.AppendLine("}");

                if (!type.IsInterface())
                {
                    AddTypeExtension(ref sbExt, type,
                                     initCollections: Config.InitializeCollections);
                }
            }

            //sb = sb.UnIndent();

            return(lastNS);
        }
Beispiel #15
0
        private void AddConstuctor(StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (type.IsInterface())
                return;
            if (Config.AddImplicitVersion == null && !Config.InitializeCollections)
                return;

            var collectionProps = new List<MetadataPropertyType>();
            if (type.Properties != null && Config.InitializeCollections)
                collectionProps = type.Properties.Where(x => x.IsCollection()).ToList();

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
            if (!addVersionInfo && collectionProps.Count <= 0) return;

            if (addVersionInfo)
            {
                var @virtual = Config.MakeVirtual ? "Overridable " : "";
                sb.AppendLine("Public {0}Property Version As Integer".Fmt(@virtual));
                sb.AppendLine();
            }

            sb.AppendLine("Public Sub New()".Fmt(NameOnly(type.Name)));
            //sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
                sb.AppendLine("Version = {0}".Fmt(Config.AddImplicitVersion));

            foreach (var prop in collectionProps)
            {
                var suffix = prop.IsArray() ? "{}" : "";
                sb.AppendLine("{0} = New {1}{2}".Fmt(
                prop.Name.SafeToken(),
                Type(prop.Type, prop.GenericArgs, includeNested:true),
                suffix));
            }

            sb = sb.UnIndent();
            sb.AppendLine("End Sub");
            sb.AppendLine();
        }
        private void ExtractTypeAliases(CreateTypeOptions options, List<string> typeAliases, List<string> extends, ref StringBuilderWrapper sbExt)
        {
            var implStr = options.ImplementsFn();
            if (!string.IsNullOrEmpty(implStr))
            {
                var interfaceParts = implStr.SplitOnFirst('<');
                if (interfaceParts.Length > 1)
                {
                    implStr = interfaceParts[0];

                    //Strip 'I' prefix for interfaces and use as typealias for protocol
                    var alias = implStr.StartsWith("I")
                        ? implStr.Substring(1)
                        : implStr;

                    var genericType = interfaceParts[1].Substring(0, interfaceParts[1].Length - 1);


                    //Workaround segfault for adding JsonSerializable extension to String and
                    //segfault when NSString extension is not declared in same file as DTO's  
                    if (alias == "Return" && genericType == "String")
                    {
                        typeAliases.Add("typealias {0} = {1}".Fmt(alias, "NSString"));
                        if (!emittedNSStringExtension)
                        {
                            emittedNSStringExtension = true;
                            sbExt.AppendLine(@"
extension NSString : JsonSerializable
{
    public static var typeName:String { return ""NSString"" }
    
    public static func reflect() -> Type<NSString> {
        return Type<NSString>(properties:[])
    }
    
    public func toString() -> String {
        return self as String
    }
    
    public func toJson() -> String {
        return jsonString(self as String)
    }
    
    public static func fromJson(json:String) -> NSString? {
        return parseJson(json) as? NSString
    }
    
    public static func fromString(string: String) -> NSString? {
        return string
    }
    
    public static func fromObject(any:AnyObject) -> NSString?
    {
        switch any {
        case let s as NSString: return s
        default:return nil
        }
    }
}");
                        }
                    }
                    else
                    {
                        typeAliases.Add("typealias {0} = {1}".Fmt(alias, genericType));
                    }
                }

                extends.Add(implStr);
            }
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            if (type.IsEnum.GetValueOrDefault())
            {
                var hasIntValue = type.EnumNames.Count == (type.EnumValues != null ? type.EnumValues.Count : 0);
                var enumConstructor = hasIntValue ? "(val value:Int)" : "";

                sb.AppendLine("enum class {0}{1}".Fmt(typeName, enumConstructor));
                sb.AppendLine("{");
                sb = sb.Indent();


                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = hasIntValue ? type.EnumValues[i] : null;

                        var serializeAs = JsConfig.TreatEnumAsInteger || (type.Attributes.Safe().Any(x => x.Name == "Flags"))
                            ? "@SerializedName(\"{0}\") ".Fmt(value)
                            : "";

                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name.ToPascalCase())
                            : serializeAs + "{0}({1}),".Fmt(name.ToPascalCase(), value));
                    }

                    //if (hasIntValue)
                    //{
                    //    sb.AppendLine();
                    //    sb.AppendLine("private final int value;");
                    //    sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                    //    sb.AppendLine("public int getValue() { return value; }");
                    //}
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    extends.Add(Type(type.Inherits).InheritedType());

                string responseTypeExpression = null;

                var interfaces = new List<string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var parts = implStr.SplitOnFirst('<');
                            var returnType = parts[1].Substring(0, parts[1].Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? "object : TypeToken<{0}>(){{}}.type".Fmt(returnType)
                                : "{0}::class.java".Fmt(returnType);
                        }
                    }
                    if (!type.Implements.IsEmpty())
                    {
                        foreach (var interfaceRef in type.Implements)
                        {
                            interfaces.Add(Type(interfaceRef));
                        }
                    }
                }

                var extend = extends.Count > 0 
                    ? " : " + extends[0] + "()"
                    : "";

                if (interfaces.Count > 0)
                    extend += (extend.IsNullOrEmpty() ? " : " : ", ") + string.Join(", ", interfaces.ToArray());

                sb.AppendLine("open {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("val {0}:Int = {1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                    initCollections: !type.IsInterface() && Config.InitializeCollections,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (responseTypeExpression != null)
                {
                    sb.AppendLine("companion object {{ private val responseType = {0} }}".Fmt(responseTypeExpression));
                    sb.AppendLine("override fun getResponseType(): Any? = responseType");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            return lastNS;
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                if (type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty())
                {
                    var typeDeclaration = !Config.ExportAsTypes
                        ? "enum"
                        : "export enum";

                    sb.AppendLine($"{typeDeclaration} {Type(type.Name, type.GenericArgs)}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name  = type.EnumNames[i];
                            var value = type.EnumValues?[i];

                            sb.AppendLine(value == null //Enum Value's are not impacted by JS Style
                                ? $"{name},"
                                : $"{name} = {value},");
                        }
                    }

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    var sbType = StringBuilderCache.Allocate();

                    var typeDeclaration = !Config.ExportAsTypes
                        ? "type"
                        : "export type";

                    sbType.Append($"{typeDeclaration} {Type(type.Name, type.GenericArgs)} = ");

                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        if (i > 0)
                        {
                            sbType.Append(" | ");
                        }

                        sbType.Append('"').Append(type.EnumNames[i]).Append('"');
                    }

                    sbType.Append(";");

                    sb.AppendLine(StringBuilderCache.ReturnAndFree(sbType));
                }
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InDeclarationType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                var implStr    = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (Config.ExportAsTypes)
                    {
                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types      = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            if (returnType == "any")
                            {
                                returnType = "Object";
                            }

                            // This is to avoid invalid syntax such as "return new string()"
                            if (primitiveDefaultValues.TryGetValue(returnType, out var replaceReturnType))
                            {
                                returnType = replaceReturnType;
                            }

                            responseTypeExpression = replaceReturnType == null ?
                                                     "createResponse() {{ return new {0}(); }}".Fmt(returnType) :
                                                     "createResponse() {{ return {0}; }}".Fmt(returnType);
                        }
                        else if (implStr == "IReturnVoid")
                        {
                            responseTypeExpression = "createResponse() {}";
                        }
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var isClass = Config.ExportAsTypes && !type.IsInterface.GetValueOrDefault();
                var extend  = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                        {
                            extend = " extends ";
                        }
                        else
                        {
                            extend += ", ";
                        }

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !Config.ExportAsTypes
                    ? "interface"
                    : $"export {(isClass ? "class" : "interface")}";

                sb.AppendLine("{0} {1}{2}".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}{1}: number; //{2}".Fmt(
                                      "Version".PropertyStyle(), isClass ? "" : "?", Config.AddImplicitVersion));
                }

                if (Config.ExportAsTypes)
                {
                    if (type.Name == "IReturn`1")
                    {
                        sb.AppendLine("createResponse() : T;");
                    }
                    else if (type.Name == "IReturnVoid")
                    {
                        sb.AppendLine("createResponse() : void;");
                    }
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (Config.ExportAsTypes && responseTypeExpression != null)
                {
                    sb.AppendLine(responseTypeExpression);
                    sb.AppendLine("getTypeName() {{ return \"{0}\"; }}".Fmt(type.Name));
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            return(lastNS);
        }
Beispiel #19
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            if (type.IgnoreSystemType())
            {
                return(lastNS);
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name.PropertyStyle())
                            : "{0} = {1},".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        extends.Add(implStr);
                    }
                }

                var extend = extends.Count > 0
                    ? " extends " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("interface {0}{1}".Fmt(Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}: number; //{1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type);

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return(lastNS);
        }
Beispiel #20
0
        private string AppendType(ref StringBuilderWrapper sb, ref StringBuilderWrapper sbExt, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            //sb = sb.Indent();

            if (Config.ExcludeGenericBaseTypes && type.Inherits != null && !type.Inherits.GenericArgs.IsEmpty())
            {
                sb.AppendLine("//Excluded {0} : {1}<{2}>".Fmt(type.Name, type.Inherits.Name.SplitOnFirst('`')[0], string.Join(",", type.Inherits.GenericArgs)));
                return(lastNS);
            }

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0} : Int".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "case {0}".Fmt(name)
                            : "case {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");

                AddEnumExtension(ref sbExt, type);
            }
            else
            {
                var defType  = "class";
                var typeName = Type(type.Name, type.GenericArgs).AddGenericConstraints();
                var extends  = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    var baseType = Type(type.Inherits).InheritedType();

                    //Swift requires re-declaring base type generics definition on super type
                    var genericDefPos = baseType.IndexOf("<");
                    if (genericDefPos >= 0)
                    {
                        //Need to declare BaseType is JsonSerializable
                        var subBaseType = baseType.Substring(genericDefPos)
                                          .AddGenericConstraints();

                        typeName += subBaseType;
                    }

                    extends.Add(baseType);
                }
                else if (Config.BaseClass != null && !type.IsInterface())
                {
                    extends.Add(Config.BaseClass);
                }

                var typeAliases = new List <string>();

                if (options.ImplementsFn != null)
                {
                    //Swift doesn't support Generic Interfaces like IReturn<T>
                    //Converting them into protocols with typealiases instead
                    ExtractTypeAliases(options, typeAliases, extends, ref sbExt);

                    if (!type.Implements.IsEmpty())
                    {
                        type.Implements.Each(x => extends.Add(Type(x)));
                    }
                }

                if (type.IsInterface())
                {
                    defType = "protocol";

                    //Extract Protocol Arguments into different typealiases
                    if (!type.GenericArgs.IsEmpty())
                    {
                        typeName = Type(type.Name, null);
                        foreach (var arg in type.GenericArgs)
                        {
                            typeAliases.Add("public typealias {0} = {0}".Fmt(arg));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " : " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("public {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                if (typeAliases.Count > 0)
                {
                    foreach (var typeAlias in typeAliases)
                    {
                        sb.AppendLine(typeAlias);
                    }
                    sb.AppendLine();
                }

                if (!type.IsInterface())
                {
                    if (extends.Count > 0 && OverrideInitForBaseClasses.Contains(extends[0]))
                    {
                        sb.AppendLine("required public override init(){}");
                    }
                    else
                    {
                        sb.AppendLine("required public init(){}");
                    }
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public var {0}:Int = {1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                              initCollections: !type.IsInterface() && Config.InitializeCollections,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                sb = sb.UnIndent();
                sb.AppendLine("}");

                if (!type.IsInterface())
                {
                    AddTypeExtension(ref sbExt, type,
                                     initCollections: Config.InitializeCollections);
                }
            }

            //sb = sb.UnIndent();

            return(lastNS);
        }
Beispiel #21
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List <MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
            {
                return(lastNS);
            }

            var ns = Config.GlobalNamespace ?? type.Namespace;

            if (ns != lastNS)
            {
                if (lastNS != null)
                {
                    sb.AppendLine("End Namespace");
                }

                lastNS = ns;

                sb.AppendLine();
                sb.AppendLine($"Namespace {MetadataExtensions.SafeToken(ns)}");
                //sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine($"<GeneratedCode(\"AddServiceStackReference\", \"{Env.VersionString}\")>");
            }

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("Public Enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues?[i];
                        if (KeyWords.Contains(name))
                        {
                            name = $"[{name}]";
                        }

                        var memberValue = type.GetEnumMemberValue(i);
                        if (memberValue != null)
                        {
                            AppendAttributes(sb, new List <MetadataAttribute> {
                                new MetadataAttribute {
                                    Name = "EnumMember",
                                    Args = new List <MetadataPropertyType> {
                                        new MetadataPropertyType {
                                            Name  = "Value",
                                            Value = memberValue,
                                            Type  = "String",
                                        }
                                    }
                                }
                            });
                        }
                        sb.AppendLine(value == null
                            ? $"{name},"
                            : $"{name} = {value},");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("End Enum");
            }
            else
            {
                var partial = Config.MakePartial && !type.IsInterface() ? "Partial " : "";
                var defType = type.IsInterface() ? "Interface" : "Class";
                sb.AppendLine("Public {0}{1} {2}".Fmt(partial, defType, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    sb.AppendLine($"    Inherits {Type(type.Inherits, includeNested: true)}");
                }

                var implements = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        implements.Add(implStr);
                    }
                }

                type.Implements.Each(x => implements.Add(Type(x)));

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                {
                    implements.Add("IExtensibleDataObject");
                }

                if (implements.Count > 0)
                {
                    foreach (var x in implements)
                    {
                        sb.AppendLine($"    Implements {x}");
                    }
                }

                sb = sb.Indent();

                AddConstructor(sb, type, options);
                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                    {
                        continue;
                    }

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                               new CreateTypeOptions {
                        IsNestedType = true
                    });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine(type.IsInterface() ? "End Interface" : "End Class");
            }

            PostTypeFilter?.Invoke(sb, type);

            sb = sb.UnIndent();
            return(lastNS);
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0},".Fmt(name.PropertyStyle())
                            : "{0} = {1},".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    extends.Add(Type(type.Inherits).InheritedType());

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        extends.Add(implStr);
                }

                var extend = extends.Count > 0
                    ? " extends " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("interface {0}{1}".Fmt(Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}?: number; //{1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return lastNS;
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                var isIntEnum = type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty();
                if ((isIntEnum || !UseUnionTypeEnums) && Config.ExportAsTypes)
                {
                    var typeDeclaration = !Config.ExportAsTypes
                        ? "enum"
                        : "export enum";

                    sb.AppendLine($"{typeDeclaration} {Type(type.Name, type.GenericArgs)}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name  = type.EnumNames[i];
                            var value = type.EnumValues?[i];

                            var memberValue = type.GetEnumMemberValue(i);
                            if (memberValue != null)
                            {
                                sb.AppendLine($"{name} = '{memberValue}',");
                                continue;
                            }

                            sb.AppendLine(value == null
                                ? $"{name} = '{name}',"
                                : $"{name} = {value},");
                        }
                    }

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    var sbType = StringBuilderCache.Allocate();

                    var typeDeclaration = !Config.ExportAsTypes
                        ? "type"
                        : "export type";

                    sbType.Append($"{typeDeclaration} {Type(type.Name, type.GenericArgs)} = ");

                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        if (i > 0)
                        {
                            sbType.Append(" | ");
                        }

                        sbType.Append('"').Append(type.EnumNames[i]).Append('"');
                    }

                    sbType.Append(";");

                    sb.AppendLine(StringBuilderCache.ReturnAndFree(sbType));
                }
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(DeclarationType(type.Inherits.Name, type.Inherits.GenericArgs, out var addDeclaration));

                    if (addDeclaration != null && !AddedDeclarations.Contains(addDeclaration))
                    {
                        AddedDeclarations.Add(addDeclaration);
                        sb.AppendLine(addDeclaration);
                        sb.AppendLine();
                    }
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                var implStr    = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (Config.ExportAsTypes)
                    {
                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types      = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            // This is to avoid invalid syntax such as "return new string()"
                            primitiveDefaultValues.TryGetValue(returnType, out var replaceReturnType);

                            if (returnType == "any")
                            {
                                replaceReturnType = "{}";
                            }
                            else if (returnType.EndsWith("[]"))
                            {
                                replaceReturnType = $"new Array<{returnType.Substring(0, returnType.Length -2)}>()";
                            }

                            responseTypeExpression = replaceReturnType == null ?
                                                     "public createResponse() {{ return new {0}(); }}".Fmt(returnType) :
                                                     "public createResponse() {{ return {0}; }}".Fmt(replaceReturnType);
                        }
                        else if (implStr == "IReturnVoid")
                        {
                            responseTypeExpression = "public createResponse() {}";
                        }
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var isClass  = Config.ExportAsTypes && !type.IsInterface.GetValueOrDefault();
                var modifier = isClass ? "public " : "";
                var extend   = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                        {
                            extend = " extends ";
                        }
                        else
                        {
                            extend += ", ";
                        }

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !Config.ExportAsTypes
                    ? "interface"
                    : $"export {(isClass ? "class" : "interface")}";

                var typeName = Type(type.Name, type.GenericArgs);
                sb.AppendLine($"{typeDeclaration} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine(modifier + "{0}{1}: number; //{2}".Fmt(
                                      "Version".PropertyStyle(), isClass ? "" : "?", Config.AddImplicitVersion));
                }

                if (Config.ExportAsTypes)
                {
                    if (type.Name == "IReturn`1")
                    {
                        sb.AppendLine("createResponse(): T;");
                    }
                    else if (type.Name == "IReturnVoid")
                    {
                        sb.AppendLine("createResponse(): void;");
                    }
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (EmitPartialConstructors && Config.ExportAsTypes && isClass)
                {
                    sb.AppendLine();
                    var callSuper = type.Inherits != null
                        ? !(extend.StartsWith(" extends Array<") || extend.StartsWith(" extends Dictionary<"))
                            ? "super(init); "
                            : "super(); "
                        : "";
                    sb.AppendLine($"public constructor(init?: Partial<{typeName}>) {{ {callSuper}(Object as any).assign(this, init); }}");
                }

                if (Config.ExportAsTypes && responseTypeExpression != null)
                {
                    sb.AppendLine(responseTypeExpression);
                    sb.AppendLine("public getTypeName() {{ return '{0}'; }}".Fmt(type.Name));
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            return(lastNS);
        }
Beispiel #24
0
        private static void AddConstuctor(this StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (Config.AddImplicitVersion == null && !Config.InitializeCollections) 
                return;

            var collectionProps = new List<MetadataPropertyType>();
            if (type.Properties != null && Config.InitializeCollections)
                collectionProps = type.Properties.Where(IsCollection).ToList();

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
            if (!addVersionInfo && collectionProps.Count <= 0) return;

            if (addVersionInfo)
            {
                var @virtual = Config.MakeVirtual ? "virtual " : "";
                sb.AppendLine("public {0}int Version {{ get; set; }}".Fmt(@virtual));
                sb.AppendLine();
            }

            sb.AppendLine("public {0}()".Fmt(type.Name.SafeToken()));
            sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
                sb.AppendLine("Version = {0};".Fmt(Config.AddImplicitVersion));

            foreach (var prop in collectionProps)
            {
                sb.AppendLine("{0} = new {1}{{}};".Fmt(
                prop.Name.SafeToken(),
                Type(prop.Type, prop.GenericArgs)));
            }

            sb = sb.UnIndent();
            sb.AppendLine("}");
            sb.AppendLine();
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            if (type == null || (type.Namespace != null && type.Namespace.StartsWith("System")))
                return lastNS;

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("type {0} =".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : i.ToString();
                        sb.AppendLine("| {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
            }
            else
            {
                //sb.AppendLine("[<CLIMutable>]"); // only for Record Types
                sb.AppendLine("[<AllowNullLiteral>]");
                sb.AppendLine("type {0}() = ".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();
                var startLen = sb.Length;

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    sb.AppendLine("inherit {0}()".Fmt(Type(type.Inherits)));

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        sb.AppendLine("interface {0}".Fmt(implStr));
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                {
                    sb.AppendLine("interface IExtensibleDataObject with");
                    sb.AppendLine("    member val ExtensionData:ExtensionDataObject = null with get, set");
                    sb.AppendLine("end");
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                if (addVersionInfo)
                {
                    sb.AppendLine("member val Version:int = {0} with get, set".Fmt(Config.AddImplicitVersion));
                }

                AddProperties(sb, type);

                if (sb.Length == startLen)
                    sb.AppendLine("class end");

                sb = sb.UnIndent();
            }

            sb = sb.UnIndent();
            return lastNS;
        }
Beispiel #26
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                var hasIntValue     = type.EnumNames.Count == (type.EnumValues?.Count ?? 0);
                var enumConstructor = hasIntValue ? "(val value:Int)" : "";

                sb.AppendLine($"enum class {typeName}{enumConstructor}");
                sb.AppendLine("{");
                sb = sb.Indent();


                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = hasIntValue ? type.EnumValues[i] : null;

                        var serializeAs = JsConfig.TreatEnumAsInteger || type.Attributes.Safe().Any(x => x.Name == "Flags")
                            ? $"@SerializedName(\"{value}\") "
                            : "";

                        sb.AppendLine(value == null
                            ? $"{name.ToPascalCase()},"
                            : serializeAs + $"{name.ToPascalCase()}({value}),");
                    }

                    //if (hasIntValue)
                    //{
                    //    sb.AppendLine();
                    //    sb.AppendLine("private final int value;");
                    //    sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                    //    sb.AppendLine("public int getValue() { return value; }");
                    //}
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InheritedType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types      = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? $"object : TypeToken<{returnType}>(){{}}.type"
                                : $"{returnType}::class.java";
                        }
                    }
                }
                type.Implements.Each(x => interfaces.Add(Type(x)));

                var extend = extends.Count > 0
                    ? " : " + extends[0] + "()"
                    : "";

                if (interfaces.Count > 0)
                {
                    extend += (extend.IsNullOrEmpty() ? " : " : ", ") + string.Join(", ", interfaces.ToArray());
                }

                sb.AppendLine($"open {defType} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine($"val {"Version".PropertyStyle()}:Int = {Config.AddImplicitVersion}");
                }

                AddProperties(sb, type,
                              initCollections: !type.IsInterface() && Config.InitializeCollections,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (responseTypeExpression != null)
                {
                    sb.AppendLine($"companion object {{ private val responseType = {responseTypeExpression} }}");
                    sb.AppendLine($"override fun getResponseType(): Any? = {typeName}.responseType");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            return(lastNS);
        }
Beispiel #27
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            if (type == null || (type.Namespace != null && type.Namespace.StartsWith("System")))
            {
                return(lastNS);
            }

            if (type.Namespace != lastNS)
            {
                if (lastNS != null)
                {
                    sb.AppendLine("}");
                }

                lastNS = type.Namespace;

                sb.AppendLine();
                sb.AppendLine("namespace {0}".Fmt(type.Namespace.SafeToken()));
                sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var partial = Config.MakePartial ? "partial " : "";

            sb.AppendLine("public {0}class {1}".Fmt(partial, Type(type.Name, type.GenericArgs)));

            //: BaseClass, Interfaces
            var inheritsList = new List <string>();

            if (type.Inherits != null)
            {
                inheritsList.Add(Type(type.Inherits));
            }
            if (options.ImplementsFn != null)
            {
                var implStr = options.ImplementsFn();
                if (!string.IsNullOrEmpty(implStr))
                {
                    inheritsList.Add(implStr);
                }
            }

            var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;

            if (makeExtensible)
            {
                inheritsList.Add("IExtensibleDataObject");
            }
            if (inheritsList.Count > 0)
            {
                sb.AppendLine("    : {0}".Fmt(string.Join(", ", inheritsList.ToArray())));
            }

            sb.AppendLine("{");
            sb = sb.Indent();

            AddConstuctor(sb, type, options);
            AddProperties(sb, type);

            sb = sb.UnIndent();
            sb.AppendLine("}");

            sb = sb.UnIndent();
            return(lastNS);
        }
Beispiel #28
0
        private void AddConstuctor(StringBuilderWrapper sb, MetadataType type, CreateTypeOptions options)
        {
            if (type.IsInterface())
                return;

            var initCollections = feature.ShouldInitializeCollections(type, Config.InitializeCollections);
            if (Config.AddImplicitVersion == null && !initCollections)
                return;

            var collectionProps = new List<MetadataPropertyType>();
            if (type.Properties != null && initCollections)
                collectionProps = type.Properties.Where(x => x.IsCollection()).ToList();

            var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
            if (!addVersionInfo && collectionProps.Count <= 0) return;

            if (addVersionInfo)
            {
                var @virtual = Config.MakeVirtual ? "virtual " : "";
                sb.AppendLine("public {0}int Version {{ get; set; }}".Fmt(@virtual));
                sb.AppendLine();
            }

            sb.AppendLine("public {0}()".Fmt(NameOnly(type.Name)));
            sb.AppendLine("{");
            sb = sb.Indent();

            if (addVersionInfo)
                sb.AppendLine("Version = {0};".Fmt(Config.AddImplicitVersion));

            foreach (var prop in collectionProps)
            {
                sb.AppendLine("{0} = new {1}{{}};".Fmt(
                prop.Name.SafeToken(),
                Type(prop.Type, prop.GenericArgs, includeNested: true)));
            }

            sb = sb.UnIndent();
            sb.AppendLine("}");
            sb.AppendLine();
        }
Beispiel #29
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (options?.Routes != null)
            {
                AppendAttributes(sb, options.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine("[<GeneratedCode(\"AddServiceStackReference\", \"{0}\")>]".Fmt(Env.VersionString));
            }

            sb.Emit(type, Lang.FSharp);
            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("type {0} =".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : i.ToString();
                        sb.AppendLine("| {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
            }
            else
            {
                //sb.AppendLine("[<CLIMutable>]"); // only for Record Types
                var classCtor = type.IsInterface() ? "" : "()";
                sb.AppendLine("[<AllowNullLiteral>]");
                sb.AppendLine("type {0}{1} = ".Fmt(Type(type.Name, type.GenericArgs), classCtor));
                sb = sb.Indent();
                var startLen = sb.Length;

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    sb.AppendLine("inherit {0}()".Fmt(Type(type.Inherits)));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        sb.AppendLine($"interface {implStr}");
                    }
                }

                InnerTypeFilter?.Invoke(sb, type);

                if (!type.IsInterface())
                {
                    var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                    if (makeExtensible)
                    {
                        sb.AppendLine("interface IExtensibleDataObject with");
                        sb.AppendLine("    member val ExtensionData:ExtensionDataObject = null with get, set");
                        sb.AppendLine("end");
                    }

                    var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                    if (addVersionInfo)
                    {
                        sb.AppendLine("member val Version:int = {0} with get, set".Fmt(Config.AddImplicitVersion));
                    }
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != nameof(ResponseStatus)));

                if (sb.Length == startLen)
                {
                    sb.AppendLine(type.IsInterface() ? "interface end" : "class end");
                }

                sb = sb.UnIndent();
            }

            PostTypeFilter?.Invoke(sb, type);

            sb = sb.UnIndent();
            return(lastNS);
        }
        private string AppendType(ref StringBuilderWrapper sb, ref StringBuilderWrapper sbExt, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            //sb = sb.Indent();

            var hasGenericBaseType = type.Inherits != null && !type.Inherits.GenericArgs.IsEmpty();
            if (Config.ExcludeGenericBaseTypes && hasGenericBaseType)
            {
                sb.AppendLine("//Excluded {0} : {1}<{2}>".Fmt(type.Name, type.Inherits.Name.SplitOnFirst('`')[0], string.Join(",", type.Inherits.GenericArgs)));
                return lastNS;
            }

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0} : Int".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "case {0}".Fmt(name)
                            : "case {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");

                AddEnumExtension(ref sbExt, type);
            }
            else
            {
                var defType = "class";
                var typeName = Type(type.Name, type.GenericArgs).AddGenericConstraints();
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    var baseType = Type(type.Inherits).InheritedType();

                    //Swift requires re-declaring base type generics definition on super type
                    var genericDefPos = baseType.IndexOf("<");
                    if (genericDefPos >= 0)
                    {
                        //Need to declare BaseType is JsonSerializable
                        var subBaseType = baseType.Substring(genericDefPos)
                            .AddGenericConstraints();

                        typeName += subBaseType;
                    }

                    extends.Add(baseType);
                }
                else if (Config.BaseClass != null && !type.IsInterface())
                {
                    extends.Add(Config.BaseClass);
                }

                var typeAliases = new List<string>();

                if (options.ImplementsFn != null)
                {
                    //Swift doesn't support Generic Interfaces like IReturn<T> 
                    //Converting them into protocols with typealiases instead 
                    ExtractTypeAliases(options, typeAliases, extends, ref sbExt);

                    if (!type.Implements.IsEmpty())
                        type.Implements.Each(x => extends.Add(Type(x)));
                }

                if (type.IsInterface())
                {
                    defType = "protocol";

                    //Extract Protocol Arguments into different typealiases
                    if (!type.GenericArgs.IsEmpty())
                    {
                        typeName = Type(type.Name, null);
                        foreach (var arg in type.GenericArgs)
                        {
                            typeAliases.Add("public typealias {0} = {0}".Fmt(arg));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " : " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("public {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                if (typeAliases.Count > 0)
                {
                    foreach (var typeAlias in typeAliases)
                    {
                        sb.AppendLine(typeAlias);
                    }
                    sb.AppendLine();
                }

                if (!type.IsInterface())
                {
                    if (extends.Count > 0 && OverrideInitForBaseClasses.Contains(extends[0]))
                    {
                        sb.AppendLine("required public override init(){}");
                    }
                    else
                    {
                        sb.AppendLine("required public init(){}");
                    }
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public var {0}:Int = {1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                    initCollections: !type.IsInterface() && Config.InitializeCollections,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                sb = sb.UnIndent();
                sb.AppendLine("}");

                if (!type.IsInterface())
                {
                    AddTypeExtension(ref sbExt, type,
                        initCollections: Config.InitializeCollections);
                }
            }

            //sb = sb.UnIndent();

            return lastNS;
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List <MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type == null ||
                (type.IsNested.GetValueOrDefault() && !options.IsNestedType) ||
                (type.Namespace != null && type.Namespace.StartsWith("System")))
            {
                return(lastNS);
            }

            if (type.Namespace != lastNS)
            {
                if (lastNS != null)
                {
                    sb.AppendLine("End Namespace");
                }

                lastNS = type.Namespace;

                sb.AppendLine();
                sb.AppendLine("Namespace {0}".Fmt(type.Namespace.SafeToken()));
                //sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("Public Enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                //sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "{0}".Fmt(name)
                            : "{0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("End Enum");
            }
            else
            {
                var partial = Config.MakePartial ? "Partial " : "";
                sb.AppendLine("Public {0}Class {1}".Fmt(partial, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    sb.AppendLine("    Inherits {0}".Fmt(Type(type.Inherits, includeNested: true)));
                }

                var implements = new List <string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        implements.Add(implStr);
                    }
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                {
                    implements.Add("IExtensibleDataObject");
                }

                if (implements.Count > 0)
                {
                    foreach (var x in implements)
                    {
                        sb.AppendLine("    Implements {0}".Fmt(x));
                    }
                }

                //sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type);

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                    {
                        continue;
                    }

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                               new CreateTypeOptions {
                        IsNestedType = true
                    });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine("End Class");
            }

            sb = sb.UnIndent();
            return(lastNS);
        }
Beispiel #32
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("type {0} =".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : i.ToString();
                        sb.AppendLine("| {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
            }
            else
            {
                //sb.AppendLine("[<CLIMutable>]"); // only for Record Types
                var classCtor = type.IsInterface() ? "" : "()";
                sb.AppendLine("[<AllowNullLiteral>]");
                sb.AppendLine("type {0}{1} = ".Fmt(Type(type.Name, type.GenericArgs), classCtor));
                sb = sb.Indent();
                var startLen = sb.Length;

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    sb.AppendLine("inherit {0}()".Fmt(Type(type.Inherits)));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        sb.AppendLine("interface {0}".Fmt(implStr));
                    }
                }

                if (!type.IsInterface())
                {
                    var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                    if (makeExtensible)
                    {
                        sb.AppendLine("interface IExtensibleDataObject with");
                        sb.AppendLine("    member val ExtensionData:ExtensionDataObject = null with get, set");
                        sb.AppendLine("end");
                    }

                    var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                    if (addVersionInfo)
                    {
                        sb.AppendLine("member val Version:int = {0} with get, set".Fmt(Config.AddImplicitVersion));
                    }
                }

                AddProperties(sb, type);

                if (sb.Length == startLen)
                {
                    sb.AppendLine(type.IsInterface() ? "interface end" : "class end");
                }

                sb = sb.UnIndent();
            }

            sb = sb.UnIndent();
            return(lastNS);
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List <MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type.IsNested.GetValueOrDefault() && !options.IsNestedType)
            {
                return(lastNS);
            }

            var ns = Config.GlobalNamespace ?? type.Namespace;

            if (ns != lastNS)
            {
                if (lastNS != null)
                {
                    sb.AppendLine("End Namespace");
                }

                lastNS = ns;

                sb.AppendLine();
                sb.AppendLine($"Namespace {MetadataExtensions.SafeToken(ns)}");
                //sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (options?.Routes != null)
            {
                AppendAttributes(sb, options.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine($"<GeneratedCode(\"AddServiceStackReference\", \"{Env.VersionString}\")>");
            }

            sb.Emit(type, Lang.Vb);
            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("Public Enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name  = type.EnumNames[i];
                        var value = type.EnumValues?[i];
                        if (KeyWords.Contains(name))
                        {
                            name = $"[{name}]";
                        }

                        var memberValue = type.GetEnumMemberValue(i);
                        if (memberValue != null)
                        {
                            AppendAttributes(sb, new List <MetadataAttribute> {
                                new MetadataAttribute {
                                    Name = "EnumMember",
                                    Args = new List <MetadataPropertyType> {
                                        new() {
                                            Name  = "Value",
                                            Value = memberValue,
                                            Type  = "String",
                                        }
                                    }
                                }
                            });
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS, List<MetadataType> allTypes, CreateTypeOptions options)
        {
            if (type == null || 
                (type.IsNested.GetValueOrDefault() && !options.IsNestedType) || 
                (type.Namespace != null && type.Namespace.StartsWith("System")))
                return lastNS;

            if (type.Namespace != lastNS)
            {
                if (lastNS != null)
                    sb.AppendLine("}");

                lastNS = type.Namespace;

                sb.AppendLine();
                sb.AppendLine("namespace {0}".Fmt(type.Namespace.SafeToken()));
                sb.AppendLine("{");
            }

            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0}".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null 
                            ? "{0},".Fmt(name) 
                            : "{0} = {1},".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var partial = Config.MakePartial ? "partial " : "";
                sb.AppendLine("public {0}class {1}".Fmt(partial, Type(type.Name, type.GenericArgs)));

                //: BaseClass, Interfaces
                var inheritsList = new List<string>();
                if (type.Inherits != null)
                {
                    inheritsList.Add(Type(type.Inherits, includeNested:true));
                }

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        inheritsList.Add(implStr);
                }

                var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                if (makeExtensible)
                    inheritsList.Add("IExtensibleDataObject");
                if (inheritsList.Count > 0)
                    sb.AppendLine("    : {0}".Fmt(string.Join(", ", inheritsList.ToArray())));

                sb.AppendLine("{");
                sb = sb.Indent();

                AddConstuctor(sb, type, options);
                AddProperties(sb, type);

                foreach (var innerTypeRef in type.InnerTypes.Safe())
                {
                    var innerType = allTypes.FirstOrDefault(x => x.Name == innerTypeRef.Name);
                    if (innerType == null)
                        continue;

                    sb = sb.UnIndent();
                    AppendType(ref sb, innerType, lastNS, allTypes,
                        new CreateTypeOptions { IsNestedType = true });
                    sb = sb.Indent();
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();
            return lastNS;
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                if (type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty())
                {
                    var typeDeclaration = !Config.ExportAsTypes
                        ? "enum"
                        : "export enum";

                    sb.AppendLine("{0} {1}".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs)));
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name = type.EnumNames[i];
                            var value = type.EnumValues != null ? type.EnumValues[i] : null;

                            sb.AppendLine(value == null //Enum Value's are not impacted by JS Style
                                ? "{0},".Fmt(name)
                                : "{0} = {1},".Fmt(name, value));
                        }
                    }

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    var sbType = StringBuilderCache.Allocate();

                    var typeDeclaration = !Config.ExportAsTypes
                        ? "type"
                        : "export type";

                    sbType.Append("{0} {1} = ".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs)));

                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        if (i > 0)
                            sbType.Append(" | ");

                        sbType.Append('"').Append(type.EnumNames[i]).Append('"');
                    }

                    sbType.Append(";");

                    sb.AppendLine(StringBuilderCache.ReturnAndFree(sbType));
                }
            }
            else
            {
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    extends.Add(Type(type.Inherits).InDeclarationType());

                string responseTypeExpression = null;

                var interfaces = new List<string>();
                var implStr = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (implStr.StartsWith("IReturn<"))
                    {
                        var types = implStr.RightPart('<');
                        var returnType = types.Substring(0, types.Length - 1);

                        if (returnType == "any")
                            returnType = "Object";

                        // This is to avoid invalid syntax such as "return new string()"
                        string replaceReturnType;
                        if (primitiveDefaultValues.TryGetValue(returnType, out replaceReturnType))
                            returnType = replaceReturnType;

                        responseTypeExpression = replaceReturnType == null ?
                            "createResponse() {{ return new {0}(); }}".Fmt(returnType) :
                            "createResponse() {{ return {0}; }}".Fmt(returnType);
                    }
                    else if (implStr == "IReturnVoid")
                    {
                        responseTypeExpression = "createResponse() {}";
                    }
                }

                var isClass = Config.ExportAsTypes && !type.IsInterface.GetValueOrDefault();
                var extend = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                            extend = " extends ";
                        else
                            extend += ", ";

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !Config.ExportAsTypes
                    ? "interface"
                    : $"export {(isClass ? "class" : "interface")}"; 

                sb.AppendLine("{0} {1}{2}".Fmt(typeDeclaration, Type(type.Name, type.GenericArgs), extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("{0}{1}: number; //{2}".Fmt(
                        "Version".PropertyStyle(), isClass ? "" : "?", Config.AddImplicitVersion));
                }

                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (Config.ExportAsTypes && responseTypeExpression != null)
                {
                    sb.AppendLine(responseTypeExpression);
                    sb.AppendLine("getTypeName() {{ return \"{0}\"; }}".Fmt(type.Name));
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            return lastNS;
        }
Beispiel #36
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            var typeName = Type(type.Name, type.GenericArgs);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public static enum {0}".Fmt(typeName));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    var hasIntValue = false;
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;

                        var delim = i == type.EnumNames.Count - 1 ? ";" : ",";
                        var serializeAs = JsConfig.TreatEnumAsInteger || (type.Attributes.Safe().Any(x => x.Name == "Flags"))
                            ? "@SerializedName(\"{0}\") ".Fmt(value)
                            : "";

                        sb.AppendLine(value == null
                            ? "{0}{1}".Fmt(name.ToPascalCase(), delim)
                            : serializeAs + "{0}({1}){2}".Fmt(name.ToPascalCase(), value, delim));

                        hasIntValue = hasIntValue || value != null;
                    }

                    if (hasIntValue)
                    {
                        sb.AppendLine();
                        sb.AppendLine("private final int value;");
                        sb.AppendLine("{0}(final int intValue) {{ value = intValue; }}".Fmt(typeName));
                        sb.AppendLine("public int getValue() { return value; }");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }
            else
            {
                var defType = type.IsInterface()
                    ? "interface"
                    : "class";
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    extends.Add(Type(type.Inherits).InheritedType());

                string responseTypeExpression = null;

                var interfaces = new List<string>();
                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                    {
                        interfaces.Add(implStr);

                        if (implStr.StartsWith("IReturn<"))
                        {
                            var types = implStr.RightPart('<');
                            var returnType = types.Substring(0, types.Length - 1);

                            //Can't get .class from Generic Type definition
                            responseTypeExpression = returnType.Contains("<")
                                ? "new TypeToken<{0}>(){{}}.getType()".Fmt(returnType)
                                : "{0}.class".Fmt(returnType);
                        }
                    }
                    if (!type.Implements.IsEmpty())
                    {
                        foreach (var interfaceRef in type.Implements)
                        {
                            interfaces.Add(Type(interfaceRef));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " extends " + extends[0]
                    : "";

                if (interfaces.Count > 0)
                    extend += " implements " + string.Join(", ", interfaces.ToArray());

                var addPropertyAccessors = Config.AddPropertyAccessors && !type.IsInterface();
                var settersReturnType = addPropertyAccessors && Config.SettersReturnThis ? typeName : null;

                sb.AppendLine("public static {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                if (addVersionInfo)
                {
                    sb.AppendLine("public Integer {0} = {1};".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));

                    if (addPropertyAccessors)
                        sb.AppendPropertyAccessor("Integer", "Version", settersReturnType);
                }

                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name),
                    addPropertyAccessors: addPropertyAccessors,
                    settersReturnType: settersReturnType);

                if (responseTypeExpression != null)
                {
                    sb.AppendLine("private static Object responseType = {0};".Fmt(responseTypeExpression));
                    sb.AppendLine("public Object getResponseType() { return responseType; }");
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            sb = sb.UnIndent();

            return lastNS;
        }
Beispiel #37
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                var enumType = Type(type.Name, type.GenericArgs);
                RegisterType(type, enumType);

                var isIntEnum = type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty();
                if (!isIntEnum)
                {
                    sb.AppendLine($"enum {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    foreach (var name in type.EnumNames.Safe())
                    {
                        sb.AppendLine($"{name},");
                    }
                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    sb.AppendLine($"class {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name  = type.EnumNames[i];
                            var value = type.EnumValues?[i];

                            sb.AppendLine($"static const {enumType} {name} = const {enumType}._({value});");
                        }
                    }


                    sb.AppendLine();
                    sb.AppendLine("final int _value;");
                    sb.AppendLine($"const {enumType}._(this._value);");
                    sb.AppendLine($"int get value => _value;");

                    var enumNames = (type.EnumNames ?? TypeConstants.EmptyStringList).Join(",");
                    sb.AppendLine($"static List<{enumType}> get values => const [{enumNames}];");

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InDeclarationType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                var implStr    = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (implStr.StartsWith("IReturn<"))
                    {
                        var types      = implStr.RightPart('<');
                        var returnType = types.Substring(0, types.Length - 1);

                        if (returnType == "any")
                        {
                            returnType = "dynamic";
                        }

                        // This is to avoid invalid syntax such as "return new string()"
                        responseTypeExpression = defaultValues.TryGetValue(returnType, out var newReturnInstance)
                            ? $"createResponse() {{ return {newReturnInstance}; }}"
                            : $"createResponse() {{ return new {returnType}(); }}";
                    }
                    else if (implStr == "IReturnVoid")
                    {
                        responseTypeExpression = "createResponse() {}";
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var isClass         = type.IsInterface != true;
                var isAbstractClass = type.IsInterface == true || type.IsAbstract == true;
                var baseClass       = extends.Count > 0 ? extends[0] : null;
                var hasDtoBaseClass = baseClass != null;
                var hasListBase     = baseClass != null && baseClass.StartsWith("List<");
                if (hasListBase)
                {
                    baseClass       = "ListBase" + baseClass.Substring(4);
                    hasDtoBaseClass = false;
                }
                if (!isAbstractClass)
                {
                    interfaces.Add("IConvertible");
                }
                var extend = baseClass != null
                    ? " extends " + baseClass
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                        {
                            extend = " extends ";
                        }
                        else
                        {
                            extend += ", ";
                        }

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !isAbstractClass ? "class" : "abstract class";

                var typeName = Type(type.Name, type.GenericArgs);

                RegisterType(type, typeName);

                sb.AppendLine($"{typeDeclaration} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest && !isAbstractClass;
                if (addVersionInfo)
                {
                    sb.AppendLine($"int {"Version".PropertyStyle()};");
                }

                if (type.Name == "IReturn`1")
                {
                    sb.AppendLine("T createResponse();");
                    sb.AppendLine("String getTypeName();");
                }
                else if (type.Name == "IReturnVoid")
                {
                    sb.AppendLine("void createResponse();");
                    sb.AppendLine("String getTypeName();");
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (isClass)
                {
                    var typeNameWithoutGenericArgs = typeName.LeftPart('<');
                    var props = (type.Properties ?? TypeConstants <MetadataPropertyType> .EmptyList).ToList();

                    if (addVersionInfo)
                    {
                        props.Insert(0, new MetadataPropertyType {
                            Name          = "Version".PropertyStyle(),
                            Type          = "Int32",
                            TypeNamespace = "System",
                            IsValueType   = true,
                            Value         = Config.AddImplicitVersion.ToString()
                        });
                    }

                    if (props.Count > 0)
                    {
                        sb.AppendLine();
                    }

                    if (hasListBase)
                    {
                        var genericArg = baseClass.Substring(9, baseClass.Length - 10);
                        sb.AppendLine($"final List<{genericArg}> l = [];");
                        sb.AppendLine("void set length(int newLength) { l.length = newLength; }");
                        sb.AppendLine("int get length => l.length;");
                        sb.AppendLine($"{genericArg} operator [](int index) => l[index];");
                        sb.AppendLine($"void operator []=(int index, {genericArg} value) {{ l[index] = value; }}");
                    }

                    var sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append(typeNameWithoutGenericArgs + "({");
                            }
                            else
                            {
                                sbBody.Append(",");
                            }
                            sbBody.Append($"this.{prop.Name.PropertyStyle().PropertyName()}");
                            if (!string.IsNullOrEmpty(prop.Value))
                            {
                                sbBody.Append("=" + prop.Value);
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody) + "});");
                        }
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + "();");
                    }

                    if (props.Count > 0)
                    {
                        sbBody = StringBuilderCacheAlt.Allocate();
                        sbBody.Append(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json)");
                        sbBody.Append(" { fromMap(json); }");
                        sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                        sb.AppendLine();
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json) : " +
                                      (hasDtoBaseClass ? "super.fromJson(json);" : "super();"));
                    }

                    sbBody = StringBuilderCacheAlt.Allocate();
                    sbBody.AppendLine("fromMap(Map<String, dynamic> json) {");
                    if (hasDtoBaseClass)
                    {
                        sbBody.AppendLine("        super.fromMap(json);");
                    }
                    foreach (var prop in props)
                    {
                        var propType = DartPropertyType(prop);
                        var jsonName = prop.Name.PropertyStyle();
                        var propName = jsonName.PropertyName();
                        if (UseTypeConversion(prop))
                        {
                            bool registerType = true;
                            if (type.GenericArgs?.Length > 0 && prop.GenericArgs?.Length > 0)
                            {
                                var argIndexes = new List <int>();
                                foreach (var arg in prop.GenericArgs)
                                {
                                    var argIndex = Array.IndexOf(type.GenericArgs, arg);
                                    argIndexes.Add(argIndex);
                                }
                                if (argIndexes.All(x => x != -1))
                                {
                                    propType     = prop.Type.LeftPart('`') + "<${runtimeGenericTypeDefs(this,[" + argIndexes.Join(",") + "]).join(\",\")}>";
                                    registerType = false;
                                }
                            }

                            if (registerType)
                            {
                                RegisterPropertyType(prop, propType);
                            }

                            sbBody.AppendLine($"        {propName} = JsonConverters.fromJson(json['{jsonName}'],'{propType}',context);");
                        }
                        else
                        {
                            if (DartToJsonConverters.TryGetValue(propType, out var conversionFn))
                            {
                                sbBody.AppendLine($"        {propName} = JsonConverters.{conversionFn}(json['{jsonName}']);");
                            }
                            else
                            {
                                sbBody.AppendLine($"        {propName} = json['{jsonName}'];");
                            }
                        }
                    }
                    sbBody.AppendLine("        return this;");
                    sbBody.AppendLine("    }");
                    sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));

                    sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append("Map<String, dynamic> toJson() => ");
                                if (hasDtoBaseClass)
                                {
                                    sbBody.Append("super.toJson()..addAll(");
                                }

                                sbBody.AppendLine("{");
                            }
                            else
                            {
                                sbBody.AppendLine(",");
                            }

                            var propType = DartPropertyType(prop);
                            var jsonName = prop.Name.PropertyStyle();
                            var propName = jsonName.PropertyName();
                            if (UseTypeConversion(prop))
                            {
                                sbBody.Append($"        '{jsonName}': JsonConverters.toJson({propName},'{propType}',context)");
                            }
                            else
                            {
                                sbBody.Append($"        '{jsonName}': {propName}");
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                            sb.AppendLine(hasDtoBaseClass ? "});" : "};");
                            sb.AppendLine();
                        }
                    }
                    else
                    {
                        sb.AppendLine("Map<String, dynamic> toJson() => " +
                                      (hasDtoBaseClass ? "super.toJson();" : "{};"));
                    }

                    if (responseTypeExpression != null)
                    {
                        sb.AppendLine(responseTypeExpression);
                        sb.AppendLine($"String getTypeName() {{ return \"{type.Name}\"; }}");
                    }

                    if (isClass)
                    {
                        sb.AppendLine("TypeContext context = _ctx;");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            return(lastNS);
        }
Beispiel #38
0
        private string AppendType(ref StringBuilderWrapper sb, ref StringBuilderWrapper sbExt, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            if (type.IgnoreSystemType())
                return lastNS;

            //sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("public enum {0} : Int".Fmt(Type(type.Name, type.GenericArgs)));
                sb.AppendLine("{");
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : null;
                        sb.AppendLine(value == null
                            ? "case {0}".Fmt(name.PropertyStyle())
                            : "case {0} = {1}".Fmt(name.PropertyStyle(), value));
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");

                AddEnumExtension(ref sbExt, type);
            }
            else
            {
                var defType = "class";
                var typeName = Type(type.Name, type.GenericArgs);
                var extends = new List<string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    var baseType = Type(type.Inherits).InheritedType();

                    //Swift requires re-declaring base type generics definition on super type
                    var genericDefPos = baseType.IndexOf("<");
                    if (genericDefPos >= 0)
                    {
                        typeName += baseType.Substring(genericDefPos);
                    }

                    extends.Add(baseType);
                }

                var typeAliases = new List<string>();

                if (options.ImplementsFn != null)
                {
                    //Swift doesn't support Generic Interfaces like IReturn<T> 
                    //Converting them into protocols with typealiases instead 
                    ExtractTypeAliases(options, typeAliases, extends);
                }

                if (type.IsInterface())
                {
                    defType = "protocol";

                    //Extract Protocol Arguments into different typealiases
                    if (!type.GenericArgs.IsEmpty())
                    {
                        typeName = Type(type.Name, null);
                        foreach (var arg in type.GenericArgs)
                        {
                            typeAliases.Add("typealias {0} = {0}".Fmt(arg));
                        }
                    }
                }

                var extend = extends.Count > 0
                    ? " : " + (string.Join(", ", extends.ToArray()))
                    : "";

                sb.AppendLine("public {0} {1}{2}".Fmt(defType, typeName, extend));
                sb.AppendLine("{");

                sb = sb.Indent();

                if (typeAliases.Count > 0)
                {
                    foreach (var typeAlias in typeAliases)
                    {
                        sb.AppendLine(typeAlias);
                    }
                    sb.AppendLine();
                }

                if (!type.IsInterface())
                {
                    sb.AppendLine("required public init(){}");
                }

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsOperation;
                if (addVersionInfo)
                {
                    sb.AppendLine("public var {0}:Int = {1}".Fmt("Version".PropertyStyle(), Config.AddImplicitVersion));
                }

                AddProperties(sb, type, 
                    initCollections:!type.IsInterface() && Config.InitializeCollections);

                sb = sb.UnIndent();
                sb.AppendLine("}");

                if (!type.IsInterface())
                {
                    AddTypeExtension(ref sbExt, type,
                        initCollections: Config.InitializeCollections);
                }
            }

            //sb = sb.UnIndent();

            return lastNS;
        }
Beispiel #39
0
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
            CreateTypeOptions options)
        {
            sb = sb.Indent();

            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine("[<GeneratedCode(\"AddServiceStackReference\", \"{0}\")>]".Fmt(Env.VersionString));
            }

            if (type.IsEnum.GetValueOrDefault())
            {
                sb.AppendLine("type {0} =".Fmt(Type(type.Name, type.GenericArgs)));
                sb = sb.Indent();

                if (type.EnumNames != null)
                {
                    for (var i = 0; i < type.EnumNames.Count; i++)
                    {
                        var name = type.EnumNames[i];
                        var value = type.EnumValues != null ? type.EnumValues[i] : i.ToString();
                        sb.AppendLine("| {0} = {1}".Fmt(name, value));
                    }
                }

                sb = sb.UnIndent();
            }
            else
            {
                //sb.AppendLine("[<CLIMutable>]"); // only for Record Types
                var classCtor = type.IsInterface() ? "" : "()";
                sb.AppendLine("[<AllowNullLiteral>]");
                sb.AppendLine("type {0}{1} = ".Fmt(Type(type.Name, type.GenericArgs), classCtor));
                sb = sb.Indent();
                var startLen = sb.Length;

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                    sb.AppendLine("inherit {0}()".Fmt(Type(type.Inherits)));

                if (options.ImplementsFn != null)
                {
                    var implStr = options.ImplementsFn();
                    if (!string.IsNullOrEmpty(implStr))
                        sb.AppendLine("interface {0}".Fmt(implStr));
                }

                if (!type.IsInterface())
                {
                    var makeExtensible = Config.MakeDataContractsExtensible && type.Inherits == null;
                    if (makeExtensible)
                    {
                        sb.AppendLine("interface IExtensibleDataObject with");
                        sb.AppendLine("    member val ExtensionData:ExtensionDataObject = null with get, set");
                        sb.AppendLine("end");
                    }

                    var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest;
                    if (addVersionInfo)
                    {
                        sb.AppendLine("member val Version:int = {0} with get, set".Fmt(Config.AddImplicitVersion));
                    }
                }

                AddProperties(sb, type,
                    includeResponseStatus: Config.AddResponseStatus && options.IsResponse
                        && type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (sb.Length == startLen)
                    sb.AppendLine(type.IsInterface() ? "interface end" : "class end");

                sb = sb.UnIndent();
            }

            sb = sb.UnIndent();
            return lastNS;
        }