Search in sources :

Example 1 with Symbol

use of cz.habarta.typescript.generator.compiler.Symbol in project typescript-generator by vojtechhabarta.

the class JsonDeserializationExtension method createDeserializationGenericFunctionConstructor.

private static TsMethodModel createDeserializationGenericFunctionConstructor(SymbolTable symbolTable, TsModel tsModel, TsBeanModel bean) {
    final Symbol beanIdentifier = symbolTable.getSymbol(bean.getOrigin());
    List<TsType.GenericVariableType> typeParameters = getTypeParameters(bean.getOrigin());
    final TsType.ReferenceType dataType = new TsType.GenericReferenceType(beanIdentifier, typeParameters);
    final List<TsParameterModel> constructorFnOfParameters = getConstructorFnOfParameters(typeParameters);
    final List<TsExpression> arguments = new ArrayList<>();
    arguments.add(new TsIdentifierReference("data"));
    for (TsParameterModel constructorFnOfParameter : constructorFnOfParameters) {
        arguments.add(new TsIdentifierReference(constructorFnOfParameter.name));
    }
    final List<TsStatement> body = new ArrayList<>();
    body.add(new TsReturnStatement(new TsArrowFunction(Arrays.asList(new TsParameter("data", null)), new TsCallExpression(new TsMemberExpression(new TsTypeReferenceExpression(new TsType.ReferenceType(beanIdentifier)), "fromData"), null, arguments))));
    return new TsMethodModel("fromDataFn", TsModifierFlags.None.setStatic(), typeParameters, constructorFnOfParameters, new TsType.FunctionType(Arrays.asList(new TsParameter("data", dataType)), dataType), body, null);
}
Also used : TsStatement(cz.habarta.typescript.generator.emitter.TsStatement) TsMemberExpression(cz.habarta.typescript.generator.emitter.TsMemberExpression) TsExpression(cz.habarta.typescript.generator.emitter.TsExpression) Symbol(cz.habarta.typescript.generator.compiler.Symbol) ArrayList(java.util.ArrayList) TsType(cz.habarta.typescript.generator.TsType) TsReturnStatement(cz.habarta.typescript.generator.emitter.TsReturnStatement) TsArrowFunction(cz.habarta.typescript.generator.emitter.TsArrowFunction) TsCallExpression(cz.habarta.typescript.generator.emitter.TsCallExpression) TsTypeReferenceExpression(cz.habarta.typescript.generator.emitter.TsTypeReferenceExpression) TsParameter(cz.habarta.typescript.generator.TsParameter) TsIdentifierReference(cz.habarta.typescript.generator.emitter.TsIdentifierReference) TsMethodModel(cz.habarta.typescript.generator.emitter.TsMethodModel) TsParameterModel(cz.habarta.typescript.generator.emitter.TsParameterModel)

Example 2 with Symbol

use of cz.habarta.typescript.generator.compiler.Symbol in project typescript-generator by vojtechhabarta.

the class OnePossiblePropertyValueAssigningExtension method findOnlyValueForEnumReferenceType.

private static Optional<TsExpression> findOnlyValueForEnumReferenceType(TsModel model, TsType.EnumReferenceType propertyType) {
    Symbol symbol = propertyType.symbol;
    Optional<TsEnumModel> enumModelOption = model.getOriginalStringEnums().stream().filter(candidate -> candidate.getName().getFullName().equals(symbol.getFullName())).findAny();
    if (!enumModelOption.isPresent()) {
        return Optional.empty();
    }
    TsEnumModel enumModel = enumModelOption.get();
    if (enumModel.getMembers().size() != 1) {
        return Optional.empty();
    }
    EnumMemberModel singleElement = enumModel.getMembers().iterator().next();
    Object enumValue = singleElement.getEnumValue();
    TsStringLiteral expression = new TsStringLiteral((String) enumValue);
    return Optional.of(expression);
}
Also used : TsSuperExpression(cz.habarta.typescript.generator.emitter.TsSuperExpression) EmitterExtensionFeatures(cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures) TsBeanModel(cz.habarta.typescript.generator.emitter.TsBeanModel) TsStringLiteral(cz.habarta.typescript.generator.emitter.TsStringLiteral) TsMemberExpression(cz.habarta.typescript.generator.emitter.TsMemberExpression) TsExpressionStatement(cz.habarta.typescript.generator.emitter.TsExpressionStatement) ArrayList(java.util.ArrayList) TsExpression(cz.habarta.typescript.generator.emitter.TsExpression) TsConstructorModel(cz.habarta.typescript.generator.emitter.TsConstructorModel) Extension(cz.habarta.typescript.generator.Extension) SymbolTable(cz.habarta.typescript.generator.compiler.SymbolTable) Collection(java.util.Collection) TsModifierFlags(cz.habarta.typescript.generator.emitter.TsModifierFlags) EnumMemberModel(cz.habarta.typescript.generator.compiler.EnumMemberModel) TsModel(cz.habarta.typescript.generator.emitter.TsModel) Collectors(java.util.stream.Collectors) TsThisExpression(cz.habarta.typescript.generator.emitter.TsThisExpression) TsStatement(cz.habarta.typescript.generator.emitter.TsStatement) List(java.util.List) TsEnumModel(cz.habarta.typescript.generator.emitter.TsEnumModel) TsAssignmentExpression(cz.habarta.typescript.generator.emitter.TsAssignmentExpression) TsCallExpression(cz.habarta.typescript.generator.emitter.TsCallExpression) Optional(java.util.Optional) Symbol(cz.habarta.typescript.generator.compiler.Symbol) TsType(cz.habarta.typescript.generator.TsType) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) Collections(java.util.Collections) TsPropertyModel(cz.habarta.typescript.generator.emitter.TsPropertyModel) EnumMemberModel(cz.habarta.typescript.generator.compiler.EnumMemberModel) TsStringLiteral(cz.habarta.typescript.generator.emitter.TsStringLiteral) Symbol(cz.habarta.typescript.generator.compiler.Symbol) TsEnumModel(cz.habarta.typescript.generator.emitter.TsEnumModel)

Example 3 with Symbol

use of cz.habarta.typescript.generator.compiler.Symbol in project typescript-generator by vojtechhabarta.

the class DefaultTypeProcessor method processType.

@Override
public Result processType(Type javaType, Context context) {
    if (Objects.equals(javaType, Object.class)) {
        return new Result(TsType.Any);
    }
    if (javaType instanceof Class) {
        final Class<?> javaClass = (Class<?>) javaType;
        if (isAssignableFrom(known.stringClasses, javaClass)) {
            return new Result(TsType.String);
        }
        if (isAssignableFrom(known.numberClasses, javaClass)) {
            return new Result(TsType.Number);
        }
        if (isAssignableFrom(known.booleanClasses, javaClass)) {
            return new Result(TsType.Boolean);
        }
        if (isAssignableFrom(known.dateClasses, javaClass)) {
            return new Result(TsType.Date);
        }
        if (isAssignableFrom(known.voidClasses, javaClass)) {
            return new Result(TsType.Void);
        }
    }
    if (javaType instanceof Class) {
        final Class<?> javaClass = (Class<?>) javaType;
        final Symbol importedSymbol = context.getSymbolIfImported(javaClass);
        if (importedSymbol != null) {
            return new Result(new TsType.ReferenceType(importedSymbol));
        }
    }
    if (javaType instanceof Class) {
        final Class<?> javaClass = (Class<?>) javaType;
        if (isAssignableFrom(known.anyClasses, javaClass)) {
            return new Result(TsType.Any);
        }
        if (javaClass.isArray()) {
            final Result result = context.processTypeInsideCollection(javaClass.getComponentType());
            return new Result(new TsType.BasicArrayType(result.getTsType()), result.getDiscoveredClasses());
        }
        if (javaClass.isEnum()) {
            return new Result(new TsType.EnumReferenceType(context.getSymbol(javaClass)), javaClass);
        }
        // list, map, optional, wrapper
        final Result knownGenericTypeResult = processKnownGenericType(javaClass, javaClass, context);
        if (knownGenericTypeResult != null) {
            return knownGenericTypeResult;
        }
        if (OptionalInt.class.isAssignableFrom(javaClass) || OptionalLong.class.isAssignableFrom(javaClass) || OptionalDouble.class.isAssignableFrom(javaClass)) {
            return new Result(TsType.Number.optional());
        }
        // generic structural type used without type arguments
        if (javaClass.getTypeParameters().length > 0) {
            final List<TsType> tsTypeArguments = new ArrayList<>();
            for (int i = 0; i < javaClass.getTypeParameters().length; i++) {
                tsTypeArguments.add(TsType.Any);
            }
            return new Result(new TsType.GenericReferenceType(context.getSymbol(javaClass), tsTypeArguments));
        }
        // structural type
        return new Result(new TsType.ReferenceType(context.getSymbol(javaClass)), javaClass);
    }
    if (javaType instanceof ParameterizedType) {
        final ParameterizedType parameterizedType = (ParameterizedType) javaType;
        if (parameterizedType.getRawType() instanceof Class) {
            final Class<?> javaClass = (Class<?>) parameterizedType.getRawType();
            // list, map, optional, wrapper
            final Result knownGenericTypeResult = processKnownGenericType(javaType, javaClass, context);
            if (knownGenericTypeResult != null) {
                return knownGenericTypeResult;
            }
            // generic structural type
            final List<Class<?>> discoveredClasses = new ArrayList<>();
            discoveredClasses.add(javaClass);
            final List<TsType> tsTypeArguments = new ArrayList<>();
            for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
                final TypeProcessor.Result typeArgumentResult = context.processType(typeArgument);
                tsTypeArguments.add(typeArgumentResult.getTsType());
                discoveredClasses.addAll(typeArgumentResult.getDiscoveredClasses());
            }
            return new Result(new TsType.GenericReferenceType(context.getSymbol(javaClass), tsTypeArguments), discoveredClasses);
        }
    }
    if (javaType instanceof GenericArrayType) {
        final GenericArrayType genericArrayType = (GenericArrayType) javaType;
        final Result result = context.processTypeInsideCollection(genericArrayType.getGenericComponentType());
        return new Result(new TsType.BasicArrayType(result.getTsType()), result.getDiscoveredClasses());
    }
    if (javaType instanceof TypeVariable) {
        final TypeVariable<?> typeVariable = (TypeVariable<?>) javaType;
        if (typeVariable.getGenericDeclaration() instanceof Method) {
            // example method: public <T extends Number> T getData();
            return context.processType(typeVariable.getBounds()[0]);
        }
        return new Result(new TsType.GenericVariableType(typeVariable.getName()));
    }
    if (javaType instanceof WildcardType) {
        final WildcardType wildcardType = (WildcardType) javaType;
        final Type[] upperBounds = wildcardType.getUpperBounds();
        return upperBounds.length > 0 ? context.processType(upperBounds[0]) : new Result(TsType.Any);
    }
    if (javaType instanceof JUnionType) {
        final JUnionType unionType = (JUnionType) javaType;
        final List<Result> results = unionType.getTypes().stream().map(type -> context.processType(type)).collect(Collectors.toList());
        return new Result(new TsType.UnionType(results.stream().map(result -> result.getTsType()).collect(Collectors.toList())), results.stream().flatMap(result -> result.getDiscoveredClasses().stream()).collect(Collectors.toList()));
    }
    if (javaType instanceof JTypeWithNullability) {
        final JTypeWithNullability typeWithNullability = (JTypeWithNullability) javaType;
        final Result result = context.processType(typeWithNullability.getType());
        return new Result(typeWithNullability.isNullable() ? new TsType.NullableType(result.getTsType()) : result.getTsType(), result.getDiscoveredClasses());
    }
    return null;
}
Also used : JUnionType(cz.habarta.typescript.generator.type.JUnionType) GenericArrayType(java.lang.reflect.GenericArrayType) Arrays(java.util.Arrays) Date(java.util.Date) WildcardType(java.lang.reflect.WildcardType) OptionalDouble(java.util.OptionalDouble) JTypeWithNullability(cz.habarta.typescript.generator.type.JTypeWithNullability) OptionalInt(java.util.OptionalInt) GenericsResolver(cz.habarta.typescript.generator.util.GenericsResolver) ArrayList(java.util.ArrayList) OptionalLong(java.util.OptionalLong) Calendar(java.util.Calendar) Map(java.util.Map) Method(java.lang.reflect.Method) TypeVariable(java.lang.reflect.TypeVariable) Collection(java.util.Collection) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Optional(java.util.Optional) Symbol(cz.habarta.typescript.generator.compiler.Symbol) Utils(cz.habarta.typescript.generator.util.Utils) Temporal(java.time.temporal.Temporal) Symbol(cz.habarta.typescript.generator.compiler.Symbol) ArrayList(java.util.ArrayList) ParameterizedType(java.lang.reflect.ParameterizedType) TypeVariable(java.lang.reflect.TypeVariable) GenericArrayType(java.lang.reflect.GenericArrayType) Method(java.lang.reflect.Method) OptionalDouble(java.util.OptionalDouble) JUnionType(cz.habarta.typescript.generator.type.JUnionType) GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) JTypeWithNullability(cz.habarta.typescript.generator.type.JTypeWithNullability) JUnionType(cz.habarta.typescript.generator.type.JUnionType)

Example 4 with Symbol

use of cz.habarta.typescript.generator.compiler.Symbol in project typescript-generator by vojtechhabarta.

the class RequiredPropertyConstructorExtension method getPredefinedValueForProperty.

private static Optional<TsExpression> getPredefinedValueForProperty(TsPropertyModel property, TsModel model) {
    if (property.tsType instanceof TsType.UnionType) {
        List<TsType> unionTypeElements = ((TsType.UnionType) property.tsType).types;
        if (unionTypeElements.size() != 1) {
            return Optional.empty();
        }
        TsType onlyElement = unionTypeElements.iterator().next();
        if (!(onlyElement instanceof TsType.StringLiteralType)) {
            return Optional.empty();
        }
        TsType.StringLiteralType onlyValue = (TsType.StringLiteralType) onlyElement;
        TsStringLiteral expression = new TsStringLiteral(onlyValue.literal);
        return Optional.of(expression);
    }
    if (property.tsType instanceof TsType.EnumReferenceType) {
        Symbol symbol = ((TsType.EnumReferenceType) property.tsType).symbol;
        Optional<TsEnumModel> enumModelOption = model.getOriginalStringEnums().stream().filter(candidate -> candidate.getName().getFullName().equals(symbol.getFullName())).findAny();
        if (!enumModelOption.isPresent()) {
            return Optional.empty();
        }
        TsEnumModel enumModel = enumModelOption.get();
        if (enumModel.getMembers().size() != 1) {
            return Optional.empty();
        }
        EnumMemberModel singleElement = enumModel.getMembers().iterator().next();
        Object enumValue = singleElement.getEnumValue();
        TsStringLiteral expression = new TsStringLiteral((String) enumValue);
        return Optional.of(expression);
    }
    return Optional.empty();
}
Also used : TsSuperExpression(cz.habarta.typescript.generator.emitter.TsSuperExpression) Arrays(java.util.Arrays) EmitterExtensionFeatures(cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures) TsBeanModel(cz.habarta.typescript.generator.emitter.TsBeanModel) TsStringLiteral(cz.habarta.typescript.generator.emitter.TsStringLiteral) TsMemberExpression(cz.habarta.typescript.generator.emitter.TsMemberExpression) HashMap(java.util.HashMap) TsExpressionStatement(cz.habarta.typescript.generator.emitter.TsExpressionStatement) ArrayList(java.util.ArrayList) TsExpression(cz.habarta.typescript.generator.emitter.TsExpression) TsIdentifierReference(cz.habarta.typescript.generator.emitter.TsIdentifierReference) TsConstructorModel(cz.habarta.typescript.generator.emitter.TsConstructorModel) Extension(cz.habarta.typescript.generator.Extension) SymbolTable(cz.habarta.typescript.generator.compiler.SymbolTable) Map(java.util.Map) TsParameterModel(cz.habarta.typescript.generator.emitter.TsParameterModel) TsModifierFlags(cz.habarta.typescript.generator.emitter.TsModifierFlags) EnumMemberModel(cz.habarta.typescript.generator.compiler.EnumMemberModel) TsModel(cz.habarta.typescript.generator.emitter.TsModel) TsThisExpression(cz.habarta.typescript.generator.emitter.TsThisExpression) TsStatement(cz.habarta.typescript.generator.emitter.TsStatement) List(java.util.List) TsEnumModel(cz.habarta.typescript.generator.emitter.TsEnumModel) TsAssignmentExpression(cz.habarta.typescript.generator.emitter.TsAssignmentExpression) TsCallExpression(cz.habarta.typescript.generator.emitter.TsCallExpression) ModelTransformer(cz.habarta.typescript.generator.compiler.ModelTransformer) Optional(java.util.Optional) Symbol(cz.habarta.typescript.generator.compiler.Symbol) TsType(cz.habarta.typescript.generator.TsType) Pattern(java.util.regex.Pattern) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) TsPropertyModel(cz.habarta.typescript.generator.emitter.TsPropertyModel) Symbol(cz.habarta.typescript.generator.compiler.Symbol) TsType(cz.habarta.typescript.generator.TsType) TsEnumModel(cz.habarta.typescript.generator.emitter.TsEnumModel) EnumMemberModel(cz.habarta.typescript.generator.compiler.EnumMemberModel) TsStringLiteral(cz.habarta.typescript.generator.emitter.TsStringLiteral)

Example 5 with Symbol

use of cz.habarta.typescript.generator.compiler.Symbol in project typescript-generator by vojtechhabarta.

the class PropertyPolymorphismExtension method getTransformers.

@Override
public List<TransformerDefinition> getTransformers() {
    return Arrays.asList(new TransformerDefinition(TransformationPhase.BeforeSymbolResolution, new ModelTransformer() {

        @Override
        public TsModel transformModel(SymbolTable symbolTable, TsModel model) {
            List<TsBeanModel> newBeans = new ArrayList<>();
            for (TsBeanModel bean : model.getBeans()) {
                // replace references
                List<TsPropertyModel> newProperties = new ArrayList<>();
                for (TsPropertyModel property : bean.getProperties()) {
                    if (property.tsType instanceof ReferenceType) {
                        ReferenceType type = (ReferenceType) property.tsType;
                        TsBeanModel referencedBean = model.getBean(type.symbol);
                        if (isPolymorphicBase.test(referencedBean.getOrigin())) {
                            Symbol refSymbol = symbolTable.addSuffixToSymbol(type.symbol, "Ref");
                            newProperties.add(property.withTsType(new TsType.ReferenceType(refSymbol)));
                            continue;
                        }
                    }
                    newProperties.add(property);
                }
                newBeans.add(bean.withProperties(newProperties));
            }
            // add reference beans
            {
                List<TsBeanModel> bases = new ArrayList<>();
                Map<Class<?>, Set<Class<?>>> subTypes = new HashMap<>();
                Map<Class<?>, TsBeanModel> beanByOrigin = new HashMap<>();
                for (TsBeanModel bean : model.getBeans()) {
                    Class<?> origin = bean.getOrigin();
                    if (origin == null) {
                        continue;
                    }
                    beanByOrigin.put(origin, bean);
                    if (isPolymorphicBase.test(origin)) {
                        bases.add(bean);
                    }
                    fillSubTypes(origin, subTypes, origin, new HashSet<>());
                }
                for (TsBeanModel base : bases) {
                    List<TsPropertyModel> refProperties = new ArrayList<>();
                    for (Class<?> subType : subTypes.getOrDefault(base.getOrigin(), Collections.emptySet())) {
                        refProperties.add(new TsPropertyModel(getPropertyName.apply(subType), new ReferenceType(symbolTable.getSymbol(subType)), null, true, null));
                    }
                    newBeans.add(new TsBeanModel(base.getOrigin(), TsBeanCategory.Data, false, symbolTable.addSuffixToSymbol(base.getName(), "Ref"), null, null, null, null, refProperties, null, null, null));
                }
            }
            return model.withBeans(newBeans);
        }
    }));
}
Also used : Symbol(cz.habarta.typescript.generator.compiler.Symbol) ArrayList(java.util.ArrayList) TsPropertyModel(cz.habarta.typescript.generator.emitter.TsPropertyModel) SymbolTable(cz.habarta.typescript.generator.compiler.SymbolTable) ReferenceType(cz.habarta.typescript.generator.TsType.ReferenceType) ModelTransformer(cz.habarta.typescript.generator.compiler.ModelTransformer) TsModel(cz.habarta.typescript.generator.emitter.TsModel) ArrayList(java.util.ArrayList) List(java.util.List) TsBeanModel(cz.habarta.typescript.generator.emitter.TsBeanModel) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Symbol (cz.habarta.typescript.generator.compiler.Symbol)6 ArrayList (java.util.ArrayList)6 TsType (cz.habarta.typescript.generator.TsType)4 TsCallExpression (cz.habarta.typescript.generator.emitter.TsCallExpression)4 TsMemberExpression (cz.habarta.typescript.generator.emitter.TsMemberExpression)4 TsPropertyModel (cz.habarta.typescript.generator.emitter.TsPropertyModel)4 TsStatement (cz.habarta.typescript.generator.emitter.TsStatement)4 List (java.util.List)4 SymbolTable (cz.habarta.typescript.generator.compiler.SymbolTable)3 TsAssignmentExpression (cz.habarta.typescript.generator.emitter.TsAssignmentExpression)3 TsBeanModel (cz.habarta.typescript.generator.emitter.TsBeanModel)3 TsExpression (cz.habarta.typescript.generator.emitter.TsExpression)3 TsExpressionStatement (cz.habarta.typescript.generator.emitter.TsExpressionStatement)3 TsIdentifierReference (cz.habarta.typescript.generator.emitter.TsIdentifierReference)3 TsModel (cz.habarta.typescript.generator.emitter.TsModel)3 TsParameterModel (cz.habarta.typescript.generator.emitter.TsParameterModel)3 TsSuperExpression (cz.habarta.typescript.generator.emitter.TsSuperExpression)3 Optional (java.util.Optional)3 Extension (cz.habarta.typescript.generator.Extension)2 EnumMemberModel (cz.habarta.typescript.generator.compiler.EnumMemberModel)2