Skip to main content

lisette_syntax/
constant.rs

1use std::cmp::Ordering;
2use std::fmt;
3
4use num_bigint::BigInt;
5use num_rational::BigRational;
6use num_traits::{One, Signed, ToPrimitive, Zero};
7
8use crate::ast::{
9    BinaryOperator, BindingId, Expression, FormatStringPart, Literal, Span, UnaryOperator,
10};
11use crate::display_form::DisplayForm;
12use crate::lex::{rune_codepoint, string_bytes};
13use crate::program::{
14    Definition, DotAccessResolution, is_go_import, resolved_definition_name, strip_prelude_prefix,
15};
16use crate::types::{self, SimpleKind, Type};
17
18pub const MAX_CONSTANT_SHIFT: u32 = 1074;
19
20const MAX_INTEGER_BITS: u64 = 512;
21
22#[derive(Debug, Clone, PartialEq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub enum Value {
25    Bool(bool),
26    String(Vec<u8>),
27    Integer(BigInt),
28    Rune(BigInt),
29    Float(BigRational),
30    Complex(BigRational, BigRational),
31}
32
33#[derive(Debug, Clone, PartialEq)]
34pub struct Constant {
35    pub value: Value,
36    pub go_type: Option<SimpleKind>,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40pub enum ConstantError {
41    DivisionByZero {
42        span: Span,
43    },
44    Overflow {
45        span: Span,
46        value: Box<Value>,
47        kind: SimpleKind,
48        in_conversion: bool,
49    },
50    Truncated {
51        span: Span,
52    },
53    ShiftCount {
54        span: Span,
55    },
56    TooLarge {
57        span: Span,
58    },
59}
60
61pub type Evaluation = Result<Option<Constant>, ConstantError>;
62
63pub trait ConstantSource {
64    fn definition(&self, qualified_name: &str) -> Option<&Definition>;
65
66    fn local_constant(&self, _binding: BindingId) -> Option<Constant> {
67        None
68    }
69
70    fn named_constant(&self, qualified_name: &str) -> Option<Value> {
71        let definition = self.definition(qualified_name)?;
72        let value = definition.const_value()?.value()?;
73        Some(match self.underlying_kind(&definition.ty.body) {
74            Some(kind) => represent(value.clone(), kind, Span::dummy()).unwrap_or(value),
75            None => value,
76        })
77    }
78
79    fn underlying_kind(&self, ty: &Type) -> Option<SimpleKind> {
80        types::underlying_simple_kind(ty, |id| self.definition(id))
81    }
82
83    fn array_length(&self, ty: &Type) -> Option<u64> {
84        let lookup = |id: &str| self.definition(id);
85        types::underlying_type(&ty.receiver_shape(), lookup).array_len()
86    }
87
88    fn is_newtype(&self, qualified_name: &str) -> bool {
89        self.definition(qualified_name)
90            .is_some_and(Definition::is_newtype)
91    }
92}
93
94pub fn local_constant(
95    initializer: &Expression,
96    ty: &Type,
97    source: &dyn ConstantSource,
98) -> Option<Constant> {
99    let value = value_of(initializer, source)?;
100    let kind = source.underlying_kind(ty);
101    let value = match kind {
102        Some(kind) => represent(value, kind, initializer.get_span()).ok()?,
103        None => value,
104    };
105    let go_type = kind.filter(|kind| !matches!(kind, SimpleKind::String | SimpleKind::Bool));
106    Some(Constant { value, go_type })
107}
108
109pub struct Literals;
110
111impl ConstantSource for Literals {
112    fn definition(&self, _qualified_name: &str) -> Option<&Definition> {
113        None
114    }
115}
116
117macro_rules! constant {
118    ($evaluation:expr) => {
119        match $evaluation? {
120            Some(constant) => constant,
121            None => return Ok(None),
122        }
123    };
124}
125
126pub fn evaluate(expression: &Expression, source: &dyn ConstantSource) -> Evaluation {
127    let span = expression.get_span();
128    match expression {
129        Expression::Paren { expression, .. } => evaluate(expression, source),
130        Expression::Literal {
131            literal: Literal::FormatString(parts),
132            ..
133        } => format_string(parts, source),
134        Expression::Literal { literal, span, .. } => match literal_value(literal) {
135            Some(value) => fits(value, *span).map(|value| Some(untyped(value))),
136            None => Ok(None),
137        },
138        Expression::Identifier { resolution, ty, .. } => {
139            if let Some(binding) = resolution.binding_id() {
140                return Ok(source.local_constant(binding));
141            }
142            Ok(resolution
143                .definition()
144                .and_then(|name| named(name, ty, source)))
145        }
146        Expression::DotAccess {
147            expression: receiver,
148            resolution:
149                DotAccessResolution::TupleStructField {
150                    is_newtype: true, ..
151                },
152            ty,
153            ..
154        } => convert_to(receiver, ty, span, source),
155        Expression::DotAccess { resolution, ty, .. } => Ok(resolution
156            .defined_name()
157            .and_then(|name| named(name, ty, source))),
158        Expression::Unary {
159            operator,
160            expression,
161            ..
162        } => {
163            let operand = constant!(evaluate(expression, source));
164            unary(operator, operand, span)
165        }
166        Expression::Binary {
167            operator,
168            left,
169            right,
170            ..
171        } => {
172            let left = constant!(evaluate(left, source));
173            let right = constant!(evaluate(right, source));
174            binary(*operator, left, right, span).map(Some)
175        }
176        Expression::Cast {
177            expression: operand,
178            ty,
179            ..
180        } => convert_to(operand, ty, span, source),
181        Expression::Call { .. } => evaluate_call(expression, source),
182        _ => Ok(None),
183    }
184}
185
186fn format_string(parts: &[FormatStringPart], source: &dyn ConstantSource) -> Evaluation {
187    let mut bytes = Vec::new();
188    for part in parts {
189        match part {
190            FormatStringPart::Text(text) => {
191                let text = text.replace("{{", "{").replace("}}", "}");
192                let Some(decoded) = string_bytes(&text, false) else {
193                    return Ok(None);
194                };
195                bytes.extend_from_slice(&decoded);
196            }
197            FormatStringPart::Expression(part) => {
198                if DisplayForm::of(&part.get_type(), |id| source.definition(id))
199                    != DisplayForm::String
200                {
201                    return Ok(None);
202                }
203                let Value::String(value) = constant!(evaluate(part, source)).value else {
204                    return Ok(None);
205                };
206                bytes.extend(value);
207            }
208        }
209    }
210    Ok(Some(untyped(Value::String(bytes))))
211}
212
213fn convert_to(
214    operand: &Expression,
215    ty: &Type,
216    span: Span,
217    source: &dyn ConstantSource,
218) -> Evaluation {
219    let operand = constant!(evaluate(operand, source));
220    let Some(kind) = source.underlying_kind(ty) else {
221        return Ok(None);
222    };
223    convert(operand, kind, span).map(|constant| constant.map(typed_as(kind)))
224}
225
226pub fn value_of(expression: &Expression, source: &dyn ConstantSource) -> Option<Value> {
227    evaluate(expression, source)
228        .ok()
229        .flatten()
230        .map(|constant| constant.value)
231}
232
233fn untyped(value: Value) -> Constant {
234    Constant {
235        value,
236        go_type: None,
237    }
238}
239
240fn typed_as(kind: SimpleKind) -> impl Fn(Value) -> Constant {
241    move |value| Constant {
242        value,
243        go_type: Some(kind),
244    }
245}
246
247fn named(name: &str, ty: &Type, source: &dyn ConstantSource) -> Option<Constant> {
248    let value = source.named_constant(name)?;
249    let typed = if is_go_import(name) {
250        ty.is_nominal() || converts_go_constant(&value, ty)
251    } else {
252        true
253    };
254    let go_type = source
255        .underlying_kind(ty)
256        .filter(|kind| typed && kind.is_arithmetic());
257    Some(Constant { value, go_type })
258}
259
260pub fn converts_go_constant(value: &Value, ty: &Type) -> bool {
261    ty.is_unsigned_int()
262        && matches!(value, Value::Integer(integer) if *integer > BigInt::from(i64::MAX))
263}
264
265pub fn builtin_length_receiver(call: &Expression) -> Option<&Expression> {
266    let Expression::Call {
267        expression: callee,
268        args,
269        spread: None,
270        ..
271    } = call
272    else {
273        return None;
274    };
275    match callee.unwrap_parens() {
276        Expression::DotAccess {
277            expression: receiver,
278            resolution:
279                DotAccessResolution::InstanceMethod {
280                    method: Some(method),
281                    ..
282                },
283            ..
284        } if args.is_empty()
285            && method.name == "length"
286            && matches!(method.owner.as_str(), "prelude.string" | "prelude.Array") =>
287        {
288            Some(receiver)
289        }
290        _ => None,
291    }
292}
293
294fn evaluate_call(expression: &Expression, source: &dyn ConstantSource) -> Evaluation {
295    let Expression::Call {
296        expression: callee,
297        args,
298        spread,
299        type_arguments,
300        ty,
301        span,
302        ..
303    } = expression
304    else {
305        return Ok(None);
306    };
307    if spread.is_some() {
308        return Ok(None);
309    }
310    if let Some(receiver) = builtin_length_receiver(expression) {
311        return length(receiver, source);
312    }
313    let Some(callee) = resolved_definition_name(callee) else {
314        return Ok(None);
315    };
316    if source.is_newtype(callee) {
317        let [argument] = args.as_slice() else {
318            return Ok(None);
319        };
320        return convert_to(argument, ty, *span, source);
321    }
322    let ordering = match strip_prelude_prefix(callee) {
323        Some("min") => Ordering::Less,
324        Some("max") => Ordering::Greater,
325        Some("zero") => return Ok(zero_value(ty, source)),
326        Some("real" | "imaginary") => {
327            let [argument] = args.as_slice() else {
328                return Ok(None);
329            };
330            let argument = constant!(evaluate(argument, source));
331            let (real, imaginary) = match raise(argument.value, NumericKind::Complex) {
332                Value::Complex(real, imaginary) => (real, imaginary),
333                _ => return Ok(None),
334            };
335            let part = if callee == "prelude.real" {
336                real
337            } else {
338                imaginary
339            };
340            let go_type = argument.go_type.map(|kind| match kind {
341                SimpleKind::Complex64 => SimpleKind::Float32,
342                _ => SimpleKind::Float64,
343            });
344            return finish(Value::Float(part), go_type, *span).map(Some);
345        }
346        Some("complex") => {
347            let [real, imaginary] = args.as_slice() else {
348                return Ok(None);
349            };
350            let real = constant!(evaluate(real, source));
351            let imaginary = constant!(evaluate(imaginary, source));
352            let go_type = real.go_type.or(imaginary.go_type).map(|kind| match kind {
353                SimpleKind::Float32 => SimpleKind::Complex64,
354                _ => SimpleKind::Complex128,
355            });
356            let (Some(real), Some(imaginary)) = (rational(&real.value), rational(&imaginary.value))
357            else {
358                return Ok(None);
359            };
360            return finish(Value::Complex(real, imaginary), go_type, *span).map(Some);
361        }
362        _ => return Ok(None),
363    };
364    let mut arguments = args.iter();
365    let Some(first) = arguments.next() else {
366        return Ok(None);
367    };
368    let mut chosen = constant!(evaluate(first, source));
369    for argument in arguments {
370        let candidate = constant!(evaluate(argument, source));
371        let Some(next) = choose(chosen, candidate, ordering, *span)? else {
372            return Ok(None);
373        };
374        chosen = next;
375    }
376    if !type_arguments.is_empty()
377        && let Some(kind) = source.underlying_kind(ty)
378    {
379        return finish(chosen.value, Some(kind), *span).map(Some);
380    }
381    Ok(Some(chosen))
382}
383
384fn zero_value(ty: &Type, source: &dyn ConstantSource) -> Option<Constant> {
385    let kind = source.underlying_kind(ty)?;
386    let value = match kind {
387        SimpleKind::Bool => Value::Bool(false),
388        SimpleKind::String => Value::String(Vec::new()),
389        kind if kind.integer_range().is_some() => Value::Integer(BigInt::zero()),
390        SimpleKind::Float32 | SimpleKind::Float64 => Value::Float(BigRational::zero()),
391        SimpleKind::Complex64 | SimpleKind::Complex128 => {
392            Value::Complex(BigRational::zero(), BigRational::zero())
393        }
394        _ => return None,
395    };
396    Some(typed_as(kind)(value))
397}
398
399fn length(receiver: &Expression, source: &dyn ConstantSource) -> Evaluation {
400    let typed_int = typed_as(SimpleKind::Int);
401    if let Some(length) = source.array_length(&receiver.get_type()) {
402        return Ok(Some(typed_int(Value::Integer(BigInt::from(length)))));
403    }
404    let receiver = constant!(evaluate(receiver, source));
405    Ok(match receiver.value {
406        Value::String(bytes) => Some(typed_int(Value::Integer(BigInt::from(bytes.len())))),
407        _ => None,
408    })
409}
410
411fn choose(current: Constant, candidate: Constant, ordering: Ordering, span: Span) -> Evaluation {
412    let (go_type, left, right) = align(current, candidate, span)?;
413    let value = match compare(&left, &right) {
414        Some(found) if found == ordering => left,
415        Some(_) => right,
416        None => return Ok(None),
417    };
418    Ok(Some(Constant { value, go_type }))
419}
420
421fn align(
422    left: Constant,
423    right: Constant,
424    span: Span,
425) -> Result<(Option<SimpleKind>, Value, Value), ConstantError> {
426    let go_type = left.go_type.or(right.go_type);
427    let (left, right) = match go_type {
428        Some(kind) => (
429            represent(left.value, kind, span)?,
430            represent(right.value, kind, span)?,
431        ),
432        None => promote(left.value, right.value),
433    };
434    Ok((go_type, left, right))
435}
436
437fn unary(operator: &UnaryOperator, operand: Constant, span: Span) -> Evaluation {
438    let value = match (operator, operand.value) {
439        (UnaryOperator::Negative, Value::Integer(value)) => Value::Integer(-value),
440        (UnaryOperator::Negative, Value::Rune(value)) => Value::Rune(-value),
441        (UnaryOperator::Negative, Value::Float(value)) => Value::Float(-value),
442        (UnaryOperator::Negative, Value::Complex(real, imaginary)) => {
443            Value::Complex(-real, -imaginary)
444        }
445        (UnaryOperator::Not, Value::Bool(value)) => Value::Bool(!value),
446        (UnaryOperator::BitwiseNot, Value::Integer(value) | Value::Rune(value)) => {
447            Value::Integer(complement(value, operand.go_type))
448        }
449        _ => return Ok(None),
450    };
451    finish(value, operand.go_type, span).map(Some)
452}
453
454fn complement(value: BigInt, go_type: Option<SimpleKind>) -> BigInt {
455    match go_type
456        .filter(|kind| kind.is_unsigned())
457        .and_then(SimpleKind::integer_range)
458    {
459        Some((_, max)) => BigInt::from(max) ^ value,
460        None => -value - 1,
461    }
462}
463
464fn binary(
465    operator: BinaryOperator,
466    left: Constant,
467    right: Constant,
468    span: Span,
469) -> Result<Constant, ConstantError> {
470    use BinaryOperator::*;
471    if matches!(operator, ShiftLeft | ShiftRight) {
472        return shift(operator, left, right, span);
473    }
474    let (go_type, left, right) = align(left, right, span)?;
475    let comparison = |accepts: fn(Ordering) -> bool| -> Result<Constant, ConstantError> {
476        let ordering = compare(&left, &right).ok_or(ConstantError::Truncated { span })?;
477        Ok(untyped(Value::Bool(accepts(ordering))))
478    };
479    match operator {
480        Equal => return Ok(untyped(Value::Bool(left == right))),
481        NotEqual => return Ok(untyped(Value::Bool(left != right))),
482        LessThan => return comparison(Ordering::is_lt),
483        LessThanOrEqual => return comparison(Ordering::is_le),
484        GreaterThan => return comparison(Ordering::is_gt),
485        GreaterThanOrEqual => return comparison(Ordering::is_ge),
486        _ => {}
487    }
488    let value = arithmetic(operator, left, right, span)?;
489    finish(fits(value, span)?, go_type, span)
490}
491
492fn arithmetic(
493    operator: BinaryOperator,
494    left: Value,
495    right: Value,
496    span: Span,
497) -> Result<Value, ConstantError> {
498    use BinaryOperator::*;
499    let division_by_zero = ConstantError::DivisionByZero { span };
500    Ok(match (operator, left, right) {
501        (And, Value::Bool(left), Value::Bool(right)) => Value::Bool(left && right),
502        (Or, Value::Bool(left), Value::Bool(right)) => Value::Bool(left || right),
503        (Addition, Value::String(mut left), Value::String(right)) => {
504            left.extend(right);
505            Value::String(left)
506        }
507        (_, Value::Integer(left), Value::Integer(right)) => {
508            Value::Integer(integer_arithmetic(operator, left, right, span)?)
509        }
510        (_, Value::Rune(left), Value::Rune(right)) => {
511            Value::Rune(integer_arithmetic(operator, left, right, span)?)
512        }
513        (_, Value::Float(left), Value::Float(right)) => match operator {
514            Addition => Value::Float(left + right),
515            Subtraction => Value::Float(left - right),
516            Multiplication => Value::Float(left * right),
517            Division if right.is_zero() => return Err(division_by_zero),
518            Division => Value::Float(left / right),
519            _ => return Err(ConstantError::Truncated { span }),
520        },
521        (_, Value::Complex(a, b), Value::Complex(c, d)) => match operator {
522            Addition => Value::Complex(a + c, b + d),
523            Subtraction => Value::Complex(a - c, b - d),
524            Multiplication => Value::Complex(&a * &c - &b * &d, &a * &d + &b * &c),
525            Division => {
526                let denominator = &c * &c + &d * &d;
527                if denominator.is_zero() {
528                    return Err(division_by_zero);
529                }
530                Value::Complex(
531                    (&a * &c + &b * &d) / &denominator,
532                    (&b * &c - &a * &d) / &denominator,
533                )
534            }
535            _ => return Err(ConstantError::Truncated { span }),
536        },
537        _ => return Err(ConstantError::Truncated { span }),
538    })
539}
540
541fn integer_arithmetic(
542    operator: BinaryOperator,
543    left: BigInt,
544    right: BigInt,
545    span: Span,
546) -> Result<BigInt, ConstantError> {
547    use BinaryOperator::*;
548    match operator {
549        Division | Remainder if right.is_zero() => Err(ConstantError::DivisionByZero { span }),
550        Addition => Ok(left + right),
551        Subtraction => Ok(left - right),
552        Multiplication => Ok(left * right),
553        Division => Ok(left / right),
554        Remainder => Ok(left % right),
555        BitwiseAnd => Ok(left & right),
556        BitwiseOr => Ok(left | right),
557        BitwiseXor => Ok(left ^ right),
558        BitwiseAndNot => Ok(left & (-right - 1)),
559        _ => Err(ConstantError::Truncated { span }),
560    }
561}
562
563fn shift(
564    operator: BinaryOperator,
565    left: Constant,
566    right: Constant,
567    span: Span,
568) -> Result<Constant, ConstantError> {
569    let count = match right.value {
570        Value::Integer(count) | Value::Rune(count) => count,
571        Value::Float(count) => float_integer(&count, span)?,
572        _ => return Err(ConstantError::Truncated { span }),
573    };
574    let Some(amount) = count
575        .to_u32()
576        .filter(|amount| *amount <= MAX_CONSTANT_SHIFT)
577    else {
578        return Err(ConstantError::ShiftCount { span });
579    };
580    let (shifted, rune) = match left.value {
581        Value::Integer(value) => (value, false),
582        Value::Rune(value) => (value, true),
583        Value::Float(value) => (float_integer(&value, span)?, false),
584        _ => return Err(ConstantError::Truncated { span }),
585    };
586    let shifted = if operator == BinaryOperator::ShiftLeft {
587        shifted << amount
588    } else {
589        shifted >> amount
590    };
591    let value = if rune {
592        Value::Rune(shifted)
593    } else {
594        Value::Integer(shifted)
595    };
596    finish(fits(value, span)?, left.go_type, span)
597}
598
599fn fits(value: Value, span: Span) -> Result<Value, ConstantError> {
600    match &value {
601        Value::Integer(integer) | Value::Rune(integer) if integer.bits() > MAX_INTEGER_BITS => {
602            Err(ConstantError::TooLarge { span })
603        }
604        _ => Ok(value),
605    }
606}
607
608fn float_integer(value: &BigRational, span: Span) -> Result<BigInt, ConstantError> {
609    if !value.is_integer() {
610        return Err(ConstantError::Truncated { span });
611    }
612    Ok(value.to_integer())
613}
614
615fn finish(
616    value: Value,
617    go_type: Option<SimpleKind>,
618    span: Span,
619) -> Result<Constant, ConstantError> {
620    match go_type {
621        Some(kind) => Ok(Constant {
622            value: represent(value, kind, span)?,
623            go_type,
624        }),
625        None => Ok(untyped(value)),
626    }
627}
628
629fn convert(
630    operand: Constant,
631    kind: SimpleKind,
632    span: Span,
633) -> Result<Option<Value>, ConstantError> {
634    let value = match (operand.value, kind) {
635        (Value::Integer(value) | Value::Rune(value), SimpleKind::String) => {
636            let character = value
637                .to_u32()
638                .and_then(char::from_u32)
639                .unwrap_or(char::REPLACEMENT_CHARACTER);
640            Value::String(character.to_string().into_bytes())
641        }
642        (value @ Value::String(_), SimpleKind::String)
643        | (value @ Value::Bool(_), SimpleKind::Bool) => value,
644        (value, kind) if kind.is_arithmetic() && is_numeric_value(&value) => {
645            return represent(value, kind, span)
646                .map(Some)
647                .map_err(|error| match error {
648                    ConstantError::Overflow {
649                        span, value, kind, ..
650                    } => ConstantError::Overflow {
651                        span,
652                        value,
653                        kind,
654                        in_conversion: true,
655                    },
656                    error => error,
657                });
658        }
659        _ => return Ok(None),
660    };
661    Ok(Some(value))
662}
663
664pub fn represent(value: Value, kind: SimpleKind, span: Span) -> Result<Value, ConstantError> {
665    let overflow = |value: Value| ConstantError::Overflow {
666        span,
667        value: Box::new(value),
668        kind,
669        in_conversion: false,
670    };
671    if let Some((min, max)) = kind.integer_range() {
672        let integer = match value {
673            Value::Integer(value) | Value::Rune(value) => value,
674            Value::Float(real) if real.is_integer() => real.to_integer(),
675            Value::Complex(real, imaginary) if imaginary.is_zero() && real.is_integer() => {
676                real.to_integer()
677            }
678            Value::Float(_) | Value::Complex(..) => return Err(ConstantError::Truncated { span }),
679            _ => return Err(overflow(value)),
680        };
681        if integer < BigInt::from(min) || integer > BigInt::from(max) {
682            return Err(overflow(Value::Integer(integer)));
683        }
684        return Ok(Value::Integer(integer));
685    }
686    let single = matches!(kind, SimpleKind::Float32 | SimpleKind::Complex64);
687    match kind {
688        SimpleKind::Float32 | SimpleKind::Float64 => {
689            let real = match value {
690                Value::Complex(real, imaginary) if imaginary.is_zero() => real,
691                Value::Complex(..) => return Err(ConstantError::Truncated { span }),
692                value => rational(&value).ok_or_else(|| overflow(value))?,
693            };
694            let rounded = round_float(&real, single).ok_or_else(|| overflow(Value::Float(real)))?;
695            Ok(Value::Float(rounded))
696        }
697        SimpleKind::Complex64 | SimpleKind::Complex128 => {
698            let (real, imaginary) = match value {
699                Value::Complex(real, imaginary) => (real, imaginary),
700                value => (
701                    rational(&value).ok_or_else(|| overflow(value))?,
702                    BigRational::zero(),
703                ),
704            };
705            match (round_float(&real, single), round_float(&imaginary, single)) {
706                (Some(real), Some(imaginary)) => Ok(Value::Complex(real, imaginary)),
707                _ => Err(overflow(Value::Complex(real, imaginary))),
708            }
709        }
710        SimpleKind::String if matches!(value, Value::String(_)) => Ok(value),
711        SimpleKind::Bool if matches!(value, Value::Bool(_)) => Ok(value),
712        _ => Err(overflow(value)),
713    }
714}
715
716fn round_float(value: &BigRational, single: bool) -> Option<BigRational> {
717    let (precision, min_exponent, max) = if single {
718        (24, -149, f64::from(f32::MAX))
719    } else {
720        (53, -1074, f64::MAX)
721    };
722    if value.is_zero() {
723        return Some(BigRational::zero());
724    }
725    let magnitude = value.abs();
726    let mut exponent = magnitude.numer().bits() as i64 - magnitude.denom().bits() as i64;
727    if magnitude < power_of_two(exponent) {
728        exponent -= 1;
729    }
730    let scale = power_of_two((exponent - precision + 1).max(min_exponent));
731    let scaled = &magnitude / &scale;
732    let mut mantissa = scaled.to_integer();
733    let remainder = scaled.fract() * BigInt::from(2);
734    if remainder > BigRational::one() || (remainder.is_one() && mantissa.bit(0)) {
735        mantissa += 1;
736    }
737    let rounded = BigRational::from_integer(mantissa) * scale;
738    if rounded > BigRational::from_float(max)? {
739        return None;
740    }
741    Some(if value.is_negative() {
742        -rounded
743    } else {
744        rounded
745    })
746}
747
748fn power_of_two(exponent: i64) -> BigRational {
749    let power = BigRational::from_integer(BigInt::one() << exponent.unsigned_abs());
750    if exponent < 0 { power.recip() } else { power }
751}
752
753fn rational(value: &Value) -> Option<BigRational> {
754    match value {
755        Value::Integer(value) | Value::Rune(value) => {
756            Some(BigRational::from_integer(value.clone()))
757        }
758        Value::Float(value) => Some(value.clone()),
759        _ => None,
760    }
761}
762
763#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
764enum NumericKind {
765    None,
766    Integer,
767    Rune,
768    Float,
769    Complex,
770}
771
772fn numeric_kind(value: &Value) -> NumericKind {
773    match value {
774        Value::Integer(_) => NumericKind::Integer,
775        Value::Rune(_) => NumericKind::Rune,
776        Value::Float(_) => NumericKind::Float,
777        Value::Complex(..) => NumericKind::Complex,
778        Value::Bool(_) | Value::String(_) => NumericKind::None,
779    }
780}
781
782fn promote(left: Value, right: Value) -> (Value, Value) {
783    let target = numeric_kind(&left).max(numeric_kind(&right));
784    (raise(left, target), raise(right, target))
785}
786
787fn raise(value: Value, target: NumericKind) -> Value {
788    match (value, target) {
789        (Value::Integer(value), NumericKind::Rune) => Value::Rune(value),
790        (Value::Integer(value) | Value::Rune(value), NumericKind::Float) => {
791            Value::Float(BigRational::from_integer(value))
792        }
793        (Value::Integer(value) | Value::Rune(value), NumericKind::Complex) => {
794            Value::Complex(BigRational::from_integer(value), BigRational::zero())
795        }
796        (Value::Float(value), NumericKind::Complex) => Value::Complex(value, BigRational::zero()),
797        (value, _) => value,
798    }
799}
800
801fn compare(left: &Value, right: &Value) -> Option<Ordering> {
802    match (left, right) {
803        (Value::Integer(left), Value::Integer(right)) | (Value::Rune(left), Value::Rune(right)) => {
804            Some(left.cmp(right))
805        }
806        (Value::Float(left), Value::Float(right)) => Some(left.cmp(right)),
807        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
808        _ => None,
809    }
810}
811
812fn is_numeric_value(value: &Value) -> bool {
813    !matches!(value, Value::Bool(_) | Value::String(_))
814}
815
816pub fn literal_value(literal: &Literal) -> Option<Value> {
817    Some(match literal {
818        Literal::Integer { value, text } => {
819            Value::Integer(integer_literal(*value, text.as_deref())?)
820        }
821        Literal::Float { value, text } => Value::Float(
822            decimal(text.as_deref().unwrap_or(&value.to_string()))
823                .or_else(|| BigRational::from_float(*value))?,
824        ),
825        Literal::Imaginary(coefficient) => Value::Complex(
826            BigRational::zero(),
827            decimal(&coefficient.to_string()).or_else(|| BigRational::from_float(*coefficient))?,
828        ),
829        Literal::Boolean(value) => Value::Bool(*value),
830        Literal::String { value, raw } => Value::String(string_bytes(value, *raw)?.into_owned()),
831        Literal::Char(text) => Value::Rune(rune_codepoint(text)?.into()),
832        Literal::FormatString(_) | Literal::Slice(_) => return None,
833    })
834}
835
836pub fn exceeds_u64(text: &str) -> bool {
837    integer_literal(0, Some(text)).is_none_or(|value| value > BigInt::from(u64::MAX))
838}
839
840fn integer_literal(value: u64, text: Option<&str>) -> Option<BigInt> {
841    let Some(text) = text else {
842        return Some(value.into());
843    };
844    let text = text.replace('_', "");
845    let (negative, digits) = match text.strip_prefix('-') {
846        Some(digits) => (true, digits),
847        None => (false, text.as_str()),
848    };
849    let (radix, digits) = match digits.get(..2) {
850        Some("0x" | "0X") => (16, &digits[2..]),
851        Some("0o" | "0O") => (8, &digits[2..]),
852        Some("0b" | "0B") => (2, &digits[2..]),
853        _ => (10, digits),
854    };
855    let magnitude = match u64::from_str_radix(digits, radix) {
856        Ok(small) => BigInt::from(small),
857        Err(_) => BigInt::parse_bytes(digits.as_bytes(), radix)?,
858    };
859    Some(if negative { -magnitude } else { magnitude })
860}
861
862fn decimal(text: &str) -> Option<BigRational> {
863    let text = text.replace('_', "");
864    let (negative, text) = match text.strip_prefix('-') {
865        Some(rest) => (true, rest),
866        None => (false, text.as_str()),
867    };
868    let (mantissa, exponent) = match text.find(['e', 'E']) {
869        Some(at) => (&text[..at], text[at + 1..].parse::<i64>().ok()?),
870        None => (text, 0),
871    };
872    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
873    let digits = format!("{whole}{fraction}");
874    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
875        return None;
876    }
877    let significand = BigInt::parse_bytes(digits.as_bytes(), 10)?;
878    let scale = exponent - fraction.len() as i64;
879    let power = num_traits::pow(
880        BigInt::from(10),
881        usize::try_from(scale.unsigned_abs()).ok()?,
882    );
883    let magnitude = if scale < 0 {
884        BigRational::new(significand, power)
885    } else {
886        BigRational::from_integer(significand * power)
887    };
888    Some(if negative { -magnitude } else { magnitude })
889}
890
891impl Value {
892    pub fn from_i128(value: i128) -> Self {
893        Value::Integer(value.into())
894    }
895
896    pub fn from_f64(value: f64) -> Option<Self> {
897        BigRational::from_float(value).map(Value::Float)
898    }
899
900    pub fn as_integer(&self) -> Option<i128> {
901        match self {
902            Value::Integer(value) | Value::Rune(value) => value.to_i128(),
903            _ => None,
904        }
905    }
906
907    pub fn is_zero(&self) -> bool {
908        match self {
909            Value::Integer(value) | Value::Rune(value) => value.is_zero(),
910            Value::Float(value) => value.is_zero(),
911            Value::Complex(real, imaginary) => real.is_zero() && imaginary.is_zero(),
912            Value::Bool(_) | Value::String(_) => false,
913        }
914    }
915}
916
917impl fmt::Display for Value {
918    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
919        let float = |value: &BigRational| match value.to_f64().filter(|value| value.is_finite()) {
920            Some(approximate)
921                if approximate != 0.0 && !(1e-6..1e21).contains(&approximate.abs()) =>
922            {
923                format!("{approximate:e}")
924            }
925            Some(approximate) => approximate.to_string(),
926            None => value.to_integer().to_string(),
927        };
928        match self {
929            Value::Bool(value) => write!(f, "{value}"),
930            Value::String(bytes) => write!(f, "{:?}", String::from_utf8_lossy(bytes)),
931            Value::Integer(value) | Value::Rune(value) => write!(f, "{value}"),
932            Value::Float(value) => write!(f, "{}", float(value)),
933            Value::Complex(real, imaginary) => {
934                write!(f, "({} + {}i)", float(real), float(imaginary))
935            }
936        }
937    }
938}