From b2733aa171a4aa5546c5388e4a21f7488aadd721 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 27 Jul 2024 18:43:03 -0500 Subject: [PATCH] cl-interpret/builtin: Add `len` builtin as a quick hack to write more interesting programs. This is temporary, I just want a way to get the length of a thing atm. --- compiler/cl-interpret/src/builtin.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/compiler/cl-interpret/src/builtin.rs b/compiler/cl-interpret/src/builtin.rs index 8c28d26..2ac205b 100644 --- a/compiler/cl-interpret/src/builtin.rs +++ b/compiler/cl-interpret/src/builtin.rs @@ -10,6 +10,7 @@ use cl_ast::Sym; use std::{ io::{stdout, Write}, rc::Rc, + slice, }; builtins! { @@ -57,6 +58,19 @@ builtins! { println!("{}", *env); Ok(ConValue::Empty) } + + pub fn len(list) -> IResult { + Ok(ConValue::Int(match list { + ConValue::Empty => 0, + ConValue::String(s) => s.chars().count() as _, + ConValue::Ref(r) => return len.call(env, slice::from_ref(r.as_ref())), + ConValue::Array(t) => t.len() as _, + ConValue::Tuple(t) => t.len() as _, + ConValue::RangeExc(start, end) => (end - start) as _, + ConValue::RangeInc(start, end) => (end - start + 1) as _, + _ => Err(Error::TypeError)?, + })) + } } builtins! { const BINARY;