fmt.odin 87 KB

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