fmt.odin 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216
  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. if ptr == nil {
  2497. io.write_string(fi.writer, "<nil>", &fi.n)
  2498. return
  2499. }
  2500. if fi.indirection_level < 1 {
  2501. fi.indirection_level += 1
  2502. defer fi.indirection_level -= 1
  2503. io.write_byte(fi.writer, '&', &fi.n)
  2504. fmt_value(fi, a, verb)
  2505. return
  2506. }
  2507. }
  2508. }
  2509. }
  2510. fmt_pointer(fi, ptr, verb)
  2511. }
  2512. case runtime.Type_Info_Soa_Pointer:
  2513. ptr := (^runtime.Raw_Soa_Pointer)(v.data)^
  2514. fmt_soa_pointer(fi, ptr, verb)
  2515. case runtime.Type_Info_Multi_Pointer:
  2516. ptr := (^rawptr)(v.data)^
  2517. if ptr == nil {
  2518. io.write_string(fi.writer, "<nil>", &fi.n)
  2519. return
  2520. }
  2521. if verb != 'p' && info.elem != nil {
  2522. a := any{ptr, info.elem.id}
  2523. elem := runtime.type_info_base(info.elem)
  2524. if elem != nil {
  2525. if n, ok := fi.optional_len.?; ok {
  2526. fi.optional_len = nil
  2527. fmt_array(fi, ptr, n, elem.size, elem, verb)
  2528. return
  2529. } else if fi.use_nul_termination {
  2530. fi.use_nul_termination = false
  2531. fmt_array_nul_terminated(fi, ptr, -1, elem.size, elem, verb)
  2532. return
  2533. }
  2534. #partial switch e in elem.variant {
  2535. case runtime.Type_Info_Integer:
  2536. switch verb {
  2537. case 's', 'q':
  2538. switch elem.id {
  2539. case u8:
  2540. fmt_cstring(fi, cstring(ptr), verb)
  2541. return
  2542. case u16, u32, rune:
  2543. n := search_nul_termination(ptr, elem.size, -1)
  2544. fmt_array(fi, ptr, n, elem.size, elem, verb)
  2545. return
  2546. }
  2547. }
  2548. case runtime.Type_Info_Array,
  2549. runtime.Type_Info_Slice,
  2550. runtime.Type_Info_Dynamic_Array,
  2551. runtime.Type_Info_Map:
  2552. if fi.indirection_level < 1 {
  2553. fi.indirection_level += 1
  2554. defer fi.indirection_level -= 1
  2555. io.write_byte(fi.writer, '&', &fi.n)
  2556. fmt_value(fi, a, verb)
  2557. return
  2558. }
  2559. case runtime.Type_Info_Struct,
  2560. runtime.Type_Info_Union:
  2561. if fi.indirection_level < 1 {
  2562. fi.indirection_level += 1
  2563. defer fi.indirection_level -= 1
  2564. io.write_byte(fi.writer, '&', &fi.n)
  2565. fmt_value(fi, a, verb)
  2566. return
  2567. }
  2568. }
  2569. }
  2570. }
  2571. fmt_pointer(fi, ptr, verb)
  2572. case runtime.Type_Info_Enumerated_Array:
  2573. fi.record_level += 1
  2574. defer fi.record_level -= 1
  2575. if fi.hash {
  2576. io.write_byte(fi.writer, '[' if verb != 'w' else '{', &fi.n)
  2577. io.write_byte(fi.writer, '\n', &fi.n)
  2578. defer {
  2579. fmt_write_indent(fi)
  2580. io.write_byte(fi.writer, ']' if verb != 'w' else '}', &fi.n)
  2581. }
  2582. indent := fi.indent
  2583. fi.indent += 1
  2584. defer fi.indent = indent
  2585. for i in 0..<info.count {
  2586. fmt_write_indent(fi)
  2587. idx, ok := stored_enum_value_to_string(info.index, info.min_value, i)
  2588. if ok {
  2589. io.write_byte(fi.writer, '.', &fi.n)
  2590. io.write_string(fi.writer, idx, &fi.n)
  2591. } else {
  2592. io.write_i64(fi.writer, i64(info.min_value)+i64(i), 10, &fi.n)
  2593. }
  2594. io.write_string(fi.writer, " = ", &fi.n)
  2595. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2596. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2597. io.write_string(fi.writer, ",\n", &fi.n)
  2598. }
  2599. } else {
  2600. io.write_byte(fi.writer, '[' if verb != 'w' else '{', &fi.n)
  2601. defer io.write_byte(fi.writer, ']' if verb != 'w' else '}', &fi.n)
  2602. for i in 0..<info.count {
  2603. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2604. idx, ok := stored_enum_value_to_string(info.index, info.min_value, i)
  2605. if ok {
  2606. io.write_byte(fi.writer, '.', &fi.n)
  2607. io.write_string(fi.writer, idx, &fi.n)
  2608. } else {
  2609. io.write_i64(fi.writer, i64(info.min_value)+i64(i), 10, &fi.n)
  2610. }
  2611. io.write_string(fi.writer, " = ", &fi.n)
  2612. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2613. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2614. }
  2615. }
  2616. case runtime.Type_Info_Array:
  2617. n := info.count
  2618. ptr := v.data
  2619. if ol, ok := fi.optional_len.?; ok {
  2620. fi.optional_len = nil
  2621. n = min(n, ol)
  2622. } else if fi.use_nul_termination {
  2623. fi.use_nul_termination = false
  2624. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2625. return
  2626. }
  2627. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2628. case runtime.Type_Info_Slice:
  2629. slice := cast(^mem.Raw_Slice)v.data
  2630. n := slice.len
  2631. ptr := slice.data
  2632. if ol, ok := fi.optional_len.?; ok {
  2633. fi.optional_len = nil
  2634. n = min(n, ol)
  2635. } else if fi.use_nul_termination {
  2636. fi.use_nul_termination = false
  2637. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2638. return
  2639. }
  2640. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2641. case runtime.Type_Info_Dynamic_Array:
  2642. array := cast(^mem.Raw_Dynamic_Array)v.data
  2643. n := array.len
  2644. ptr := array.data
  2645. if ol, ok := fi.optional_len.?; ok {
  2646. fi.optional_len = nil
  2647. n = min(n, ol)
  2648. } else if fi.use_nul_termination {
  2649. fi.use_nul_termination = false
  2650. fmt_array_nul_terminated(fi, ptr, n, info.elem_size, info.elem, verb)
  2651. return
  2652. }
  2653. fmt_array(fi, ptr, n, info.elem_size, info.elem, verb)
  2654. case runtime.Type_Info_Simd_Vector:
  2655. io.write_byte(fi.writer, '<', &fi.n)
  2656. defer io.write_byte(fi.writer, '>', &fi.n)
  2657. for i in 0..<info.count {
  2658. if i > 0 { io.write_string(fi.writer, ", ", &fi.n) }
  2659. data := uintptr(v.data) + uintptr(i*info.elem_size)
  2660. fmt_arg(fi, any{rawptr(data), info.elem.id}, verb)
  2661. }
  2662. case runtime.Type_Info_Map:
  2663. switch verb {
  2664. case:
  2665. fmt_bad_verb(fi, verb)
  2666. case 'v', 'w':
  2667. if verb == 'v' {
  2668. io.write_string(fi.writer, "map", &fi.n)
  2669. }
  2670. io.write_byte(fi.writer, '[' if verb != 'w' else '{', &fi.n)
  2671. defer io.write_byte(fi.writer, ']' if verb != 'w' else '}', &fi.n)
  2672. hash := fi.hash; defer fi.hash = hash
  2673. indent := fi.indent; defer fi.indent -= 1
  2674. do_trailing_comma := hash
  2675. fi.indent += 1
  2676. if hash {
  2677. io.write_byte(fi.writer, '\n', &fi.n)
  2678. }
  2679. defer {
  2680. if hash {
  2681. for _ in 0..<indent { io.write_byte(fi.writer, '\t', &fi.n) }
  2682. }
  2683. }
  2684. m := (^mem.Raw_Map)(v.data)
  2685. if m != nil {
  2686. if info.map_info == nil {
  2687. return
  2688. }
  2689. map_cap := uintptr(runtime.map_cap(m^))
  2690. ks, vs, hs, _, _ := runtime.map_kvh_data_dynamic(m^, info.map_info)
  2691. j := 0
  2692. for bucket_index in 0..<map_cap {
  2693. runtime.map_hash_is_valid(hs[bucket_index]) or_continue
  2694. if !do_trailing_comma && j > 0 { io.write_string(fi.writer, ", ") }
  2695. if hash {
  2696. fmt_write_indent(fi)
  2697. }
  2698. j += 1
  2699. key := runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index)
  2700. value := runtime.map_cell_index_dynamic(vs, info.map_info.vs, bucket_index)
  2701. fmt_arg(&Info{writer = fi.writer}, any{rawptr(key), info.key.id}, verb)
  2702. if hash {
  2703. io.write_string(fi.writer, " = ", &fi.n)
  2704. } else {
  2705. io.write_string(fi.writer, "=", &fi.n)
  2706. }
  2707. fmt_arg(fi, any{rawptr(value), info.value.id}, verb)
  2708. if do_trailing_comma { io.write_string(fi.writer, ",\n", &fi.n) }
  2709. }
  2710. }
  2711. }
  2712. case runtime.Type_Info_Struct:
  2713. fmt_struct(fi, v, verb, info, "")
  2714. case runtime.Type_Info_Union:
  2715. fmt_union(fi, v, verb, info, type_info.size)
  2716. case runtime.Type_Info_Enum:
  2717. fmt_enum(fi, v, verb)
  2718. case runtime.Type_Info_Procedure:
  2719. ptr := (^rawptr)(v.data)^
  2720. if ptr == nil {
  2721. io.write_string(fi.writer, "nil", &fi.n)
  2722. } else {
  2723. reflect.write_typeid(fi.writer, v.id, &fi.n)
  2724. io.write_string(fi.writer, " @ ", &fi.n)
  2725. fmt_pointer(fi, ptr, 'p')
  2726. }
  2727. case runtime.Type_Info_Type_Id:
  2728. id := (^typeid)(v.data)^
  2729. reflect.write_typeid(fi.writer, id, &fi.n)
  2730. case runtime.Type_Info_Bit_Set:
  2731. fmt_bit_set(fi, v, verb = verb)
  2732. case runtime.Type_Info_Relative_Pointer:
  2733. ptr := reflect.relative_pointer_to_absolute_raw(v.data, info.base_integer.id)
  2734. absolute_ptr := any{ptr, info.pointer.id}
  2735. fmt_value(fi, absolute_ptr, verb)
  2736. case runtime.Type_Info_Relative_Multi_Pointer:
  2737. ptr := reflect.relative_pointer_to_absolute_raw(v.data, info.base_integer.id)
  2738. absolute_ptr := any{ptr, info.pointer.id}
  2739. fmt_value(fi, absolute_ptr, verb)
  2740. case runtime.Type_Info_Matrix:
  2741. fmt_matrix(fi, v, verb, info)
  2742. case runtime.Type_Info_Bit_Field:
  2743. fmt_bit_field(fi, v, verb, info, "")
  2744. }
  2745. }
  2746. // This proc helps keep some of the code around whether or not to print an
  2747. // intermediate plus sign in complexes and quaternions more readable.
  2748. @(private)
  2749. _cq_should_print_intermediate_plus :: proc "contextless" (fi: ^Info, f: f64) -> bool {
  2750. if !fi.plus && f >= 0 {
  2751. #partial switch math.classify(f) {
  2752. case .Neg_Zero, .Inf:
  2753. // These two classes print their own signs.
  2754. return false
  2755. case:
  2756. return true
  2757. }
  2758. }
  2759. return false
  2760. }
  2761. // Formats a complex number based on the given formatting verb
  2762. //
  2763. // Inputs:
  2764. // - fi: A pointer to an Info struct containing formatting information.
  2765. // - c: The complex128 value to be formatted.
  2766. // - bits: The number of bits in the complex number (32 or 64).
  2767. // - verb: The formatting verb rune ('f', 'F', 'v', 'h', 'H', 'w').
  2768. //
  2769. fmt_complex :: proc(fi: ^Info, c: complex128, bits: int, verb: rune) {
  2770. switch verb {
  2771. case 'f', 'F', 'v', 'h', 'H', 'w':
  2772. r, i := real(c), imag(c)
  2773. fmt_float(fi, r, bits/2, verb)
  2774. if _cq_should_print_intermediate_plus(fi, i) {
  2775. io.write_rune(fi.writer, '+', &fi.n)
  2776. }
  2777. fmt_float(fi, i, bits/2, verb)
  2778. io.write_rune(fi.writer, 'i', &fi.n)
  2779. case:
  2780. fmt_bad_verb(fi, verb)
  2781. return
  2782. }
  2783. }
  2784. // Formats a quaternion number based on the given formatting verb
  2785. //
  2786. // Inputs:
  2787. // - fi: A pointer to an Info struct containing formatting information.
  2788. // - q: The quaternion256 value to be formatted.
  2789. // - bits: The number of bits in the quaternion number (64, 128, or 256).
  2790. // - verb: The formatting verb rune ('f', 'F', 'v', 'h', 'H', 'w').
  2791. //
  2792. fmt_quaternion :: proc(fi: ^Info, q: quaternion256, bits: int, verb: rune) {
  2793. switch verb {
  2794. case 'f', 'F', 'v', 'h', 'H', 'w':
  2795. r, i, j, k := real(q), imag(q), jmag(q), kmag(q)
  2796. fmt_float(fi, r, bits/4, verb)
  2797. if _cq_should_print_intermediate_plus(fi, i) {
  2798. io.write_rune(fi.writer, '+', &fi.n)
  2799. }
  2800. fmt_float(fi, i, bits/4, verb)
  2801. io.write_rune(fi.writer, 'i', &fi.n)
  2802. if _cq_should_print_intermediate_plus(fi, j) {
  2803. io.write_rune(fi.writer, '+', &fi.n)
  2804. }
  2805. fmt_float(fi, j, bits/4, verb)
  2806. io.write_rune(fi.writer, 'j', &fi.n)
  2807. if _cq_should_print_intermediate_plus(fi, k) {
  2808. io.write_rune(fi.writer, '+', &fi.n)
  2809. }
  2810. fmt_float(fi, k, bits/4, verb)
  2811. io.write_rune(fi.writer, 'k', &fi.n)
  2812. case:
  2813. fmt_bad_verb(fi, verb)
  2814. return
  2815. }
  2816. }
  2817. // Formats an argument based on its type and the given formatting verb
  2818. //
  2819. // Inputs:
  2820. // - fi: A pointer to an Info struct containing formatting information.
  2821. // - arg: The value to be formatted.
  2822. // - verb: The formatting verb rune (e.g. 'T').
  2823. //
  2824. // NOTE: Uses user formatters if available and not ignored.
  2825. //
  2826. fmt_arg :: proc(fi: ^Info, arg: any, verb: rune) {
  2827. if arg == nil {
  2828. io.write_string(fi.writer, "<nil>")
  2829. return
  2830. }
  2831. fi.arg = arg
  2832. if verb == 'T' {
  2833. ti := type_info_of(arg.id)
  2834. switch a in arg {
  2835. case ^runtime.Type_Info: ti = a
  2836. }
  2837. reflect.write_type(fi.writer, ti, &fi.n)
  2838. return
  2839. }
  2840. if _user_formatters != nil {
  2841. formatter := _user_formatters[arg.id]
  2842. if formatter != nil {
  2843. if ok := formatter(fi, arg, verb); !ok {
  2844. fmt_bad_verb(fi, verb)
  2845. }
  2846. return
  2847. }
  2848. }
  2849. arg_info := type_info_of(arg.id)
  2850. if info, ok := arg_info.variant.(runtime.Type_Info_Named); ok {
  2851. fmt_named(fi, arg, verb, info)
  2852. return
  2853. }
  2854. base_arg := arg
  2855. base_arg.id = runtime.typeid_base(base_arg.id)
  2856. switch a in base_arg {
  2857. case bool: fmt_bool(fi, a, verb)
  2858. case b8: fmt_bool(fi, bool(a), verb)
  2859. case b16: fmt_bool(fi, bool(a), verb)
  2860. case b32: fmt_bool(fi, bool(a), verb)
  2861. case b64: fmt_bool(fi, bool(a), verb)
  2862. case any: fmt_arg(fi, a, verb)
  2863. case rune: fmt_rune(fi, a, verb)
  2864. case f16: fmt_float(fi, f64(a), 16, verb)
  2865. case f32: fmt_float(fi, f64(a), 32, verb)
  2866. case f64: fmt_float(fi, a, 64, verb)
  2867. case f16le: fmt_float(fi, f64(a), 16, verb)
  2868. case f32le: fmt_float(fi, f64(a), 32, verb)
  2869. case f64le: fmt_float(fi, f64(a), 64, verb)
  2870. case f16be: fmt_float(fi, f64(a), 16, verb)
  2871. case f32be: fmt_float(fi, f64(a), 32, verb)
  2872. case f64be: fmt_float(fi, f64(a), 64, verb)
  2873. case complex32: fmt_complex(fi, complex128(a), 32, verb)
  2874. case complex64: fmt_complex(fi, complex128(a), 64, verb)
  2875. case complex128: fmt_complex(fi, a, 128, verb)
  2876. case quaternion64: fmt_quaternion(fi, quaternion256(a), 64, verb)
  2877. case quaternion128: fmt_quaternion(fi, quaternion256(a), 128, verb)
  2878. case quaternion256: fmt_quaternion(fi, a, 256, verb)
  2879. case i8: fmt_int(fi, u64(a), true, 8, verb)
  2880. case u8: fmt_int(fi, u64(a), false, 8, verb)
  2881. case i16: fmt_int(fi, u64(a), true, 16, verb)
  2882. case u16: fmt_int(fi, u64(a), false, 16, verb)
  2883. case i32: fmt_int(fi, u64(a), true, 32, verb)
  2884. case u32: fmt_int(fi, u64(a), false, 32, verb)
  2885. case i64: fmt_int(fi, u64(a), true, 64, verb)
  2886. case u64: fmt_int(fi, a, false, 64, verb)
  2887. case int: fmt_int(fi, u64(a), true, 8*size_of(int), verb)
  2888. case uint: fmt_int(fi, u64(a), false, 8*size_of(uint), verb)
  2889. case uintptr: fmt_int(fi, u64(a), false, 8*size_of(uintptr), verb)
  2890. case string: fmt_string(fi, a, verb)
  2891. case cstring: fmt_cstring(fi, a, verb)
  2892. case typeid: reflect.write_typeid(fi.writer, a, &fi.n)
  2893. case i16le: fmt_int(fi, u64(a), true, 16, verb)
  2894. case u16le: fmt_int(fi, u64(a), false, 16, verb)
  2895. case i32le: fmt_int(fi, u64(a), true, 32, verb)
  2896. case u32le: fmt_int(fi, u64(a), false, 32, verb)
  2897. case i64le: fmt_int(fi, u64(a), true, 64, verb)
  2898. case u64le: fmt_int(fi, u64(a), false, 64, verb)
  2899. case i16be: fmt_int(fi, u64(a), true, 16, verb)
  2900. case u16be: fmt_int(fi, u64(a), false, 16, verb)
  2901. case i32be: fmt_int(fi, u64(a), true, 32, verb)
  2902. case u32be: fmt_int(fi, u64(a), false, 32, verb)
  2903. case i64be: fmt_int(fi, u64(a), true, 64, verb)
  2904. case u64be: fmt_int(fi, u64(a), false, 64, verb)
  2905. case i128: fmt_int_128(fi, u128(a), true, 128, verb)
  2906. case u128: fmt_int_128(fi, a, false, 128, verb)
  2907. case i128le: fmt_int_128(fi, u128(a), true, 128, verb)
  2908. case u128le: fmt_int_128(fi, u128(a), false, 128, verb)
  2909. case i128be: fmt_int_128(fi, u128(a), true, 128, verb)
  2910. case u128be: fmt_int_128(fi, u128(a), false, 128, verb)
  2911. case: fmt_value(fi, arg, verb)
  2912. }
  2913. }