From 7206d60ac91135e698a84c77d34911647c76624b Mon Sep 17 00:00:00 2001 From: Jeff Date: Fri, 13 Oct 2023 13:53:00 -0400 Subject: [PATCH] Add random tools --- src/abstract_tree/function_call.rs | 2 ++ src/abstract_tree/tool.rs | 21 +++++++++++++++++++++ src/error.rs | 2 +- tree-sitter-dust | 2 +- 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/abstract_tree/function_call.rs b/src/abstract_tree/function_call.rs index 5b51257..f2bf6c2 100644 --- a/src/abstract_tree/function_call.rs +++ b/src/abstract_tree/function_call.rs @@ -33,6 +33,8 @@ impl AbstractTree for FunctionCall { "assert" => Tool::Assert, "assert_equal" => Tool::AssertEqual, "output" => Tool::Output, + "random" => Tool::Random, + "random_integer" => Tool::RandomInteger, "read" => Tool::Read, "help" => Tool::Help, _ => panic!("Tool name not recognized."), diff --git a/src/abstract_tree/tool.rs b/src/abstract_tree/tool.rs index 3b8a5c0..5b2e5df 100644 --- a/src/abstract_tree/tool.rs +++ b/src/abstract_tree/tool.rs @@ -1,5 +1,6 @@ use std::fs::read_to_string; +use rand::{random, thread_rng, Rng}; use serde::{Deserialize, Serialize}; use crate::{Error, Result, Table, Value}; @@ -9,8 +10,10 @@ pub enum Tool { Assert, AssertEqual, Output, + Random, Read, Help, + RandomInteger, } impl Tool { @@ -62,6 +65,24 @@ impl Tool { Value::Empty } + Tool::Random => todo!(), + Tool::RandomInteger => { + if values.len() == 0 { + Value::Integer(random()) + } else if values.len() == 2 { + let range = values[0].as_int()?..values[1].as_int()?; + let mut rng = thread_rng(); + let random = rng.gen_range(range); + + Value::Integer(random) + } else { + return Err(Error::ExpectedToolArgumentAmount { + tool_name: "random_integer", + expected: 2, + actual: values.len(), + }); + } + } Tool::Read => { if values.len() != 1 { return Err(Error::ExpectedToolArgumentAmount { diff --git a/src/error.rs b/src/error.rs index da10d53..cb1eb8b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,7 +1,7 @@ //! Error and Result types. //! //! To deal with errors from dependencies, either create a new error variant -//! or use the MacroFailure variant if the error can only occur inside a macro. +//! or use the ToolFailure variant if the error can only occur inside a tool. use crate::{value::Value, Identifier}; diff --git a/tree-sitter-dust b/tree-sitter-dust index 0b6c6b7..7021c7f 160000 --- a/tree-sitter-dust +++ b/tree-sitter-dust @@ -1 +1 @@ -Subproject commit 0b6c6b7e25e137c8d5ad09d19584d028a371fd16 +Subproject commit 7021c7f7894b54ddf8c46c91477613b3071819a4