1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
|
from contextlib import contextmanager
import os
from stone.backend import CodeBackend
from stone.backends.swift_helpers import (
fmt_class,
fmt_func,
fmt_obj,
fmt_type,
fmt_var,
fmt_objc_type,
mapped_list_info,
)
from stone.ir import (
Boolean,
Bytes,
Float32,
Float64,
Int32,
Int64,
List,
Map,
String,
Timestamp,
UInt32,
UInt64,
Void,
is_list_type,
is_map_type,
is_timestamp_type,
is_union_type,
is_user_defined_type,
unwrap_nullable,
is_nullable_type,
)
_serial_type_table = {
Boolean: 'BoolSerializer',
Bytes: 'NSDataSerializer',
Float32: 'FloatSerializer',
Float64: 'DoubleSerializer',
Int32: 'Int32Serializer',
Int64: 'Int64Serializer',
List: 'ArraySerializer',
Map: 'DictionarySerializer',
String: 'StringSerializer',
Timestamp: 'NSDateSerializer',
UInt32: 'UInt32Serializer',
UInt64: 'UInt64Serializer',
Void: 'VoidSerializer',
}
_nsnumber_type_table = {
Boolean: '.boolValue',
Bytes: '',
Float32: '.floatValue',
Float64: '.doubleValue',
Int32: '.int32Value',
Int64: '.int64Value',
List: '',
String: '',
Timestamp: '',
UInt32: '.uint32Value',
UInt64: '.uint64Value',
Void: '',
Map: '',
}
stone_warning = """\
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
"""
# This will be at the top of the generated file.
base = """\
{}\
import Foundation
""".format(stone_warning)
undocumented = '(no description)'
class SwiftBaseBackend(CodeBackend):
"""Wrapper class over Stone generator for Swift logic."""
# pylint: disable=abstract-method
@contextmanager
def function_block(self, func, args, return_type=None):
signature = '{}({})'.format(func, args)
if return_type:
signature += ' -> {}'.format(return_type)
with self.block(signature):
yield
def _func_args(self, args_list, newlines=False, force_first=False, not_init=False):
out = []
first = True
for k, v in args_list:
# this is a temporary hack -- injected client-side args
# do not have a separate field for default value. Right now,
# default values are stored along with the type, e.g.
# `Bool = True` is a type, hence this check.
if first and force_first and '=' not in v:
k = "{0} {0}".format(k)
if first and v is not None and not_init:
out.append('{}'.format(v))
elif v is not None:
out.append('{}: {}'.format(k, v))
first = False
sep = ', '
if newlines:
sep += '\n' + self.make_indent()
return sep.join(out)
def _struct_init_args(self, data_type, namespace=None): # pylint: disable=unused-argument
args = []
for field in data_type.all_fields:
name = fmt_var(field.name)
value = fmt_type(field.data_type)
data_type, nullable = unwrap_nullable(field.data_type)
if field.has_default:
if is_union_type(data_type):
default = '.{}'.format(fmt_var(field.default.tag_name))
else:
default = fmt_obj(field.default)
value += ' = {}'.format(default)
elif nullable:
value += ' = nil'
arg = (name, value)
args.append(arg)
return args
def _objc_init_args(self, data_type, include_defaults=True):
args = []
for field in data_type.all_fields:
name = fmt_var(field.name)
value = fmt_objc_type(field.data_type)
data_type, nullable = unwrap_nullable(field.data_type)
if not include_defaults and (field.has_default or nullable):
continue
arg = (name, value)
args.append(arg)
return args
def _objc_no_defualts_func_args(self, data_type, args_data=None):
args = []
for field in data_type.all_fields:
name = fmt_var(field.name)
_, nullable = unwrap_nullable(field.data_type)
if field.has_default or nullable:
continue
arg = (name, name)
args.append(arg)
if args_data is not None:
_, type_data_list = tuple(args_data)
extra_args = [tuple(type_data[:-1]) for type_data in type_data_list]
for name, _, extra_type in extra_args:
if not is_nullable_type(extra_type):
arg = (name, name)
args.append(arg)
return self._func_args(args)
def _objc_init_args_to_swift(self, data_type, args_data=None, include_defaults=True):
args = []
for field in data_type.all_fields:
name = fmt_var(field.name)
field_data_type, nullable = unwrap_nullable(field.data_type)
if not include_defaults and (field.has_default or nullable):
continue
nsnumber_type = _nsnumber_type_table.get(field_data_type.__class__)
value = '{}{}{}'.format(name,
'?' if nullable and nsnumber_type else '',
nsnumber_type)
if is_list_type(field_data_type):
_, prefix, suffix, list_data_type, _ = mapped_list_info(field_data_type)
value = '{}{}'.format(name,
'?' if nullable else '')
list_nsnumber_type = _nsnumber_type_table.get(list_data_type.__class__)
if not is_user_defined_type(list_data_type) and not list_nsnumber_type:
value = name
else:
value = '{}.map {}'.format(value,
prefix)
if is_user_defined_type(list_data_type):
value = '{}{{ $0.{} }}'.format(value,
self._objc_swift_var_name(list_data_type))
else:
value = '{}{{ $0{} }}'.format(value,
list_nsnumber_type)
value = '{}{}'.format(value,
suffix)
elif is_map_type(field_data_type):
if is_user_defined_type(field_data_type.value_data_type):
value = '{}{}.mapValues {{ $0.swift }}'.format(name,
'?' if nullable else '')
elif is_user_defined_type(field_data_type):
value = '{}{}.{}'.format(name,
'?' if nullable else '',
self._objc_swift_var_name(field_data_type))
arg = (name, value)
args.append(arg)
if args_data is not None:
_, type_data_list = tuple(args_data)
extra_args = [tuple(type_data[:-1]) for type_data in type_data_list]
for name, _, _ in extra_args:
args.append((name, name))
return self._func_args(args)
def _objc_swift_var_name(self, data_type):
parent_type = data_type.parent_type
uw_parent_type, _ = unwrap_nullable(parent_type)
sub_count = 1 if parent_type else 0
while is_user_defined_type(uw_parent_type) and parent_type.parent_type:
sub_count += 1
parent_type = parent_type.parent_type
uw_parent_type, _ = unwrap_nullable(parent_type)
if sub_count == 0 or is_union_type(data_type):
return 'swift'
else:
name = 'Swift'
i = 1
while i <= sub_count:
name = '{}{}'.format('sub' if i == sub_count else 'Sub',
name)
i += 1
return name
def _docf(self, tag, val):
if tag == 'route':
if ':' in val:
val, version = val.split(':', 1)
version = int(version)
else:
version = 1
return fmt_func(val, version)
elif tag == 'field':
if '.' in val:
cls, field = val.split('.')
return ('{} in {}'.format(fmt_var(field),
fmt_class(cls)))
else:
return fmt_var(val)
elif tag in ('type', 'val', 'link'):
return val
else:
return val
def _write_output_in_target_folder(self, output, file_name):
full_path = self.target_folder_path
if not os.path.exists(full_path):
os.mkdir(full_path)
full_path = os.path.join(full_path, file_name)
with open(full_path, "w", encoding='utf-8') as fh:
fh.write(output)
def fmt_serial_type(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_type(data_type.data_type))
if is_map_type(data_type):
result = result + '<{}, {}>'.format(fmt_serial_type(data_type.key_data_type),
fmt_serial_type(data_type.value_data_type))
return result if not nullable else 'NullableSerializer'
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_map_type(data_type):
result = result + '({})'.format(fmt_serial_obj(data_type.value_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)
|