fmt.odin 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739
  1. package fmt
  2. import "core:math/bits"
  3. import "core:mem"
  4. import "core:io"
  5. import "core:reflect"
  6. import "core:runtime"
  7. import "core:strconv"
  8. import "core:strings"
  9. import "core:time"
  10. import "core:unicode/utf8"
  11. import "core:intrinsics"
  12. // Internal data structure that stores the required information for formatted printing
  13. Info :: struct {
  14. minus: bool,
  15. plus: bool,
  16. space: bool,
  17. zero: bool,
  18. hash: bool,
  19. width_set: bool,
  20. prec_set: bool,
  21. width: int,
  22. prec: int,
  23. indent: int,
  24. reordered: bool,
  25. good_arg_index: bool,
  26. ignore_user_formatters: bool,
  27. in_bad: bool,
  28. writer: io.Writer,
  29. arg: any, // Temporary
  30. indirection_level: int,
  31. record_level: int,
  32. optional_len: Maybe(int),
  33. use_nul_termination: bool,
  34. n: int, // bytes written
  35. }
  36. // Custom formatter signature. It returns true if the formatting was successful and false when it could not be done
  37. User_Formatter :: #type proc(fi: ^Info, arg: any, verb: rune) -> bool
  38. // Example User Formatter:
  39. // SomeType :: struct {
  40. // value: int,
  41. // }
  42. // // Custom Formatter for SomeType
  43. // User_Formatter :: proc(fi: ^fmt.Info, arg: any, verb: rune) -> bool {
  44. // m := cast(^SomeType)arg.data
  45. // switch verb {
  46. // case 'v', 'd':
  47. // fmt.fmt_int(fi, u64(m.value), true, 8 * size_of(SomeType), verb)
  48. // case:
  49. // return false
  50. // }
  51. // return true
  52. // }
  53. // main :: proc() {
  54. // // Ensure the fmt._user_formatters map is initialized
  55. // fmt.set_user_formatters(new(map[typeid]fmt.User_Formatter))
  56. // err := fmt.register_user_formatter(type_info_of(SomeType).id, User_Formatter)
  57. // assert(err == .None)
  58. // // Use the custom formatter
  59. // x := SomeType{42}
  60. // fmt.println("Custom type value: ", x)
  61. // }
  62. Register_User_Formatter_Error :: enum {
  63. None,
  64. No_User_Formatter,
  65. Formatter_Previously_Found,
  66. }
  67. // NOTE(bill): This is a pointer to prevent accidental additions
  68. // it is prefixed with `_` rather than marked with a private attribute so that users can access it if necessary
  69. _user_formatters: ^map[typeid]User_Formatter
  70. // Sets user-defined formatters for custom print formatting of specific types
  71. //
  72. // Inputs:
  73. // - m: A pointer to a map of typeids to User_Formatter structs.
  74. //
  75. // NOTE: Must be called before using register_user_formatter.
  76. //
  77. set_user_formatters :: proc(m: ^map[typeid]User_Formatter) {
  78. assert(_user_formatters == nil, "set_user_formatters must not be called more than once.")
  79. _user_formatters = m
  80. }
  81. // Registers a user-defined formatter for a specific typeid
  82. //
  83. // Inputs:
  84. // - id: The typeid of the custom type.
  85. // - formatter: The User_Formatter function for the custom type.
  86. //
  87. // Returns: A Register_User_Formatter_Error value indicating the success or failure of the operation.
  88. //
  89. // WARNING: set_user_formatters must be called before using this procedure.
  90. //
  91. register_user_formatter :: proc(id: typeid, formatter: User_Formatter) -> Register_User_Formatter_Error {
  92. if _user_formatters == nil {
  93. return .No_User_Formatter
  94. }
  95. if prev, found := _user_formatters[id]; found && prev != nil {
  96. return .Formatter_Previously_Found
  97. }
  98. _user_formatters[id] = formatter
  99. return .None
  100. }
  101. // Creates a formatted string
  102. //
  103. // *Allocates Using Context's Allocator*
  104. //
  105. // Inputs:
  106. // - args: A variadic list of arguments to be formatted.
  107. // - sep: An optional separator string (default is a single space).
  108. //
  109. // Returns: A formatted string.
  110. //
  111. aprint :: proc(args: ..any, sep := " ") -> string {
  112. str: strings.Builder
  113. strings.builder_init(&str)
  114. sbprint(buf=&str, args=args, sep=sep)
  115. return strings.to_string(str)
  116. }
  117. // Creates a formatted string with a newline character at the end
  118. //
  119. // *Allocates Using Context's Allocator*
  120. //
  121. // Inputs:
  122. // - args: A variadic list of arguments to be formatted.
  123. // - sep: An optional separator string (default is a single space).
  124. //
  125. // Returns: A formatted string with a newline character at the end.
  126. //
  127. aprintln :: proc(args: ..any, sep := " ") -> string {
  128. str: strings.Builder
  129. strings.builder_init(&str)
  130. sbprintln(buf=&str, args=args, sep=sep)
  131. return strings.to_string(str)
  132. }
  133. // Creates a formatted string using a format string and arguments
  134. //
  135. // *Allocates Using Context's Allocator*
  136. //
  137. // Inputs:
  138. // - fmt: A format string with placeholders for the provided arguments.
  139. // - args: A variadic list of arguments to be formatted.
  140. //
  141. // Returns: A formatted string. The returned string must be freed accordingly.
  142. //
  143. aprintf :: proc(fmt: string, args: ..any) -> string {
  144. str: strings.Builder
  145. strings.builder_init(&str)
  146. sbprintf(&str, fmt, ..args)
  147. return strings.to_string(str)
  148. }
  149. // Creates a formatted string
  150. //
  151. // *Allocates Using Context's Temporary Allocator*
  152. //
  153. // Inputs:
  154. // - args: A variadic list of arguments to be formatted.
  155. // - sep: An optional separator string (default is a single space).
  156. //
  157. // Returns: A formatted string.
  158. //
  159. tprint :: proc(args: ..any, sep := " ") -> string {
  160. str: strings.Builder
  161. strings.builder_init(&str, context.temp_allocator)
  162. sbprint(buf=&str, args=args, sep=sep)
  163. return strings.to_string(str)
  164. }
  165. // Creates a formatted string with a newline character at the end
  166. //
  167. // *Allocates Using Context's Temporary Allocator*
  168. //
  169. // Inputs:
  170. // - args: A variadic list of arguments to be formatted.
  171. // - sep: An optional separator string (default is a single space).
  172. //
  173. // Returns: A formatted string with a newline character at the end.
  174. //
  175. tprintln :: proc(args: ..any, sep := " ") -> string {
  176. str: strings.Builder
  177. strings.builder_init(&str, context.temp_allocator)
  178. sbprintln(buf=&str, args=args, sep=sep)
  179. return strings.to_string(str)
  180. }
  181. // Creates a formatted string using a format string and arguments
  182. //
  183. // *Allocates Using Context's Temporary Allocator*
  184. //
  185. // Inputs:
  186. // - fmt: A format string with placeholders for the provided arguments.
  187. // - args: A variadic list of arguments to be formatted.
  188. //
  189. // Returns: A formatted string.
  190. //
  191. tprintf :: proc(fmt: string, args: ..any) -> string {
  192. str: strings.Builder
  193. strings.builder_init(&str, context.temp_allocator)
  194. sbprintf(&str, fmt, ..args)
  195. return strings.to_string(str)
  196. }
  197. // Creates a formatted string using a supplied buffer as the backing array. Writes into the buffer.
  198. //
  199. // Inputs:
  200. // - buf: The backing buffer
  201. // - args: A variadic list of arguments to be formatted
  202. // - sep: An optional separator string (default is a single space)
  203. //
  204. // Returns: A formatted string
  205. //
  206. bprint :: proc(buf: []byte, args: ..any, sep := " ") -> string {
  207. sb := strings.builder_from_bytes(buf[0:len(buf)])
  208. return sbprint(buf=&sb, args=args, sep=sep)
  209. }
  210. // Creates a formatted string using a supplied buffer as the backing array, appends newline. Writes into the buffer.
  211. //
  212. // Inputs:
  213. // - buf: The backing buffer
  214. // - args: A variadic list of arguments to be formatted
  215. // - sep: An optional separator string (default is a single space)
  216. //
  217. // Returns: A formatted string with a newline character at the end
  218. //
  219. bprintln :: proc(buf: []byte, args: ..any, sep := " ") -> string {
  220. sb := strings.builder_from_bytes(buf[0:len(buf)])
  221. return sbprintln(buf=&sb, args=args, sep=sep)
  222. }
  223. // Creates a formatted string using a supplied buffer as the backing array. Writes into the buffer.
  224. //
  225. // Inputs:
  226. // - buf: The backing buffer
  227. // - fmt: A format string with placeholders for the provided arguments
  228. // - args: A variadic list of arguments to be formatted
  229. //
  230. // Returns: A formatted string
  231. //
  232. bprintf :: proc(buf: []byte, fmt: string, args: ..any) -> string {
  233. sb := strings.builder_from_bytes(buf[0:len(buf)])
  234. return sbprintf(&sb, fmt, ..args)
  235. }
  236. // Runtime assertion with a formatted message
  237. //
  238. // Inputs:
  239. // - condition: The boolean condition to be asserted
  240. // - fmt: A format string with placeholders for the provided arguments
  241. // - args: A variadic list of arguments to be formatted
  242. // - loc: The location of the caller
  243. //
  244. // Returns: True if the condition is met, otherwise triggers a runtime assertion with a formatted message
  245. //
  246. assertf :: proc(condition: bool, fmt: string, args: ..any, loc := #caller_location) -> bool {
  247. if !condition {
  248. p := context.assertion_failure_proc
  249. if p == nil {
  250. p = runtime.default_assertion_failure_proc
  251. }
  252. message := tprintf(fmt, ..args)
  253. p("Runtime assertion", message, loc)
  254. }
  255. return condition
  256. }
  257. // Runtime panic with a formatted message
  258. //
  259. // Inputs:
  260. // - fmt: A format string with placeholders for the provided arguments
  261. // - args: A variadic list of arguments to be formatted
  262. // - loc: The location of the caller
  263. //
  264. panicf :: proc(fmt: string, args: ..any, loc := #caller_location) -> ! {
  265. p := context.assertion_failure_proc
  266. if p == nil {
  267. p = runtime.default_assertion_failure_proc
  268. }
  269. message := tprintf(fmt, ..args)
  270. p("Panic", message, loc)
  271. }
  272. // Creates a formatted C string
  273. //
  274. // *Allocates Using Context's Allocator*
  275. //
  276. // Inputs:
  277. // - format: A format string with placeholders for the provided arguments
  278. // - args: A variadic list of arguments to be formatted
  279. //
  280. // Returns: A formatted C string
  281. //
  282. caprintf :: proc(format: string, args: ..any) -> cstring {
  283. str: strings.Builder
  284. strings.builder_init(&str)
  285. sbprintf(&str, format, ..args)
  286. strings.write_byte(&str, 0)
  287. s := strings.to_string(str)
  288. return cstring(raw_data(s))
  289. }
  290. // Creates a formatted C string
  291. //
  292. // *Allocates Using Context's Temporary Allocator*
  293. //
  294. // Inputs:
  295. // - format: A format string with placeholders for the provided arguments
  296. // - args: A variadic list of arguments to be formatted
  297. //
  298. // Returns: A formatted C string
  299. //
  300. ctprintf :: proc(format: string, args: ..any) -> cstring {
  301. str: strings.Builder
  302. strings.builder_init(&str, context.temp_allocator)
  303. sbprintf(&str, format, ..args)
  304. strings.write_byte(&str, 0)
  305. s := strings.to_string(str)
  306. return cstring(raw_data(s))
  307. }
  308. // Formats using the default print settings and writes to the given strings.Builder
  309. //
  310. // Inputs:
  311. // - buf: A pointer to a strings.Builder to store the formatted string
  312. // - args: A variadic list of arguments to be formatted
  313. // - sep: An optional separator string (default is a single space)
  314. //
  315. // Returns: A formatted string
  316. //
  317. sbprint :: proc(buf: ^strings.Builder, args: ..any, sep := " ") -> string {
  318. wprint(w=strings.to_writer(buf), args=args, sep=sep)
  319. return strings.to_string(buf^)
  320. }
  321. // Formats and writes to a strings.Builder buffer using the default print settings
  322. //
  323. // Inputs:
  324. // - buf: A pointer to a strings.Builder buffer
  325. // - args: A variadic list of arguments to be formatted
  326. // - sep: An optional separator string (default is a single space)
  327. //
  328. // Returns: The resulting formatted string
  329. //
  330. sbprintln :: proc(buf: ^strings.Builder, args: ..any, sep := " ") -> string {
  331. wprintln(w=strings.to_writer(buf), args=args, sep=sep)
  332. return strings.to_string(buf^)
  333. }
  334. // Formats and writes to a strings.Builder buffer according to the specified format string
  335. //
  336. // Inputs:
  337. // - buf: A pointer to a strings.Builder buffer
  338. // - fmt: The format string
  339. // - args: A variadic list of arguments to be formatted
  340. //
  341. // Returns: The resulting formatted string
  342. //
  343. sbprintf :: proc(buf: ^strings.Builder, fmt: string, args: ..any) -> string {
  344. wprintf(w=strings.to_writer(buf), fmt=fmt, args=args)
  345. return strings.to_string(buf^)
  346. }
  347. // Formats and writes to an io.Writer using the default print settings
  348. //
  349. // Inputs:
  350. // - w: An io.Writer to write to
  351. // - args: A variadic list of arguments to be formatted
  352. // - sep: An optional separator string (default is a single space)
  353. //
  354. // Returns: The number of bytes written
  355. //
  356. wprint :: proc(w: io.Writer, args: ..any, sep := " ") -> int {
  357. fi: Info
  358. fi.writer = w
  359. // NOTE(bill): Old approach
  360. // prev_string := false;
  361. // for arg, i in args {
  362. // is_string := arg != nil && reflect.is_string(type_info_of(arg.id));
  363. // if i > 0 && !is_string && !prev_string {
  364. // io.write_byte(writer, ' ');
  365. // }
  366. // fmt_value(&fi, args[i], 'v');
  367. // prev_string = is_string;
  368. // }
  369. // NOTE(bill, 2020-06-19): I have found that the previous approach was not what people were expecting
  370. // and were expecting `*print` to be the same `*println` except for the added newline
  371. // so I am going to keep the same behaviour as `*println` for `*print`
  372. for _, i in args {
  373. if i > 0 {
  374. io.write_string(fi.writer, sep, &fi.n)
  375. }
  376. fmt_value(&fi, args[i], 'v')
  377. }
  378. io.flush(auto_cast w)
  379. return fi.n
  380. }
  381. // Formats and writes to an io.Writer using the default print settings with a newline character at the end
  382. //
  383. // Inputs:
  384. // - w: An io.Writer to write to
  385. // - args: A variadic list of arguments to be formatted
  386. // - sep: An optional separator string (default is a single space)
  387. //
  388. // Returns: The number of bytes written
  389. //
  390. wprintln :: proc(w: io.Writer, args: ..any, sep := " ") -> int {
  391. fi: Info
  392. fi.writer = w
  393. for _, i in args {
  394. if i > 0 {
  395. io.write_string(fi.writer, sep, &fi.n)
  396. }
  397. fmt_value(&fi, args[i], 'v')
  398. }
  399. io.write_byte(fi.writer, '\n', &fi.n)
  400. io.flush(auto_cast w)
  401. return fi.n
  402. }
  403. // Formats and writes to an io.Writer according to the specified format string
  404. //
  405. // Inputs:
  406. // - w: An io.Writer to write to
  407. // - fmt: The format string
  408. // - args: A variadic list of arguments to be formatted
  409. //
  410. // Returns: The number of bytes written
  411. //
  412. wprintf :: proc(w: io.Writer, fmt: string, args: ..any) -> int {
  413. fi: Info
  414. arg_index: int = 0
  415. end := len(fmt)
  416. was_prev_index := false
  417. loop: for i := 0; i < end; /**/ {
  418. fi = Info{writer = w, good_arg_index = true, reordered = fi.reordered, n = fi.n}
  419. prev_i := i
  420. for i < end && !(fmt[i] == '%' || fmt[i] == '{' || fmt[i] == '}') {
  421. i += 1
  422. }
  423. if i > prev_i {
  424. io.write_string(fi.writer, fmt[prev_i:i], &fi.n)
  425. }
  426. if i >= end {
  427. break loop
  428. }
  429. char := fmt[i]
  430. // Process a "char"
  431. i += 1
  432. if char == '}' {
  433. if i < end && fmt[i] == char {
  434. // Skip extra one
  435. i += 1
  436. }
  437. io.write_byte(fi.writer, char, &fi.n)
  438. continue loop
  439. } else if char == '{' {
  440. if i < end && fmt[i] == char {
  441. // Skip extra one
  442. i += 1
  443. io.write_byte(fi.writer, char, &fi.n)
  444. continue loop
  445. }
  446. }
  447. if char == '%' {
  448. prefix_loop: for ; i < end; i += 1 {
  449. switch fmt[i] {
  450. case '+':
  451. fi.plus = true
  452. case '-':
  453. fi.minus = true
  454. fi.zero = false
  455. case ' ':
  456. fi.space = true
  457. case '#':
  458. fi.hash = true
  459. case '0':
  460. fi.zero = !fi.minus
  461. case:
  462. break prefix_loop
  463. }
  464. }
  465. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  466. // Width
  467. if i < end && fmt[i] == '*' {
  468. i += 1
  469. fi.width, arg_index, fi.width_set = int_from_arg(args, arg_index)
  470. if !fi.width_set {
  471. io.write_string(w, "%!(BAD WIDTH)", &fi.n)
  472. }
  473. if fi.width < 0 {
  474. fi.width = -fi.width
  475. fi.minus = true
  476. fi.zero = false
  477. }
  478. was_prev_index = false
  479. } else {
  480. fi.width, i, fi.width_set = _parse_int(fmt, i)
  481. if was_prev_index && fi.width_set { // %[6]2d
  482. fi.good_arg_index = false
  483. }
  484. }
  485. // Precision
  486. if i < end && fmt[i] == '.' {
  487. i += 1
  488. if was_prev_index { // %[6].2d
  489. fi.good_arg_index = false
  490. }
  491. if i < end && fmt[i] == '*' {
  492. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  493. i += 1
  494. fi.prec, arg_index, fi.prec_set = int_from_arg(args, arg_index)
  495. if fi.prec < 0 {
  496. fi.prec = 0
  497. fi.prec_set = false
  498. }
  499. if !fi.prec_set {
  500. io.write_string(fi.writer, "%!(BAD PRECISION)", &fi.n)
  501. }
  502. was_prev_index = false
  503. } else {
  504. fi.prec, i, fi.prec_set = _parse_int(fmt, i)
  505. }
  506. }
  507. if !was_prev_index {
  508. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  509. }
  510. if i >= end {
  511. io.write_string(fi.writer, "%!(NO VERB)", &fi.n)
  512. break loop
  513. }
  514. verb, w := utf8.decode_rune_in_string(fmt[i:])
  515. i += w
  516. switch {
  517. case verb == '%':
  518. io.write_byte(fi.writer, '%', &fi.n)
  519. case !fi.good_arg_index:
  520. io.write_string(fi.writer, "%!(BAD ARGUMENT NUMBER)", &fi.n)
  521. case arg_index >= len(args):
  522. io.write_string(fi.writer, "%!(MISSING ARGUMENT)", &fi.n)
  523. case:
  524. fmt_arg(&fi, args[arg_index], verb)
  525. arg_index += 1
  526. }
  527. } else if char == '{' {
  528. if i < end && fmt[i] != '}' && fmt[i] != ':' {
  529. new_arg_index, new_i, ok := _parse_int(fmt, i)
  530. if ok {
  531. fi.reordered = true
  532. was_prev_index = true
  533. arg_index = new_arg_index
  534. i = new_i
  535. } else {
  536. io.write_string(fi.writer, "%!(BAD ARGUMENT NUMBER ", &fi.n)
  537. // Skip over the bad argument
  538. start_index := i
  539. for i < end && fmt[i] != '}' && fmt[i] != ':' {
  540. i += 1
  541. }
  542. fmt_arg(&fi, fmt[start_index:i], 'v')
  543. io.write_string(fi.writer, ")", &fi.n)
  544. }
  545. }
  546. verb: rune = 'v'
  547. if i < end && fmt[i] == ':' {
  548. i += 1
  549. prefix_loop_percent: for ; i < end; i += 1 {
  550. switch fmt[i] {
  551. case '+':
  552. fi.plus = true
  553. case '-':
  554. fi.minus = true
  555. fi.zero = false
  556. case ' ':
  557. fi.space = true
  558. case '#':
  559. fi.hash = true
  560. case '0':
  561. fi.zero = !fi.minus
  562. case:
  563. break prefix_loop_percent
  564. }
  565. }
  566. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  567. // Width
  568. if i < end && fmt[i] == '*' {
  569. i += 1
  570. fi.width, arg_index, fi.width_set = int_from_arg(args, arg_index)
  571. if !fi.width_set {
  572. io.write_string(fi.writer, "%!(BAD WIDTH)", &fi.n)
  573. }
  574. if fi.width < 0 {
  575. fi.width = -fi.width
  576. fi.minus = true
  577. fi.zero = false
  578. }
  579. was_prev_index = false
  580. } else {
  581. fi.width, i, fi.width_set = _parse_int(fmt, i)
  582. if was_prev_index && fi.width_set { // %[6]2d
  583. fi.good_arg_index = false
  584. }
  585. }
  586. // Precision
  587. if i < end && fmt[i] == '.' {
  588. i += 1
  589. if was_prev_index { // %[6].2d
  590. fi.good_arg_index = false
  591. }
  592. if i < end && fmt[i] == '*' {
  593. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  594. i += 1
  595. fi.prec, arg_index, fi.prec_set = int_from_arg(args, arg_index)
  596. if fi.prec < 0 {
  597. fi.prec = 0
  598. fi.prec_set = false
  599. }
  600. if !fi.prec_set {
  601. io.write_string(fi.writer, "%!(BAD PRECISION)", &fi.n)
  602. }
  603. was_prev_index = false
  604. } else {
  605. fi.prec, i, fi.prec_set = _parse_int(fmt, i)
  606. }
  607. }
  608. if !was_prev_index {
  609. arg_index, i, was_prev_index = _arg_number(&fi, arg_index, fmt, i, len(args))
  610. }
  611. if i >= end {
  612. io.write_string(fi.writer, "%!(NO VERB)", &fi.n)
  613. break loop
  614. }
  615. w: int = 1
  616. verb, w = utf8.decode_rune_in_string(fmt[i:])
  617. i += w
  618. }
  619. if i >= end {
  620. io.write_string(fi.writer, "%!(MISSING CLOSE BRACE)", &fi.n)
  621. break loop
  622. }
  623. brace, w := utf8.decode_rune_in_string(fmt[i:])
  624. i += w
  625. switch {
  626. case brace != '}':
  627. io.write_string(fi.writer, "%!(MISSING CLOSE BRACE)", &fi.n)
  628. case !fi.good_arg_index:
  629. io.write_string(fi.writer, "%!(BAD ARGUMENT NUMBER)", &fi.n)
  630. case arg_index >= len(args):
  631. io.write_string(fi.writer, "%!(MISSING ARGUMENT)", &fi.n)
  632. case:
  633. fmt_arg(&fi, args[arg_index], verb)
  634. arg_index += 1
  635. }
  636. }
  637. }
  638. if !fi.reordered && arg_index < len(args) {
  639. io.write_string(fi.writer, "%!(EXTRA ", &fi.n)
  640. for arg, index in args[arg_index:] {
  641. if index > 0 {
  642. io.write_string(fi.writer, ", ", &fi.n)
  643. }
  644. if arg == nil {
  645. io.write_string(fi.writer, "<nil>", &fi.n)
  646. } else {
  647. fmt_arg(&fi, args[index], 'v')
  648. }
  649. }
  650. io.write_string(fi.writer, ")", &fi.n)
  651. }
  652. io.flush(auto_cast w)
  653. return fi.n
  654. }
  655. // Writes a ^runtime.Type_Info value to an io.Writer
  656. //
  657. // Inputs:
  658. // - w: An io.Writer to write to
  659. // - info: A pointer to a runtime.Type_Info value
  660. //
  661. // Returns: The number of bytes written and an io.Error if encountered
  662. //
  663. wprint_type :: proc(w: io.Writer, info: ^runtime.Type_Info) -> (int, io.Error) {
  664. n, err := reflect.write_type(w, info)
  665. io.flush(auto_cast w)
  666. return n, err
  667. }
  668. // Writes a typeid value to an io.Writer
  669. //
  670. // Inputs:
  671. // - w: An io.Writer to write to
  672. // - id: A typeid value
  673. //
  674. // Returns: The number of bytes written and an io.Error if encountered
  675. //
  676. wprint_typeid :: proc(w: io.Writer, id: typeid) -> (int, io.Error) {
  677. n, err := reflect.write_type(w, type_info_of(id))
  678. io.flush(auto_cast w)
  679. return n, err
  680. }
  681. // Parses an integer from a given string starting at a specified offset
  682. //
  683. // Inputs:
  684. // - s: The string to parse the integer from
  685. // - offset: The position in the string to start parsing the integer
  686. //
  687. // Returns:
  688. // - result: The parsed integer
  689. // - new_offset: The position in the string after parsing the integer
  690. // - ok: A boolean indicating if the parsing was successful
  691. //
  692. _parse_int :: proc(s: string, offset: int) -> (result: int, new_offset: int, ok: bool) {
  693. is_digit :: #force_inline proc(r: byte) -> bool { return '0' <= r && r <= '9' }
  694. new_offset = offset
  695. for new_offset < len(s) {
  696. c := s[new_offset]
  697. if !is_digit(c) {
  698. break
  699. }
  700. new_offset += 1
  701. result *= 10
  702. result += int(c)-'0'
  703. }
  704. ok = new_offset > offset
  705. return
  706. }
  707. // Parses an argument number from a format string and determines if it's valid
  708. //
  709. // Inputs:
  710. // - fi: A pointer to an Info structure
  711. // - arg_index: The current argument index
  712. // - format: The format string to parse
  713. // - offset: The current position in the format string
  714. // - arg_count: The total number of arguments
  715. //
  716. // Returns:
  717. // - index: The parsed argument index
  718. // - new_offset: The new position in the format string
  719. // - ok: A boolean indicating if the parsed argument number is valid
  720. //
  721. _arg_number :: proc(fi: ^Info, arg_index: int, format: string, offset, arg_count: int) -> (index, new_offset: int, ok: bool) {
  722. parse_arg_number :: proc(format: string) -> (int, int, bool) {
  723. if len(format) < 3 {
  724. return 0, 1, false
  725. }
  726. for i in 1..<len(format) {
  727. if format[i] == ']' {
  728. width, new_index, ok := _parse_int(format, 1)
  729. if !ok || new_index != i {
  730. return 0, i+1, false
  731. }
  732. return width-1, i+1, true
  733. }
  734. }
  735. return 0, 1, false
  736. }
  737. if len(format) <= offset || format[offset] != '[' {
  738. return arg_index, offset, false
  739. }
  740. fi.reordered = true
  741. width: int
  742. index, width, ok = parse_arg_number(format[offset:])
  743. if ok && 0 <= index && index < arg_count {
  744. return index, offset+width, true
  745. }
  746. fi.good_arg_index = false
  747. return arg_index, offset+width, false
  748. }
  749. // Retrieves an integer from a list of any type at the specified index
  750. //
  751. // Inputs:
  752. // - args: A list of values of any type
  753. // - arg_index: The index to retrieve the integer from
  754. //
  755. // Returns:
  756. // - int: The integer value at the specified index
  757. // - new_arg_index: The new argument index
  758. // - ok: A boolean indicating if the conversion to integer was successful
  759. //
  760. int_from_arg :: proc(args: []any, arg_index: int) -> (int, int, bool) {
  761. num := 0
  762. new_arg_index := arg_index
  763. ok := true
  764. if arg_index < len(args) {
  765. num, ok = reflect.as_int(args[arg_index])
  766. }
  767. if ok {
  768. new_arg_index += 1
  769. }
  770. return num, new_arg_index, ok
  771. }
  772. // Writes a bad verb error message
  773. //
  774. // Inputs:
  775. // - fi: A pointer to an Info structure
  776. // - verb: The invalid format verb
  777. //
  778. fmt_bad_verb :: proc(using fi: ^Info, verb: rune) {
  779. prev_in_bad := fi.in_bad
  780. defer fi.in_bad = prev_in_bad
  781. fi.in_bad = true
  782. io.write_string(writer, "%!", &fi.n)
  783. io.write_rune(writer, verb, &fi.n)
  784. io.write_byte(writer, '(', &fi.n)
  785. if arg.id != nil {
  786. reflect.write_typeid(writer, arg.id, &fi.n)
  787. io.write_byte(writer, '=', &fi.n)
  788. fmt_value(fi, arg, 'v')
  789. } else {
  790. io.write_string(writer, "<nil>", &fi.n)
  791. }
  792. io.write_byte(writer, ')', &fi.n)
  793. }
  794. // Formats a boolean value according to the specified format verb
  795. //
  796. // Inputs:
  797. // - fi: A pointer to an Info structure
  798. // - b: The boolean value to format
  799. // - verb: The format verb
  800. //
  801. fmt_bool :: proc(using fi: ^Info, b: bool, verb: rune) {
  802. switch verb {
  803. case 't', 'v':
  804. fmt_string(fi, b ? "true" : "false", 's')
  805. case:
  806. fmt_bad_verb(fi, verb)
  807. }
  808. }
  809. // Writes padding characters for formatting
  810. //
  811. // Inputs:
  812. // - fi: A pointer to an Info structure
  813. // - width: The number of padding characters to write
  814. //
  815. fmt_write_padding :: proc(fi: ^Info, width: int) {
  816. if width <= 0 {
  817. return
  818. }
  819. pad_byte: byte = ' '
  820. if !fi.space {
  821. pad_byte = '0'
  822. }
  823. for i := 0; i < width; i += 1 {
  824. io.write_byte(fi.writer, pad_byte, &fi.n)
  825. }
  826. }
  827. // Formats an integer value with specified base, sign, bit size, and digits
  828. //
  829. // Inputs:
  830. // - fi: A pointer to an Info structure
  831. // - u: The integer value to format
  832. // - base: The base for integer formatting
  833. // - is_signed: A boolean indicating if the integer is signed
  834. // - bit_size: The bit size of the integer
  835. // - digits: A string containing the digits for formatting
  836. //
  837. // WARNING: May panic if the width and precision are too big, causing a buffer overrun
  838. //
  839. _fmt_int :: proc(fi: ^Info, u: u64, base: int, is_signed: bool, bit_size: int, digits: string) {
  840. _, neg := strconv.is_integer_negative(u, is_signed, bit_size)
  841. BUF_SIZE :: 256
  842. if fi.width_set || fi.prec_set {
  843. width := fi.width + fi.prec + 3 // 3 extra bytes for sign and prefix
  844. if width > BUF_SIZE {
  845. // TODO(bill):????
  846. panic("_fmt_int: buffer overrun. Width and precision too big")
  847. }
  848. }
  849. prec := 0
  850. if fi.prec_set {
  851. prec = fi.prec
  852. if prec == 0 && u == 0 {
  853. prev_zero := fi.zero
  854. fi.zero = false
  855. fmt_write_padding(fi, fi.width)
  856. fi.zero = prev_zero
  857. return
  858. }
  859. } else if fi.zero && fi.width_set {
  860. prec = fi.width
  861. if neg || fi.plus {
  862. // There needs to be space for the "sign"
  863. prec -= 1
  864. }
  865. }
  866. switch base {
  867. case 2, 8, 10, 12, 16:
  868. break
  869. case:
  870. panic("_fmt_int: unknown base, whoops")
  871. }
  872. buf: [256]byte
  873. start := 0
  874. flags: strconv.Int_Flags
  875. if fi.hash && !fi.zero { flags |= {.Prefix} }
  876. if fi.plus { flags |= {.Plus} }
  877. s := strconv.append_bits(buf[start:], u, base, is_signed, bit_size, digits, flags)
  878. if fi.hash && fi.zero && fi.indent == 0 {
  879. c: byte = 0
  880. switch base {
  881. case 2: c = 'b'
  882. case 8: c = 'o'
  883. case 12: c = 'z'
  884. case 16: c = 'x'
  885. }
  886. if c != 0 {
  887. io.write_byte(fi.writer, '0', &fi.n)
  888. io.write_byte(fi.writer, c, &fi.n)
  889. }
  890. }
  891. prev_zero := fi.zero
  892. defer fi.zero = prev_zero
  893. fi.zero = false
  894. _pad(fi, s)
  895. }
  896. // Formats an int128 value based on the provided formatting options.
  897. //
  898. // Inputs:
  899. // - fi: A pointer to the Info struct containing formatting options.
  900. // - u: The int128 value to be formatted.
  901. // - base: The base to be used for formatting the integer (e.g. 2, 8, 10, 12, 16).
  902. // - is_signed: Whether the value should be treated as signed or unsigned.
  903. // - bit_size: The number of bits of the value (e.g. 64, 128).
  904. // - digits: A string containing the digit characters to use for the formatted integer.
  905. //
  906. // WARNING: Panics if the formatting options result in a buffer overrun.
  907. //
  908. _fmt_int_128 :: proc(fi: ^Info, u: u128, base: int, is_signed: bool, bit_size: int, digits: string) {
  909. _, neg := strconv.is_integer_negative_128(u, is_signed, bit_size)
  910. BUF_SIZE :: 256
  911. if fi.width_set || fi.prec_set {
  912. width := fi.width + fi.prec + 3 // 3 extra bytes for sign and prefix
  913. if width > BUF_SIZE {
  914. // TODO(bill):????
  915. panic("_fmt_int: buffer overrun. Width and precision too big")
  916. }
  917. }
  918. prec := 0
  919. if fi.prec_set {
  920. prec = fi.prec
  921. if prec == 0 && u == 0 {
  922. prev_zero := fi.zero
  923. fi.zero = false
  924. fmt_write_padding(fi, fi.width)
  925. fi.zero = prev_zero
  926. return
  927. }
  928. } else if fi.zero && fi.width_set {
  929. prec = fi.width
  930. if neg || fi.plus {
  931. // There needs to be space for the "sign"
  932. prec -= 1
  933. }
  934. }
  935. switch base {
  936. case 2, 8, 10, 12, 16:
  937. break
  938. case:
  939. panic("_fmt_int: unknown base, whoops")
  940. }
  941. buf: [256]byte
  942. start := 0
  943. flags: strconv.Int_Flags
  944. if fi.hash && !fi.zero { flags |= {.Prefix} }
  945. if fi.plus { flags |= {.Plus} }
  946. s := strconv.append_bits_128(buf[start:], u, base, is_signed, bit_size, digits, flags)
  947. if fi.hash && fi.zero && fi.indent == 0 {
  948. c: byte = 0
  949. switch base {
  950. case 2: c = 'b'
  951. case 8: c = 'o'
  952. case 12: c = 'z'
  953. case 16: c = 'x'
  954. }
  955. if c != 0 {
  956. io.write_byte(fi.writer, '0', &fi.n)
  957. io.write_byte(fi.writer, c, &fi.n)
  958. }
  959. }
  960. prev_zero := fi.zero
  961. defer fi.zero = prev_zero
  962. fi.zero = false
  963. _pad(fi, s)
  964. }
  965. // Hex Values:
  966. __DIGITS_LOWER := "0123456789abcdefx"
  967. __DIGITS_UPPER := "0123456789ABCDEFX"
  968. // Formats a rune value according to the specified formatting verb.
  969. //
  970. // Inputs:
  971. // - fi: A pointer to the Info struct containing formatting options.
  972. // - r: The rune value to be formatted.
  973. // - verb: The formatting verb to use (e.g. 'c', 'r', 'v', 'q').
  974. //
  975. fmt_rune :: proc(fi: ^Info, r: rune, verb: rune) {
  976. switch verb {
  977. case 'c', 'r', 'v':
  978. io.write_rune(fi.writer, r, &fi.n)
  979. case 'q':
  980. fi.n += io.write_quoted_rune(fi.writer, r)
  981. case:
  982. fmt_int(fi, u64(r), false, 32, verb)
  983. }
  984. }
  985. // Formats an integer value according to the specified formatting verb.
  986. //
  987. // Inputs:
  988. // - fi: A pointer to the Info struct containing formatting options.
  989. // - u: The integer value to be formatted.
  990. // - is_signed: Whether the value should be treated as signed or unsigned.
  991. // - bit_size: The number of bits of the value (e.g. 32, 64).
  992. // - verb: The formatting verb to use (e.g. 'v', 'b', 'o', 'i', 'd', 'z', 'x', 'X', 'c', 'r', 'U').
  993. //
  994. fmt_int :: proc(fi: ^Info, u: u64, is_signed: bool, bit_size: int, verb: rune) {
  995. switch verb {
  996. case 'v': _fmt_int(fi, u, 10, is_signed, bit_size, __DIGITS_LOWER)
  997. case 'b': _fmt_int(fi, u, 2, is_signed, bit_size, __DIGITS_LOWER)
  998. case 'o': _fmt_int(fi, u, 8, is_signed, bit_size, __DIGITS_LOWER)
  999. case 'i', 'd': _fmt_int(fi, u, 10, is_signed, bit_size, __DIGITS_LOWER)
  1000. case 'z': _fmt_int(fi, u, 12, is_signed, bit_size, __DIGITS_LOWER)
  1001. case 'x': _fmt_int(fi, u, 16, is_signed, bit_size, __DIGITS_LOWER)
  1002. case 'X': _fmt_int(fi, u, 16, is_signed, bit_size, __DIGITS_UPPER)
  1003. case 'c', 'r':
  1004. fmt_rune(fi, rune(u), verb)
  1005. case 'U':
  1006. r := rune(u)
  1007. if r < 0 || r > utf8.MAX_RUNE {
  1008. fmt_bad_verb(fi, verb)
  1009. } else {
  1010. io.write_string(fi.writer, "U+", &fi.n)
  1011. _fmt_int(fi, u, 16, false, bit_size, __DIGITS_UPPER)
  1012. }
  1013. case:
  1014. fmt_bad_verb(fi, verb)
  1015. }
  1016. }
  1017. // Formats an int128 value according to the specified formatting verb.
  1018. //
  1019. // Inputs:
  1020. // - fi: A pointer to the Info struct containing formatting options.
  1021. // - u: The int128 value to be formatted.
  1022. // - is_signed: Whether the value should be treated as signed or unsigned.
  1023. // - bit_size: The number of bits of the value (e.g. 64, 128).
  1024. // - verb: The formatting verb to use (e.g. 'v', 'b', 'o', 'i', 'd', 'z', 'x', 'X', 'c', 'r', 'U').
  1025. //
  1026. fmt_int_128 :: proc(fi: ^Info, u: u128, is_signed: bool, bit_size: int, verb: rune) {
  1027. switch verb {
  1028. case 'v': _fmt_int_128(fi, u, 10, is_signed, bit_size, __DIGITS_LOWER)
  1029. case 'b': _fmt_int_128(fi, u, 2, is_signed, bit_size, __DIGITS_LOWER)
  1030. case 'o': _fmt_int_128(fi, u, 8, is_signed, bit_size, __DIGITS_LOWER)
  1031. case 'i', 'd': _fmt_int_128(fi, u, 10, is_signed, bit_size, __DIGITS_LOWER)
  1032. case 'z': _fmt_int_128(fi, u, 12, is_signed, bit_size, __DIGITS_LOWER)
  1033. case 'x': _fmt_int_128(fi, u, 16, is_signed, bit_size, __DIGITS_LOWER)
  1034. case 'X': _fmt_int_128(fi, u, 16, is_signed, bit_size, __DIGITS_UPPER)
  1035. case 'c', 'r':
  1036. fmt_rune(fi, rune(u), verb)
  1037. case 'U':
  1038. r := rune(u)
  1039. if r < 0 || r > utf8.MAX_RUNE {
  1040. fmt_bad_verb(fi, verb)
  1041. } else {
  1042. io.write_string(fi.writer, "U+", &fi.n)
  1043. _fmt_int_128(fi, u, 16, false, bit_size, __DIGITS_UPPER)
  1044. }
  1045. case:
  1046. fmt_bad_verb(fi, verb)
  1047. }
  1048. }
  1049. // Pads a formatted string with the appropriate padding, based on the provided formatting options.
  1050. //
  1051. // Inputs:
  1052. // - fi: A pointer to the Info struct containing formatting options.
  1053. // - s: The string to be padded.
  1054. //
  1055. _pad :: proc(fi: ^Info, s: string) {
  1056. if !fi.width_set {
  1057. io.write_string(fi.writer, s, &fi.n)
  1058. return
  1059. }
  1060. width := fi.width - utf8.rune_count_in_string(s)
  1061. if fi.minus { // right pad
  1062. io.write_string(fi.writer, s, &fi.n)
  1063. fmt_write_padding(fi, width)
  1064. } else { // left pad
  1065. fmt_write_padding(fi, width)
  1066. io.write_string(fi.writer, s, &fi.n)
  1067. }
  1068. }
  1069. // Formats a floating-point number with a specific format and precision.
  1070. //
  1071. // Inputs:
  1072. // - fi: Pointer to the Info struct containing format settings.
  1073. // - v: The floating-point number to format.
  1074. // - bit_size: The size of the floating-point number in bits (16, 32, or 64).
  1075. // - verb: The format specifier character.
  1076. // - float_fmt: The byte format used for formatting the float (either 'f' or 'e').
  1077. //
  1078. // NOTE: Can return "NaN", "+Inf", "-Inf", "+<value>", or "-<value>".
  1079. //
  1080. _fmt_float_as :: proc(fi: ^Info, v: f64, bit_size: int, verb: rune, float_fmt: byte) {
  1081. prec := fi.prec if fi.prec_set else 3
  1082. buf: [386]byte
  1083. // Can return "NaN", "+Inf", "-Inf", "+<value>", "-<value>".
  1084. str := strconv.append_float(buf[:], v, float_fmt, prec, bit_size)
  1085. if !fi.plus {
  1086. // Strip sign from "+<value>" but not "+Inf".
  1087. if str[0] == '+' && str[1] != 'I' {
  1088. str = str[1:]
  1089. }
  1090. }
  1091. _pad(fi, str)
  1092. }
  1093. // Formats a floating-point number with a specific format.
  1094. //
  1095. // Inputs:
  1096. // - fi: Pointer to the Info struct containing format settings.
  1097. // - v: The floating-point number to format.
  1098. // - bit_size: The size of the floating-point number in bits (16, 32, or 64).
  1099. // - verb: The format specifier character.
  1100. //
  1101. fmt_float :: proc(fi: ^Info, v: f64, bit_size: int, verb: rune) {
  1102. switch verb {
  1103. case 'f', 'F', 'g', 'G', 'v':
  1104. _fmt_float_as(fi, v, bit_size, verb, 'f')
  1105. case 'e', 'E':
  1106. // BUG(): "%.3e" returns "3.000e+00"
  1107. _fmt_float_as(fi, v, bit_size, verb, 'e')
  1108. case 'h', 'H':
  1109. prev_fi := fi^
  1110. defer fi^ = prev_fi
  1111. fi.hash = false
  1112. fi.width = bit_size
  1113. fi.zero = true
  1114. fi.plus = false
  1115. u: u64
  1116. switch bit_size {
  1117. case 16: u = u64(transmute(u16)f16(v))
  1118. case 32: u = u64(transmute(u32)f32(v))
  1119. case 64: u = transmute(u64)v
  1120. case: panic("Unhandled float size")
  1121. }
  1122. io.write_string(fi.writer, "0h", &fi.n)
  1123. _fmt_int(fi, u, 16, false, bit_size, __DIGITS_LOWER if verb == 'h' else __DIGITS_UPPER)
  1124. case:
  1125. fmt_bad_verb(fi, verb)
  1126. }
  1127. }
  1128. // Formats a string with a specific format.
  1129. //
  1130. // Inputs:
  1131. // - fi: Pointer to the Info struct containing format settings.
  1132. // - s: The string to format.
  1133. // - verb: The format specifier character (e.g. 's', 'v', 'q', 'x', 'X').
  1134. //
  1135. fmt_string :: proc(fi: ^Info, s: string, verb: rune) {
  1136. s, verb := s, verb
  1137. if ol, ok := fi.optional_len.?; ok {
  1138. s = s[:clamp(ol, 0, len(s))]
  1139. }
  1140. if !fi.in_bad && fi.record_level > 0 && verb == 'v' {
  1141. verb = 'q'
  1142. }
  1143. switch verb {
  1144. case 's', 'v':
  1145. if fi.width_set {
  1146. if fi.width > len(s) {
  1147. if fi.minus {
  1148. io.write_string(fi.writer, s, &fi.n)
  1149. }
  1150. for _ in 0..<fi.width - len(s) {
  1151. io.write_byte(fi.writer, ' ', &fi.n)
  1152. }
  1153. if !fi.minus {
  1154. io.write_string(fi.writer, s, &fi.n)
  1155. }
  1156. }
  1157. else {
  1158. io.write_string(fi.writer, s, &fi.n)
  1159. }
  1160. }
  1161. else
  1162. {
  1163. io.write_string(fi.writer, s, &fi.n)
  1164. }
  1165. case 'q': // quoted string
  1166. io.write_quoted_string(fi.writer, s, '"', &fi.n)
  1167. case 'x', 'X':
  1168. space := fi.space
  1169. fi.space = false
  1170. defer fi.space = space
  1171. for i in 0..<len(s) {
  1172. if i > 0 && space {
  1173. io.write_byte(fi.writer, ' ', &fi.n)
  1174. }
  1175. char_set := __DIGITS_UPPER
  1176. if verb == 'x' {
  1177. char_set = __DIGITS_LOWER
  1178. }
  1179. _fmt_int(fi, u64(s[i]), 16, false, 8, char_set)
  1180. }
  1181. case:
  1182. fmt_bad_verb(fi, verb)
  1183. }
  1184. }
  1185. // Formats a C-style string with a specific format.
  1186. //
  1187. // Inputs:
  1188. // - fi: Pointer to the Info struct containing format settings.
  1189. // - s: The C-style string to format.
  1190. // - verb: The format specifier character (Ref fmt_string).
  1191. //
  1192. fmt_cstring :: proc(fi: ^Info, s: cstring, verb: rune) {
  1193. fmt_string(fi, string(s), verb)
  1194. }
  1195. // Formats a raw pointer with a specific format.
  1196. //
  1197. // Inputs:
  1198. // - fi: Pointer to the Info struct containing format settings.
  1199. // - p: The raw pointer to format.
  1200. // - verb: The format specifier character (e.g. 'p', 'v', 'b', 'o', 'i', 'd', 'z', 'x', 'X').
  1201. //
  1202. fmt_pointer :: proc(fi: ^Info, p: rawptr, verb: rune) {
  1203. u := u64(uintptr(p))
  1204. switch verb {
  1205. case 'p', 'v':
  1206. if !fi.hash && verb == 'v' {
  1207. io.write_string(fi.writer, "0x", &fi.n)
  1208. }
  1209. _fmt_int(fi, u, 16, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1210. case 'b': _fmt_int(fi, u, 2, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1211. case 'o': _fmt_int(fi, u, 8, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1212. case 'i', 'd': _fmt_int(fi, u, 10, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1213. case 'z': _fmt_int(fi, u, 12, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1214. case 'x': _fmt_int(fi, u, 16, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1215. case 'X': _fmt_int(fi, u, 16, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1216. case:
  1217. fmt_bad_verb(fi, verb)
  1218. }
  1219. }
  1220. // Formats a Structure of Arrays (SoA) pointer with a specific format.
  1221. //
  1222. // Inputs:
  1223. // - fi: Pointer to the Info struct containing format settings.
  1224. // - p: The SoA pointer to format.
  1225. // - verb: The format specifier character.
  1226. //
  1227. fmt_soa_pointer :: proc(fi: ^Info, p: runtime.Raw_Soa_Pointer, verb: rune) {
  1228. io.write_string(fi.writer, "#soa{data=0x", &fi.n)
  1229. _fmt_int(fi, u64(uintptr(p.data)), 16, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1230. io.write_string(fi.writer, ", index=", &fi.n)
  1231. _fmt_int(fi, u64(p.index), 10, false, 8*size_of(rawptr), __DIGITS_UPPER)
  1232. io.write_string(fi.writer, "}", &fi.n)
  1233. }
  1234. // String representation of an enum value.
  1235. //
  1236. // Inputs:
  1237. // - val: The enum value.
  1238. //
  1239. // Returns: The string representation of the enum value and a boolean indicating success.
  1240. //
  1241. enum_value_to_string :: proc(val: any) -> (string, bool) {
  1242. v := val
  1243. v.id = runtime.typeid_base(v.id)
  1244. type_info := type_info_of(v.id)
  1245. #partial switch e in type_info.variant {
  1246. case: return "", false
  1247. case runtime.Type_Info_Enum:
  1248. Enum_Value :: runtime.Type_Info_Enum_Value
  1249. ev_, ok := reflect.as_i64(val)
  1250. ev := Enum_Value(ev_)
  1251. if ok {
  1252. if len(e.values) == 0 {
  1253. return "", true
  1254. } else {
  1255. for val, idx in e.values {
  1256. if val == ev {
  1257. return e.names[idx], true
  1258. }
  1259. }
  1260. }
  1261. return "", false
  1262. }
  1263. }
  1264. return "", false
  1265. }
  1266. // Returns the enum value of a string representation.
  1267. //
  1268. // $T: The typeid of the enum type.
  1269. // Inputs:
  1270. // - s: The string representation of the enum value.
  1271. //
  1272. // Returns: The enum value and a boolean indicating success.
  1273. //
  1274. string_to_enum_value :: proc($T: typeid, s: string) -> (T, bool) {
  1275. ti := runtime.type_info_base(type_info_of(T))
  1276. if e, ok := ti.variant.(runtime.Type_Info_Enum); ok {
  1277. for str, idx in e.names {
  1278. if s == str {
  1279. // NOTE(bill): Unsafe cast
  1280. ptr := cast(^T)&e.values[idx]
  1281. return ptr^, true
  1282. }
  1283. }
  1284. }
  1285. return T{}, false
  1286. }
  1287. // Formats an enum value with a specific format.
  1288. //
  1289. // Inputs:
  1290. // - fi: Pointer to the Info struct containing format settings.
  1291. // - v: The enum value to format.
  1292. // - verb: The format specifier character (e.g. 'i','d','f','s','v','q').
  1293. //
  1294. fmt_enum :: proc(fi: ^Info, v: any, verb: rune) {
  1295. if v.id == nil || v.data == nil {
  1296. io.write_string(fi.writer, "<nil>", &fi.n)
  1297. return
  1298. }
  1299. type_info := type_info_of(v.id)
  1300. #partial switch e in type_info.variant {
  1301. case: fmt_bad_verb(fi, verb)
  1302. case runtime.Type_Info_Enum:
  1303. switch verb {
  1304. case: fmt_bad_verb(fi, verb)
  1305. case 'i', 'd', 'f':
  1306. fmt_arg(fi, any{v.data, runtime.type_info_base(e.base).id}, verb)
  1307. case 's', 'v', 'q':
  1308. if str, ok := enum_value_to_string(v); ok {
  1309. fmt_string(fi, str, verb)
  1310. } else {
  1311. io.write_string(fi.writer, "%!(BAD ENUM VALUE=", &fi.n)
  1312. fmt_arg(fi, any{v.data, runtime.type_info_base(e.base).id}, 'i')
  1313. io.write_string(fi.writer, ")", &fi.n)
  1314. }
  1315. }
  1316. }
  1317. }
  1318. // Converts a stored enum value to a string representation
  1319. //
  1320. // Inputs:
  1321. // - enum_type: A pointer to the runtime.Type_Info of the enumeration.
  1322. // - ev: The runtime.Type_Info_Enum_Value of the stored enum value.
  1323. // - offset: An optional integer to adjust the enumeration value (default is 0).
  1324. //
  1325. // Returns: A tuple containing the string representation of the enum value and a bool indicating success.
  1326. //
  1327. stored_enum_value_to_string :: proc(enum_type: ^runtime.Type_Info, ev: runtime.Type_Info_Enum_Value, offset: int = 0) -> (string, bool) {
  1328. et := runtime.type_info_base(enum_type)
  1329. ev := ev
  1330. ev += runtime.Type_Info_Enum_Value(offset)
  1331. #partial switch e in et.variant {
  1332. case: return "", false
  1333. case runtime.Type_Info_Enum:
  1334. if reflect.is_string(e.base) {
  1335. for val, idx in e.values {
  1336. if val == ev {
  1337. return e.names[idx], true
  1338. }
  1339. }
  1340. } else if len(e.values) == 0 {
  1341. return "", true
  1342. } else {
  1343. for val, idx in e.values {
  1344. if val == ev {
  1345. return e.names[idx], true
  1346. }
  1347. }
  1348. }
  1349. return "", false
  1350. }
  1351. return "", false
  1352. }
  1353. // Formats a bit set and writes it to the provided Info structure
  1354. //
  1355. // Inputs:
  1356. // - fi: A pointer to the Info structure where the formatted bit set will be written.
  1357. // - v: The bit set value to be formatted.
  1358. // - name: An optional string for the name of the bit set (default is an empty string).
  1359. //
  1360. fmt_bit_set :: proc(fi: ^Info, v: any, name: string = "") {
  1361. is_bit_set_different_endian_to_platform :: proc(ti: ^runtime.Type_Info) -> bool {
  1362. if ti == nil {
  1363. return false
  1364. }
  1365. t := runtime.type_info_base(ti)
  1366. #partial switch info in t.variant {
  1367. case runtime.Type_Info_Integer:
  1368. switch info.endianness {
  1369. case .Platform: return false
  1370. case .Little: return ODIN_ENDIAN != .Little
  1371. case .Big: return ODIN_ENDIAN != .Big
  1372. }
  1373. }
  1374. return false
  1375. }
  1376. byte_swap :: bits.byte_swap
  1377. type_info := type_info_of(v.id)
  1378. #partial switch info in type_info.variant {
  1379. case runtime.Type_Info_Named:
  1380. val := v
  1381. val.id = info.base.id
  1382. fmt_bit_set(fi, val, info.name)
  1383. case runtime.Type_Info_Bit_Set:
  1384. bits: u128
  1385. bit_size := u128(8*type_info.size)
  1386. do_byte_swap := is_bit_set_different_endian_to_platform(info.underlying)
  1387. switch bit_size {
  1388. case 0: bits = 0
  1389. case 8:
  1390. x := (^u8)(v.data)^
  1391. bits = u128(x)
  1392. case 16:
  1393. x := (^u16)(v.data)^
  1394. if do_byte_swap { x = byte_swap(x) }
  1395. bits = u128(x)
  1396. case 32:
  1397. x := (^u32)(v.data)^
  1398. if do_byte_swap { x = byte_swap(x) }
  1399. bits = u128(x)
  1400. case 64:
  1401. x := (^u64)(v.data)^
  1402. if do_byte_swap { x = byte_swap(x) }
  1403. bits = u128(x)
  1404. case 128:
  1405. x := (^u128)(v.data)^
  1406. if do_byte_swap { x = byte_swap(x) }
  1407. bits = x
  1408. case: panic("unknown bit_size size")
  1409. }
  1410. et := runtime.type_info_base(info.elem)
  1411. if name != "" {
  1412. io.write_string(fi.writer, name, &fi.n)
  1413. } else {
  1414. reflect.write_type(fi.writer, type_info, &fi.n)
  1415. }
  1416. io.write_byte(fi.writer, '{', &fi.n)
  1417. defer io.write_byte(fi.writer, '}', &fi.n)
  1418. e, is_enum := et.variant.(runtime.Type_Info_Enum)
  1419. commas := 0
  1420. loop: for i in 0 ..< bit_size {
  1421. if bits & (1<<i) == 0 {
  1422. continue loop
  1423. }
  1424. if commas > 0 {
  1425. io.write_string(fi.writer, ", ", &fi.n)
  1426. }
  1427. if is_enum {
  1428. for ev, evi in e.values {
  1429. v := u64(ev)
  1430. if v == u64(i) {
  1431. io.write_string(fi.writer, e.names[evi], &fi.n)
  1432. commas += 1
  1433. continue loop
  1434. }
  1435. }
  1436. }
  1437. v := i64(i) + info.lower
  1438. io.write_i64(fi.writer, v, 10, &fi.n)
  1439. commas += 1
  1440. }
  1441. }
  1442. }
  1443. // Writes the specified number of indents to the provided Info structure
  1444. //
  1445. // Inputs:
  1446. // - fi: A pointer to the Info structure where the indents will be written.
  1447. //
  1448. fmt_write_indent :: proc(fi: ^Info) {
  1449. for in 0..<fi.indent {
  1450. io.write_byte(fi.writer, '\t', &fi.n)
  1451. }
  1452. }
  1453. // Formats an array and writes it to the provided Info structure
  1454. //
  1455. // Inputs:
  1456. // - fi: A pointer to the Info structure where the formatted array will be written.
  1457. // - array_data: A raw pointer to the array data.
  1458. // - count: The number of elements in the array.
  1459. // - elem_size: The size of each element in the array.
  1460. // - elem_id: The typeid of the array elements.
  1461. // - verb: The formatting verb to be used for the array elements.
  1462. //
  1463. fmt_write_array :: proc(fi: ^Info, array_data: rawptr, count: int, elem_size: int, elem_id: typeid, verb: rune) {
  1464. io.write_byte(fi.writer, '[', &fi.n)
  1465. defer io.write_byte(fi.writer, ']', &fi.n)
  1466. if count <= 0 {
  1467. return
  1468. }
  1469. fi.record_level += 1
  1470. defer fi.record_level -= 1
  1471. if fi.hash {
  1472. io.write_byte(fi.writer, '\n', &fi.n)
  1473. defer fmt_write_indent(fi)
  1474. indent := fi.indent
  1475. fi.indent += 1
  1476. defer fi.indent = indent
  1477. for i in 0..<count {
  1478. fmt_write_indent(fi)
  1479. data := uintptr(array_data) + uintptr(i*elem_size)
  1480. fmt_arg(fi, any{rawptr(data), elem_id}, verb)
  1481. io.write_string(fi.writer, ",\n", &fi.n)
  1482. }
  1483. } else {
  1484. for i in 0..<count {
  1485. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  1486. data := uintptr(array_data) + uintptr(i*elem_size)
  1487. fmt_arg(fi, any{rawptr(data), elem_id}, verb)
  1488. }
  1489. }
  1490. }
  1491. // Handles struct tag processing for formatting
  1492. //
  1493. // Inputs:
  1494. // - data: A raw pointer to the data being processed
  1495. // - info: Type information about the struct
  1496. // - idx: The index of the tag in the struct
  1497. // - verb: A mutable pointer to the rune representing the format verb
  1498. // - optional_len: A mutable pointer to an integer holding the optional length (if applicable)
  1499. // - use_nul_termination: A mutable pointer to a boolean flag indicating if NUL termination is used
  1500. //
  1501. // Returns: A boolean value indicating whether to continue processing the tag
  1502. //
  1503. @(private)
  1504. handle_tag :: proc(data: rawptr, info: reflect.Type_Info_Struct, idx: int, verb: ^rune, optional_len: ^int, use_nul_termination: ^bool) -> (do_continue: bool) {
  1505. handle_optional_len :: proc(data: rawptr, info: reflect.Type_Info_Struct, field_name: string, optional_len: ^int) {
  1506. if optional_len == nil {
  1507. return
  1508. }
  1509. for f, i in info.names {
  1510. if f != field_name {
  1511. continue
  1512. }
  1513. ptr := rawptr(uintptr(data) + info.offsets[i])
  1514. field := any{ptr, info.types[i].id}
  1515. if new_len, iok := reflect.as_int(field); iok {
  1516. optional_len^ = max(new_len, 0)
  1517. }
  1518. break
  1519. }
  1520. }
  1521. tag := info.tags[idx]
  1522. if vt, ok := reflect.struct_tag_lookup(reflect.Struct_Tag(tag), "fmt"); ok {
  1523. value := strings.trim_space(string(vt))
  1524. switch value {
  1525. case "": return false
  1526. case "-": return true
  1527. }
  1528. r, w := utf8.decode_rune_in_string(value)
  1529. value = value[w:]
  1530. if value == "" || value[0] == ',' {
  1531. verb^ = r
  1532. if len(value) > 0 && value[0] == ',' {
  1533. field_name := value[1:]
  1534. if field_name == "0" {
  1535. if use_nul_termination != nil {
  1536. use_nul_termination^ = true
  1537. }
  1538. } else {
  1539. switch r {
  1540. case 's', 'q':
  1541. handle_optional_len(data, info, field_name, optional_len)
  1542. case 'v':
  1543. #partial switch reflect.type_kind(info.types[idx].id) {
  1544. case .String, .Multi_Pointer, .Array, .Slice, .Dynamic_Array:
  1545. handle_optional_len(data, info, field_name, optional_len)
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. return false
  1553. }
  1554. // Formats a struct for output, handling various struct types (e.g., SOA, raw unions)
  1555. //
  1556. // Inputs:
  1557. // - fi: A mutable pointer to an Info struct containing formatting state
  1558. // - v: The value to be formatted
  1559. // - the_verb: The formatting verb to be used (e.g. 'v')
  1560. // - info: Type information about the struct
  1561. // - type_name: The name of the type being formatted
  1562. //
  1563. fmt_struct :: proc(fi: ^Info, v: any, the_verb: rune, info: runtime.Type_Info_Struct, type_name: string) {
  1564. if the_verb != 'v' {
  1565. fmt_bad_verb(fi, the_verb)
  1566. return
  1567. }
  1568. if info.is_raw_union {
  1569. if type_name == "" {
  1570. io.write_string(fi.writer, "(raw union)", &fi.n)
  1571. } else {
  1572. io.write_string(fi.writer, type_name, &fi.n)
  1573. io.write_string(fi.writer, "{}", &fi.n)
  1574. }
  1575. return
  1576. }
  1577. is_soa := info.soa_kind != .None
  1578. io.write_string(fi.writer, type_name, &fi.n)
  1579. io.write_byte(fi.writer, '[' if is_soa else '{', &fi.n)
  1580. fi.record_level += 1
  1581. defer fi.record_level -= 1
  1582. hash := fi.hash; defer fi.hash = hash
  1583. indent := fi.indent; defer fi.indent -= 1
  1584. do_trailing_comma := hash
  1585. // fi.hash = false;
  1586. fi.indent += 1
  1587. if hash {
  1588. io.write_byte(fi.writer, '\n', &fi.n)
  1589. }
  1590. defer {
  1591. if hash {
  1592. for in 0..<indent { io.write_byte(fi.writer, '\t', &fi.n) }
  1593. }
  1594. io.write_byte(fi.writer, ']' if is_soa else '}', &fi.n)
  1595. }
  1596. if is_soa {
  1597. fi.indent += 1
  1598. defer fi.indent -= 1
  1599. base_type_name: string
  1600. if v, ok := info.soa_base_type.variant.(runtime.Type_Info_Named); ok {
  1601. base_type_name = v.name
  1602. }
  1603. actual_field_count := len(info.names)
  1604. n := uintptr(info.soa_len)
  1605. if info.soa_kind == .Slice {
  1606. actual_field_count = len(info.names)-1 // len
  1607. n = uintptr((^int)(uintptr(v.data) + info.offsets[actual_field_count])^)
  1608. } else if info.soa_kind == .Dynamic {
  1609. actual_field_count = len(info.names)-3 // len, cap, allocator
  1610. n = uintptr((^int)(uintptr(v.data) + info.offsets[actual_field_count])^)
  1611. }
  1612. for index in 0..<n {
  1613. if !hash && index > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  1614. field_count := -1
  1615. if !hash && field_count > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  1616. io.write_string(fi.writer, base_type_name, &fi.n)
  1617. io.write_byte(fi.writer, '{', &fi.n)
  1618. defer io.write_byte(fi.writer, '}', &fi.n)
  1619. fi.record_level += 1
  1620. defer fi.record_level -= 1
  1621. for i in 0..<actual_field_count {
  1622. verb := 'v'
  1623. name := info.names[i]
  1624. field_count += 1
  1625. if !hash && field_count > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  1626. if hash {
  1627. fmt_write_indent(fi)
  1628. }
  1629. io.write_string(fi.writer, name, &fi.n)
  1630. io.write_string(fi.writer, " = ", &fi.n)
  1631. if info.soa_kind == .Fixed {
  1632. t := info.types[i].variant.(runtime.Type_Info_Array).elem
  1633. t_size := uintptr(t.size)
  1634. if reflect.is_any(t) {
  1635. io.write_string(fi.writer, "any{}", &fi.n)
  1636. } else {
  1637. data := rawptr(uintptr(v.data) + info.offsets[i] + index*t_size)
  1638. fmt_arg(fi, any{data, t.id}, verb)
  1639. }
  1640. } else {
  1641. t := info.types[i].variant.(runtime.Type_Info_Pointer).elem
  1642. t_size := uintptr(t.size)
  1643. if reflect.is_any(t) {
  1644. io.write_string(fi.writer, "any{}", &fi.n)
  1645. } else {
  1646. field_ptr := (^^byte)(uintptr(v.data) + info.offsets[i])^
  1647. data := rawptr(uintptr(field_ptr) + index*t_size)
  1648. fmt_arg(fi, any{data, t.id}, verb)
  1649. }
  1650. }
  1651. if hash { io.write_string(fi.writer, ",\n", &fi.n) }
  1652. }
  1653. }
  1654. } else {
  1655. field_count := -1
  1656. for name, i in info.names {
  1657. optional_len: int = -1
  1658. use_nul_termination: bool = false
  1659. verb := 'v'
  1660. if handle_tag(v.data, info, i, &verb, &optional_len, &use_nul_termination) {
  1661. continue
  1662. }
  1663. field_count += 1
  1664. if optional_len >= 0 {
  1665. fi.optional_len = optional_len
  1666. }
  1667. defer if optional_len >= 0 {
  1668. fi.optional_len = nil
  1669. }
  1670. fi.use_nul_termination = use_nul_termination
  1671. defer fi.use_nul_termination = false
  1672. if !do_trailing_comma && field_count > 0 { io.write_string(fi.writer, ", ") }
  1673. if hash {
  1674. fmt_write_indent(fi)
  1675. }
  1676. io.write_string(fi.writer, name, &fi.n)
  1677. io.write_string(fi.writer, " = ", &fi.n)
  1678. if t := info.types[i]; reflect.is_any(t) {
  1679. io.write_string(fi.writer, "any{}", &fi.n)
  1680. } else {
  1681. data := rawptr(uintptr(v.data) + info.offsets[i])
  1682. fmt_arg(fi, any{data, t.id}, verb)
  1683. }
  1684. if do_trailing_comma { io.write_string(fi.writer, ",\n", &fi.n) }
  1685. }
  1686. }
  1687. }
  1688. // Searches for the first NUL-terminated element in a given buffer
  1689. //
  1690. // Inputs:
  1691. // - ptr: The raw pointer to the buffer.
  1692. // - elem_size: The size of each element in the buffer.
  1693. // - max_n: The maximum number of elements to search (use -1 for no limit).
  1694. //
  1695. // Returns: The number of elements before the first NUL-terminated element.
  1696. //
  1697. @(private)
  1698. search_nul_termination :: proc(ptr: rawptr, elem_size: int, max_n: int) -> (n: int) {
  1699. for p := uintptr(ptr); max_n < 0 || n < max_n; p += uintptr(elem_size) {
  1700. if mem.check_zero_ptr(rawptr(p), elem_size) {
  1701. break
  1702. }
  1703. n += 1
  1704. }
  1705. return n
  1706. }
  1707. // Formats a NUL-terminated array into a string representation
  1708. //
  1709. // Inputs:
  1710. // - fi: Pointer to the formatting Info struct.
  1711. // - data: The raw pointer to the array data.
  1712. // - max_n: The maximum number of elements to process.
  1713. // - elem_size: The size of each element in the array.
  1714. // - elem: Pointer to the type information of the array element.
  1715. // - verb: The formatting verb.
  1716. //
  1717. fmt_array_nul_terminated :: proc(fi: ^Info, data: rawptr, max_n: int, elem_size: int, elem: ^reflect.Type_Info, verb: rune) {
  1718. if data == nil {
  1719. io.write_string(fi.writer, "<nil>", &fi.n)
  1720. return
  1721. }
  1722. n := search_nul_termination(data, elem_size, max_n)
  1723. fmt_array(fi, data, n, elem_size, elem, verb)
  1724. }
  1725. // Formats an array into a string representation
  1726. //
  1727. // Inputs:
  1728. // - fi: Pointer to the formatting Info struct.
  1729. // - data: The raw pointer to the array data.
  1730. // - n: The number of elements in the array.
  1731. // - elem_size: The size of each element in the array.
  1732. // - elem: Pointer to the type information of the array element.
  1733. // - verb: The formatting verb (e.g. 's','q','p').
  1734. //
  1735. fmt_array :: proc(fi: ^Info, data: rawptr, n: int, elem_size: int, elem: ^reflect.Type_Info, verb: rune) {
  1736. if data == nil && n > 0 {
  1737. io.write_string(fi.writer, "nil")
  1738. return
  1739. }
  1740. if verb == 's' || verb == 'q' {
  1741. print_utf16 :: proc(fi: ^Info, s: []$T) where size_of(T) == 2, intrinsics.type_is_integer(T) {
  1742. REPLACEMENT_CHAR :: '\ufffd'
  1743. _surr1 :: 0xd800
  1744. _surr2 :: 0xdc00
  1745. _surr3 :: 0xe000
  1746. _surr_self :: 0x10000
  1747. for i := 0; i < len(s); i += 1 {
  1748. r := rune(REPLACEMENT_CHAR)
  1749. switch c := s[i]; {
  1750. case c < _surr1, _surr3 <= c:
  1751. r = rune(c)
  1752. case _surr1 <= c && c < _surr2 && i+1 < len(s) &&
  1753. _surr2 <= s[i+1] && s[i+1] < _surr3:
  1754. r1, r2 := rune(c), rune(s[i+1])
  1755. if _surr1 <= r1 && r1 < _surr2 && _surr2 <= r2 && r2 < _surr3 {
  1756. r = (r1-_surr1)<<10 | (r2 - _surr2) + _surr_self
  1757. }
  1758. i += 1
  1759. }
  1760. io.write_rune(fi.writer, r, &fi.n)
  1761. }
  1762. }
  1763. print_utf32 :: proc(fi: ^Info, s: []$T) where size_of(T) == 4 {
  1764. for r in s {
  1765. io.write_rune(fi.writer, rune(r), &fi.n)
  1766. }
  1767. }
  1768. switch reflect.type_info_base(elem).id {
  1769. case byte: fmt_string(fi, string(([^]byte)(data)[:n]), verb); return
  1770. case u16: print_utf16(fi, ([^]u16)(data)[:n]); return
  1771. case u16le: print_utf16(fi, ([^]u16le)(data)[:n]); return
  1772. case u16be: print_utf16(fi, ([^]u16be)(data)[:n]); return
  1773. case u32: print_utf32(fi, ([^]u32)(data)[:n]); return
  1774. case u32le: print_utf32(fi, ([^]u32le)(data)[:n]); return
  1775. case u32be: print_utf32(fi, ([^]u32be)(data)[:n]); return
  1776. case rune: print_utf32(fi, ([^]rune)(data)[:n]); return
  1777. }
  1778. }
  1779. if verb == 'p' {
  1780. fmt_pointer(fi, data, 'p')
  1781. } else {
  1782. fmt_write_array(fi, data, n, elem_size, elem.id, verb)
  1783. }
  1784. }
  1785. // Formats a named type into a string representation
  1786. //
  1787. // Inputs:
  1788. // - fi: Pointer to the formatting Info struct.
  1789. // - v: The value to format.
  1790. // - verb: The formatting verb.
  1791. // - info: The named type information.
  1792. //
  1793. // NOTE: This procedure supports built-in custom formatters for core library types such as runtime.Source_Code_Location, time.Duration, and time.Time.
  1794. //
  1795. fmt_named :: proc(fi: ^Info, v: any, verb: rune, info: runtime.Type_Info_Named) {
  1796. write_padded_number :: proc(fi: ^Info, i: i64, width: int) {
  1797. n := width-1
  1798. for x := i; x >= 10; x /= 10 {
  1799. n -= 1
  1800. }
  1801. for in 0..<n {
  1802. io.write_byte(fi.writer, '0', &fi.n)
  1803. }
  1804. io.write_i64(fi.writer, i, 10, &fi.n)
  1805. }
  1806. // Built-in Custom Formatters for core library types
  1807. switch a in v {
  1808. case runtime.Source_Code_Location:
  1809. io.write_string(fi.writer, a.file_path, &fi.n)
  1810. io.write_byte(fi.writer, '(', &fi.n)
  1811. io.write_int(fi.writer, int(a.line), 10, &fi.n)
  1812. io.write_byte(fi.writer, ':', &fi.n)
  1813. io.write_int(fi.writer, int(a.column), 10, &fi.n)
  1814. io.write_byte(fi.writer, ')', &fi.n)
  1815. return
  1816. case time.Duration:
  1817. ffrac :: proc(buf: []byte, v: u64, prec: int) -> (nw: int, nv: u64) {
  1818. v := v
  1819. w := len(buf)
  1820. print := false
  1821. for in 0..<prec {
  1822. digit := v % 10
  1823. print = print || digit != 0
  1824. if print {
  1825. w -= 1
  1826. buf[w] = byte(digit) + '0'
  1827. }
  1828. v /= 10
  1829. }
  1830. if print {
  1831. w -= 1
  1832. buf[w] = '.'
  1833. }
  1834. return w, v
  1835. }
  1836. fint :: proc(buf: []byte, v: u64) -> int {
  1837. v := v
  1838. w := len(buf)
  1839. if v == 0 {
  1840. w -= 1
  1841. buf[w] = '0'
  1842. } else {
  1843. for v > 0 {
  1844. w -= 1
  1845. buf[w] = byte(v%10) + '0'
  1846. v /= 10
  1847. }
  1848. }
  1849. return w
  1850. }
  1851. buf: [32]byte
  1852. w := len(buf)
  1853. u := u64(a)
  1854. neg := a < 0
  1855. if neg {
  1856. u = -u
  1857. }
  1858. if u < u64(time.Second) {
  1859. prec: int
  1860. w -= 1
  1861. buf[w] = 's'
  1862. w -= 1
  1863. switch {
  1864. case u == 0:
  1865. io.write_string(fi.writer, "0s", &fi.n)
  1866. return
  1867. case u < u64(time.Microsecond):
  1868. prec = 0
  1869. buf[w] = 'n'
  1870. case u < u64(time.Millisecond):
  1871. prec = 3
  1872. // U+00B5 'µ' micro sign == 0xC2 0xB5
  1873. w -= 1 // Need room for two bytes
  1874. copy(buf[w:], "µ")
  1875. case:
  1876. prec = 6
  1877. buf[w] = 'm'
  1878. }
  1879. w, u = ffrac(buf[:w], u, prec)
  1880. w = fint(buf[:w], u)
  1881. } else {
  1882. w -= 1
  1883. buf[w] = 's'
  1884. w, u = ffrac(buf[:w], u, 9)
  1885. w = fint(buf[:w], u%60)
  1886. u /= 60
  1887. if u > 0 {
  1888. w -= 1
  1889. buf[w] = 'm'
  1890. w = fint(buf[:w], u%60)
  1891. u /= 60
  1892. if u > 0 {
  1893. w -= 1
  1894. buf[w] = 'h'
  1895. w = fint(buf[:w], u)
  1896. }
  1897. }
  1898. }
  1899. if neg {
  1900. w -= 1
  1901. buf[w] = '-'
  1902. }
  1903. io.write_string(fi.writer, string(buf[w:]), &fi.n)
  1904. return
  1905. case time.Time:
  1906. t := a
  1907. y, mon, d := time.date(t)
  1908. h, min, s := time.clock(t)
  1909. ns := (t._nsec - (t._nsec/1e9 + time.UNIX_TO_ABSOLUTE)*1e9) % 1e9
  1910. write_padded_number(fi, i64(y), 4)
  1911. io.write_byte(fi.writer, '-', &fi.n)
  1912. write_padded_number(fi, i64(mon), 2)
  1913. io.write_byte(fi.writer, '-', &fi.n)
  1914. write_padded_number(fi, i64(d), 2)
  1915. io.write_byte(fi.writer, ' ', &fi.n)
  1916. write_padded_number(fi, i64(h), 2)
  1917. io.write_byte(fi.writer, ':', &fi.n)
  1918. write_padded_number(fi, i64(min), 2)
  1919. io.write_byte(fi.writer, ':', &fi.n)
  1920. write_padded_number(fi, i64(s), 2)
  1921. io.write_byte(fi.writer, '.', &fi.n)
  1922. write_padded_number(fi, (ns), 9)
  1923. io.write_string(fi.writer, " +0000 UTC", &fi.n)
  1924. return
  1925. }
  1926. #partial switch b in info.base.variant {
  1927. case runtime.Type_Info_Struct:
  1928. fmt_struct(fi, v, verb, b, info.name)
  1929. case runtime.Type_Info_Bit_Set:
  1930. fmt_bit_set(fi, v)
  1931. case:
  1932. fmt_value(fi, any{v.data, info.base.id}, verb)
  1933. }
  1934. }
  1935. // Formats a union type into a string representation
  1936. //
  1937. // Inputs:
  1938. // - fi: Pointer to the formatting Info struct.
  1939. // - v: The value to format.
  1940. // - verb: The formatting verb.
  1941. // - info: The union type information.
  1942. // - type_size: The size of the union type.
  1943. //
  1944. fmt_union :: proc(fi: ^Info, v: any, verb: rune, info: runtime.Type_Info_Union, type_size: int) {
  1945. if type_size == 0 {
  1946. io.write_string(fi.writer, "nil", &fi.n)
  1947. return
  1948. }
  1949. if reflect.type_info_union_is_pure_maybe(info) {
  1950. if v.data == nil {
  1951. io.write_string(fi.writer, "nil", &fi.n)
  1952. } else {
  1953. id := info.variants[0].id
  1954. fmt_arg(fi, any{v.data, id}, verb)
  1955. }
  1956. return
  1957. }
  1958. tag: i64 = -1
  1959. tag_ptr := uintptr(v.data) + info.tag_offset
  1960. tag_any := any{rawptr(tag_ptr), info.tag_type.id}
  1961. switch i in tag_any {
  1962. case u8: tag = i64(i)
  1963. case i8: tag = i64(i)
  1964. case u16: tag = i64(i)
  1965. case i16: tag = i64(i)
  1966. case u32: tag = i64(i)
  1967. case i32: tag = i64(i)
  1968. case u64: tag = i64(i)
  1969. case i64: tag = i
  1970. case: panic("Invalid union tag type")
  1971. }
  1972. assert(tag >= 0)
  1973. if v.data == nil {
  1974. io.write_string(fi.writer, "nil", &fi.n)
  1975. } else if info.no_nil {
  1976. id := info.variants[tag].id
  1977. fmt_arg(fi, any{v.data, id}, verb)
  1978. } else if tag == 0 {
  1979. io.write_string(fi.writer, "nil", &fi.n)
  1980. } else {
  1981. id := info.variants[tag-1].id
  1982. fmt_arg(fi, any{v.data, id}, verb)
  1983. }
  1984. }
  1985. // Formats a matrix as a string
  1986. //
  1987. // Inputs:
  1988. // - fi: A pointer to an Info struct containing formatting information.
  1989. // - v: The matrix value to be formatted.
  1990. // - verb: The formatting verb rune.
  1991. // - info: A runtime.Type_Info_Matrix struct containing matrix type information.
  1992. //
  1993. fmt_matrix :: proc(fi: ^Info, v: any, verb: rune, info: runtime.Type_Info_Matrix) {
  1994. io.write_string(fi.writer, "matrix[", &fi.n)
  1995. defer io.write_byte(fi.writer, ']', &fi.n)
  1996. fi.indent += 1
  1997. if fi.hash {
  1998. // Printed as it is written
  1999. io.write_byte(fi.writer, '\n', &fi.n)
  2000. for row in 0..<info.row_count {
  2001. fmt_write_indent(fi)
  2002. for col in 0..<info.column_count {
  2003. if col > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2004. offset := (row + col*info.elem_stride)*info.elem_size
  2005. data := uintptr(v.data) + uintptr(offset)
  2006. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2007. }
  2008. io.write_string(fi.writer, ",\n", &fi.n)
  2009. }
  2010. } else {
  2011. // Printed in Row-Major layout to match text layout
  2012. for row in 0..<info.row_count {
  2013. if row > 0 { io.write_string(fi.writer, "; ", &fi.n) }
  2014. for col in 0..<info.column_count {
  2015. if col > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2016. offset := (row + col*info.elem_stride)*info.elem_size
  2017. data := uintptr(v.data) + uintptr(offset)
  2018. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2019. }
  2020. }
  2021. }
  2022. fi.indent -= 1
  2023. if fi.hash {
  2024. fmt_write_indent(fi)
  2025. }
  2026. }
  2027. // Formats a value based on its type and formatting verb
  2028. //
  2029. // Inputs:
  2030. // - fi: A pointer to an Info struct containing formatting information.
  2031. // - v: The value to be formatted.
  2032. // - verb: The formatting verb rune.
  2033. //
  2034. // NOTE: Uses user formatters if available and not ignored.
  2035. //
  2036. fmt_value :: proc(fi: ^Info, v: any, verb: rune) {
  2037. if v.data == nil || v.id == nil {
  2038. io.write_string(fi.writer, "<nil>", &fi.n)
  2039. return
  2040. }
  2041. if _user_formatters != nil && !fi.ignore_user_formatters {
  2042. formatter := _user_formatters[v.id]
  2043. if formatter != nil {
  2044. fi.ignore_user_formatters = false
  2045. if ok := formatter(fi, v, verb); !ok {
  2046. fi.ignore_user_formatters = true
  2047. fmt_bad_verb(fi, verb)
  2048. }
  2049. return
  2050. }
  2051. }
  2052. fi.ignore_user_formatters = false
  2053. type_info := type_info_of(v.id)
  2054. switch info in type_info.variant {
  2055. case runtime.Type_Info_Any: // Ignore
  2056. case runtime.Type_Info_Parameters: // Ignore
  2057. case runtime.Type_Info_Named:
  2058. fmt_named(fi, v, verb, info)
  2059. case runtime.Type_Info_Boolean: fmt_arg(fi, v, verb)
  2060. case runtime.Type_Info_Integer: fmt_arg(fi, v, verb)
  2061. case runtime.Type_Info_Rune: fmt_arg(fi, v, verb)
  2062. case runtime.Type_Info_Float: fmt_arg(fi, v, verb)
  2063. case runtime.Type_Info_Complex: fmt_arg(fi, v, verb)
  2064. case runtime.Type_Info_Quaternion: fmt_arg(fi, v, verb)
  2065. case runtime.Type_Info_String: fmt_arg(fi, v, verb)
  2066. case runtime.Type_Info_Pointer:
  2067. if v.id == typeid_of(^runtime.Type_Info) {
  2068. reflect.write_type(fi.writer, (^^runtime.Type_Info)(v.data)^, &fi.n)
  2069. } else {
  2070. ptr := (^rawptr)(v.data)^
  2071. if verb != 'p' && info.elem != nil {
  2072. a := any{ptr, info.elem.id}
  2073. elem := runtime.type_info_base(info.elem)
  2074. if elem != nil {
  2075. #partial switch e in elem.variant {
  2076. case runtime.Type_Info_Array,
  2077. runtime.Type_Info_Slice,
  2078. runtime.Type_Info_Dynamic_Array,
  2079. runtime.Type_Info_Map:
  2080. if ptr == nil {
  2081. io.write_string(fi.writer, "<nil>", &fi.n)
  2082. return
  2083. }
  2084. if fi.indirection_level < 1 {
  2085. fi.indirection_level += 1
  2086. defer fi.indirection_level -= 1
  2087. io.write_byte(fi.writer, '&')
  2088. fmt_value(fi, a, verb)
  2089. return
  2090. }
  2091. case runtime.Type_Info_Struct,
  2092. runtime.Type_Info_Union:
  2093. if ptr == nil {
  2094. io.write_string(fi.writer, "<nil>", &fi.n)
  2095. return
  2096. }
  2097. if fi.indirection_level < 1 {
  2098. fi.indirection_level += 1
  2099. defer fi.indirection_level -= 1
  2100. io.write_byte(fi.writer, '&', &fi.n)
  2101. fmt_value(fi, a, verb)
  2102. return
  2103. }
  2104. }
  2105. }
  2106. }
  2107. fmt_pointer(fi, ptr, verb)
  2108. }
  2109. case runtime.Type_Info_Soa_Pointer:
  2110. ptr := (^runtime.Raw_Soa_Pointer)(v.data)^
  2111. fmt_soa_pointer(fi, ptr, verb)
  2112. case runtime.Type_Info_Multi_Pointer:
  2113. ptr := (^rawptr)(v.data)^
  2114. if ptr == nil {
  2115. io.write_string(fi.writer, "<nil>", &fi.n)
  2116. return
  2117. }
  2118. if verb != 'p' && info.elem != nil {
  2119. a := any{ptr, info.elem.id}
  2120. elem := runtime.type_info_base(info.elem)
  2121. if elem != nil {
  2122. if n, ok := fi.optional_len.?; ok {
  2123. fmt_array(fi, ptr, n, elem.size, elem, verb)
  2124. return
  2125. } else if fi.use_nul_termination {
  2126. fmt_array_nul_terminated(fi, ptr, -1, elem.size, elem, verb)
  2127. return
  2128. }
  2129. #partial switch e in elem.variant {
  2130. case runtime.Type_Info_Integer:
  2131. switch verb {
  2132. case 's', 'q':
  2133. switch elem.id {
  2134. case u8:
  2135. fmt_cstring(fi, cstring(ptr), verb)
  2136. return
  2137. case u16, u32, rune:
  2138. n := search_nul_termination(ptr, elem.size, -1)
  2139. fmt_array(fi, ptr, n, elem.size, elem, verb)
  2140. return
  2141. }
  2142. }
  2143. case runtime.Type_Info_Array,
  2144. runtime.Type_Info_Slice,
  2145. runtime.Type_Info_Dynamic_Array,
  2146. runtime.Type_Info_Map:
  2147. if fi.indirection_level < 1 {
  2148. fi.indirection_level += 1
  2149. defer fi.indirection_level -= 1
  2150. io.write_byte(fi.writer, '&', &fi.n)
  2151. fmt_value(fi, a, verb)
  2152. return
  2153. }
  2154. case runtime.Type_Info_Struct,
  2155. runtime.Type_Info_Union:
  2156. if fi.indirection_level < 1 {
  2157. fi.indirection_level += 1
  2158. defer fi.indirection_level -= 1
  2159. io.write_byte(fi.writer, '&', &fi.n)
  2160. fmt_value(fi, a, verb)
  2161. return
  2162. }
  2163. }
  2164. }
  2165. }
  2166. fmt_pointer(fi, ptr, verb)
  2167. case runtime.Type_Info_Enumerated_Array:
  2168. fi.record_level += 1
  2169. defer fi.record_level -= 1
  2170. if fi.hash {
  2171. io.write_string(fi.writer, "[\n", &fi.n)
  2172. defer {
  2173. io.write_byte(fi.writer, '\n', &fi.n)
  2174. fmt_write_indent(fi)
  2175. io.write_byte(fi.writer, ']', &fi.n)
  2176. }
  2177. indent := fi.indent
  2178. fi.indent += 1
  2179. defer fi.indent = indent
  2180. for i in 0..<info.count {
  2181. fmt_write_indent(fi)
  2182. idx, ok := stored_enum_value_to_string(info.index, info.min_value, i)
  2183. if ok {
  2184. io.write_byte(fi.writer, '.', &fi.n)
  2185. io.write_string(fi.writer, idx, &fi.n)
  2186. } else {
  2187. io.write_i64(fi.writer, i64(info.min_value)+i64(i), 10, &fi.n)
  2188. }
  2189. io.write_string(fi.writer, " = ", &fi.n)
  2190. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2191. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2192. io.write_string(fi.writer, ",\n", &fi.n)
  2193. }
  2194. } else {
  2195. io.write_byte(fi.writer, '[', &fi.n)
  2196. defer io.write_byte(fi.writer, ']', &fi.n)
  2197. for i in 0..<info.count {
  2198. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2199. idx, ok := stored_enum_value_to_string(info.index, info.min_value, i)
  2200. if ok {
  2201. io.write_byte(fi.writer, '.', &fi.n)
  2202. io.write_string(fi.writer, idx, &fi.n)
  2203. } else {
  2204. io.write_i64(fi.writer, i64(info.min_value)+i64(i), 10, &fi.n)
  2205. }
  2206. io.write_string(fi.writer, " = ", &fi.n)
  2207. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2208. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2209. }
  2210. }
  2211. case runtime.Type_Info_Array:
  2212. n := info.count
  2213. ptr := v.data
  2214. if ol, ok := fi.optional_len.?; ok {
  2215. n = min(n, ol)
  2216. } else if fi.use_nul_termination {
  2217. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2218. return
  2219. }
  2220. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2221. case runtime.Type_Info_Slice:
  2222. slice := cast(^mem.Raw_Slice)v.data
  2223. n := slice.len
  2224. ptr := slice.data
  2225. if ol, ok := fi.optional_len.?; ok {
  2226. n = min(n, ol)
  2227. } else if fi.use_nul_termination {
  2228. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2229. return
  2230. }
  2231. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2232. case runtime.Type_Info_Dynamic_Array:
  2233. array := cast(^mem.Raw_Dynamic_Array)v.data
  2234. n := array.len
  2235. ptr := array.data
  2236. if ol, ok := fi.optional_len.?; ok {
  2237. n = min(n, ol)
  2238. } else if fi.use_nul_termination {
  2239. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2240. return
  2241. }
  2242. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2243. case runtime.Type_Info_Simd_Vector:
  2244. io.write_byte(fi.writer, '<', &fi.n)
  2245. defer io.write_byte(fi.writer, '>', &fi.n)
  2246. for i in 0..<info.count {
  2247. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2248. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2249. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2250. }
  2251. case runtime.Type_Info_Map:
  2252. if verb != 'v' {
  2253. fmt_bad_verb(fi, verb)
  2254. return
  2255. }
  2256. io.write_string(fi.writer, "map[", &fi.n)
  2257. defer io.write_byte(fi.writer, ']', &fi.n)
  2258. fi.record_level += 1
  2259. defer fi.record_level -= 1
  2260. m := (^mem.Raw_Map)(v.data)
  2261. if m != nil {
  2262. if info.map_info == nil {
  2263. return
  2264. }
  2265. map_cap := uintptr(runtime.map_cap(m^))
  2266. ks, vs, hs, _, _ := runtime.map_kvh_data_dynamic(m^, info.map_info)
  2267. j := 0
  2268. for bucket_index in 0..<map_cap {
  2269. if !runtime.map_hash_is_valid(hs[bucket_index]) {
  2270. continue
  2271. }
  2272. if j > 0 {
  2273. io.write_string(fi.writer, ", ", &fi.n)
  2274. }
  2275. j += 1
  2276. key := runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index)
  2277. value := runtime.map_cell_index_dynamic(vs, info.map_info.vs, bucket_index)
  2278. fmt_arg(&Info{writer = fi.writer}, any{rawptr(key), info.key.id}, 'v')
  2279. io.write_string(fi.writer, "=", &fi.n)
  2280. fmt_arg(fi, any{rawptr(value), info.value.id}, 'v')
  2281. }
  2282. }
  2283. case runtime.Type_Info_Struct:
  2284. fmt_struct(fi, v, verb, info, "")
  2285. case runtime.Type_Info_Union:
  2286. fmt_union(fi, v, verb, info, type_info.size)
  2287. case runtime.Type_Info_Enum:
  2288. fmt_enum(fi, v, verb)
  2289. case runtime.Type_Info_Procedure:
  2290. ptr := (^rawptr)(v.data)^
  2291. if ptr == nil {
  2292. io.write_string(fi.writer, "nil", &fi.n)
  2293. } else {
  2294. reflect.write_typeid(fi.writer, v.id, &fi.n)
  2295. io.write_string(fi.writer, " @ ", &fi.n)
  2296. fmt_pointer(fi, ptr, 'p')
  2297. }
  2298. case runtime.Type_Info_Type_Id:
  2299. id := (^typeid)(v.data)^
  2300. reflect.write_typeid(fi.writer, id, &fi.n)
  2301. case runtime.Type_Info_Bit_Set:
  2302. fmt_bit_set(fi, v)
  2303. case runtime.Type_Info_Relative_Pointer:
  2304. ptr := reflect.relative_pointer_to_absolute_raw(v.data, info.base_integer.id)
  2305. absolute_ptr := any{ptr, info.pointer.id}
  2306. fmt_value(fi, absolute_ptr, verb)
  2307. case runtime.Type_Info_Relative_Slice:
  2308. ptr := reflect.relative_pointer_to_absolute_raw(v.data, info.base_integer.id)
  2309. if verb == 'p' {
  2310. fmt_pointer(fi, ptr, 'p')
  2311. } else if ptr == nil {
  2312. io.write_string(fi.writer, "[]", &fi.n)
  2313. } else {
  2314. len_ptr := uintptr(v.data) + uintptr(info.base_integer.size)
  2315. len_any := any{rawptr(len_ptr), info.base_integer.id}
  2316. len, _ := reflect.as_int(len_any)
  2317. slice_type := reflect.type_info_base(info.slice).variant.(runtime.Type_Info_Slice)
  2318. fi.record_level += 1
  2319. defer fi.record_level -= 1
  2320. io.write_byte(fi.writer, '[', &fi.n)
  2321. defer io.write_byte(fi.writer, ']', &fi.n)
  2322. for i in 0..<len {
  2323. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2324. data := uintptr(ptr) + uintptr(i*slice_type.elem_size)
  2325. fmt_arg(fi, any{rawptr(data), slice_type.elem.id}, verb)
  2326. }
  2327. }
  2328. case runtime.Type_Info_Matrix:
  2329. fmt_matrix(fi, v, verb, info)
  2330. }
  2331. }
  2332. // Formats a complex number based on the given formatting verb
  2333. //
  2334. // Inputs:
  2335. // - fi: A pointer to an Info struct containing formatting information.
  2336. // - c: The complex128 value to be formatted.
  2337. // - bits: The number of bits in the complex number (32 or 64).
  2338. // - verb: The formatting verb rune ('f', 'F', 'v', 'h', 'H').
  2339. //
  2340. fmt_complex :: proc(fi: ^Info, c: complex128, bits: int, verb: rune) {
  2341. switch verb {
  2342. case 'f', 'F', 'v', 'h', 'H':
  2343. r, i := real(c), imag(c)
  2344. fmt_float(fi, r, bits/2, verb)
  2345. if !fi.plus && i >= 0 {
  2346. io.write_rune(fi.writer, '+', &fi.n)
  2347. }
  2348. fmt_float(fi, i, bits/2, verb)
  2349. io.write_rune(fi.writer, 'i', &fi.n)
  2350. case:
  2351. fmt_bad_verb(fi, verb)
  2352. return
  2353. }
  2354. }
  2355. // Formats a quaternion number based on the given formatting verb
  2356. //
  2357. // Inputs:
  2358. // - fi: A pointer to an Info struct containing formatting information.
  2359. // - q: The quaternion256 value to be formatted.
  2360. // - bits: The number of bits in the quaternion number (64, 128, or 256).
  2361. // - verb: The formatting verb rune ('f', 'F', 'v', 'h', 'H').
  2362. //
  2363. fmt_quaternion :: proc(fi: ^Info, q: quaternion256, bits: int, verb: rune) {
  2364. switch verb {
  2365. case 'f', 'F', 'v', 'h', 'H':
  2366. r, i, j, k := real(q), imag(q), jmag(q), kmag(q)
  2367. fmt_float(fi, r, bits/4, verb)
  2368. if !fi.plus && i >= 0 {
  2369. io.write_rune(fi.writer, '+', &fi.n)
  2370. }
  2371. fmt_float(fi, i, bits/4, verb)
  2372. io.write_rune(fi.writer, 'i', &fi.n)
  2373. if !fi.plus && j >= 0 {
  2374. io.write_rune(fi.writer, '+', &fi.n)
  2375. }
  2376. fmt_float(fi, j, bits/4, verb)
  2377. io.write_rune(fi.writer, 'j', &fi.n)
  2378. if !fi.plus && k >= 0 {
  2379. io.write_rune(fi.writer, '+', &fi.n)
  2380. }
  2381. fmt_float(fi, k, bits/4, verb)
  2382. io.write_rune(fi.writer, 'k', &fi.n)
  2383. case:
  2384. fmt_bad_verb(fi, verb)
  2385. return
  2386. }
  2387. }
  2388. // Formats an argument based on its type and the given formatting verb
  2389. //
  2390. // Inputs:
  2391. // - fi: A pointer to an Info struct containing formatting information.
  2392. // - arg: The value to be formatted.
  2393. // - verb: The formatting verb rune (e.g. 'T').
  2394. //
  2395. // NOTE: Uses user formatters if available and not ignored.
  2396. //
  2397. fmt_arg :: proc(fi: ^Info, arg: any, verb: rune) {
  2398. if arg == nil {
  2399. io.write_string(fi.writer, "<nil>")
  2400. return
  2401. }
  2402. fi.arg = arg
  2403. if verb == 'T' {
  2404. ti := type_info_of(arg.id)
  2405. switch a in arg {
  2406. case ^runtime.Type_Info: ti = a
  2407. }
  2408. reflect.write_type(fi.writer, ti, &fi.n)
  2409. return
  2410. }
  2411. if _user_formatters != nil {
  2412. formatter := _user_formatters[arg.id]
  2413. if formatter != nil {
  2414. if ok := formatter(fi, arg, verb); !ok {
  2415. fmt_bad_verb(fi, verb)
  2416. }
  2417. return
  2418. }
  2419. }
  2420. custom_types: switch a in arg {
  2421. case runtime.Source_Code_Location:
  2422. if fi.hash && verb == 'v' {
  2423. io.write_string(fi.writer, a.file_path, &fi.n)
  2424. io.write_byte(fi.writer, '(', &fi.n)
  2425. io.write_i64(fi.writer, i64(a.line), 10, &fi.n)
  2426. io.write_byte(fi.writer, ':', &fi.n)
  2427. io.write_i64(fi.writer, i64(a.column), 10, &fi.n)
  2428. io.write_byte(fi.writer, ')', &fi.n)
  2429. return
  2430. }
  2431. }
  2432. base_arg := arg
  2433. base_arg.id = runtime.typeid_base(base_arg.id)
  2434. switch a in base_arg {
  2435. case bool: fmt_bool(fi, a, verb)
  2436. case b8: fmt_bool(fi, bool(a), verb)
  2437. case b16: fmt_bool(fi, bool(a), verb)
  2438. case b32: fmt_bool(fi, bool(a), verb)
  2439. case b64: fmt_bool(fi, bool(a), verb)
  2440. case any: fmt_arg(fi, a, verb)
  2441. case rune: fmt_rune(fi, a, verb)
  2442. case f16: fmt_float(fi, f64(a), 16, verb)
  2443. case f32: fmt_float(fi, f64(a), 32, verb)
  2444. case f64: fmt_float(fi, a, 64, verb)
  2445. case f16le: fmt_float(fi, f64(a), 16, verb)
  2446. case f32le: fmt_float(fi, f64(a), 32, verb)
  2447. case f64le: fmt_float(fi, f64(a), 64, verb)
  2448. case f16be: fmt_float(fi, f64(a), 16, verb)
  2449. case f32be: fmt_float(fi, f64(a), 32, verb)
  2450. case f64be: fmt_float(fi, f64(a), 64, verb)
  2451. case complex32: fmt_complex(fi, complex128(a), 32, verb)
  2452. case complex64: fmt_complex(fi, complex128(a), 64, verb)
  2453. case complex128: fmt_complex(fi, a, 128, verb)
  2454. case quaternion64: fmt_quaternion(fi, quaternion256(a), 64, verb)
  2455. case quaternion128: fmt_quaternion(fi, quaternion256(a), 128, verb)
  2456. case quaternion256: fmt_quaternion(fi, a, 256, verb)
  2457. case i8: fmt_int(fi, u64(a), true, 8, verb)
  2458. case u8: fmt_int(fi, u64(a), false, 8, verb)
  2459. case i16: fmt_int(fi, u64(a), true, 16, verb)
  2460. case u16: fmt_int(fi, u64(a), false, 16, verb)
  2461. case i32: fmt_int(fi, u64(a), true, 32, verb)
  2462. case u32: fmt_int(fi, u64(a), false, 32, verb)
  2463. case i64: fmt_int(fi, u64(a), true, 64, verb)
  2464. case u64: fmt_int(fi, a, false, 64, verb)
  2465. case int: fmt_int(fi, u64(a), true, 8*size_of(int), verb)
  2466. case uint: fmt_int(fi, u64(a), false, 8*size_of(uint), verb)
  2467. case uintptr: fmt_int(fi, u64(a), false, 8*size_of(uintptr), verb)
  2468. case string: fmt_string(fi, a, verb)
  2469. case cstring: fmt_cstring(fi, a, verb)
  2470. case typeid: reflect.write_typeid(fi.writer, a, &fi.n)
  2471. case i16le: fmt_int(fi, u64(a), true, 16, verb)
  2472. case u16le: fmt_int(fi, u64(a), false, 16, verb)
  2473. case i32le: fmt_int(fi, u64(a), true, 32, verb)
  2474. case u32le: fmt_int(fi, u64(a), false, 32, verb)
  2475. case i64le: fmt_int(fi, u64(a), true, 64, verb)
  2476. case u64le: fmt_int(fi, u64(a), false, 64, verb)
  2477. case i16be: fmt_int(fi, u64(a), true, 16, verb)
  2478. case u16be: fmt_int(fi, u64(a), false, 16, verb)
  2479. case i32be: fmt_int(fi, u64(a), true, 32, verb)
  2480. case u32be: fmt_int(fi, u64(a), false, 32, verb)
  2481. case i64be: fmt_int(fi, u64(a), true, 64, verb)
  2482. case u64be: fmt_int(fi, u64(a), false, 64, verb)
  2483. case i128: fmt_int_128(fi, u128(a), true, 128, verb)
  2484. case u128: fmt_int_128(fi, a, false, 128, verb)
  2485. case i128le: fmt_int_128(fi, u128(a), true, 128, verb)
  2486. case u128le: fmt_int_128(fi, u128(a), false, 128, verb)
  2487. case i128be: fmt_int_128(fi, u128(a), true, 128, verb)
  2488. case u128be: fmt_int_128(fi, u128(a), false, 128, verb)
  2489. case: fmt_value(fi, arg, verb)
  2490. }
  2491. }