internal_rtti.odin 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. if specific_type_info.is_cstring {
  112. cstr_ptr := (^cstring)(ptr)
  113. if cstr_ptr != nil {
  114. // Prevent memory leaks from us setting this value multiple times.
  115. delete(cstr_ptr^)
  116. }
  117. cstr_ptr^ = strings.clone_to_cstring(str)
  118. } else {
  119. (^string)(ptr)^ = str
  120. }
  121. case runtime.Type_Info_Boolean:
  122. value := strconv.parse_bool(str) or_return
  123. switch type_info.id {
  124. case bool: (^bool)(ptr)^ = value
  125. case b8: (^b8) (ptr)^ = b8(value)
  126. case b16: (^b16) (ptr)^ = b16(value)
  127. case b32: (^b32) (ptr)^ = b32(value)
  128. case b64: (^b64) (ptr)^ = b64(value)
  129. }
  130. case runtime.Type_Info_Bit_Set:
  131. // Parse a string of 1's and 0's, from left to right,
  132. // least significant bit to most significant bit.
  133. value: u128
  134. // NOTE: `upper` is inclusive, i.e: `0..=31`
  135. max_bit_index := u128(1 + specific_type_info.upper - specific_type_info.lower)
  136. bit_index := u128(0)
  137. #no_bounds_check for string_index in 0..<uint(len(str)) {
  138. if bit_index == max_bit_index {
  139. // The string's too long for this bit_set.
  140. return false
  141. }
  142. switch str[string_index] {
  143. case '1':
  144. value |= 1 << bit_index
  145. bit_index += 1
  146. case '0':
  147. bit_index += 1
  148. continue
  149. case '_':
  150. continue
  151. case:
  152. return false
  153. }
  154. }
  155. if specific_type_info.underlying != nil {
  156. set_unbounded_integer_by_type(ptr, value, specific_type_info.underlying.id)
  157. } else {
  158. switch 8*type_info.size {
  159. case 8: (^u8) (ptr)^ = cast(u8) value
  160. case 16: (^u16) (ptr)^ = cast(u16) value
  161. case 32: (^u32) (ptr)^ = cast(u32) value
  162. case 64: (^u64) (ptr)^ = cast(u64) value
  163. case 128: (^u128)(ptr)^ = value
  164. }
  165. }
  166. case:
  167. fmt.panicf("Unsupported base data type: %v", specific_type_info)
  168. }
  169. return true
  170. }
  171. // This proc exists to make error handling easier, since everything in the base
  172. // type one above works on booleans. It's a simple parsing error if it's false.
  173. //
  174. // However, here we have to be more careful about how we handle errors,
  175. // especially with files.
  176. //
  177. // We want to provide as informative as an error as we can.
  178. @(optimization_mode="favor_size", disabled=NO_CORE_NAMED_TYPES)
  179. parse_and_set_pointer_by_named_type :: proc(ptr: rawptr, str: string, data_type: typeid, arg_tag: string, out_error: ^Error) {
  180. // Core types currently supported:
  181. //
  182. // - os.Handle
  183. // - time.Time
  184. // - datetime.DateTime
  185. // - net.Host_Or_Endpoint
  186. GENERIC_RFC_3339_ERROR :: "Invalid RFC 3339 string. Try this format: `yyyy-mm-ddThh:mm:ssZ`, for example `2024-02-29T16:30:00Z`."
  187. out_error^ = nil
  188. if data_type == os.Handle {
  189. // NOTE: `os` is hopefully available everywhere, even if it might panic on some calls.
  190. wants_read := false
  191. wants_write := false
  192. mode: int
  193. if file, ok := get_struct_subtag(arg_tag, SUBTAG_FILE); ok {
  194. for i in 0..<len(file) {
  195. #no_bounds_check switch file[i] {
  196. case 'r': wants_read = true
  197. case 'w': wants_write = true
  198. case 'c': mode |= os.O_CREATE
  199. case 'a': mode |= os.O_APPEND
  200. case 't': mode |= os.O_TRUNC
  201. }
  202. }
  203. }
  204. // Sane default.
  205. // owner/group/other: r--r--r--
  206. perms: int = 0o444
  207. if wants_read && wants_write {
  208. mode |= os.O_RDWR
  209. perms |= 0o200
  210. } else if wants_write {
  211. mode |= os.O_WRONLY
  212. perms |= 0o200
  213. } else {
  214. mode |= os.O_RDONLY
  215. }
  216. if permstr, ok := get_struct_subtag(arg_tag, SUBTAG_PERMS); ok {
  217. if value, parse_ok := strconv.parse_u64_of_base(permstr, 8); parse_ok {
  218. perms = int(value)
  219. }
  220. }
  221. handle, errno := os.open(str, mode, perms)
  222. if errno != 0 {
  223. // NOTE(Feoramund): os.Errno is system-dependent, and there's
  224. // currently no good way to translate them all into strings.
  225. //
  226. // The upcoming `os2` package will hopefully solve this.
  227. //
  228. // We can at least provide the number for now, so the user can look
  229. // it up.
  230. out_error^ = Open_File_Error {
  231. str,
  232. errno,
  233. mode,
  234. perms,
  235. }
  236. return
  237. }
  238. (^os.Handle)(ptr)^ = handle
  239. return
  240. }
  241. when IMPORTING_TIME {
  242. if data_type == time.Time {
  243. // NOTE: The leap second data is discarded.
  244. res, consumed := time.rfc3339_to_time_utc(str)
  245. if consumed == 0 {
  246. // The RFC 3339 parsing facilities provide no indication as to what
  247. // went wrong, so just treat it as a regular parsing error.
  248. out_error^ = Parse_Error {
  249. .Bad_Value,
  250. GENERIC_RFC_3339_ERROR,
  251. }
  252. return
  253. }
  254. (^time.Time)(ptr)^ = res
  255. return
  256. } else if data_type == datetime.DateTime {
  257. // NOTE: The UTC offset and leap second data are discarded.
  258. res, _, _, consumed := time.rfc3339_to_components(str)
  259. if consumed == 0 {
  260. out_error^ = Parse_Error {
  261. .Bad_Value,
  262. GENERIC_RFC_3339_ERROR,
  263. }
  264. return
  265. }
  266. (^datetime.DateTime)(ptr)^ = res
  267. return
  268. }
  269. }
  270. when IMPORTING_NET {
  271. if try_net_parse_workaround(data_type, str, ptr, out_error) {
  272. return
  273. }
  274. }
  275. out_error ^= Parse_Error {
  276. // The caller will add more details.
  277. .Unsupported_Type,
  278. "",
  279. }
  280. }
  281. @(optimization_mode="favor_size")
  282. set_unbounded_integer_by_type :: proc(ptr: rawptr, value: $T, data_type: typeid) where intrinsics.type_is_integer(T) {
  283. switch data_type {
  284. case i8: (^i8) (ptr)^ = cast(i8) value
  285. case i16: (^i16) (ptr)^ = cast(i16) value
  286. case i32: (^i32) (ptr)^ = cast(i32) value
  287. case i64: (^i64) (ptr)^ = cast(i64) value
  288. case i128: (^i128) (ptr)^ = cast(i128) value
  289. case int: (^int) (ptr)^ = cast(int) value
  290. case i16le: (^i16le) (ptr)^ = cast(i16le) value
  291. case i32le: (^i32le) (ptr)^ = cast(i32le) value
  292. case i64le: (^i64le) (ptr)^ = cast(i64le) value
  293. case i128le: (^i128le) (ptr)^ = cast(i128le) value
  294. case i16be: (^i16be) (ptr)^ = cast(i16be) value
  295. case i32be: (^i32be) (ptr)^ = cast(i32be) value
  296. case i64be: (^i64be) (ptr)^ = cast(i64be) value
  297. case i128be: (^i128be) (ptr)^ = cast(i128be) value
  298. case u8: (^u8) (ptr)^ = cast(u8) value
  299. case u16: (^u16) (ptr)^ = cast(u16) value
  300. case u32: (^u32) (ptr)^ = cast(u32) value
  301. case u64: (^u64) (ptr)^ = cast(u64) value
  302. case u128: (^u128) (ptr)^ = cast(u128) value
  303. case uint: (^uint) (ptr)^ = cast(uint) value
  304. case uintptr: (^uintptr)(ptr)^ = cast(uintptr) value
  305. case u16le: (^u16le) (ptr)^ = cast(u16le) value
  306. case u32le: (^u32le) (ptr)^ = cast(u32le) value
  307. case u64le: (^u64le) (ptr)^ = cast(u64le) value
  308. case u128le: (^u128le) (ptr)^ = cast(u128le) value
  309. case u16be: (^u16be) (ptr)^ = cast(u16be) value
  310. case u32be: (^u32be) (ptr)^ = cast(u32be) value
  311. case u64be: (^u64be) (ptr)^ = cast(u64be) value
  312. case u128be: (^u128be) (ptr)^ = cast(u128be) value
  313. case rune: (^rune) (ptr)^ = cast(rune) value
  314. case:
  315. fmt.panicf("Unsupported integer backing type: %v", data_type)
  316. }
  317. }
  318. @(optimization_mode="favor_size")
  319. parse_and_set_pointer_by_type :: proc(ptr: rawptr, str: string, type_info: ^runtime.Type_Info, arg_tag: string) -> (error: Error) {
  320. #partial switch specific_type_info in type_info.variant {
  321. case runtime.Type_Info_Named:
  322. if global_custom_type_setter != nil {
  323. // The program gets to go first.
  324. error_message, handled, alloc_error := global_custom_type_setter(ptr, type_info.id, str, arg_tag)
  325. if alloc_error != nil {
  326. // There was an allocation error. Bail out.
  327. return Parse_Error {
  328. alloc_error,
  329. "Custom type setter encountered allocation error.",
  330. }
  331. }
  332. if handled {
  333. // The program handled the type.
  334. if len(error_message) != 0 {
  335. // However, there was an error. Pass it along.
  336. error = Parse_Error {
  337. .Bad_Value,
  338. error_message,
  339. }
  340. }
  341. return
  342. }
  343. }
  344. // Might be a named enum. Need to check here first, since we handle all enums.
  345. if enum_type_info, is_enum := specific_type_info.base.variant.(runtime.Type_Info_Enum); is_enum {
  346. if value, ok := reflect.enum_from_name_any(type_info.id, str); ok {
  347. set_unbounded_integer_by_type(ptr, value, enum_type_info.base.id)
  348. } else {
  349. return Parse_Error {
  350. .Bad_Value,
  351. fmt.tprintf("Invalid value name. Valid names are: %s", enum_type_info.names),
  352. }
  353. }
  354. } else {
  355. parse_and_set_pointer_by_named_type(ptr, str, type_info.id, arg_tag, &error)
  356. if error != nil {
  357. // So far, it's none of the types that we recognize.
  358. // Check to see if we can set it by base type, if allowed.
  359. if _, is_indistinct := get_struct_subtag(arg_tag, SUBTAG_INDISTINCT); is_indistinct {
  360. return parse_and_set_pointer_by_type(ptr, str, specific_type_info.base, arg_tag)
  361. }
  362. }
  363. }
  364. case runtime.Type_Info_Dynamic_Array:
  365. ptr := cast(^runtime.Raw_Dynamic_Array)ptr
  366. // Try to convert the value first.
  367. elem_backing, alloc_error := mem.alloc_bytes(specific_type_info.elem.size, specific_type_info.elem.align)
  368. if alloc_error != nil {
  369. return Parse_Error {
  370. alloc_error,
  371. "Failed to allocate element backing for dynamic array.",
  372. }
  373. }
  374. defer delete(elem_backing)
  375. parse_and_set_pointer_by_type(raw_data(elem_backing), str, specific_type_info.elem, arg_tag) or_return
  376. if !runtime.__dynamic_array_resize(ptr, specific_type_info.elem.size, specific_type_info.elem.align, ptr.len + 1) {
  377. // NOTE: This is purely an assumption that it's OOM.
  378. // Regardless, the resize failed.
  379. return Parse_Error {
  380. runtime.Allocator_Error.Out_Of_Memory,
  381. "Failed to resize dynamic array.",
  382. }
  383. }
  384. subptr := rawptr(
  385. uintptr(ptr.data) +
  386. uintptr((ptr.len - 1) * specific_type_info.elem.size))
  387. mem.copy(subptr, raw_data(elem_backing), len(elem_backing))
  388. case runtime.Type_Info_Enum:
  389. // This is a nameless enum.
  390. // The code here is virtually the same as above for named enums.
  391. if value, ok := reflect.enum_from_name_any(type_info.id, str); ok {
  392. set_unbounded_integer_by_type(ptr, value, specific_type_info.base.id)
  393. } else {
  394. return Parse_Error {
  395. .Bad_Value,
  396. fmt.tprintf("Invalid value name. Valid names are: %s", specific_type_info.names),
  397. }
  398. }
  399. case:
  400. if !parse_and_set_pointer_by_base_type(ptr, str, type_info) {
  401. return Parse_Error {
  402. // The caller will add more details.
  403. .Bad_Value,
  404. "",
  405. }
  406. }
  407. }
  408. return
  409. }
  410. get_struct_subtag :: get_subtag
  411. get_field_name :: proc(field: reflect.Struct_Field) -> string {
  412. if args_tag, ok := reflect.struct_tag_lookup(field.tag, TAG_ARGS); ok {
  413. if name_subtag, name_ok := get_struct_subtag(args_tag, SUBTAG_NAME); name_ok {
  414. return name_subtag
  415. }
  416. }
  417. name, _ := strings.replace_all(field.name, "_", "-", context.temp_allocator)
  418. return name
  419. }
  420. get_field_pos :: proc(field: reflect.Struct_Field) -> (int, bool) {
  421. if args_tag, ok := reflect.struct_tag_lookup(field.tag, TAG_ARGS); ok {
  422. if pos_subtag, pos_ok := get_struct_subtag(args_tag, SUBTAG_POS); pos_ok {
  423. if value, parse_ok := strconv.parse_u64_of_base(pos_subtag, 10); parse_ok {
  424. return int(value), true
  425. }
  426. }
  427. }
  428. return 0, false
  429. }
  430. // Get a struct field by its field name or `name` subtag.
  431. get_field_by_name :: proc(model: ^$T, name: string) -> (result: reflect.Struct_Field, index: int, error: Error) {
  432. for field, i in reflect.struct_fields_zipped(T) {
  433. if get_field_name(field) == name {
  434. return field, i, nil
  435. }
  436. }
  437. error = Parse_Error {
  438. .Missing_Flag,
  439. fmt.tprintf("Unable to find any flag named `%s`.", name),
  440. }
  441. return
  442. }
  443. // Get a struct field by its `pos` subtag.
  444. get_field_by_pos :: proc(model: ^$T, pos: int) -> (result: reflect.Struct_Field, index: int, ok: bool) {
  445. for field, i in reflect.struct_fields_zipped(T) {
  446. args_tag := reflect.struct_tag_lookup(field.tag, TAG_ARGS) or_continue
  447. pos_subtag := get_struct_subtag(args_tag, SUBTAG_POS) or_continue
  448. value, parse_ok := strconv.parse_u64_of_base(pos_subtag, 10)
  449. if parse_ok && cast(int)value == pos {
  450. return field, i, true
  451. }
  452. }
  453. return
  454. }