added typecasts for int and float

This commit is contained in:
Ava Hahn 2023-03-07 13:43:51 -08:00
parent a429b546d0
commit 06d30ac263
Signed by untrusted user who does not match committer: affine
GPG key ID: 3A4645B8CF806069
4 changed files with 130 additions and 2 deletions

View file

@ -228,6 +228,28 @@ pub fn static_stdlib(syms: &mut SymTable) -> Result<(), String> {
},
);
syms.insert(
"int".to_string(),
Symbol {
name: String::from("int"),
args: Args::Lazy(1),
conditional_branches: false,
docs: math::INTCAST_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(math::intcast_callback)),
},
);
syms.insert(
"float".to_string(),
Symbol {
name: String::from("float"),
args: Args::Lazy(1),
conditional_branches: false,
docs: math::FLOATCAST_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(math::floatcast_callback)),
},
);
Ok(())
}

View file

@ -125,3 +125,45 @@ pub fn mul_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, String> {
Ok(res)
}
}
pub const INTCAST_DOCSTRING: &str = "takes a single arg and attempts to cast it to an Integer.
This will work for a float or a potentially a string.
If the cast to Integer fails, it will return Nothing and print an error.
Casting a float to an int will drop its decimal.";
pub fn intcast_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, String> {
// special case for float
if let Ctr::Float(f) = *ast.car {
Ok(Ctr::Integer(f as i128))
} else if let Ctr::String(ref s) = *ast.car {
let int = str::parse::<i128>(s);
if int.is_err() {
Err(int.err().unwrap().to_string())
} else {
Ok(Ctr::Integer(int.ok().unwrap()))
}
} else {
Err("int cast only takes a float or a string".to_string())
}
}
pub const FLOATCAST_DOCSTRING: &str = "takes a single arg and attempts to cast it to a float.
This will work for an integer or potentially a string.
If the cast to integer fails, this function will return nothing and print an error.
Casting an integer to a float can result in bad behaviour since float nodes are based on 64bit floats and int nodes are based on 128 bit integers.";
pub fn floatcast_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, String> {
// special case for float
if let Ctr::Integer(i) = *ast.car {
Ok(Ctr::Float(i as f64))
} else if let Ctr::String(ref s) = *ast.car {
let int = str::parse::<f64>(&s);
if int.is_err() {
Err(int.err().unwrap().to_string())
} else {
Ok(Ctr::Float(int.ok().unwrap()))
}
} else {
Err("float cast only takes an integer or a string".to_string())
}
}