fmt.odin 88 KB

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