From 393380272cc25c11a20d3472f34825ccfd873293 Mon Sep 17 00:00:00 2001 From: GsLogimaker Date: Tue, 12 Dec 2023 15:20:39 -0600 Subject: [PATCH] Fix most warnings and remove some unused code --- Cargo.toml | 1 - qu/Cargo.toml | 3 +- qu/benches/vm_benchmark.rs | 15 +- qu/src/compiler.rs | 329 ++++--------------------------------- qu/src/errors.rs | 4 +- qu/src/import.rs | 22 +-- qu/src/lib.rs | 70 +++++--- qu/src/objects.rs | 133 +++------------ qu/src/parser.rs | 2 - qu/src/tokens.rs | 1 - qu/src/vm.rs | 46 +----- qube/Cargo.toml | 2 - 12 files changed, 122 insertions(+), 506 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4cec1aa..2e0adb5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,4 +29,3 @@ members = [ ] [workspace.dependencies] -lazy_static = "1.4.0" diff --git a/qu/Cargo.toml b/qu/Cargo.toml index cde8108..e6f11ee 100644 --- a/qu/Cargo.toml +++ b/qu/Cargo.toml @@ -31,10 +31,9 @@ edition = "2021" [dependencies] -lazy_static = { workspace = true } [dev-dependencies] -criterion = "0.4.0" +criterion = "0.5.1" [features] qu_panic_upon_error = [] diff --git a/qu/benches/vm_benchmark.rs b/qu/benches/vm_benchmark.rs index 1ec97b0..cf9ead5 100644 --- a/qu/benches/vm_benchmark.rs +++ b/qu/benches/vm_benchmark.rs @@ -5,21 +5,8 @@ use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; -use qu::Qu; -use qu::QuCompiler; -use qu::QuMsg; -use qu::QuOp; -use qu::QuStackId; - -fn speed(c: &mut Criterion) { - let mut qu = Qu::new(); - - let n1:QuStackId = 0.into(); - let nterms:QuStackId = 1.into(); - let n2:QuStackId = 2.into(); - let count:QuStackId = 3.into(); - let zero:QuStackId = 20.into(); +fn speed(_c: &mut Criterion) { } diff --git a/qu/src/compiler.rs b/qu/src/compiler.rs index 43b2afb..d866d7c 100644 --- a/qu/src/compiler.rs +++ b/qu/src/compiler.rs @@ -1,7 +1,6 @@ use crate::Class; use crate::ExternalFunction; -use crate::ExternalFunctionDefinition; use crate::Module; use crate::QuOp; use crate::QuOp::*; @@ -16,7 +15,10 @@ use crate::import::QuStruct; use crate::import::ClassId; use crate::import::Registerer; use crate::objects::Bool; +use crate::parser::KEYWORD_BOOL_FALSE; +use crate::parser::KEYWORD_BOOL_TRUE; use crate::parser::KEYWORD_IF; +use crate::parser::KEYWORD_WHILE; use crate::parser::QuOperator; use crate::parser::parsed::*; @@ -34,57 +36,6 @@ use std::hash::Hash; pub(crate) const CONSTRUCTOR_NAME:&str = ":new"; // TODO: Fix compiler's documentation -#[derive(Debug, Clone)] -pub struct ClassMetadata { - constants_map: HashMap, - external_functions_map: HashMap, - functions_map: HashMap, - - /// The name of this class. - name: String, - /// The ID of this class. - id: usize, -} impl Default for ClassMetadata { - fn default() -> Self { - Self { - name: "void".to_owned(), - constants_map: Default::default(), - external_functions_map: Default::default(), - functions_map: Default::default(), - id: Default::default(), - } - } -} - - -#[derive(Debug, Clone)] -enum CodeItem<'a> { - Class(&'a ClassMetadata), - Constant, - ExternalFunction(&'a ExternalFunction), - ExternalClass(&'a QuStruct), - Function(&'a FunctionMetadata), - Variable, -} impl<'a> From<&'a ModuleItem> for CodeItem<'a> { - fn from(value: &'a ModuleItem) -> Self { - match value { - ModuleItem::Class(class_metadata) => { - CodeItem::Class(&class_metadata) - }, - ModuleItem::Constant => { - CodeItem::Constant - }, - ModuleItem::Function(function_metadata) => { - CodeItem::Function(&function_metadata) - }, - ModuleItem::StaticVariable => { - CodeItem::Variable - }, - } - } -} - - pub type ConstantId = usize; @@ -144,7 +95,6 @@ struct Context { static_type, definitions, )?; self.variables.push(VariableMetadata { - name: name, stack_id, }); @@ -162,7 +112,6 @@ struct Context { static_type, definitions, )?; self.variables.push(VariableMetadata { - name: name, stack_id, }); @@ -183,7 +132,7 @@ struct Context { ContextFrame::Class(_, frame) => frame, ContextFrame::Function(_, frame) => frame, }; - let scope = frame.scopes.pop().unwrap(); + frame.scopes.pop().unwrap(); } @@ -283,7 +232,7 @@ struct Context { break 'frames Some(item); } }, - ContextFrame::Function(function_id, _) => { + ContextFrame::Function(_function_id, _) => { continue; }, } @@ -412,7 +361,7 @@ struct Context { } } }, - ContextFrame::Function(function_id, _) => { + ContextFrame::Function(_function_id, _) => { continue; }, } @@ -679,7 +628,7 @@ pub type RegistrationMethod = dyn Fn(&mut Registerer) -> Result<(), QuMsg>; pub struct Definitions { pub constants: GrowingStack, pub classes: Vec, - pub external_functions: Vec, + pub external_functions: Vec, pub functions: Vec, pub function_groups: Vec, pub modules: Vec, @@ -934,7 +883,7 @@ pub struct Definitions { *function_group_map.get(&identity.name).unwrap() }; - let mut group = &mut self.function_groups[group_id]; + let group = &mut self.function_groups[group_id]; if group.map.contains_key(&identity) { todo!("Return error here") } @@ -950,23 +899,9 @@ pub struct Definitions { self.find_class_id(::name()) } - - pub fn define_class_constant( - &mut self, - module: ModuleId, - class: &mut ClassMetadata, - name: String, - value: T, - ) -> ConstantId { - let constant_id = self.define_constant(module, value); - class.constants_map.insert(name, constant_id); - constant_id - } - - pub fn define_constant( &mut self, - module: ModuleId, + _module: ModuleId, value: T, ) -> ConstantId { let constant_id = self.constants.allocate(size_of::()); @@ -1016,7 +951,6 @@ pub struct Definitions { let function_id = self.functions.len(); self.functions.push(FunctionMetadata { identity: identity.clone(), - id: funciton_id, ..Default::default() }); @@ -1065,7 +999,6 @@ pub struct Definitions { let module_id = self.modules.len(); self.modules.push(ModuleMetadata { name: name.clone(), - id: module_id, ..Default::default() }); self.module_map.insert(name, module_id); @@ -1112,10 +1045,9 @@ pub struct Definitions { pub fn define_module_function( &mut self, - module_id: ModuleId, + _module_id: ModuleId, identity: FunctionIdentity, ) -> Result { - let class_id = identity.parameters.get(0); // TODO: Determin if static function mappings should be kept // if let Some(class_id) = class_id { @@ -1131,7 +1063,6 @@ pub struct Definitions { let id = FunctionId::from(self.functions.len()); self.functions.push(FunctionMetadata { - id, identity: identity, ..Default::default() }); @@ -1184,7 +1115,7 @@ pub struct Definitions { pub fn get_external_function( &self, id: ExternalFunctionId - ) -> Result<&ExternalFunctionDefinition, QuMsg> { + ) -> Result<&ExternalFunction, QuMsg> { let external_function = self.external_functions .get(usize::from(id)) .ok_or_else(|| -> QuMsg { format!( @@ -1296,20 +1227,7 @@ pub struct Definitions { } Ok(&mut self.modules[id]) } - - - fn get_module_class_id( - &self, module_id: ModuleId, class_name: &str, - ) -> Result { - let module = self.get_module(module_id)?; - let class_id = *module.class_map - .get(class_name) - .ok_or_else(|| -> QuMsg { format!( - "The module '{}' has no class names '{}'", module.name, class_name - ).into()})?; - Ok(class_id) - } - + fn get_module_constant_id( &self, module_id: ModuleId, name: &str, @@ -1414,7 +1332,7 @@ pub struct Definitions { pub fn register_function_in_module( &mut self, module_id: ModuleId, - external_function:ExternalFunctionDefinition, + external_function:ExternalFunction, ) -> Result<(), QuMsg> { // Get class id of first parameter let class_id = match external_function.parameters.first() { @@ -1462,7 +1380,7 @@ pub struct Definitions { pub fn register_static_function_in_class( &mut self, class_id: ClassId, - external_function:ExternalFunctionDefinition, + external_function:ExternalFunction, ) -> Result<(), QuMsg> { // Also register function with module. // self.add_static_external_function_mapping_in_class( @@ -1496,7 +1414,7 @@ pub struct Definitions { pub fn register_static_function_in_module( &mut self, module_id: ModuleId, - external_function:ExternalFunctionDefinition, + external_function:ExternalFunction, ) -> Result<(), QuMsg> { // Also register function with module. // self.add_static_external_function_mapping_in_module( @@ -1543,29 +1461,9 @@ pub struct Definitions { } -#[derive(Debug, Default, Clone)] -pub struct ExternalClassMetadata { - functions_map: HashMap, - /// The name of this class. - name: String, - /// The ID of this class. - id: usize, -} - - pub type ExternalFunctionId = usize; -#[derive(Debug, Default, Clone)] -pub struct ExternalFunctionMetadata { - functions_map: HashMap, - /// The name of this class. - name: String, - /// The ID of this class. - id: usize, -} - - #[derive(Debug, Clone)] struct FrameData { scopes: Vec, @@ -1649,21 +1547,12 @@ pub struct FunctionIdentity { #[derive(Debug, Default, Clone)] pub struct FunctionMetadata { - id: FunctionId, pub identity: FunctionIdentity, /// The value that the VM's program counter should be set to in order to /// start this function. pub code_block: usize, } - -#[derive(Debug, Default, Clone)] -pub struct FunctionIdentityMap { - map: HashMap>>, -} impl FunctionIdentityMap { -} - - #[derive(Debug, Default, Clone)] pub struct GrowingStack { allocated: usize, @@ -1696,17 +1585,6 @@ pub struct GrowingStack { pub type ModuleId = usize; - -#[derive(Debug, Default, Clone)] -/// An item that is owned by a Qu module. See [`ModuleMetadata`]. -enum ModuleItem { - Class(Box), - #[default] - Constant, - Function(Box), - StaticVariable, -} - #[derive(Debug, Clone)] /// Reresents a Qu module. pub struct ModuleMetadata { @@ -1719,8 +1597,6 @@ pub struct ModuleMetadata { /// The name of this module. name: String, - /// The ID of this module. - id: ModuleId, } impl ModuleMetadata { fn has_item(&self, identity: &str) -> bool { self.constants_map.contains_key(identity) @@ -1788,7 +1664,6 @@ pub struct ModuleMetadata { class_map: Default::default(), constants_map : Default::default(), name: "__main__".into(), - id : Default::default(), external_functions_map: Default::default(), functions_map: Default::default(), function_groups_map: Default::default(), @@ -2002,7 +1877,6 @@ type VariableId = usize; #[derive(Debug, Default, Clone)] struct VariableMetadata { - name: String, stack_id: QuStackId, } @@ -2011,12 +1885,10 @@ struct VariableMetadata { #[derive(Debug, Default, Clone)] pub struct QuCompiler { context: Context, - name_refs: HashMap, - types_map: HashMap, } impl QuCompiler { /// Creates and returns a new [QuCompiler]. pub fn new() -> Self { - let mut inst = Self { + let inst = Self { ..Default::default() }; @@ -2029,7 +1901,7 @@ pub struct QuCompiler { call_expression: &CallExpression, definitions: &mut Definitions, ) -> Result { - let mut caller_id = match &call_expression.caller { + let caller_id = match &call_expression.caller { Some(caller_expression) => { // Caller is inferred by dot notation self.get_expr_type(caller_expression, definitions)? @@ -2453,7 +2325,7 @@ pub struct QuCompiler { )?; let builder = match item { - ItemId::Class(id) => { + ItemId::Class(_) => { let mut builder = QuAsmBuilder::new(); builder.return_type = definitions.class_id::()?; builder @@ -2570,7 +2442,7 @@ pub struct QuCompiler { let code= { // --- Compile Pieces --- // Code block - let mut block_code = self.cmp_scope(body, definitions)?; + let block_code = self.cmp_scope(body, definitions)?; let block_code_len = block_code.len(); let mut b = QuAsmBuilder::new(); @@ -2773,11 +2645,6 @@ pub struct QuCompiler { body: &CodeScope, definitions: &mut Definitions, ) -> Result { - let needs_added_end_op = match body.code_block.statements.last() { - Some(Statement::Return(_)) => false, - _ => true, - }; - let (identity, parameters) = { let mut parameters_types = vec![]; let mut parameters_names = vec![]; @@ -2818,7 +2685,7 @@ pub struct QuCompiler { self.context.open_frame(ContextFrame::Function( func_id, FrameData::default(), )); - let mut body_code = { + let body_code = { // Allocate return value self.context.define_variable( "return value".into(), @@ -2847,10 +2714,7 @@ pub struct QuCompiler { definitions.get_function_mut(func_id)?.code_block = definitions .byte_code_blocks .len(); - let bytcode = body_code.compile( - &self.name_refs, - definitions - )?; + let bytcode = body_code.ops; definitions.byte_code_blocks.push(bytcode); let code = QuAsmBuilder::new(); @@ -3101,7 +2965,7 @@ pub struct QuCompiler { let code = self.cmp_code_block( code_block, definitions - )?.compile(&self.name_refs, definitions)?; + )?.ops; definitions.byte_code_blocks.push(code); Ok(QuAsmBuilder::new()) @@ -3220,15 +3084,12 @@ pub struct QuCompiler { &mut self, code_block:&CodeBlock, definitions: &mut Definitions ) -> Result, QuMsg> { // Main code - let mut code = { - let mut code = self.cmp_module(code_block, definitions)?; + let code = { + let code = self.cmp_module(code_block, definitions)?; Ok::(code) }?; - Ok(code.compile( - &self.name_refs, - definitions, - )?) + Ok(code.ops) } @@ -3309,7 +3170,7 @@ pub struct QuCompiler { Expression::Number(_) => { definitions.class_id::()? }, - Expression::Tuple(tuple) => { + Expression::Tuple(_tuple) => { unimplemented!() }, Expression::Var(var) => { @@ -3319,14 +3180,14 @@ pub struct QuCompiler { )?; let id = match item { - ItemId::Class(id) => { + ItemId::Class(_) => { definitions.class_id::()? }, ItemId::Constant(_) => todo!(), ItemId::ExternalFunction(_) => todo!(), ItemId::Function(_) => todo!(), ItemId::FunctionGroup(_) => todo!(), - ItemId::Module(id) => { + ItemId::Module(_) => { definitions.class_id::()? }, ItemId::StaticVariable(_) => todo!(), @@ -3402,151 +3263,29 @@ pub struct QuCompiler { } } - -#[derive(Debug, Clone)] -enum QuBuilderPiece { - ReprCall(String, QuStackId), - // Struct name, fn name, args, output - //ReprCallExt(String, Vec, QuStackId), - /// A [`Vec`] of code. - Ops(Vec), -} impl QuBuilderPiece { - fn len(&self) -> usize{ - match self { - QuBuilderPiece::ReprCall(_, _) => 1, - //QuBuilderPiece::ReprCallExt(_, _, _) => 1, - QuBuilderPiece::Ops(v) => v.len(), - } - } -} - - #[derive(Debug, Default, Clone)] struct QuAsmBuilder { - code_pieces: Vec, + ops: Vec, return_type: ClassId, } impl QuAsmBuilder { fn new() -> Self { return Self { - code_pieces: vec![], + ops: vec![], return_type: ClassId::new(0), } } - - - /// Adds a builder piece - fn add_bp(&mut self, repr:QuBuilderPiece) { - self.code_pieces.push(repr); - } - fn add_builder(&mut self, mut builder:QuAsmBuilder) { - self.code_pieces.append(&mut builder.code_pieces); + self.ops.append(&mut builder.ops); } fn add_op(&mut self, op:QuOp) { - self.code_pieces.push(QuBuilderPiece::Ops(vec![op])); - } - - - fn add_ops(&mut self, ops:Vec) { - self.code_pieces.push(QuBuilderPiece::Ops(ops)); - } - - - fn compile( - &mut self, - name_references: &HashMap, - definitions: &mut Definitions, - ) -> Result, QuMsg> { - let mut code = vec![]; - - for x in &mut self.code_pieces { - match x { - QuBuilderPiece::Ops(ops) => code.append(ops), - QuBuilderPiece::ReprCall( - name, - output, - ) => { - let Some(fn_index) = name_references.get(name) else { - panic!("Compiler could not find a function by name {name}."); - }; - panic!(); - //code.push(Call((*fn_index).into(), *output)); - } -// QuBuilderPiece::ReprCallExt( -// fn_name, -// args, -// output -// ) => { -// // TODO: Implement static typing -// let struct_data = definitions.get_class( -// args.get(0) -// .unwrap_or(&QuStackId::from(0)) -// .class_id() -// )?; -// -// let id -// = struct_data.get_fn_id(fn_name)?; -// code.push(CallExt(id, take(args), *output)); -// }, - }; - } - - - return Ok(code); + self.ops.push(op); } - fn len(&self) -> usize { - let mut l = 0; - for x in &self.code_pieces { - l += x.len(); - } - return l; + return self.ops.len(); } -} - - -#[derive(Debug, Default, Clone)] -struct QuVarIdentity { - name: String, - static_type: String, - stack_id: QuStackId, -} impl QuVarIdentity { - - fn new(name:String, static_type:String, id:QuStackId) -> Self { - QuVarIdentity{name, static_type, stack_id: id} - } - - - fn object_id(&self) -> ClassId { - self.stack_id.class_id() - } - -} impl PartialEq for QuVarIdentity { - fn eq(&self, other:&str) -> bool { - &self.name == other - } -} - - -pub enum CompilerInstruction { - // (fn_name, args, result_variable) - CallExt(FunctionIdentity, Vec, String), - CloseFrame, - CloseScope, - // (name, body_size) - DefineFn(String, usize), - // (name, type) - DefineVariable(String, String), - End, - JumpBy(isize), - JumpByIfNot(isize), - OpenFrame, - OpenScope, - // (var_name) - Return(String), -} +} \ No newline at end of file diff --git a/qu/src/errors.rs b/qu/src/errors.rs index 661d001..90e41a9 100644 --- a/qu/src/errors.rs +++ b/qu/src/errors.rs @@ -1,6 +1,6 @@ -use crate::{tokens::QuCharIndex}; -use std::{fmt::{self, Display, Debug}}; +use crate::tokens::QuCharIndex; +use std::fmt::{self, Display, Debug}; pub const ERR_TITLE_EMPTY_CODE_BLOCK:&str = "EMPTY CODE BLOCK"; diff --git a/qu/src/import.rs b/qu/src/import.rs index 808bea1..6839152 100644 --- a/qu/src/import.rs +++ b/qu/src/import.rs @@ -1,20 +1,13 @@ use std::collections::HashMap; use std::fmt::Debug; -use std::fmt::format; use std::mem::size_of; -use std::process::id; -use std::slice::SliceIndex; use crate::ExternalFunction; -use crate::ExternalFunctionDefinition; -use crate::Module; use crate::QuMsg; use crate::QuRegisterStruct; use crate::QuStackId; use crate::QuVm; -use crate::QuVoid; -use crate::Vector2; use crate::compiler::ConstantId; use crate::compiler::Definitions; use crate::compiler::ExternalFunctionId; @@ -22,7 +15,6 @@ use crate::compiler::FunctionGroupId; use crate::compiler::FunctionId; use crate::compiler::FunctionIdentity; use crate::compiler::ItemId; -use crate::compiler::FunctionGroup; use crate::compiler::ModuleId; use crate::compiler::ModuleMetadata; use crate::compiler::SomeFunctionId; @@ -69,7 +61,7 @@ pub struct ModuleBuilder<'a> { out: ClassId, body: &'static ExternalFunctionPointer, ) -> Result<(), QuMsg> { - self.definitions.register_function_in_module(self.module_id, ExternalFunctionDefinition { + self.definitions.register_function_in_module(self.module_id, ExternalFunction { name: name.into(), pointer: body, parameters: Vec::from(args), @@ -88,7 +80,7 @@ pub struct ModuleBuilder<'a> { ) -> Result<(), QuMsg> { self.definitions.register_static_function_in_class( for_class, - ExternalFunctionDefinition { + ExternalFunction { name: name.into(), pointer: body, parameters: Vec::from(args), @@ -145,7 +137,9 @@ pub struct QuRegistered { } - pub fn get_fn_data_by_id(&self, fn_id:FunctionId + pub fn get_fn_data_by_id( + &self, + fn_id:FunctionId ) -> Result<&ExternalFunction, QuMsg>{ match self.fns.get(fn_id) { Some(v) => Ok(v), @@ -276,14 +270,14 @@ pub struct QuStruct { pub static_functions_map: HashMap, pub name: String, - pub register_fn: &'static dyn Fn(&mut Definitions) -> Vec, + pub register_fn: &'static dyn Fn(&mut Definitions) -> Vec, /// The size of the struct in bytes. pub size: u8, } impl QuStruct { pub fn new( name:impl Into, - fn_registerer:&'static dyn Fn(&mut Definitions) -> Vec, + fn_registerer:&'static dyn Fn(&mut Definitions) -> Vec, size:usize, ) -> Self { let name = name.into(); @@ -362,7 +356,7 @@ pub struct QuStruct { external_functions_map: Default::default(), functions_map: Default::default(), name: Default::default(), - register_fn: &|definitions:&mut Definitions| {vec![]}, + register_fn: &|_d:&mut Definitions| {vec![]}, size: Default::default(), function_groups_map: Default::default(), static_functions_map: Default::default(), diff --git a/qu/src/lib.rs b/qu/src/lib.rs index 79345a6..33ce1cb 100644 --- a/qu/src/lib.rs +++ b/qu/src/lib.rs @@ -28,8 +28,6 @@ SOFTWARE. #![warn(missing_docs)] #![warn(rustdoc::broken_intra_doc_links)] -extern crate lazy_static; - mod compiler; mod errors; mod import; @@ -73,6 +71,7 @@ pub use vm::QuStackId; /// # return Ok(()); /// # } /// ``` +#[derive(Default)] pub struct Qu<'a> { vm: QuVm, ph: PhantomData<&'a ()>, @@ -95,8 +94,9 @@ pub struct Qu<'a> { } } - - /// Compiles Qu script into a [`Vec`]. + /// Compiles Qu script without running it. + /// + /// Does not return the compiled bytecode. /// /// # Errors /// @@ -110,15 +110,20 @@ pub struct Qu<'a> { /// # fn main(){example().unwrap()} /// # fn example() -> Result<(), qu::QuMsg> { /// let mut qu = Qu::new(); - /// let bytecode = qu.compile("var count int = 0")?; + /// qu.compile(" + /// fn foo() int: + /// return 3 + /// ")?; + /// let result:i32 = *qu.run_and_get("return foo()")?; + /// assert_eq!(result, 3); /// # return Ok(()); /// # } /// ``` - pub fn compile(&mut self, code:&str) -> Result, QuMsg> { + pub fn compile(&mut self, code:&str) -> Result<(), QuMsg> { // Compile let mut c = QuCompiler::new(); - let code = c.compile(code, &mut self.vm.definitions)?; - return Ok(code); + c.compile(code, &mut self.vm.definitions)?; + Ok(()) } @@ -172,15 +177,7 @@ pub struct Qu<'a> { } - /// - pub fn read<'b, T:'a + QuRegisterStruct>( - &self, at_reg:QuStackId - ) -> Result<&T, QuMsg> { - self.vm.read::(at_reg) - } - - - /// Runs [`&str`] as Qu script. + /// Run a [`&str`] as Qu script. /// /// # Errors /// @@ -202,20 +199,43 @@ pub struct Qu<'a> { /// # } /// ``` pub fn run(&mut self, script:&str) -> Result<(), QuMsg> { - let code = self.compile(script)?; + self.compile(script)?; self.vm.loop_ops(self.vm.definitions.byte_code_blocks.len()-1) } + /// Run a [`&str`] as Qu script and get the result. + /// + /// This is evuivalent to running [`Qu::run`] followed + /// by [`Qu::get_result`]. + /// + /// # Errors + /// + /// If `code` contains improper syntax or a problem occurs at runtime + /// then an [`Err`] is returned. + /// + /// # Example + /// + /// ``` + /// # use qu::QuMsg; + /// # fn main(){example().unwrap()} + /// # fn example() -> Result<(), QuMsg> { + /// use qu::Qu; + /// + /// let mut qu = Qu::new(); + /// + /// let value:i32 = *qu.run_and_get("return 5 + 6")?; + /// assert_eq!(value, 5 + 6); + /// # return Ok(()); + /// # } + /// ``` pub fn run_and_get( &mut self, script:&str, ) -> Result<&T, QuMsg> { self.run(script)?; let return_id = self.vm.return_value_id(); - self.read( - QuStackId::new(0, return_id) - ) + self.vm.read::(QuStackId::new(0, return_id)) } } @@ -457,8 +477,7 @@ mod lib { var counter void return counter "#; - - let res:i32 = *qu.run_and_get(script).unwrap(); + qu.run_and_get::(script).unwrap(); } @@ -543,7 +562,7 @@ mod lib { // #[test] // TODO: Allow accessing functions from class name (Requires constant evaluation) - fn class_dot_notation() { + fn _class_dot_notation() { let mut qu = Qu::new(); let result:i32 = *qu.run_and_get("return int.sub(5, 8)").unwrap(); assert_eq!(result, 5-8); @@ -648,7 +667,8 @@ mod lib { // TODO: Prevent functions definitions from having multiple parameters of // the same name // #[test] - fn function_multiple_parameters_same_name() { + // #[should_panic] + fn _function_multiple_parameters_same_name() { let mut qu = Qu::new(); let script = r#" fn some(a int, a int, c int) int: diff --git a/qu/src/objects.rs b/qu/src/objects.rs index 952ebff..08bc359 100644 --- a/qu/src/objects.rs +++ b/qu/src/objects.rs @@ -1,8 +1,6 @@ //! Defines all types and objects used by Qu. - -use crate::QuVm; use crate::QuMsg; use crate::compiler::CONSTRUCTOR_NAME; use crate::compiler::Definitions; @@ -13,7 +11,6 @@ use crate::import::ExternalFunctionPointer; use crate::import::Registerer; use crate::vm::QuExtFn; use crate::vm::QuVoidExtFn; -use crate::vm::QuStackId; use std::fmt::Debug; use std::ops::Add; use std::ops::Div; @@ -70,7 +67,7 @@ pub fn fundamentals_module(registerer: &mut Registerer) -> Result<(), QuMsg> { // void functions { - qufn!(m, api, copy(void) void { + qufn!(m, _api, copy(void) void { Ok(()) }); } @@ -243,12 +240,13 @@ pub fn fundamentals_module(registerer: &mut Registerer) -> Result<(), QuMsg> { Ok(()) } +/// A method for registering the math module in Qu. pub fn math_module(registerer: &mut Registerer) -> Result<(), QuMsg> { registerer.add_module( "math", &|m| { - let vector2 = m.add_class::()?; - let fundamentals = m.get_module(FUNDAMENTALS_MODULE)?; + let fundamentals = + m.get_module(FUNDAMENTALS_MODULE)?; let int = fundamentals.get_class_id("int")?; m.add_function( "foo", @@ -274,66 +272,30 @@ pub type QuExtFnData = (String, QuExtFn, Vec, usize); pub type QuVoidFnForm = (String, QuVoidExtFn, Vec); +/// A reference to a Qu class. #[derive(Debug, Default, Clone, Copy)] pub struct Class { - id: ClassId, + _id: ClassId, } impl QuRegisterStruct for Class { fn name() -> &'static str {"__Class__"} } +/// Defines information about an external function that can be sued by Qu. #[derive(Clone)] pub struct ExternalFunction { + /// The name of the function. + /// + /// This is the name used when calling this function from a Qu script. pub name: String, - pub pointer: QuExtFn, - pub parameters: Vec, - pub return_type: ClassId, -} impl ExternalFunction { - pub fn new( - name: &str, - pointer: QuExtFn, - parameters: Vec, - return_type: ClassId, - ) -> Self{ - Self { - name: name.into(), - pointer, - parameters: parameters, - return_type, - } - } - - - pub fn call( - &self, vm:&mut QuVm, parameters: &Vec, output_id: QuStackId, - ) -> Result<(), QuMsg> { - (self.pointer)(vm, parameters, output_id) - } -} impl Debug for ExternalFunction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ExternalFunction") - .field("name", &self.name) - .field("parameters", &self.parameters) - .field("return_type", &self.return_type) - .finish() - } -} impl Default for ExternalFunction { - fn default() -> Self { - Self { - pointer: &|_, _, _| {Ok(())}, - ..Default::default() - } - } -} - - -#[derive(Clone)] -pub struct ExternalFunctionDefinition { - pub name: String, + /// The pointer to the function. pub pointer: &'static ExternalFunctionPointer, + /// The arguments this function takes. pub parameters: Vec, + /// The return type of the function. pub return_type: ClassId, -} impl ExternalFunctionDefinition { +} impl ExternalFunction { + /// Instantiates a new [`ExternalFunctionDefinition`]. pub fn new( name: &str, pointer: &'static ExternalFunctionPointer, @@ -347,7 +309,7 @@ pub struct ExternalFunctionDefinition { return_type, } } -} impl Debug for ExternalFunctionDefinition { +} impl Debug for ExternalFunction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ExternalFunctionDefinition") .field("name", &self.name) @@ -355,7 +317,7 @@ pub struct ExternalFunctionDefinition { .field("return_type", &self.return_type) .finish() } -} impl Default for ExternalFunctionDefinition { +} impl Default for ExternalFunction { fn default() -> Self { Self { name: Default::default(), @@ -367,49 +329,14 @@ pub struct ExternalFunctionDefinition { } - -#[derive(Debug, Default, Clone)] -pub struct FunctionPointer { - pub pc_target: usize, -} - - +/// A reference to a Qu module. #[derive(Debug, Default, Clone, Copy)] -pub struct Module { - id: ModuleId, +pub struct Module { // TODO: Lock modules to the vm they came from. + _id: ModuleId, } impl QuRegisterStruct for Module { fn name() -> &'static str {"__Module__"} } - -/// Defines all the types supported by Qu. -#[derive(Debug, Default, Clone)] -pub enum QuType { - #[default] Void, - Int, - Bool, - String, - Tuple(Vec), - Array, - Dictionary, - Object(usize), -} impl From for QuType { - - fn from(f:u8) -> Self { - match f { - 0 => QuType::Void, - 1 => QuType::Int, - 2 => QuType::Bool, - 3 => QuType::String, - 4 => panic!(),//QuType::Tuple(Vec::default()), - 5 => QuType::Array, - 6 => QuType::Dictionary, - 7 => QuType::Object(0), - _ => panic!(), - } - } -} - /// Defines a block of code. /// /// Often used for Qu functions. @@ -460,6 +387,7 @@ pub struct QuFnObject { } +/// A wrapper for Qu booleans. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Bool (bool, bool, bool, bool); impl Bool { @@ -483,8 +411,8 @@ impl Bool { } } impl QuRegisterStruct for Bool { fn register_fns( - definitions: &mut Definitions - ) -> Vec {vec![]} + _definitions: &mut Definitions + ) -> Vec {vec![]} fn name() -> &'static str {"bool"} } @@ -500,7 +428,6 @@ impl QuRegisterStruct for i32 { } - #[derive(Debug, Default, Clone, Copy)] /// Represents a void type in Qu. pub struct QuVoid(); @@ -513,8 +440,8 @@ impl QuRegisterStruct for QuVoid { pub trait QuRegisterStruct { /// Returns functions that are callable by [`QuVm`]. fn register_fns( - definitions: &mut Definitions - ) -> Vec where Self: Sized { + _definitions: &mut Definitions + ) -> Vec where Self: Sized { Vec::default() } @@ -523,16 +450,6 @@ pub trait QuRegisterStruct { fn name() -> &'static str; } - -#[derive(Copy, Clone, Debug, Default)] -pub struct Vector2 { - x: i32, - y: i32, -} impl QuRegisterStruct for Vector2 { - fn name() -> &'static str {"Vector2"} -} - - #[cfg(test)] mod test_objects { diff --git a/qu/src/parser.rs b/qu/src/parser.rs index a17e994..142696a 100644 --- a/qu/src/parser.rs +++ b/qu/src/parser.rs @@ -1,6 +1,4 @@ -use std::convert::identity; -use std::fmt::format; use std::vec; use crate::errors; diff --git a/qu/src/tokens.rs b/qu/src/tokens.rs index f53de1b..ba3c0c2 100644 --- a/qu/src/tokens.rs +++ b/qu/src/tokens.rs @@ -9,7 +9,6 @@ use crate::parser::KEYWORD_CLASS; use crate::parser::KEYWORD_IF; use crate::parser::KEYWORD_ELSE; use crate::parser::KEYWORD_ELIF; -use crate::parser::QuOperator; pub const TOKEN_TYPE_KEYWORD:u8 = 1; diff --git a/qu/src/vm.rs b/qu/src/vm.rs index 48f2879..1d8d136 100644 --- a/qu/src/vm.rs +++ b/qu/src/vm.rs @@ -1,32 +1,14 @@ -use std::collections::HashSet; use std::fmt::Debug; -use std::hash::Hash; use std::mem::size_of; -use std::sync::Arc; -use core::ops::Deref; -use std::sync::Mutex; -use std::sync::RwLock; -use std::sync::Weak; - -use lazy_static::__Deref; - -use crate::Bool; -use crate::Class; -use crate::ExternalFunctionDefinition; -use crate::Module; use crate::QuMsg; use crate::QuRegisterStruct; -use crate::QuVoid; -use crate::Vector2; use crate::compiler::Definitions; use crate::compiler::ExternalFunctionId; use crate::compiler::FunctionId; -use crate::import; use crate::import::ArgsAPI; use crate::import::ClassId; -use crate::objects; use crate::objects::fundamentals_module; use crate::objects::math_module; @@ -51,8 +33,7 @@ pub enum QuOp { Call(FunctionId, QuStackId), /// Calls a function defined outside of Qu (like in Rust). CallExt(ExternalFunctionId, Vec, QuStackId), - // Fn name, fn body length. (DEPCRICATED) - DefineFn(FunctionId, usize), + /// Ends the current scope End, /// Moves the program counter by the given [`isize`]. JumpBy(isize), @@ -75,8 +56,6 @@ pub enum QuOp { arg2, ) => write!(f, "CallExt({:?}, {:?}, {:?})", arg0, arg1, arg2,), - Self::DefineFn(arg0, arg1) => - write!(f, "DefineFn({:?}, {:?})", arg0, arg1), Self::End => write!(f, "End"), Self::JumpBy(arg0) => @@ -153,7 +132,7 @@ impl QuStackId { } /// Returns a readable [`String`] representation of the Id. - fn readable(&self, definitions: &Definitions) -> String { + fn _readable(&self, definitions: &Definitions) -> String { format!( "{}:{}", self.0, @@ -249,7 +228,7 @@ pub struct QuVm { vm.definitions.define_module( MAIN_MODULE.into(), - &|mut b| {Ok(())}, + &|_| {Ok(())}, ).unwrap(); vm @@ -315,18 +294,6 @@ pub struct QuVm { return Ok(()); } - - /// Sets the start of the function with the given function_id to the - /// current program counter. - fn op_define_fn(&mut self, function_id: usize, length: usize) { - todo!("Define functions with code_block rather than pc_start"); - // self.definitions.get_function_mut(function_id) - // .unwrap() - // .pc_start = self.pc; - // self.pc += length; - } - - fn op_jump_by(&mut self, mut pc:usize, by:isize) -> usize { // Add if by > 0 { @@ -429,7 +396,7 @@ pub struct QuVm { .unwrap() .identity .name, - output.readable(&self.definitions), + output._readable(&self.definitions), ); }, QuOp::CallExt(function_id, args, output) => { @@ -449,7 +416,7 @@ pub struct QuVm { .get_external_function(*function_id) .unwrap() .name, - output.readable(&self.definitions), + output._readable(&self.definitions), ); }, QuOp::End => { @@ -482,7 +449,7 @@ pub struct QuVm { println!( "Value {} -> {}", value, - output.readable(&self.definitions), + output._readable(&self.definitions), ); }, QuOp::Return(return_type) => { @@ -497,7 +464,6 @@ pub struct QuVm { QuOp::Call(fn_id, ouput) => self.op_call_fn(*fn_id, *ouput)?, QuOp::CallExt(fn_id, args, output) => self.external_call_by_id(*fn_id, args.clone(), *output)?, QuOp::End => break, - QuOp::DefineFn(fn_id, length) => self.op_define_fn(*fn_id, *length), QuOp::JumpByIfNot(by) => pc = self.op_jump_by_if_not(pc, *by), QuOp::JumpBy( by) => pc = self.op_jump_by(pc, *by), QuOp::Value(value, output) => self.op_load_int(*value, *output), diff --git a/qube/Cargo.toml b/qube/Cargo.toml index c2d023e..465bc8a 100644 --- a/qube/Cargo.toml +++ b/qube/Cargo.toml @@ -29,9 +29,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -lazy_static = { workspace = true } qu = { path="../qu" } [dev-dependencies] -criterion = "0.4.0"