Files
regorus/src/builtins/conversions.rs
Anand Krishnamoorthi 01fc234a33 add std feature (#231)
- `std` feature is enabled by default
- By default enable #![no_std] compilation
- Import std create if `std` feature is enabled or if testing
- Use core, alloc types
- Make it clear where std types are being used
- In no std, use BTreeMap in place of HashMap.
   HashMap is not available in no std due to lack of a
   secure random number generator

Note: The project does not yet compile without std feature being specified.
But it's really close to being able to do so.

Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
2024-05-09 11:28:42 -07:00

43 lines
1.5 KiB
Rust

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use crate::ast::{Expr, Ref};
use crate::builtins;
use crate::builtins::utils::ensure_args_count;
use crate::lexer::Span;
use crate::value::Value;
use crate::*;
use anyhow::{bail, Result};
pub fn register(m: &mut builtins::BuiltinsMap<&'static str, builtins::BuiltinFcn>) {
m.insert("to_number", (to_number, 1));
}
fn to_number(span: &Span, params: &[Ref<Expr>], args: &[Value], _strict: bool) -> Result<Value> {
let name = "to_number";
ensure_args_count(span, name, params, args, 1)?;
let span = params[0].span();
Ok(match &args[0] {
Value::Null => Value::from(0u64),
Value::Bool(true) => Value::from(1u64),
Value::Bool(false) => Value::from(0u64),
Value::Number(_) => args[0].clone(),
// Eventhough the doc says that strings are converted using strconv.Atoi golang method,
// in practice strings seems to be read as json numbers. This means that floating point
// numbers are read and the string representation is limited to what json allows.
Value::String(s) => match Value::from_json_str(s) {
Ok(Value::Number(n)) => Value::Number(n),
_ => {
bail!(span.error("could not parse string as number"));
}
},
_ => {
bail!(
span.error(format!("`{name}` expects bool/number/string/null argument.").as_str())
);
}
})
}