fmt.odin 76 KB

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