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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! faster std.format impl
#![allow(clippy::too_many_arguments)]

use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
use thiserror::Error;

use crate::{error::ErrorKind::*, throw, typed::Typed, Error, ObjValue, Result, Val};

#[derive(Debug, Clone, Error, Trace)]
pub enum FormatError {
	#[error("truncated format code")]
	TruncatedFormatCode,
	#[error("unrecognized conversion type: {0}")]
	UnrecognizedConversionType(char),

	#[error("not enough values")]
	NotEnoughValues,

	#[error("cannot use * width with object")]
	CannotUseStarWidthWithObject,
	#[error("mapping keys required")]
	MappingKeysRequired,
	#[error("no such format field: {0}")]
	NoSuchFormatField(IStr),
}

impl From<FormatError> for Error {
	fn from(e: FormatError) -> Self {
		Self::new(Format(e))
	}
}

use FormatError::*;

type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;

pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let bytes = str.as_bytes();
	if bytes[0] == b'(' {
		let mut i = 1;
		while i < bytes.len() {
			if bytes[i] == b')' {
				return Ok((&str[1..i], &str[i + 1..]));
			}
			i += 1;
		}
		Err(TruncatedFormatCode)
	} else {
		Ok(("", str))
	}
}

#[cfg(test)]
pub mod tests_key {
	use super::*;

	#[test]
	fn parse_key() {
		assert_eq!(
			try_parse_mapping_key("(hello ) world").unwrap(),
			("hello ", " world")
		);
		assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));
		assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));
		assert_eq!(
			try_parse_mapping_key(" () world").unwrap(),
			("", " () world")
		);
	}

	#[test]
	#[should_panic]
	fn parse_key_missing_start() {
		try_parse_mapping_key("").unwrap();
	}

	#[test]
	#[should_panic]
	fn parse_key_missing_end() {
		try_parse_mapping_key("(   ").unwrap();
	}
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Default, Debug)]
pub struct CFlags {
	pub alt: bool,
	pub zero: bool,
	pub left: bool,
	pub blank: bool,
	pub sign: bool,
}

pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let bytes = str.as_bytes();
	let mut i = 0;
	let mut out = CFlags::default();
	loop {
		if bytes.len() == i {
			return Err(TruncatedFormatCode);
		}
		match bytes[i] {
			b'#' => out.alt = true,
			b'0' => out.zero = true,
			b'-' => out.left = true,
			b' ' => out.blank = true,
			b'+' => out.sign = true,
			_ => break,
		}
		i += 1;
	}
	Ok((out, &str[i..]))
}

#[derive(Debug, PartialEq, Eq)]
pub enum Width {
	Star,
	Fixed(usize),
}
pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let bytes = str.as_bytes();
	if bytes[0] == b'*' {
		return Ok((Width::Star, &str[1..]));
	}
	let mut out: usize = 0;
	let mut digits = 0;
	while let Some(digit) = (bytes[digits] as char).to_digit(10) {
		out *= 10;
		out += digit as usize;
		digits += 1;
		if digits == bytes.len() {
			return Err(TruncatedFormatCode);
		}
	}
	Ok((Width::Fixed(out), &str[digits..]))
}

pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let bytes = str.as_bytes();
	if bytes[0] == b'.' {
		try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))
	} else {
		Ok((None, str))
	}
}

// Only skips
pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let bytes = str.as_bytes();
	let mut idx = 0;
	while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {
		idx += 1;
		if bytes.len() == idx {
			return Err(TruncatedFormatCode);
		}
	}
	Ok(((), &str[idx..]))
}

#[derive(Debug, PartialEq, Eq)]
pub enum ConvTypeV {
	Decimal,
	Octal,
	Hexadecimal,
	Scientific,
	Float,
	Shorter,
	Char,
	String,
	Percent,
}
pub struct ConvType {
	v: ConvTypeV,
	caps: bool,
}

pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}

	let code = str.as_bytes()[0];
	let v: (ConvTypeV, bool) = match code {
		b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),
		b'o' => (ConvTypeV::Octal, false),
		b'x' => (ConvTypeV::Hexadecimal, false),
		b'X' => (ConvTypeV::Hexadecimal, true),
		b'e' => (ConvTypeV::Scientific, false),
		b'E' => (ConvTypeV::Scientific, true),
		b'f' => (ConvTypeV::Float, false),
		b'F' => (ConvTypeV::Float, true),
		b'g' => (ConvTypeV::Shorter, false),
		b'G' => (ConvTypeV::Shorter, true),
		b'c' => (ConvTypeV::Char, false),
		b's' => (ConvTypeV::String, false),
		b'%' => (ConvTypeV::Percent, false),
		c => return Err(UnrecognizedConversionType(c as char)),
	};

	Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))
}

#[derive(Debug)]
pub struct Code<'s> {
	mkey: &'s str,
	cflags: CFlags,
	width: Width,
	precision: Option<Width>,
	convtype: ConvTypeV,
	caps: bool,
}
pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {
	if str.is_empty() {
		return Err(TruncatedFormatCode);
	}
	let (mkey, str) = try_parse_mapping_key(str)?;
	let (cflags, str) = try_parse_cflags(str)?;
	let (width, str) = try_parse_field_width(str)?;
	let (precision, str) = try_parse_precision(str)?;
	let (_, str) = try_parse_length_modifier(str)?;
	let (convtype, str) = parse_conversion_type(str)?;

	Ok((
		Code {
			mkey,
			cflags,
			width,
			precision,
			convtype: convtype.v,
			caps: convtype.caps,
		},
		str,
	))
}

#[derive(Debug)]
pub enum Element<'s> {
	String(&'s str),
	Code(Code<'s>),
}
pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {
	let mut bytes = str.as_bytes();
	let mut out = vec![];
	let mut offset = 0;

	loop {
		while offset != bytes.len() && bytes[offset] != b'%' {
			offset += 1;
		}
		if offset != 0 {
			out.push(Element::String(&str[0..offset]));
		}
		if offset == bytes.len() {
			return Ok(out);
		}
		str = &str[offset + 1..];
		let code;
		(code, str) = parse_code(str)?;
		bytes = str.as_bytes();
		offset = 0;

		out.push(Element::Code(code));
	}
}

const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";

#[inline]
pub fn render_integer(
	out: &mut String,
	iv: f64,
	padding: usize,
	precision: usize,
	blank: bool,
	sign: bool,
	radix: i64,
	prefix: &str,
	caps: bool,
) {
	let radix = radix as f64;
	let iv = iv.floor();
	// Digit char indexes in reverse order, i.e
	// for radix = 16 and n = 12f: [15, 2, 1]
	let digits = if iv == 0.0 {
		vec![0u8]
	} else {
		let mut v = iv.abs();
		let mut nums = Vec::with_capacity(1);
		while v != 0.0 {
			nums.push((v % radix) as u8);
			v = (v / radix).floor();
		}
		nums
	};
	let neg = iv < 0.0;
	#[allow(clippy::bool_to_int_with_if)]
	let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });
	let zp2 = zp
		.max(precision)
		.saturating_sub(prefix.len() + digits.len());

	if neg {
		out.push('-');
	} else if sign {
		out.push('+');
	} else if blank {
		out.push(' ');
	}

	out.reserve(zp2);
	for _ in 0..zp2 {
		out.push('0');
	}
	out.push_str(prefix);

	for digit in digits.into_iter().rev() {
		let ch = NUMBERS[digit as usize] as char;
		out.push(if caps { ch.to_ascii_uppercase() } else { ch });
	}
}

pub fn render_decimal(
	out: &mut String,
	iv: f64,
	padding: usize,
	precision: usize,
	blank: bool,
	sign: bool,
) {
	render_integer(out, iv, padding, precision, blank, sign, 10, "", false);
}
pub fn render_octal(
	out: &mut String,
	iv: f64,
	padding: usize,
	precision: usize,
	alt: bool,
	blank: bool,
	sign: bool,
) {
	render_integer(
		out,
		iv,
		padding,
		precision,
		blank,
		sign,
		8,
		if alt && iv != 0.0 { "0" } else { "" },
		false,
	);
}

#[allow(clippy::fn_params_excessive_bools)]
pub fn render_hexadecimal(
	out: &mut String,
	iv: f64,
	padding: usize,
	precision: usize,
	alt: bool,
	blank: bool,
	sign: bool,
	caps: bool,
) {
	render_integer(
		out,
		iv,
		padding,
		precision,
		blank,
		sign,
		16,
		match (alt, caps) {
			(true, true) => "0X",
			(true, false) => "0x",
			(false, _) => "",
		},
		caps,
	);
}

#[allow(clippy::fn_params_excessive_bools)]
pub fn render_float(
	out: &mut String,
	n: f64,
	mut padding: usize,
	precision: usize,
	blank: bool,
	sign: bool,
	ensure_pt: bool,
	trailing: bool,
) {
	#[allow(clippy::bool_to_int_with_if)]
	let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };
	padding = padding.saturating_sub(dot_size + precision);
	render_decimal(out, n.floor(), padding, 0, blank, sign);
	if precision == 0 {
		if ensure_pt {
			out.push('.');
		}
		return;
	}
	let frac = n
		.fract()
		.mul_add(10.0_f64.powf(precision as f64), 0.5)
		.floor();
	if trailing || frac > 0.0 {
		out.push('.');
		let mut frac_str = String::new();
		render_decimal(&mut frac_str, frac, precision, 0, false, false);
		let mut trim = frac_str.len();
		if !trailing {
			for b in frac_str.as_bytes().iter().rev() {
				if *b == b'0' {
					trim -= 1;
				}
			}
		}
		out.push_str(&frac_str[..trim]);
	} else if ensure_pt {
		out.push('.');
	}
}

#[allow(clippy::fn_params_excessive_bools)]
pub fn render_float_sci(
	out: &mut String,
	n: f64,
	mut padding: usize,
	precision: usize,
	blank: bool,
	sign: bool,
	ensure_pt: bool,
	trailing: bool,
	caps: bool,
) {
	let exponent = n.log10().floor();
	let mantissa = if exponent as i16 == -324 {
		n * 10.0 / 10.0_f64.powf(exponent + 1.0)
	} else {
		n / 10.0_f64.powf(exponent)
	};
	let mut exponent_str = String::new();
	render_decimal(&mut exponent_str, exponent, 3, 0, false, true);

	// +1 for e
	padding = padding.saturating_sub(exponent_str.len() + 1);

	render_float(
		out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,
	);
	out.push(if caps { 'E' } else { 'e' });
	out.push_str(&exponent_str);
}

#[allow(clippy::too_many_lines)]
pub fn format_code(
	out: &mut String,
	value: &Val,
	code: &Code<'_>,
	width: usize,
	precision: Option<usize>,
) -> Result<()> {
	let clfags = &code.cflags;
	let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));
	let padding = if clfags.zero && !clfags.left {
		width
	} else {
		0
	};

	// TODO: If left padded, can optimize by writing directly to out
	let mut tmp_out = String::new();

	match code.convtype {
		ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),
		ConvTypeV::Decimal => {
			let value = f64::from_untyped(value.clone())?;
			render_decimal(
				&mut tmp_out,
				value,
				padding,
				iprec,
				clfags.blank,
				clfags.sign,
			);
		}
		ConvTypeV::Octal => {
			let value = f64::from_untyped(value.clone())?;
			render_octal(
				&mut tmp_out,
				value,
				padding,
				iprec,
				clfags.alt,
				clfags.blank,
				clfags.sign,
			);
		}
		ConvTypeV::Hexadecimal => {
			let value = f64::from_untyped(value.clone())?;
			render_hexadecimal(
				&mut tmp_out,
				value,
				padding,
				iprec,
				clfags.alt,
				clfags.blank,
				clfags.sign,
				code.caps,
			);
		}
		ConvTypeV::Scientific => {
			let value = f64::from_untyped(value.clone())?;
			render_float_sci(
				&mut tmp_out,
				value,
				padding,
				fpprec,
				clfags.blank,
				clfags.sign,
				clfags.alt,
				true,
				code.caps,
			);
		}
		ConvTypeV::Float => {
			let value = f64::from_untyped(value.clone())?;
			render_float(
				&mut tmp_out,
				value,
				padding,
				fpprec,
				clfags.blank,
				clfags.sign,
				clfags.alt,
				true,
			);
		}
		ConvTypeV::Shorter => {
			let value = f64::from_untyped(value.clone())?;
			let exponent = value.log10().floor();
			if exponent < -4.0 || exponent >= fpprec as f64 {
				render_float_sci(
					&mut tmp_out,
					value,
					padding,
					fpprec - 1,
					clfags.blank,
					clfags.sign,
					clfags.alt,
					clfags.alt,
					code.caps,
				);
			} else {
				let digits_before_pt = 1.max(exponent as usize + 1);
				render_float(
					&mut tmp_out,
					value,
					padding,
					fpprec - digits_before_pt,
					clfags.blank,
					clfags.sign,
					clfags.alt,
					clfags.alt,
				);
			}
		}
		ConvTypeV::Char => match value.clone() {
			Val::Num(n) => tmp_out.push(
				std::char::from_u32(n as u32)
					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
			),
			Val::Str(s) => {
				let s = s.into_flat();
				if s.chars().count() != 1 {
					throw!("%c expected 1 char string, got {}", s.chars().count(),);
				}
				tmp_out.push_str(&s);
			}
			_ => {
				throw!(TypeMismatch(
					"%c requires number/string",
					vec![ValType::Num, ValType::Str],
					value.value_type(),
				));
			}
		},
		ConvTypeV::Percent => tmp_out.push('%'),
	};

	let padding = width.saturating_sub(tmp_out.len());

	if !clfags.left {
		for _ in 0..padding {
			out.push(' ');
		}
	}
	out.push_str(&tmp_out);
	if clfags.left {
		for _ in 0..padding {
			out.push(' ');
		}
	}

	Ok(())
}

pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {
	let codes = parse_codes(str)?;
	let mut out = String::new();
	let value_count = values.len();

	for code in codes {
		match code {
			Element::String(s) => {
				out.push_str(s);
			}
			Element::Code(c) => {
				let width = match c.width {
					Width::Star => {
						if values.is_empty() {
							throw!(NotEnoughValues);
						}
						let value = &values[0];
						values = &values[1..];
						usize::from_untyped(value.clone())?
					}
					Width::Fixed(n) => n,
				};
				let precision = match c.precision {
					Some(Width::Star) => {
						if values.is_empty() {
							throw!(NotEnoughValues);
						}
						let value = &values[0];
						values = &values[1..];
						Some(usize::from_untyped(value.clone())?)
					}
					Some(Width::Fixed(n)) => Some(n),
					None => None,
				};

				// %% should not consume a value
				let value = if c.convtype == ConvTypeV::Percent {
					&Val::Null
				} else {
					if values.is_empty() {
						throw!(NotEnoughValues);
					}
					let value = &values[0];
					values = &values[1..];
					value
				};

				format_code(&mut out, value, &c, width, precision)?;
			}
		}
	}

	if !values.is_empty() {
		throw!(
			"too many values to format, expected {value_count}, got {}",
			value_count + values.len()
		)
	}

	Ok(out)
}

pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
	let codes = parse_codes(str)?;
	let mut out = String::new();

	for code in codes {
		match code {
			Element::String(s) => {
				out.push_str(s);
			}
			Element::Code(c) => {
				// TODO: Operate on ref
				let f: IStr = c.mkey.into();
				let width = match c.width {
					Width::Star => {
						throw!(CannotUseStarWidthWithObject);
					}
					Width::Fixed(n) => n,
				};
				let precision = match c.precision {
					Some(Width::Star) => {
						throw!(CannotUseStarWidthWithObject);
					}
					Some(Width::Fixed(n)) => Some(n),
					None => None,
				};

				let value = if c.convtype == ConvTypeV::Percent {
					Val::Null
				} else {
					if f.is_empty() {
						throw!(MappingKeysRequired);
					}
					if let Some(v) = values.get(f.clone())? {
						v
					} else {
						throw!(NoSuchFormatField(f));
					}
				};

				format_code(&mut out, &value, &c, width, precision)?;
			}
		}
	}

	Ok(out)
}

#[cfg(test)]
pub mod test_format {
	use super::*;

	#[test]
	fn parse() {
		assert_eq!(
			parse_codes(
				"How much error budget is left looking at our %.3f%% availability gurantees?"
			)
			.unwrap()
			.len(),
			4
		);
	}

	#[test]
	fn octals() {
		assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");
		assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");
		assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), "  10");
		assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");
		assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");
		assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");
		assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10  ");
		assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");
		assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");
	}

	#[test]
	fn percent_doesnt_consumes_values() {
		assert_eq!(
			format_arr(
				"How much error budget is left looking at our %.3f%% availability gurantees?",
				&[Val::Num(4.0)]
			)
			.unwrap(),
			"How much error budget is left looking at our 4.000% availability gurantees?"
		);
	}
}