def _get_namespace_route_imports(self, namespace, include_route_args=True, include_route_deep_args=False): result = [] def _unpack_and_store_data_type(data_type): data_type, _ = unwrap_nullable(data_type) if is_list_type(data_type): while is_list_type(data_type): data_type = data_type.data_type if not is_void_type(data_type) and is_user_defined_type(data_type): result.append(data_type) for route in namespace.routes: if include_route_args: data_type, _ = unwrap_nullable(route.arg_data_type) _unpack_and_store_data_type(data_type) elif include_route_deep_args: data_type, _ = unwrap_nullable(route.arg_data_type) if is_union_type(data_type) or is_list_type(data_type): _unpack_and_store_data_type(data_type) elif not is_void_type(data_type): for field in data_type.all_fields: data_type, _ = unwrap_nullable(field.data_type) if is_struct_type(data_type) or is_union_type( data_type) or is_list_type(data_type): _unpack_and_store_data_type(data_type) _unpack_and_store_data_type(route.result_data_type) _unpack_and_store_data_type(route.error_data_type) return result
def _get_namespace_route_imports(self, namespace, include_route_args=True, include_route_deep_args=False): result = [] def _unpack_and_store_data_type(data_type): data_type, _ = unwrap_nullable(data_type) if is_list_type(data_type): while is_list_type(data_type): data_type = data_type.data_type if not is_void_type(data_type) and is_user_defined_type(data_type): result.append(data_type) for route in namespace.routes: if include_route_args: data_type, _ = unwrap_nullable(route.arg_data_type) _unpack_and_store_data_type(data_type) elif include_route_deep_args: data_type, _ = unwrap_nullable(route.arg_data_type) if is_union_type(data_type) or is_list_type(data_type): _unpack_and_store_data_type(data_type) elif not is_void_type(data_type): for field in data_type.all_fields: data_type, _ = unwrap_nullable(field.data_type) if (is_struct_type(data_type) or is_union_type(data_type) or is_list_type(data_type)): _unpack_and_store_data_type(data_type) _unpack_and_store_data_type(route.result_data_type) _unpack_and_store_data_type(route.error_data_type) return result
def _unpack_and_store_data_type(data_type): data_type, _ = unwrap_nullable(data_type) if is_list_type(data_type): while is_list_type(data_type): data_type = data_type.data_type if not is_void_type(data_type) and is_user_defined_type(data_type): result.append(data_type)
def _get_imports_m(self, data_types, default_imports): """Emits all necessary implementation file imports for the given Stone data type.""" if not isinstance(data_types, list): data_types = [data_types] import_classes = default_imports for data_type in data_types: import_classes.append(fmt_class_prefix(data_type)) if data_type.parent_type: import_classes.append(fmt_class_prefix(data_type.parent_type)) if is_struct_type(data_type) and data_type.has_enumerated_subtypes(): for _, subtype in data_type.get_all_subtypes_with_tags(): import_classes.append(fmt_class_prefix(subtype)) for field in data_type.all_fields: data_type, _ = unwrap_nullable(field.data_type) # unpack list while is_list_type(data_type): data_type = data_type.data_type if is_user_defined_type(data_type): import_classes.append(fmt_class_prefix(data_type)) if import_classes: import_classes = list(set(import_classes)) import_classes.sort() return import_classes
def _get_imports_h(self, data_types): """Emits all necessary header file imports for the given Stone data type.""" if not isinstance(data_types, list): data_types = [data_types] import_classes = [] for data_type in data_types: if is_user_defined_type(data_type): import_classes.append(fmt_class_prefix(data_type)) for field in data_type.all_fields: data_type, _ = unwrap_nullable(field.data_type) # unpack list while is_list_type(data_type): data_type = data_type.data_type if is_user_defined_type(data_type): import_classes.append(fmt_class_prefix(data_type)) import_classes = list(set(import_classes)) import_classes.sort() return import_classes
def _get_imports_m(self, data_types, default_imports): """Emits all necessary implementation file imports for the given Stone data type.""" if not isinstance(data_types, list): data_types = [data_types] import_classes = default_imports for data_type in data_types: import_classes.append(fmt_class_prefix(data_type)) if data_type.parent_type: import_classes.append(fmt_class_prefix(data_type.parent_type)) if is_struct_type( data_type) and data_type.has_enumerated_subtypes(): for tags, subtype in data_type.get_all_subtypes_with_tags(): import_classes.append(fmt_class_prefix(subtype)) for field in data_type.all_fields: data_type, _ = unwrap_nullable(field.data_type) # unpack list while is_list_type(data_type): data_type = data_type.data_type if is_user_defined_type(data_type): import_classes.append(fmt_class_prefix(data_type)) if import_classes: import_classes = list(set(import_classes)) import_classes.sort() return import_classes
def _python_type_mapping(self, ns, data_type): """Map Stone data types to their most natural equivalent in Python for documentation purposes.""" if is_string_type(data_type): return 'str' elif is_bytes_type(data_type): return 'bytes' elif is_boolean_type(data_type): return 'bool' elif is_float_type(data_type): return 'float' elif is_integer_type(data_type): return 'long' elif is_void_type(data_type): return 'None' elif is_timestamp_type(data_type): return 'datetime.datetime' elif is_alias(data_type): return self._python_type_mapping(ns, data_type.data_type) elif is_user_defined_type(data_type): class_name = class_name_for_data_type(data_type) if data_type.namespace.name != ns.name: return '%s.%s_validator' % ( data_type.namespace.name, class_name) else: return class_name elif is_list_type(data_type): # PyCharm understands this description format for a list return 'list of [{}]'.format(self._python_type_mapping( ns, data_type.data_type)) elif is_nullable_type(data_type): return 'Optional[{}]'.format( self._python_type_mapping(ns, data_type.data_type)) else: raise TypeError('Unknown data type %r' % data_type)
def _fmt_default(self, data_type): data_type, nullable = unwrap_nullable(data_type) result = 'DEFAULT' if nullable: return 'nil' if is_user_defined_type(data_type): result = fmt_func_call(fmt_alloc_call(fmt_class_prefix(data_type)), 'init', []) elif is_list_type(data_type): result = fmt_func_call(fmt_alloc_call('NSArray'), 'init', []) elif is_numeric_type(data_type): if is_float_type(data_type): result = '[NSNumber numberWithDouble:5]' else: result = '[NSNumber numberWithInt:5]' elif is_timestamp_type(data_type): result = '[[NSDateFormatter new] setDateFormat:[self convertFormat:@"test"]]' elif is_string_type(data_type): result = '@"teststring"' elif is_boolean_type(data_type): result = '@YES' return result
def is_ptr_type(data_type): data_type, _ = unwrap_nullable(data_type) if data_type.__class__ in _true_primitives: type_name = 'NSInteger' type_name = _primitive_table.get(data_type.__class__, fmt_class(data_type.name)) return type_name[-1] == '*' or is_struct_type(data_type) or is_list_type( data_type)
def map_stone_type_to_python_type(ns, data_type, override_dict=None): # type: (ApiNamespace, DataType, typing.Optional[OverrideDefaultTypesDict]) -> str """ Args: override_dict: lets you override the default behavior for a given type by hooking into a callback. (Currently only hooked up for stone's List and Nullable) """ override_dict = override_dict or {} if is_string_type(data_type): return 'str' elif is_bytes_type(data_type): return 'bytes' elif is_boolean_type(data_type): return 'bool' elif is_float_type(data_type): return 'float' elif is_integer_type(data_type): return 'long' elif is_void_type(data_type): return 'None' elif is_timestamp_type(data_type): timestamp_override = override_dict.get(Timestamp, None) if timestamp_override: return timestamp_override(ns, data_type, override_dict) return 'datetime.datetime' elif is_alias(data_type): alias_type = cast(Alias, data_type) return map_stone_type_to_python_type(ns, alias_type.data_type, override_dict) elif is_user_defined_type(data_type): user_defined_type = cast(UserDefined, data_type) class_name = class_name_for_data_type(user_defined_type) if user_defined_type.namespace.name != ns.name: return '%s.%s_validator' % (user_defined_type.namespace.name, class_name) else: return class_name elif is_list_type(data_type): list_type = cast(List, data_type) if List in override_dict: return override_dict[List](ns, list_type.data_type, override_dict) # PyCharm understands this description format for a list return 'list of [{}]'.format( map_stone_type_to_python_type(ns, list_type.data_type, override_dict)) elif is_nullable_type(data_type): nullable_type = cast(Nullable, data_type) if Nullable in override_dict: return override_dict[Nullable](ns, nullable_type.data_type, override_dict) return 'Optional[{}]'.format( map_stone_type_to_python_type(ns, nullable_type.data_type, override_dict)) else: raise TypeError('Unknown data type %r' % data_type)
def generate_validator_constructor(ns, data_type): """ Given a Stone data type, returns a string that can be used to construct the appropriate validation object in Python. """ dt, nullable_dt = unwrap_nullable(data_type) if is_list_type(dt): v = generate_func_call( 'bv.List', args=[ generate_validator_constructor(ns, dt.data_type)], kwargs=[ ('min_items', dt.min_items), ('max_items', dt.max_items)], ) elif is_numeric_type(dt): v = generate_func_call( 'bv.{}'.format(dt.name), kwargs=[ ('min_value', dt.min_value), ('max_value', dt.max_value)], ) elif is_string_type(dt): pattern = None if dt.pattern is not None: pattern = repr(dt.pattern) v = generate_func_call( 'bv.String', kwargs=[ ('min_length', dt.min_length), ('max_length', dt.max_length), ('pattern', pattern)], ) elif is_timestamp_type(dt): v = generate_func_call( 'bv.Timestamp', args=[repr(dt.format)], ) elif is_user_defined_type(dt): v = fmt_class(dt.name) + '_validator' if ns.name != dt.namespace.name: v = '{}.{}'.format(dt.namespace.name, v) elif is_alias(dt): # Assume that the alias has already been declared elsewhere. name = fmt_class(dt.name) + '_validator' if ns.name != dt.namespace.name: name = '{}.{}'.format(dt.namespace.name, name) v = name elif is_boolean_type(dt) or is_bytes_type(dt) or is_void_type(dt): v = generate_func_call('bv.{}'.format(dt.name)) else: raise AssertionError('Unsupported data type: %r' % dt) if nullable_dt: return generate_func_call('bv.Nullable', args=[v]) else: return v
def fmt_type_name(data_type): """ Returns the JSDoc name for the given data type. (Does not attempt to enumerate subtypes.) """ if is_user_defined_type(data_type): return fmt_pascal('%s%s' % (data_type.namespace.name, data_type.name)) else: fmted_type = _base_type_table.get(data_type.__class__, 'Object') if is_list_type(data_type): fmted_type += '.<' + fmt_type(data_type.data_type) + '>' return fmted_type
def fmt_type(data_type, namespace=None, use_interface=False): data_type, nullable = unwrap_nullable(data_type) if is_list_type(data_type): return "[]%s" % fmt_type(data_type.data_type, namespace, use_interface) type_name = data_type.name if use_interface and _needs_base_type(data_type): type_name = "Is" + type_name if is_composite_type(data_type) and namespace is not None and namespace.name != data_type.namespace.name: type_name = data_type.namespace.name + "." + type_name if use_interface and _needs_base_type(data_type): return _type_table.get(data_type.__class__, type_name) else: return _type_table.get(data_type.__class__, "*" + type_name)
def fmt_type(data_type): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{}.{}'.format(fmt_class(data_type.namespace.name), fmt_class(data_type.name)) else: result = _type_table.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): result = result + '<{}>'.format(fmt_type(data_type.data_type)) return result if not nullable else result + '?'
def fmt_type(data_type, namespace=None, use_interface=False): data_type, nullable = unwrap_nullable(data_type) if is_list_type(data_type): return '[]%s' % fmt_type(data_type.data_type, namespace, use_interface) type_name = data_type.name if use_interface and _needs_base_type(data_type): type_name = 'Is' + type_name if is_composite_type(data_type) and namespace is not None and \ namespace.name != data_type.namespace.name: type_name = data_type.namespace.name + '.' + type_name if use_interface and _needs_base_type(data_type): return _type_table.get(data_type.__class__, type_name) else: return _type_table.get(data_type.__class__, '*' + type_name)
def fmt_class_type(data_type): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{}'.format(fmt_class_prefix(data_type)) else: result = _primitive_table.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) result = result + '<{}>'.format(fmt_type(data_type)) return result
def fmt_type_name(data_type, inside_namespace=None): """ Produces a TypeScript type name for the given data type. inside_namespace should be set to the namespace that the reference occurs in, or None if this parameter is not relevant. """ if is_user_defined_type(data_type) or is_alias(data_type): if data_type.namespace == inside_namespace: return data_type.name else: return '%s.%s' % (data_type.namespace.name, data_type.name) else: fmted_type = _base_type_table.get(data_type.__class__, 'Object') if is_list_type(data_type): fmted_type += '<' + fmt_type(data_type.data_type, inside_namespace) + '>' return fmted_type
def get_route_io_data_types(self): """ Returns a list of all user-defined data types that are referenced as either an argument, result, or error of a route. If a List or Nullable data type is referenced, then the contained data type is returned assuming it's a user-defined type. """ data_types = set() for route in self.routes: for dtype in (route.arg_data_type, route.result_data_type, route.error_data_type): while is_list_type(dtype) or is_nullable_type(dtype): dtype = dtype.data_type if is_composite_type(dtype) or is_alias(dtype): data_types.add(dtype) return sorted(data_types, key=lambda dt: dt.name)
def _swift_type_mapping(self, data_type, serializer=False): suffix = 'Serializer' if serializer else '' if is_nullable_type(data_type): data_type = data_type.data_type nullable = True else: nullable = False if is_list_type(data_type): ret = 'Array{}<{}>'.format( suffix, self._swift_type_mapping(data_type.data_type, serializer) ) suffix = '' elif is_string_type(data_type): ret = 'String' elif is_timestamp_type(data_type): ret = 'NSDate' elif is_boolean_type(data_type): ret = 'Bool' elif is_bytes_type(data_type): ret = 'NSData' elif is_void_type(data_type): ret = 'Void' elif isinstance(data_type, Int32): ret = 'Int32' elif isinstance(data_type, Int64): ret = 'Int64' elif isinstance(data_type, UInt32): ret = 'UInt32' elif isinstance(data_type, UInt64): ret = 'UInt64' elif isinstance(data_type, Float32): ret = 'Float' elif isinstance(data_type, Float64): ret = 'Double' elif is_user_defined_type(data_type): ret = '{}.{}'.format(fmt_class(data_type.namespace.name), self.class_data_type(data_type)) ret += suffix if nullable: if serializer: ret = 'NullableSerializer<{}>'.format(ret) else: ret += '?' return ret
def fmt_class_type(data_type, suppress_ptr=False): data_type, _ = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{}'.format(fmt_class_prefix(data_type)) else: result = _primitive_table.get( data_type.__class__, fmt_class(data_type.name)) if suppress_ptr: result = result.replace(' *', '') result = result.replace('*', '') if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) result = result + '<{}>'.format(fmt_type(data_type)) return result
def fmt_serial_obj(data_type): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{}.{}Serializer()' result = result.format(fmt_class(data_type.namespace.name), fmt_class(data_type.name)) else: result = _serial_type_table.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): result = result + '({})'.format(fmt_serial_obj(data_type.data_type)) elif is_timestamp_type(data_type): result = result + '("{}")'.format(data_type.format) else: result = 'Serialization._{}'.format(result) return result if not nullable else 'NullableSerializer({})'.format(result)
def get_route_io_data_types(self): # type: () -> List[UserDefined] """ Returns a list of all user-defined data types that are referenced as either an argument, result, or error of a route. If a List or Nullable data type is referenced, then the contained data type is returned assuming it's a user-defined type. """ data_types = set() # type: Set[UserDefined] for route in self.routes: for dtype in (route.arg_data_type, route.result_data_type, route.error_data_type): while is_list_type(dtype) or is_nullable_type(dtype): dtype_as_list = cast(Union[DataTypeList, Nullable], dtype) dtype = dtype_as_list.data_type if is_composite_type(dtype) or is_alias(dtype): data_types.add(dtype) return sorted(data_types, key=lambda dt: dt.name)
def _determine_validator_type(self, data_type): if is_nullable_type(data_type): data_type = data_type.data_type nullable = True else: nullable = False if is_list_type(data_type): item_validator = self._determine_validator_type(data_type.data_type) if item_validator: v = "arrayValidator({})".format( self._func_args([ ("minItems", data_type.min_items), ("maxItems", data_type.max_items), ("itemValidator", item_validator), ]) ) else: return None elif is_numeric_type(data_type): v = "comparableValidator({})".format( self._func_args([ ("minValue", data_type.min_value), ("maxValue", data_type.max_value), ]) ) elif is_string_type(data_type): pat = data_type.pattern if data_type.pattern else None if isinstance(pat, six.text_type): pat = pat.encode('unicode_escape') v = "stringValidator({})".format( self._func_args([ ("minLength", data_type.min_length), ("maxLength", data_type.max_length), ("pattern", '"{}"'.format(pat) if pat else None), ]) ) else: return None if nullable: v = "nullableValidator({})".format(v) return v
def fmt_route_type(data_type, tag=False, has_default=False): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{} *'.format(fmt_class_prefix(data_type)) else: result = _primitive_table_user_interface.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) result = result + '<{}> *'.format(fmt_type(data_type)) if is_user_defined_type(data_type) and tag: if nullable or has_default: result += ' _Nullable' elif not is_void_type(data_type): result += ' _Nonnull' return result
def fmt_route_type(data_type, tag=False, has_default=False): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): result = '{} *'.format(fmt_class_prefix(data_type)) else: result = _primitive_table_user_interface.get( data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) result = result + '<{}> *'.format(fmt_type(data_type)) if is_user_defined_type(data_type) and tag: if nullable or has_default: result += ' _Nullable' elif not is_void_type(data_type): result += ' _Nonnull' return result
def fmt_type(data_type, tag=False, has_default=False, no_ptr=False, is_prop=False): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): base = '{}' if no_ptr else '{} *' result = base.format(fmt_class_prefix(data_type)) else: result = _primitive_table.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) base = '<{}>' if no_ptr else '<{}> *' result = result + base.format(fmt_type(data_type)) if tag: if (nullable or has_default) and not is_prop: result = 'nullable ' + result return result
def fmt_default_value(namespace, field): if is_tag_ref(field.default): return '{}.{}Serializer().serialize(.{})'.format( fmt_class(namespace.name), fmt_class(field.default.union_data_type.name), fmt_var(field.default.tag_name)) elif is_list_type(field.data_type): return '.array({})'.format(field.default) elif is_numeric_type(field.data_type): return '.number({})'.format(field.default) elif is_string_type(field.data_type): return '.str({})'.format(field.default) elif is_boolean_type(field.data_type): if field.default: bool_str = '1' else: bool_str = '0' return '.number({})'.format(bool_str) else: raise TypeError('Can\'t handle default value type %r' % type(field.data_type))
def fmt_type(data_type, tag=False, has_default=False, no_ptr=False): data_type, nullable = unwrap_nullable(data_type) if is_user_defined_type(data_type): base = '{}' if no_ptr else '{} *' result = base.format(fmt_class_prefix(data_type)) else: result = _primitive_table.get(data_type.__class__, fmt_class(data_type.name)) if is_list_type(data_type): data_type, _ = unwrap_nullable(data_type.data_type) base = '<{}>' if no_ptr else '<{}> *' result = result + base.format(fmt_type(data_type)) if tag: if nullable or has_default: result += ' _Nullable' elif not is_void_type(data_type): result += ' _Nonnull' return result
def _serializer_obj(self, data_type): if is_nullable_type(data_type): data_type = data_type.data_type nullable = True else: nullable = False if is_list_type(data_type): ret = 'ArraySerializer({})'.format( self._serializer_obj(data_type.data_type)) elif is_string_type(data_type): ret = 'Serialization._StringSerializer' elif is_timestamp_type(data_type): ret = 'NSDateSerializer("{}")'.format(data_type.format) elif is_boolean_type(data_type): ret = 'Serialization._BoolSerializer' elif is_bytes_type(data_type): ret = 'Serialization._NSDataSerializer' elif is_void_type(data_type): ret = 'Serialization._VoidSerializer' elif isinstance(data_type, Int32): ret = 'Serialization._Int32Serializer' elif isinstance(data_type, Int64): ret = 'Serialization._Int64Serializer' elif isinstance(data_type, UInt32): ret = 'Serialization._UInt32Serializer' elif isinstance(data_type, UInt64): ret = 'Serialization._UInt64Serializer' elif isinstance(data_type, Float32): ret = 'Serialization._FloatSerializer' elif isinstance(data_type, Float64): ret = 'Serialization._DoubleSerializer' elif is_user_defined_type(data_type): ret = "{}.{}Serializer()".format(fmt_class(data_type.namespace.name), self.class_data_type(data_type)) if nullable: ret = 'NullableSerializer({})'.format(ret) return ret
def format_type(typ): """Format a Stone data type as a TypeScript type""" # TODO - Where the type is an alias, emit the alias name and then emit # `type $alias = $wrapped;` """Return a TypeScript representation of a stone DataType""" if data_type.is_nullable_type(typ): wrapped_type, _ = data_type.unwrap_nullable(typ) # If the type is nullable, assume that it has been marked as an # optional member of the containing struct, ie. "field?: type", so we # don't need to represent the fact that it might be null in the # formatted type. ie. There is no need to generate "field?: type | # null" return '{}'.format(format_type(wrapped_type)) if data_type.is_primitive_type(typ): return _primitive_type_map.get(typ.name) elif data_type.is_list_type(typ): return '{}[]'.format(format_type(typ.data_type)) else: return typ.name
def _determine_validator_type(self, data_type, value): data_type, nullable = unwrap_nullable(data_type) if is_list_type(data_type): item_validator = self._determine_validator_type(data_type.data_type, value) if item_validator: v = "arrayValidator({})".format( self._func_args([ ("minItems", data_type.min_items), ("maxItems", data_type.max_items), ("itemValidator", item_validator), ]) ) else: return None elif is_numeric_type(data_type): v = "comparableValidator({})".format( self._func_args([ ("minValue", data_type.min_value), ("maxValue", data_type.max_value), ]) ) elif is_string_type(data_type): pat = data_type.pattern if data_type.pattern else None pat = pat.encode('unicode_escape').replace("\"", "\\\"") if pat else pat v = "stringValidator({})".format( self._func_args([ ("minLength", data_type.min_length), ("maxLength", data_type.max_length), ("pattern", '"{}"'.format(pat) if pat else None), ]) ) else: return None if nullable: v = "nullableValidator({})".format(v) return v
def _get_example_data(self, example_value, field): data_type, nullable = unwrap_nullable(field.data_type) field_name = fmt_var(field.name) result_args = [] if is_user_defined_type(data_type): obj_args = [] if is_union_type(data_type): for field in data_type.all_fields: if field.name == example_value['.tag']: if not is_void_type(field.data_type): if field.name in example_value: self._get_example_data( example_value[field.name], field) else: self._get_example_data(example_value, field) obj_args.append( (fmt_var(field.name), fmt_var(field.name))) field_value = fmt_func_call( caller=fmt_alloc_call(fmt_class_prefix(data_type)), callee='initWith{}'.format( fmt_camel_upper(example_value['.tag'])), args=fmt_func_args(obj_args)) self.emit('{} *{} = {};'.format(fmt_class_prefix(data_type), field_name, field_value)) else: if data_type.has_enumerated_subtypes(): for tags, subtype in data_type.get_all_subtypes_with_tags( ): assert len(tags) == 1, tags tag = tags[0] if tag == example_value['.tag']: self._get_example_data(example_value, subtype) else: for field in data_type.all_fields: if field.name in example_value: obj_args.append((fmt_var(field.name), self._get_example_data( example_value[field.name], field.data_type))) else: if not is_void_type(field.data_type): obj_args.append( (fmt_var(field.name), self._fmt_default(field.data_type))) field_value = fmt_func_call( fmt_alloc_call(fmt_class_prefix(data_type)), 'initWith{}'.format( fmt_camel_upper(data_type.all_fields[0].name)), fmt_func_args(obj_args)) self.emit('{} *{} = {};'.format( fmt_class_prefix(data_type), field_name, field_value)) result_args.append((field_name, field_name)) elif is_list_type(data_type): if example_value: field_value = '@[{}]'.format( self._get_example_data(example_value[0], field)) else: field_value = 'nil' self.emit('NSArray *{} = {};'.format(field_name, field_value)) result_args.append((field_name, field_name)) elif is_numeric_type(data_type): if is_float_type(data_type): field_value = '[NSNumber numberWithDouble:{}]'.format( example_value) elif isinstance(data_type, (UInt64, Int64)): field_value = '[NSNumber numberWithLong:{}]'.format( example_value) else: field_value = '[NSNumber numberWithInt:{}]'.format( example_value) result_args.append((field_name, field_value)) elif is_timestamp_type(data_type): field_value = '[DbxNSDateSerializer deserialize:@"{}" dateFormat:@"{}"]'.format( example_value, data_type.format) self.emit('NSDate *{} = {};'.format(field_name, field_value)) result_args.append((field_name, field_name)) elif is_string_type(data_type): field_value = '@"{}"'.format(example_value) result_args.append((field_name, field_value)) elif is_boolean_type(data_type): field_value = '@YES' if bool(example_value) else '@NO' result_args.append((field_name, field_value)) return result_args
def _needs_base_type(data_type): if is_struct_type(data_type) and data_type.has_enumerated_subtypes(): return True if is_list_type(data_type): return _needs_base_type(data_type.data_type) return False