2023-04-01 22:34:35 -07:00
|
|
|
use crate::obj::prelude::*;
|
|
|
|
|
use std::{any::Any, sync::LazyLock};
|
|
|
|
|
|
|
|
|
|
pub type IntValue = i64;
|
|
|
|
|
|
|
|
|
|
static INT_ATTRS: LazyLock<AttrsPtr> = LazyLock::new(|| {
|
|
|
|
|
attrs_ptr! {
|
|
|
|
|
//
|
|
|
|
|
"__str__" => builtin_fun_ptr!("__str__", |_vm, args, _state| {
|
|
|
|
|
if args.len() != 1 {
|
|
|
|
|
todo!("Throw exception: arity error");
|
|
|
|
|
}
|
|
|
|
|
let arg_any = &args[0].as_any();
|
|
|
|
|
let obj = arg_any.downcast_ref::<Int>().expect("Int.__str__ did not receive Int?");
|
|
|
|
|
|
|
|
|
|
BuiltinFunResult::Return(Some(ObjPtr::new(Str::new(obj.value().to_string()))))
|
|
|
|
|
}),
|
2023-04-07 00:00:04 -07:00
|
|
|
"__bool__" => builtin_fun_ptr!("__bool__", |_vm, args, _state| {
|
|
|
|
|
let arg_any = &args[0].as_any();
|
|
|
|
|
let obj = arg_any.downcast_ref::<Int>().expect("Int.__bool__ did not receive Int?");
|
|
|
|
|
let result = ObjPtr::clone(&BOOL_INSTS[obj.is_truthy() as usize]);
|
|
|
|
|
BuiltinFunResult::Return(Some(result))
|
|
|
|
|
}),
|
2023-04-01 22:34:35 -07:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
|
pub struct Int {
|
|
|
|
|
attrs: AttrsPtr,
|
|
|
|
|
value: IntValue,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Int {
|
|
|
|
|
pub fn new(value: IntValue) -> Self {
|
|
|
|
|
let attrs = AttrsPtr::clone(&INT_ATTRS);
|
|
|
|
|
// TODO intern
|
|
|
|
|
Int { attrs, value }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn value(&self) -> IntValue {
|
|
|
|
|
self.value
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Obj for Int {
|
|
|
|
|
fn attrs(&self) -> AttrsPtr {
|
|
|
|
|
AttrsPtr::clone(&self.attrs)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn as_any(&self) -> &(dyn Any + 'static) {
|
|
|
|
|
self
|
|
|
|
|
}
|
2023-04-07 00:00:04 -07:00
|
|
|
|
|
|
|
|
fn is_truthy(&self) -> bool {
|
|
|
|
|
self.value() != 0
|
|
|
|
|
}
|
2023-04-01 22:34:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ToString for Int {
|
|
|
|
|
fn to_string(&self) -> String {
|
|
|
|
|
format!("{}", self.value())
|
|
|
|
|
}
|
|
|
|
|
}
|