Exemple #1
0
 private bool GenerateType(TypeScriptType type, TextWriter output) {
     if (type.IsArray) {
         return GenerateArray(type as TypeScriptArray, output);
     }
     else if (type.IsClass) {
         return GenerateClass(type as TypeScriptClass, output);
     }
     else if (type.IsEnum) {
         return GenerateEnum(type as TypeScriptEnum, output);
     }
     else if (type.IsField) {
         return GenerateField(type as TypeScriptField, output);
     }
     else if (type.IsInterface) {
         return GenerateInterface(type as TypeScriptInterface, output);
     }
     else if (type.IsMethod) {
         return GenerateMethod(type as TypeScriptMethod, output);
     }
     else if (type.IsPrimitive) {
         return GeneratePrimitive(type as TypeScriptPrimitive, output);
     }
     else if (type.IsProperty) {
         return GenerateProperty(type as TypeScriptProperty, output);
     }
     
     throw new Exception($"failed to generate source for type: {type.Name}");
 }
Exemple #2
0
        /*
            class Greeter {
                greeting: string;
            }
        */
        private bool GenerateClass(TypeScriptClass tsClass, TextWriter output) {
            if (GenerateImports(tsClass, output) == false) {
                return false;
            }
            output.Write($"export interface {tsClass.Name} ");

            // Don't extend object, no need.
            if (tsClass.BaseType != null && tsClass.BaseType.Name != "Object") {
                output.Write($"extends {tsClass.BaseType.Name} ");
            }

            if (tsClass.ImplementedInterfaces.Count > 0) {
                output.Write("implements ");
                for (int i = 0; i < tsClass.ImplementedInterfaces.Count; i++) {
                    TypeScriptType tsType = tsClass.ImplementedInterfaces[i];
                    output.Write($"{tsType.Name}");
                    if (i + 1 < tsClass.ImplementedInterfaces.Count) {
                        output.Write(',');
                    }
                }
            }

            output.WriteLine('{');
            foreach (TypeScriptProperty prop in tsClass.Properties) {
                // Indent
                output.Write("  ");
                GenerateProperty(prop, output);
            }
            output.WriteLine("}");
            return true;
        }
       public TypeScriptField ConvertField(FieldInfo fieldInfo) {
           
           object value = fieldInfo.GetRawConstantValue();

           TypeScriptType tsType = null;
           return new TypeScriptField(fieldInfo.Name, value, tsType);
       } 
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public bool Convert() {
     foreach (Type type in InputTypes) {
         TypeScriptType tsType = ConvertType(type);
         MappedTypes.Add(tsType);
     }
     return true;
 }
 public ControllerToTypeScript(TypeScriptType type, bool strictNullCheck)
     : base(type, strictNullCheck)
 {
     if (!type.Type.IsWebController())
     {
         throw new ArgumentOutOfRangeException($"Type {type.Name} MUST extends System.Web.Mvc.Controller or System.Web.Http.IHttpControler", nameof(type));
     }
 }
 public StructToTypeScript(TypeScriptType type, bool strictNullCheck)
     : base(type, strictNullCheck)
 {
     if (!this.Type.Type.IsValueType)
     {
         throw new ArgumentException($"{this.Type.Name} is not a Struct.", nameof(type));
     }
 }
Exemple #7
0
 public TypeScriptOrNullType(TypeScriptType innerType)
     : base(new[]
 {
     new TypeScriptBuildInType("null"),
     innerType
 })
 {
     InnerType = innerType;
 }
Exemple #8
0
        public void TypeScriptType(Type type, string result, bool checkOptional = false)
        {
            var tst = new TypeScriptType(type, _ctxClean);

            Assert.AreEqual(result, tst.Type);
            if (checkOptional)
            {
                Assert.IsTrue(tst.NameMods.EndsWith("?"));
            }
        }
Exemple #9
0
        private TypeScriptType MaybeNull(ITypeInfo trueType, TypeScriptType type, IAttributeProvider?attributeProvider, int index)
        {
            if (options.NullabilityMode != NullabilityMode.NullableReference)
            {
                return(type);
            }

            var isNullable = TypeScriptGeneratorHelpers.NullableReferenceCanBeNull(attributeProvider, trueType, index);

            return(TypeScriptGeneratorHelpers.BuildTargetNullableTypeByOptions(type, isNullable, options));
        }
Exemple #10
0
 public EnumToTypeScript(TypeScriptType type, bool strictNullCheck)
     : base(type, strictNullCheck)
 {
     if (!this.Type.Type.IsEnum)
     {
         throw new ArgumentException($"{this.Type.Name} is not an System.Enum.", nameof(type));
     }
     var underlyingType = Enum.GetUnderlyingType(this.Type.Type);
     if (underlyingType != typeof(int))
     {
         throw new NotSupportedException($"Unsupported underlying type for enums in typescript [{underlyingType}]. Only ints are supported.");
     }
 }
Exemple #11
0
        public static TypeScriptMethod ChangeCaseCopy(
            OutputSettings outputSettings,
            TypeContext typeContext,
            string baseName,
            TypeScriptType containingType,
            string otherTypeLiteral,
            bool toContainingType,
            bool toCamelCase)
        {
            TypeReference otherType = typeContext.GetLiteralReference(otherTypeLiteral);

            TypeScriptMethod result = new TypeScriptMethod();

            result.Name     = baseName + containingType.SourceType.UnqualifiedSimpleName;
            result.Appender = new CopyMethod.OutputAppender(
                outputSettings,
                typeContext,
                containingType,
                new CaseChangeCopySettings(
                    toContainingType,
                    toCamelCase),
                toContainingType);

            if (toContainingType)
            {
                result.Arguments = new List <TypeScriptMember>()
                {
                    new TypeScriptMember()
                    {
                        Name = "source",
                        Type = otherType
                    }
                };
                result.Type = containingType;
            }
            else
            {
                result.Arguments = new List <TypeScriptMember>()
                {
                    new TypeScriptMember()
                    {
                        Name = "target",
                        Type = otherType
                    }
                };
                result.Type = otherType;
            }

            return(result);
        }
Exemple #12
0
 public OutputAppender(
     OutputSettings settings,
     TypeContext typeContext,
     TypeScriptType containingType,
     ICopySettings copySettings,
     bool toContainingType)
     : base(
         settings,
         typeContext,
         hasBody: true)
 {
     this.containingType   = containingType;
     this.CopySettings     = copySettings;
     this.ToContainingType = toContainingType;
 }
Exemple #13
0
        public static TypeScriptType BuildTargetNullableTypeByOptions(TypeScriptType innerType, bool isNullable, TypeScriptGenerationOptions options)
        {
            if (!(innerType is INullabilityWrapperType) && isNullable && options.EnableExplicitNullability)
            {
                if (!options.UseGlobalNullable)
                {
                    return(new TypeScriptOrNullType(innerType));
                }

                if (options.UseGlobalNullable)
                {
                    return(new TypeScriptNullableType(innerType));
                }
            }

            return(innerType);
        }
Exemple #14
0
        private void BeginGenerateType(TypeScriptType type) {
            string path = $"{OutputDir}/{type.Name}.ts";

            // Remove any old generated files.
            // TODO: Just change the file mode lol.
            if (File.Exists(path)) {
                File.Delete(path);
            }

            TextWriter output = new StreamWriter(File.OpenWrite(path));

            Console.WriteLine($"generating source for type: {type.Name} {type.GetType().GUID}");
            Console.WriteLine($"path: {path}\n"); 

            GenerateType(type, output); 

            output.Flush();
            output.Close();
        }
Exemple #15
0
 public static ToTypeScript Build(TypeScriptType type, bool strictNullCheck)
 {
     if (type.Type.IsWebController())
     {
         return new ControllerToTypeScript(type, strictNullCheck);
     }
     else if (type.Type.IsEnum)
     {
         return new EnumToTypeScript(type, strictNullCheck);
     }
     else if (type.Type.IsValueType)
     {
         return new StructToTypeScript(type, strictNullCheck);
     }
     else
     {
         return new ModelToTypeScript(type, strictNullCheck);
     }
 }
        public TypeScriptTypeMemberDeclaration ResolveProperty(TypeScriptUnit unit, ITypeGenerator typeGenerator, ITypeInfo type, IPropertyInfo property)
        {
            TypeScriptType tsType = typeGenerator.BuildAndImportType(unit, property.PropertyType);

            if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().GetInterfaces().Any(x => x.Name == nameof(IEnumerable)))
            {
                var elementType = property.PropertyType.GetGenericArguments()[0];
                var itemType    = typeGenerator.BuildAndImportType(unit, elementType);
                tsType = new TypeScriptArrayType(itemType);
            }
            else
            {
                tsType = typeGenerator.BuildAndImportType(unit, property.PropertyType);
            }

            var result = new TypeScriptTypeMemberDeclaration
            {
                Name     = property.Name,
                Type     = tsType,
                Optional = true
            };

            return(result);
        }
Exemple #17
0
 public bool IsPredefined(Type input, out TypeScriptType typeScriptType)
 => _mappings.TryGetValue(input, out typeScriptType);
 public static TypeScriptType Generic(TypeScriptType typeScriptType, params TypeScriptType[] genericArguments) => new GenericTypeScriptType(typeScriptType, genericArguments);
Exemple #19
0
        public void Run(Type type, TypeScriptType expected)
        {
            var item = new ConvertTypeToTypeScriptType().Convert(type);

            Assert.Equal(JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(item));
        }
 public TypeScriptCastExpression(TypeScriptExpression expression, TypeScriptType targetType)
 {
     Expression = expression;
     TargetType = targetType;
 }
 public TypeScriptEnumValueType(TypeScriptType enumType, string value)
 {
     this.enumType = enumType;
     this.value    = value;
 }
Exemple #22
0
 public TypeScriptPromiseOfType(TypeScriptType targetType)
 {
     TargetType = targetType;
 }
 public void TypeToTypeScriptType(Type type, TypeScriptType expected)
 {
     new LocalContext(new ConvertConfiguration(), null, type).GetTypeScriptType(type).Should().Be(expected);
 }
 public void TypeScriptTypeToTypeScriptTests(TypeScriptType typeScriptType, string expected)
 {
     typeScriptType.ToTypeScriptType().Should().Be(expected);
 }
 public static TypeScriptType Array(TypeScriptType typeScriptType) => new ArrayTypeScriptType(typeScriptType);
 public TypeScriptTypeSpreadMemberDeclaration(TypeScriptType type)
 {
     Type = type;
 }
        private TypeScriptType ConvertType(Type type) {

            if (type == null) return null;

            // ERROR: Hospital class contains fields of type Hospital
            // Self referencing classes cause a stack overflow from infinite recursion.

            Console.WriteLine($"converting type {type.FullName} {type.GUID}");

            // We don't want to convert types more than once so we map the converted ones
            // to their GUID
            if (type_map.ContainsKey(type.GUID)) {
                return type_map[type.GUID];
            }

            TypeScriptType result = null;

            // Some weird edge cases
            {
                // Technically not 'Primitives' but in TypeScript we are limited to very
                // few basic primatives
                switch (type.Name) {
                    case "Decimal":
                    case "String":
                    case "DateTime":
                        result = ConvertPrimitive(type);
                    break;
                }

                // The collection interface has weird name. 
                // There's a bette way to handle this i'm sure.
                if (type.Name.StartsWith("ICollection")) {
                    result = ConvertICollection(type);
                }

                // Nullable types in dotnet are wrapped in a 'System.Nullable' type
                if (type.FullName.StartsWith("System.Nullable")) {
                    result = ConvertNullableProperty(type);
                }
            }

            // This following only executes as long as there is no
            // result set from the previous edge cases.
            if (result == null) {
                if (type.IsPrimitive) {
                    result = ConvertPrimitive(type);
                }
                else if (type.IsClass) {
                    result = ConvertClass(type);
                }
                else if (type.IsInterface) {
                    result = ConvertInterface(type);
                }
                else if (type.IsArray) {
                    result = ConvertArray(type);
                }
                else if (type.IsEnum) {
                    result = ConvertEnum(type);
                }
            }

            if (result == null) {
                throw new Exception($"type failed to find converter: '{type.FullName}'");
            }

            Console.WriteLine($"mapped type '{type.FullName} {type.GUID}'");

            return result;

        } // ConvertType
 public TypeScriptNullableType(TypeScriptType innerType)
 {
     InnerType = innerType;
 }
 /// <summary>
 /// Construct an instance 
 /// </summary>
 /// <param name="name">The declared name of the property</param>
 /// <param name="type">The type of the declared property</param>
 public TypeScriptProperty(string name, TypeScriptType type) :
     base(name) {
     this.IsProperty = true;
     this.Type = type;
 }
        public TypeScriptType GetTypeScriptType(Type type, bool import = true)
        {
            if (!Configuration.ShouldConvertType(type))
            {
                return(TypeScriptType.Any);
            }

            if (Configuration.PredefinedMapping.IsPredefined(type, out var typeResult))
            {
                return(typeResult);
            }

            var actualType = Nullable.GetUnderlyingType(type) ?? type;

            if (Configuration.PredefinedMapping.IsPredefined(actualType, out var actualResult))
            {
                return(actualResult);
            }

            var dictionary = TypeHelper.GetDictionaryType(actualType);

            if (dictionary != null)
            {
                return(TypeScriptType.Dictionary(GetTypeScriptType(dictionary.GetTypeInfo().GetGenericArguments()[0]), GetTypeScriptType(dictionary.GetTypeInfo().GetGenericArguments()[1])));
            }

            var enumerable = TypeHelper.GetEnumerableType(actualType);

            if (enumerable != null)
            {
                return(TypeScriptType.Array(GetTypeScriptType(enumerable.GetTypeInfo().GetGenericArguments()[0])));
            }

            var taskType = TypeHelper.GetTaskType(actualType);

            if (taskType != null)
            {
                return(GetTypeScriptType(taskType.GetTypeInfo().GetGenericArguments()[0]));
            }

            if (actualType.IsConstructedGenericType)
            {
                var typeDefinition   = actualType.GetGenericTypeDefinition();
                var tsTypeDefinition = GetTypeScriptType(typeDefinition);
                var genericArguments = actualType.GetTypeInfo().GetGenericArguments();
                return(TypeScriptType.Generic(tsTypeDefinition, genericArguments.Select(x => GetTypeScriptType(x)).ToArray()));
            }

            if (actualType.IsGenericParameter)
            {
                return(new BuiltInTypeScriptType(actualType.Name));
            }

            if (_type != type && !Imports.ContainsKey(actualType))
            {
                var typeScriptResult = _convertContext.GetTypeScriptFile(actualType);
                if (import)
                {
                    Imports.Add(actualType, typeScriptResult);
                }
            }

            return(new BuiltInTypeScriptType(Configuration.GetTypeName(actualType)));
        }
 public TypeScriptInterfacePropertyMember(string name, TypeScriptType result)
 {
     Name   = name;
     Result = result;
 }
Exemple #32
0
 public TypeScriptArrayType(TypeScriptType itemType)
 {
     ItemType = itemType;
 }
 public static TypeScriptType Dictionary(TypeScriptType key, TypeScriptType value) => new DictionaryTypeScriptType(key, value);
Exemple #34
0
 public ModelToTypeScript(TypeScriptType type, bool strictNullCheck)
     : base(type, strictNullCheck) { }
 public TypeRedirectBuildingContext([NotNull] ITypeInfo type, [NotNull] TypeScriptType typeScriptType)
     : base(type)
 {
     this.typeScriptType = typeScriptType;
 }
Exemple #36
0
 public ToTypeScript(TypeScriptType type, bool strictNullCheck)
 {
     this.Type = type.ThrowIfNull(nameof(type));
     this.StrictNullCheck = strictNullCheck;
 }