~sircmpwn/hare

hare/fmt/fmt.ha -rw-r--r-- 14.1 KiB
5c7cd775Alexey Yerin all: add 0 value to enums used as flags 2 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use ascii;
use bufio;
use encoding::utf8;
use io;
use os;
use strconv;
use strings;
use types;

// Tagged union of the [[fmt::formattable]] types and [[fmt::modifiers]]. Used
// for functions which accept format strings.
export type field = (...formattable | *modifiers);

// Tagged union of all types which are formattable.
export type formattable =
	(...types::numeric | uintptr | str | rune | bool | nullable *void | void);

// Formats text for printing and writes it to [[os::stdout]].
export fn printf(fmt: str, args: field...) (io::error | size) =
	fprintf(os::stdout, fmt, args...);

// Formats text for printing and writes it to [[os::stdout]], followed by a line
// feed.
export fn printfln(fmt: str, args: field...) (io::error | size) =
	fprintfln(os::stdout, fmt, args...);

// Formats text for printing and writes it to [[os::stderr]].
export fn errorf(fmt: str, args: field...) (io::error | size) =
	fprintf(os::stderr, fmt, args...);

// Formats text for printing and writes it to [[os::stderr]], followed by a line
// feed.
export fn errorfln(fmt: str, args: field...) (io::error | size) =
	fprintfln(os::stderr, fmt, args...);

// Formats text for printing and writes it into a heap-allocated string. The
// caller must free the return value.
export fn asprintf(fmt: str, args: field...) str = {
	let buf = bufio::dynamic(io::mode::WRITE);
	assert(fprintf(buf, fmt, args...) is size);
	return strings::fromutf8_unsafe(bufio::finish(buf));
};

// Formats text for printing and writes it into a caller supplied buffer. The
// returned string is borrowed from this buffer.
export fn bsprintf(buf: []u8, fmt: str, args: field...) str = {
	let sink = bufio::fixed(buf, io::mode::WRITE);
	defer io::close(sink);
	let l = fprintf(sink, fmt, args...) as size;
	return strings::fromutf8_unsafe(buf[..l]);
};

// Formats text for printing and writes it to [[os::stderr]], followed by a line
// feed, then exits the program with an error status.
export @noreturn fn fatal(fmt: str, args: field...) void = {
	fprintfln(os::stderr, fmt, args...)!;
	os::exit(1);
};

// Formats text for printing and writes it to an [[io::stream]], followed by a
// line feed.
export fn fprintfln(
	s: *io::stream,
	fmt: str,
	args: field...
) (io::error | size) = {
	return fprintf(s, fmt, args...)? + io::write(s, ['\n': u32: u8])?;
};

// Formats values for printing using the default format modifiers and writes
// them to [[os::stdout]] separated by spaces.
export fn print(args: formattable...) (io::error | size) =
	fprint(os::stdout, args...);

// Formats values for printing using the default format modifiers and writes
// them to [[os::stdout]] separated by spaces and followed by a line feed.
export fn println(args: formattable...) (io::error | size) =
	fprintln(os::stdout, args...);

// Formats values for printing using the default format modifiers and writes
// them to [[os::stderr]] separated by spaces.
export fn error(args: formattable...) (io::error | size) =
	fprint(os::stderr, args...);

// Formats values for printing using the default format modifiers and writes
// them to [[os::stderr]] separated by spaces and followed by a line feed.
export fn errorln(args: formattable...) (io::error | size) =
	fprintln(os::stderr, args...);

// Formats values for printing using the default format modifiers and writes
// them into a heap-allocated string separated by spaces. The caller must free
// the return value.
export fn asprint(args: formattable...) str = {
	let buf = bufio::dynamic(io::mode::WRITE);
	assert(fprint(buf, args...) is size);
	return strings::fromutf8_unsafe(bufio::finish(buf));
};

// Formats values for printing using the default format modifiers and writes
// them into a caller supplied buffer separated by spaces. The returned string
// is borrowed from this buffer.
export fn bsprint(buf: []u8, args: formattable...) str = {
	let sink = bufio::fixed(buf, io::mode::WRITE);
	defer io::close(sink);
	assert(fprint(sink, args...) is size);
	return strings::fromutf8_unsafe(buf);
};

// Formats values for printing using the default format modifiers and writes
// them to an [[io::stream]] separated by spaces and followed by a line feed.
export fn fprintln(s: *io::stream, args: formattable...) (io::error | size) = {
	return fprint(s, args...)? + io::write(s, ['\n': u32: u8])?;
};

// Formats values for printing using the default format modifiers and writes
// them to an [[io::stream]] separated by spaces.
export fn fprint(s: *io::stream, args: formattable...) (io::error | size) = {
	let mod = modifiers { base = strconv::base::DEC, ... };
	let n = 0z;
	for (let i = 0z; i < len(args); i += 1) {
		n += format(s, args[i], &mod)?;
		if (i != len(args) - 1) {
			n += io::write(s, [' ': u32: u8])?;
		};
	};
	return n;
};

// Specifies for numerical arguments when to prepend a plus or minus sign or a
// blank space.
export type negation = enum {
	NONE,
	SPACE,
	PLUS,
};

// Specifies how to align and pad an argument within a given width.
export type padding = enum {
	ALIGN_RIGHT,
	ALIGN_LEFT,
	ZEROES,
};

// Specifies how to format an argument.
export type modifiers = struct {
	padding:   padding,
	negation:  negation,
	width:     uint,
	precision: uint,
	base:      strconv::base,
};

type modflags = enum uint {
	NONE  = 0,
	ZERO  = 1 << 0,
	MINUS = 1 << 1,
	SPACE = 1 << 2,
	PLUS  = 1 << 3,
};

type paramindex = (uint | nextparam | void);

type nextparam = void;

// Formats text for printing and writes it to an [[io::stream]].
export fn fprintf(
	s: *io::stream,
	fmt: str,
	args: field...
) (io::error | size) = {
	let n = 0z, i = 0z;
	let iter = strings::iter(fmt);
	for (true) {
		let r: rune = match (strings::next(&iter)) {
		case void =>
			break;
		case r: rune =>
			yield r;
		};

		if (r == '{') {
			r = match (strings::next(&iter)) {
			case void =>
				abort("Invalid format string (unterminated '{')");
			case r: rune =>
				yield r;
			};

			let arg = if (r == '{') {
				n += io::write(s, utf8::encoderune('{'))?;
				continue;
			} else if (ascii::isdigit(r)) {
				strings::push(&iter, r);
				yield args[scan_uint(&iter)];
			} else {
				strings::push(&iter, r);
				i += 1;
				yield args[i - 1];
			};

			const arg = match (arg) {
			case arg: formattable =>
				yield arg;
			case =>
				abort("Invalid formattable");
			};

			r = match (strings::next(&iter)) {
			case void =>
				abort("Invalid format string (unterminated '{')");
			case r: rune =>
				yield r;
			};

			let mod = &modifiers { ... };
			let pi: paramindex = void;
			switch (r) {
			case ':' =>
				scan_inline_modifiers(&iter, mod);
			case '%' =>
				scan_parametric_modifiers(&iter, &pi);
			case '}' => void;
			case =>
				abort("Invalid format string");
			};

			match (pi) {
			case pi: uint =>
				match (args[pi]) {
				case pmod: *modifiers =>
					mod = pmod;
				case =>
					abort("Explicit parameter is not *fmt::modifier");
				};
			case nextparam =>
				i += 1;
				match (args[i - 1]) {
				case pmod: *modifiers =>
					mod = pmod;
				case =>
					abort("Implicit parameter is not *fmt::modifier");
				};
			case void => void;
			};

			if (mod.base == 0) {
				mod.base = strconv::base::DEC;
			};

			n += format(s, arg, mod)?;
		} else if (r == '}') {
			match (strings::next(&iter)) {
			case void =>
				abort("Invalid format string (hanging '}')");
			case r: rune =>
				assert(r == '}', "Invalid format string (hanging '}')");
			};

			n += io::write(s, utf8::encoderune('}'))?;
		} else {
			n += io::write(s, utf8::encoderune(r))?;
		};
	};

	return n;
};

fn format(out: *io::stream, arg: formattable, mod: *modifiers) (size | io::error) = {
	let z = format_raw(io::empty, arg, mod)?;

	let pad: []u8 = [];
	if (z < mod.width: size) {
		pad = utf8::encoderune(switch (mod.padding) {
		case padding::ZEROES =>
			yield '0';
		case =>
			yield ' ';
		});
	};

	if (mod.padding == padding::ALIGN_LEFT) {
		format_raw(out, arg, mod)?;
	};

	for (z < mod.width: size) {
		z += io::write(out, pad)?;
	};

	if (mod.padding != padding::ALIGN_LEFT) {
		format_raw(out, arg, mod)?;
	};

	return z;
};

fn format_raw(
	out: *io::stream,
	arg: formattable,
	mod: *modifiers,
) (size | io::error) = {
	match (arg) {
	case s: str =>
		return io::write(out, strings::toutf8(s));
	case r: rune =>
		return io::write(out, utf8::encoderune(r));
	case b: bool =>
		return io::write(out,
			strings::toutf8(if (b) "true" else "false"));
	case n: types::numeric =>
		const s = strconv::numerictosb(n, mod.base);
		return io::write(out, strings::toutf8(s));
	case p: uintptr =>
		const s = strconv::uptrtosb(p, mod.base);
		return io::write(out, strings::toutf8(s));
	case v: nullable *void =>
		match (v) {
		case v: *void =>
			let n = io::write(out, strings::toutf8("0x"))?;
			const s = strconv::uptrtosb(v: uintptr,
				strconv::base::HEX_LOWER);
			n += io::write(out, strings::toutf8(s))?;
			return n;
		case null =>
			return format(out, "(null)", mod);
		};
	case void =>
		return io::write(out, strings::toutf8("void"));
	};
};

fn scan_uint(iter: *strings::iterator) uint = {
	let num: []u8 = [];
	defer free(num);
	for (true) {
		let r = match (strings::next(iter)) {
		case void =>
			abort("Invalid format string (unterminated '{')");
		case r: rune =>
			yield r;
		};

		if (ascii::isdigit(r)) {
			append(num, r: u32: u8);
		} else {
			strings::push(iter, r);
			match (strconv::stou(strings::fromutf8(num))) {
			case (strconv::invalid | strconv::overflow) =>
				abort("Invalid format string (invalid index)");
			case u: uint =>
				return u;
			};
		};
	};
	abort("unreachable");
};

fn scan_modifier_flags(iter: *strings::iterator, mod: *modifiers) void = {
	let flags = modflags::NONE;

	for (true) {
		let r = match (strings::next(iter)) {
		case void =>
			abort("Invalid format string (unterminated '{')");
		case r: rune =>
			yield r;
		};

		switch (r) {
		case '0' =>
			flags |= modflags::ZERO;
		case '-' =>
			flags |= modflags::MINUS;
		case ' ' =>
			flags |= modflags::SPACE;
		case '+' =>
			flags |= modflags::PLUS;
		case =>
			strings::push(iter, r);
			break;
		};
	};

	mod.padding = if (flags & modflags::MINUS != 0)
		padding::ALIGN_LEFT
	else if (flags & modflags::ZERO != 0)
		padding::ZEROES
	else
		padding::ALIGN_RIGHT;

	mod.negation = if (flags & modflags::PLUS != 0)
		negation::PLUS
	else if (flags & modflags::SPACE != 0)
		negation::SPACE
	else
		negation::NONE;
};

fn scan_modifier_width(iter: *strings::iterator, mod: *modifiers) void = {
	let r = match (strings::next(iter)) {
	case void =>
		abort("Invalid format string (unterminated '{')");
	case r: rune =>
		yield r;
	};

	let is_digit = ascii::isdigit(r);
	strings::push(iter, r);

	if (is_digit) {
		mod.width = scan_uint(iter);
	};
};

fn scan_modifier_precision(iter: *strings::iterator, mod: *modifiers) void = {
	let r = match (strings::next(iter)) {
	case void =>
		abort("Invalid format string (unterminated '{')");
	case r: rune =>
		yield r;
	};

	if (r == '.') {
		mod.precision = scan_uint(iter);
	} else {
		strings::push(iter, r);
	};
};

fn scan_modifier_base(iter: *strings::iterator, mod: *modifiers) void = {
	let r = match (strings::next(iter)) {
	case void =>
		abort("Invalid format string (unterminated '{')");
	case r: rune =>
		yield r;
	};

	switch (r) {
	case 'x' =>
		mod.base = strconv::base::HEX_LOWER;
	case 'X' =>
		mod.base = strconv::base::HEX_UPPER;
	case 'o' =>
		mod.base = strconv::base::OCT;
	case 'b' =>
		mod.base = strconv::base::BIN;
	case =>
		strings::push(iter, r);
	};
};

fn scan_inline_modifiers(iter: *strings::iterator, mod: *modifiers) void = {
	scan_modifier_flags(iter, mod);
	scan_modifier_width(iter, mod);
	scan_modifier_precision(iter, mod);
	scan_modifier_base(iter, mod);

	// eat '}'
	let terminated = match (strings::next(iter)) {
	case void =>
		yield false;
	case r: rune =>
		yield r == '}';
	};
	assert(terminated, "Invalid format string (unterminated '{')");
};

fn scan_parameter_index(iter: *strings::iterator, pi: *paramindex) void = {
	let r = match (strings::next(iter)) {
	case void =>
		abort("Invalid format string (unterminated '{')");
	case r: rune =>
		yield r;
	};

	let is_digit = ascii::isdigit(r);
	strings::push(iter, r);
	if (is_digit) {
		*pi = scan_uint(iter);
	} else {
		*pi = nextparam;
	};
};

fn scan_parametric_modifiers(iter: *strings::iterator, pi: *paramindex) void = {
	scan_parameter_index(iter, pi);

	// eat '}'
	let terminated = match (strings::next(iter)) {
	case void =>
		yield false;
	case r: rune =>
		yield r == '}';
	};
	assert(terminated, "Invalid format string (unterminated '{')");
};

@test fn fmt() void = {
	let buf: [1024]u8 = [0...];

	assert(bsprintf(buf, "hello world") == "hello world");
	assert(bsprintf(buf, "{} {}", "hello", "world") == "hello world");
	assert(bsprintf(buf, "{0} {1}", "hello", "world") == "hello world");
	assert(bsprintf(buf, "{0} {0}", "hello", "world") == "hello hello");
	assert(bsprintf(buf, "{1} {0} {1}", "hello", "world") == "world hello world");

	const mod = &modifiers { width = 7, ... };
	assert(bsprintf(buf, "{%}", "hello", mod) == "  hello");
	assert(bsprintf(buf, "{%1}", "hello", mod) == "  hello");
	assert(bsprintf(buf, "{0%1}", "hello", mod) == "  hello");
	assert(bsprintf(buf, "{0%2}", "hello", 0, mod) == "  hello");
	assert(bsprintf(buf, "{1%2}", 0, "hello", mod) == "  hello");
	assert(bsprintf(buf, "{2%0}", mod, 0, "hello") == "  hello");
	assert(bsprintf(buf, "{2%}", mod, 0, "hello") == "  hello");
	assert(bsprintf(buf, "|{1%}|{}|", mod, "hello") == "|  hello|hello|");
	assert(bsprintf(buf, "|{}|{2%}|", "hello", mod, "world") == "|hello|  world|");
	assert(bsprintf(buf, "|{%}|{%}|{%}|{%}|",
		"hello", &modifiers { ... },
		"world", &modifiers { width = 10, ... },
		123,     &modifiers { width = 10, padding = padding::ZEROES, ... },
		0xBEEF,  &modifiers { base = strconv::base::HEX, ... },
	) == "|hello|     world|0000000123|BEEF|");
	assert(bsprintf(buf, "|{%}|{%}|{0%1}|",
		"hello", &modifiers { ... },
		"world", &modifiers { ... },
	) == "|hello|world|hello|");

	assert(bsprintf(buf, "x: {:08x}", 0xBEEF) == "x: 0000beef");
	assert(bsprintf(buf, "x: {:8X}", 0xBEEF) == "x:     BEEF");
	assert(bsprintf(buf, "x: {:-8X}", 0xBEEF) == "x: BEEF    ");
	assert(bsprintf(buf, "x: {:o}", 0o755) == "x: 755");
	assert(bsprintf(buf, "x: {:b}", 0b11011) == "x: 11011");

	assert(bsprintf(buf, "{} {} {} {} {}", true, false, null, 'x', void)
		== "true false (null) x void");
};