From 701e45364c3540dbdb37908b77d0d0699261dad3 Mon Sep 17 00:00:00 2001 From: lyken Date: Tue, 20 Aug 2024 12:22:21 +0800 Subject: [PATCH] core/object: add is_instance for ndarray, tuple and list --- nac3core/src/codegen/object/list.rs | 5 +++++ nac3core/src/codegen/object/ndarray/mod.rs | 7 ++++++- nac3core/src/codegen/object/tuple.rs | 5 +++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/nac3core/src/codegen/object/list.rs b/nac3core/src/codegen/object/list.rs index 77a075da..dad5b7fd 100644 --- a/nac3core/src/codegen/object/list.rs +++ b/nac3core/src/codegen/object/list.rs @@ -65,6 +65,11 @@ impl<'ctx> ListObject<'ctx> { ListObject { item_type, instance: value } } + /// Check if an object can be converted into an ndarray. + pub fn is_instance(ctx: &mut CodeGenContext<'ctx, '_>, object: AnyObject<'ctx>) -> bool { + matches!(&*ctx.unifier.get_ty(object.ty), TypeEnum::TObj { obj_id, .. } if *obj_id == ctx.primitives.list.obj_id(&ctx.unifier).unwrap()) + } + /// Get the `len()` of this list. pub fn len( &self, diff --git a/nac3core/src/codegen/object/ndarray/mod.rs b/nac3core/src/codegen/object/ndarray/mod.rs index b270d714..75b3a31b 100644 --- a/nac3core/src/codegen/object/ndarray/mod.rs +++ b/nac3core/src/codegen/object/ndarray/mod.rs @@ -14,7 +14,7 @@ use crate::{ CodeGenContext, CodeGenerator, }, toplevel::{helper::extract_ndims, numpy::unpack_ndarray_var_tys}, - typecheck::typedef::Type, + typecheck::typedef::{Type, TypeEnum}, }; use super::any::AnyObject; @@ -70,6 +70,11 @@ impl<'ctx> NDArrayObject<'ctx> { NDArrayObject { dtype, ndims, instance: value } } + /// Check if an object can be converted into an ndarray. + pub fn is_instance(ctx: &mut CodeGenContext<'ctx, '_>, object: AnyObject<'ctx>) -> bool { + matches!(&*ctx.unifier.get_ty(object.ty), TypeEnum::TObj { obj_id, .. } if *obj_id == ctx.primitives.ndarray.obj_id(&ctx.unifier).unwrap()) + } + /// Get this ndarray's `ndims` as an LLVM constant. pub fn ndims_llvm( &self, diff --git a/nac3core/src/codegen/object/tuple.rs b/nac3core/src/codegen/object/tuple.rs index 00e52a7e..792e5aca 100644 --- a/nac3core/src/codegen/object/tuple.rs +++ b/nac3core/src/codegen/object/tuple.rs @@ -44,6 +44,11 @@ impl<'ctx> TupleObject<'ctx> { TupleObject { tys: tys.clone(), value } } + /// Check if an object can be converted into a tuple. + pub fn is_instance(ctx: &mut CodeGenContext<'ctx, '_>, object: AnyObject<'ctx>) -> bool { + matches!(&*ctx.unifier.get_ty(object.ty), TypeEnum::TTuple { .. }) + } + /// Convenience function. Create a [`TupleObject`] from an iterator of objects. pub fn from_objects( generator: &mut G,