internal_rtti.odin 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. #+private
  2. package flags
  3. import "base:intrinsics"
  4. import "base:runtime"
  5. import "core:fmt"
  6. import "core:mem"
  7. import "core:os"
  8. import "core:reflect"
  9. import "core:strconv"
  10. import "core:strings"
  11. @require import "core:time"
  12. @require import "core:time/datetime"
  13. import "core:unicode/utf8"
  14. @(optimization_mode="favor_size")
  15. parse_and_set_pointer_by_base_type :: proc(ptr: rawptr, str: string, type_info: ^runtime.Type_Info) -> bool {
  16. bounded_int :: proc(value, min, max: i128) -> (result: i128, ok: bool) {
  17. return value, min <= value && value <= max
  18. }
  19. bounded_uint :: proc(value, max: u128) -> (result: u128, ok: bool) {
  20. return value, value <= max
  21. }
  22. // NOTE(Feoramund): This procedure has been written with the goal in mind
  23. // of generating the least amount of assembly, given that this library is
  24. // likely to be called once and forgotten.
  25. //
  26. // I've rewritten the switch tables below in 3 different ways, and the
  27. // current one generates the least amount of code for me on Linux AMD64.
  28. //
  29. // The other two ways were:
  30. //
  31. // - the original implementation: use of parametric polymorphism which led
  32. // to dozens of functions generated, one for each type.
  33. //
  34. // - a `value, ok` assignment statement with the `or_return` done at the
  35. // end of the switch, instead of inline.
  36. //
  37. // This seems to be the smallest way for now.
  38. #partial switch specific_type_info in type_info.variant {
  39. case runtime.Type_Info_Integer:
  40. if specific_type_info.signed {
  41. value := strconv.parse_i128(str) or_return
  42. switch type_info.id {
  43. case i8: (^i8) (ptr)^ = cast(i8) bounded_int(value, cast(i128)min(i8), cast(i128)max(i8) ) or_return
  44. case i16: (^i16) (ptr)^ = cast(i16) bounded_int(value, cast(i128)min(i16), cast(i128)max(i16) ) or_return
  45. case i32: (^i32) (ptr)^ = cast(i32) bounded_int(value, cast(i128)min(i32), cast(i128)max(i32) ) or_return
  46. case i64: (^i64) (ptr)^ = cast(i64) bounded_int(value, cast(i128)min(i64), cast(i128)max(i64) ) or_return
  47. case i128: (^i128) (ptr)^ = value
  48. case int: (^int) (ptr)^ = cast(int) bounded_int(value, cast(i128)min(int), cast(i128)max(int) ) or_return
  49. case i16le: (^i16le) (ptr)^ = cast(i16le) bounded_int(value, cast(i128)min(i16le), cast(i128)max(i16le) ) or_return
  50. case i32le: (^i32le) (ptr)^ = cast(i32le) bounded_int(value, cast(i128)min(i32le), cast(i128)max(i32le) ) or_return
  51. case i64le: (^i64le) (ptr)^ = cast(i64le) bounded_int(value, cast(i128)min(i64le), cast(i128)max(i64le) ) or_return
  52. case i128le: (^i128le)(ptr)^ = cast(i128le) bounded_int(value, cast(i128)min(i128le), cast(i128)max(i128le)) or_return
  53. case i16be: (^i16be) (ptr)^ = cast(i16be) bounded_int(value, cast(i128)min(i16be), cast(i128)max(i16be) ) or_return
  54. case i32be: (^i32be) (ptr)^ = cast(i32be) bounded_int(value, cast(i128)min(i32be), cast(i128)max(i32be) ) or_return
  55. case i64be: (^i64be) (ptr)^ = cast(i64be) bounded_int(value, cast(i128)min(i64be), cast(i128)max(i64be) ) or_return
  56. case i128be: (^i128be)(ptr)^ = cast(i128be) bounded_int(value, cast(i128)min(i128be), cast(i128)max(i128be)) or_return
  57. }
  58. } else {
  59. value := strconv.parse_u128(str) or_return
  60. switch type_info.id {
  61. case u8: (^u8) (ptr)^ = cast(u8) bounded_uint(value, cast(u128)max(u8) ) or_return
  62. case u16: (^u16) (ptr)^ = cast(u16) bounded_uint(value, cast(u128)max(u16) ) or_return
  63. case u32: (^u32) (ptr)^ = cast(u32) bounded_uint(value, cast(u128)max(u32) ) or_return
  64. case u64: (^u64) (ptr)^ = cast(u64) bounded_uint(value, cast(u128)max(u64) ) or_return
  65. case u128: (^u128) (ptr)^ = value
  66. case uint: (^uint) (ptr)^ = cast(uint) bounded_uint(value, cast(u128)max(uint) ) or_return
  67. case uintptr: (^uintptr)(ptr)^ = cast(uintptr) bounded_uint(value, cast(u128)max(uintptr)) or_return
  68. case u16le: (^u16le) (ptr)^ = cast(u16le) bounded_uint(value, cast(u128)max(u16le) ) or_return
  69. case u32le: (^u32le) (ptr)^ = cast(u32le) bounded_uint(value, cast(u128)max(u32le) ) or_return
  70. case u64le: (^u64le) (ptr)^ = cast(u64le) bounded_uint(value, cast(u128)max(u64le) ) or_return
  71. case u128le: (^u128le) (ptr)^ = cast(u128le) bounded_uint(value, cast(u128)max(u128le) ) or_return
  72. case u16be: (^u16be) (ptr)^ = cast(u16be) bounded_uint(value, cast(u128)max(u16be) ) or_return
  73. case u32be: (^u32be) (ptr)^ = cast(u32be) bounded_uint(value, cast(u128)max(u32be) ) or_return
  74. case u64be: (^u64be) (ptr)^ = cast(u64be) bounded_uint(value, cast(u128)max(u64be) ) or_return
  75. case u128be: (^u128be) (ptr)^ = cast(u128be) bounded_uint(value, cast(u128)max(u128be) ) or_return
  76. }
  77. }
  78. case runtime.Type_Info_Rune:
  79. if utf8.rune_count_in_string(str) != 1 {
  80. return false
  81. }
  82. (^rune)(ptr)^ = utf8.rune_at_pos(str, 0)
  83. case runtime.Type_Info_Float:
  84. value := strconv.parse_f64(str) or_return
  85. switch type_info.id {
  86. case f16: (^f16) (ptr)^ = cast(f16) value
  87. case f32: (^f32) (ptr)^ = cast(f32) value
  88. case f64: (^f64) (ptr)^ = value
  89. case f16le: (^f16le)(ptr)^ = cast(f16le) value
  90. case f32le: (^f32le)(ptr)^ = cast(f32le) value
  91. case f64le: (^f64le)(ptr)^ = cast(f64le) value
  92. case f16be: (^f16be)(ptr)^ = cast(f16be) value
  93. case f32be: (^f32be)(ptr)^ = cast(f32be) value
  94. case f64be: (^f64be)(ptr)^ = cast(f64be) value
  95. }
  96. case runtime.Type_Info_Complex:
  97. value := strconv.parse_complex128(str) or_return
  98. switch type_info.id {
  99. case complex32: (^complex32) (ptr)^ = (complex32)(value)
  100. case complex64: (^complex64) (ptr)^ = (complex64)(value)
  101. case complex128: (^complex128)(ptr)^ = value
  102. }
  103. case runtime.Type_Info_Quaternion:
  104. value := strconv.parse_quaternion256(str) or_return
  105. switch type_info.id {
  106. case quaternion64: (^quaternion64) (ptr)^ = (quaternion64)(value)
  107. case quaternion128: (^quaternion128)(ptr)^ = (quaternion128)(value)
  108. case quaternion256: (^quaternion256)(ptr)^ = value
  109. }
  110. case runtime.Type_Info_String:
  111. assert(specific_type_info.encoding == .UTF_8)
  112. if specific_type_info.is_cstring {
  113. cstr_ptr := (^cstring)(ptr)
  114. if cstr_ptr != nil {
  115. // Prevent memory leaks from us setting this value multiple times.
  116. delete(cstr_ptr^)
  117. }
  118. cstr_ptr^ = strings.clone_to_cstring(str)
  119. } else {
  120. (^string)(ptr)^ = str
  121. }
  122. case runtime.Type_Info_Boolean:
  123. value := strconv.parse_bool(str) or_return
  124. switch type_info.id {
  125. case bool: (^bool)(ptr)^ = value
  126. case b8: (^b8) (ptr)^ = b8(value)
  127. case b16: (^b16) (ptr)^ = b16(value)
  128. case b32: (^b32) (ptr)^ = b32(value)
  129. case b64: (^b64) (ptr)^ = b64(value)
  130. }
  131. case runtime.Type_Info_Bit_Set:
  132. // Parse a string of 1's and 0's, from left to right,
  133. // least significant bit to most significant bit.
  134. value: u128
  135. // NOTE: `upper` is inclusive, i.e: `0..=31`
  136. max_bit_index := u128(1 + specific_type_info.upper - specific_type_info.lower)
  137. bit_index := u128(0)
  138. #no_bounds_check for string_index in 0..<uint(len(str)) {
  139. if bit_index == max_bit_index {
  140. // The string's too long for this bit_set.
  141. return false
  142. }
  143. switch str[string_index] {
  144. case '1':
  145. value |= 1 << bit_index
  146. bit_index += 1
  147. case '0':
  148. bit_index += 1
  149. continue
  150. case '_':
  151. continue
  152. case:
  153. return false
  154. }
  155. }
  156. if specific_type_info.underlying != nil {
  157. set_unbounded_integer_by_type(ptr, value, specific_type_info.underlying.id)
  158. } else {
  159. switch 8*type_info.size {
  160. case 8: (^u8) (ptr)^ = cast(u8) value
  161. case 16: (^u16) (ptr)^ = cast(u16) value
  162. case 32: (^u32) (ptr)^ = cast(u32) value
  163. case 64: (^u64) (ptr)^ = cast(u64) value
  164. case 128: (^u128)(ptr)^ = value
  165. }
  166. }
  167. case:
  168. fmt.panicf("Unsupported base data type: %v", specific_type_info)
  169. }
  170. return true
  171. }
  172. // This proc exists to make error handling easier, since everything in the base
  173. // type one above works on booleans. It's a simple parsing error if it's false.
  174. //
  175. // However, here we have to be more careful about how we handle errors,
  176. // especially with files.
  177. //
  178. // We want to provide as informative as an error as we can.
  179. @(optimization_mode="favor_size", disabled=NO_CORE_NAMED_TYPES)
  180. parse_and_set_pointer_by_named_type :: proc(ptr: rawptr, str: string, data_type: typeid, arg_tag: string, out_error: ^Error) {
  181. // Core types currently supported:
  182. //
  183. // - os.Handle
  184. // - time.Time
  185. // - datetime.DateTime
  186. // - net.Host_Or_Endpoint
  187. GENERIC_RFC_3339_ERROR :: "Invalid RFC 3339 string. Try this format: `yyyy-mm-ddThh:mm:ssZ`, for example `2024-02-29T16:30:00Z`."
  188. out_error^ = nil
  189. if data_type == os.Handle {
  190. // NOTE: `os` is hopefully available everywhere, even if it might panic on some calls.
  191. wants_read := false
  192. wants_write := false
  193. mode: int
  194. if file, ok := get_struct_subtag(arg_tag, SUBTAG_FILE); ok {
  195. for i in 0..<len(file) {
  196. #no_bounds_check switch file[i] {
  197. case 'r': wants_read = true
  198. case 'w': wants_write = true
  199. case 'c': mode |= os.O_CREATE
  200. case 'a': mode |= os.O_APPEND
  201. case 't': mode |= os.O_TRUNC
  202. }
  203. }
  204. }
  205. // Sane default.
  206. // owner/group/other: r--r--r--
  207. perms: int = 0o444
  208. if wants_read && wants_write {
  209. mode |= os.O_RDWR
  210. perms |= 0o200
  211. } else if wants_write {
  212. mode |= os.O_WRONLY
  213. perms |= 0o200
  214. } else {
  215. mode |= os.O_RDONLY
  216. }
  217. if permstr, ok := get_struct_subtag(arg_tag, SUBTAG_PERMS); ok {
  218. if value, parse_ok := strconv.parse_u64_of_base(permstr, 8); parse_ok {
  219. perms = int(value)
  220. }
  221. }
  222. handle, errno := os.open(str, mode, perms)
  223. if errno != nil {
  224. // NOTE(Feoramund): os.Error is system-dependent, and there's
  225. // currently no good way to translate them all into strings.
  226. //
  227. // The upcoming `os2` package will hopefully solve this.
  228. //
  229. // We can at least provide the number for now, so the user can look
  230. // it up.
  231. out_error^ = Open_File_Error {
  232. str,
  233. errno,
  234. mode,
  235. perms,
  236. }
  237. return
  238. }
  239. (^os.Handle)(ptr)^ = handle
  240. return
  241. }
  242. when IMPORTING_TIME {
  243. if data_type == time.Time {
  244. // NOTE: The leap second data is discarded.
  245. res, consumed := time.rfc3339_to_time_utc(str)
  246. if consumed == 0 {
  247. // The RFC 3339 parsing facilities provide no indication as to what
  248. // went wrong, so just treat it as a regular parsing error.
  249. out_error^ = Parse_Error {
  250. .Bad_Value,
  251. GENERIC_RFC_3339_ERROR,
  252. }
  253. return
  254. }
  255. (^time.Time)(ptr)^ = res
  256. return
  257. } else if data_type == datetime.DateTime {
  258. // NOTE: The UTC offset and leap second data are discarded.
  259. res, _, _, consumed := time.rfc3339_to_components(str)
  260. if consumed == 0 {
  261. out_error^ = Parse_Error {
  262. .Bad_Value,
  263. GENERIC_RFC_3339_ERROR,
  264. }
  265. return
  266. }
  267. (^datetime.DateTime)(ptr)^ = res
  268. return
  269. }
  270. }
  271. when IMPORTING_NET {
  272. if try_net_parse_workaround(data_type, str, ptr, out_error) {
  273. return
  274. }
  275. }
  276. out_error ^= Parse_Error {
  277. // The caller will add more details.
  278. .Unsupported_Type,
  279. "",
  280. }
  281. }
  282. @(optimization_mode="favor_size")
  283. set_unbounded_integer_by_type :: proc(ptr: rawptr, value: $T, data_type: typeid) where intrinsics.type_is_integer(T) {
  284. switch data_type {
  285. case i8: (^i8) (ptr)^ = cast(i8) value
  286. case i16: (^i16) (ptr)^ = cast(i16) value
  287. case i32: (^i32) (ptr)^ = cast(i32) value
  288. case i64: (^i64) (ptr)^ = cast(i64) value
  289. case i128: (^i128) (ptr)^ = cast(i128) value
  290. case int: (^int) (ptr)^ = cast(int) value
  291. case i16le: (^i16le) (ptr)^ = cast(i16le) value
  292. case i32le: (^i32le) (ptr)^ = cast(i32le) value
  293. case i64le: (^i64le) (ptr)^ = cast(i64le) value
  294. case i128le: (^i128le) (ptr)^ = cast(i128le) value
  295. case i16be: (^i16be) (ptr)^ = cast(i16be) value
  296. case i32be: (^i32be) (ptr)^ = cast(i32be) value
  297. case i64be: (^i64be) (ptr)^ = cast(i64be) value
  298. case i128be: (^i128be) (ptr)^ = cast(i128be) value
  299. case u8: (^u8) (ptr)^ = cast(u8) value
  300. case u16: (^u16) (ptr)^ = cast(u16) value
  301. case u32: (^u32) (ptr)^ = cast(u32) value
  302. case u64: (^u64) (ptr)^ = cast(u64) value
  303. case u128: (^u128) (ptr)^ = cast(u128) value
  304. case uint: (^uint) (ptr)^ = cast(uint) value
  305. case uintptr: (^uintptr)(ptr)^ = cast(uintptr) value
  306. case u16le: (^u16le) (ptr)^ = cast(u16le) value
  307. case u32le: (^u32le) (ptr)^ = cast(u32le) value
  308. case u64le: (^u64le) (ptr)^ = cast(u64le) value
  309. case u128le: (^u128le) (ptr)^ = cast(u128le) value
  310. case u16be: (^u16be) (ptr)^ = cast(u16be) value
  311. case u32be: (^u32be) (ptr)^ = cast(u32be) value
  312. case u64be: (^u64be) (ptr)^ = cast(u64be) value
  313. case u128be: (^u128be) (ptr)^ = cast(u128be) value
  314. case rune: (^rune) (ptr)^ = cast(rune) value
  315. case:
  316. fmt.panicf("Unsupported integer backing type: %v", data_type)
  317. }
  318. }
  319. @(optimization_mode="favor_size")
  320. parse_and_set_pointer_by_type :: proc(ptr: rawptr, str: string, type_info: ^runtime.Type_Info, arg_tag: string) -> (error: Error) {
  321. #partial switch specific_type_info in type_info.variant {
  322. case runtime.Type_Info_Named:
  323. if global_custom_type_setter != nil {
  324. // The program gets to go first.
  325. error_message, handled, alloc_error := global_custom_type_setter(ptr, type_info.id, str, arg_tag)
  326. if alloc_error != nil {
  327. // There was an allocation error. Bail out.
  328. return Parse_Error {
  329. alloc_error,
  330. "Custom type setter encountered allocation error.",
  331. }
  332. }
  333. if handled {
  334. // The program handled the type.
  335. if len(error_message) != 0 {
  336. // However, there was an error. Pass it along.
  337. error = Parse_Error {
  338. .Bad_Value,
  339. error_message,
  340. }
  341. }
  342. return
  343. }
  344. }
  345. // Might be a named enum. Need to check here first, since we handle all enums.
  346. if enum_type_info, is_enum := specific_type_info.base.variant.(runtime.Type_Info_Enum); is_enum {
  347. if value, ok := reflect.enum_from_name_any(type_info.id, str); ok {
  348. set_unbounded_integer_by_type(ptr, value, enum_type_info.base.id)
  349. } else {
  350. return Parse_Error {
  351. .Bad_Value,
  352. fmt.tprintf("Invalid value name. Valid names are: %s", enum_type_info.names),
  353. }
  354. }
  355. } else {
  356. parse_and_set_pointer_by_named_type(ptr, str, type_info.id, arg_tag, &error)
  357. if error != nil {
  358. // So far, it's none of the types that we recognize.
  359. // Check to see if we can set it by base type, if allowed.
  360. if _, is_indistinct := get_struct_subtag(arg_tag, SUBTAG_INDISTINCT); is_indistinct {
  361. return parse_and_set_pointer_by_type(ptr, str, specific_type_info.base, arg_tag)
  362. }
  363. }
  364. }
  365. case runtime.Type_Info_Dynamic_Array:
  366. ptr := cast(^runtime.Raw_Dynamic_Array)ptr
  367. // Try to convert the value first.
  368. elem_backing, alloc_error := mem.alloc_bytes(specific_type_info.elem.size, specific_type_info.elem.align)
  369. if alloc_error != nil {
  370. return Parse_Error {
  371. alloc_error,
  372. "Failed to allocate element backing for dynamic array.",
  373. }
  374. }
  375. defer delete(elem_backing)
  376. parse_and_set_pointer_by_type(raw_data(elem_backing), str, specific_type_info.elem, arg_tag) or_return
  377. if !runtime.__dynamic_array_resize(ptr, specific_type_info.elem.size, specific_type_info.elem.align, ptr.len + 1) {
  378. // NOTE: This is purely an assumption that it's OOM.
  379. // Regardless, the resize failed.
  380. return Parse_Error {
  381. runtime.Allocator_Error.Out_Of_Memory,
  382. "Failed to resize dynamic array.",
  383. }
  384. }
  385. subptr := rawptr(
  386. uintptr(ptr.data) +
  387. uintptr((ptr.len - 1) * specific_type_info.elem.size))
  388. mem.copy(subptr, raw_data(elem_backing), len(elem_backing))
  389. case runtime.Type_Info_Enum:
  390. // This is a nameless enum.
  391. // The code here is virtually the same as above for named enums.
  392. if value, ok := reflect.enum_from_name_any(type_info.id, str); ok {
  393. set_unbounded_integer_by_type(ptr, value, specific_type_info.base.id)
  394. } else {
  395. return Parse_Error {
  396. .Bad_Value,
  397. fmt.tprintf("Invalid value name. Valid names are: %s", specific_type_info.names),
  398. }
  399. }
  400. case:
  401. if !parse_and_set_pointer_by_base_type(ptr, str, type_info) {
  402. return Parse_Error {
  403. // The caller will add more details.
  404. .Bad_Value,
  405. "",
  406. }
  407. }
  408. }
  409. return
  410. }
  411. get_struct_subtag :: get_subtag
  412. get_field_name :: proc(field: reflect.Struct_Field) -> string {
  413. if args_tag, ok := reflect.struct_tag_lookup(field.tag, TAG_ARGS); ok {
  414. if name_subtag, name_ok := get_struct_subtag(args_tag, SUBTAG_NAME); name_ok {
  415. return name_subtag
  416. }
  417. }
  418. name, _ := strings.replace_all(field.name, "_", "-", context.temp_allocator)
  419. return name
  420. }
  421. get_field_pos :: proc(field: reflect.Struct_Field) -> (int, bool) {
  422. if args_tag, ok := reflect.struct_tag_lookup(field.tag, TAG_ARGS); ok {
  423. if pos_subtag, pos_ok := get_struct_subtag(args_tag, SUBTAG_POS); pos_ok {
  424. if value, parse_ok := strconv.parse_u64_of_base(pos_subtag, 10); parse_ok {
  425. return int(value), true
  426. }
  427. }
  428. }
  429. return 0, false
  430. }
  431. // Get a struct field by its field name or `name` subtag.
  432. get_field_by_name :: proc(model: ^$T, name: string) -> (result: reflect.Struct_Field, index: int, error: Error) {
  433. for field, i in reflect.struct_fields_zipped(T) {
  434. if get_field_name(field) == name {
  435. return field, i, nil
  436. }
  437. }
  438. error = Parse_Error {
  439. .Missing_Flag,
  440. fmt.tprintf("Unable to find any flag named `%s`.", name),
  441. }
  442. return
  443. }
  444. // Get a struct field by its `pos` subtag.
  445. get_field_by_pos :: proc(model: ^$T, pos: int) -> (result: reflect.Struct_Field, index: int, ok: bool) {
  446. for field, i in reflect.struct_fields_zipped(T) {
  447. args_tag := reflect.struct_tag_lookup(field.tag, TAG_ARGS) or_continue
  448. pos_subtag := get_struct_subtag(args_tag, SUBTAG_POS) or_continue
  449. value, parse_ok := strconv.parse_u64_of_base(pos_subtag, 10)
  450. if parse_ok && cast(int)value == pos {
  451. return field, i, true
  452. }
  453. }
  454. return
  455. }