fmt.odin 85 KB

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