fmt.odin 75 KB

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