From d514a05af1e7249412b3ecd257cd4673db3cd14b Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 29 Apr 2019 12:43:58 +0200 Subject: =?UTF-8?q?Make=20parse=20tokens=20more=20static=20and=20efficient?= =?UTF-8?q?=20=F0=9F=97=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/func.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) (limited to 'src/func.rs') diff --git a/src/func.rs b/src/func.rs index d85d7a18..d90cd85e 100644 --- a/src/func.rs +++ b/src/func.rs @@ -4,16 +4,12 @@ use std::any::Any; use std::collections::HashMap; use std::fmt::Debug; -use crate::syntax::{Token, FuncHeader, Expression}; -use crate::parsing::ParseResult; +use crate::syntax::{FuncHeader, Expression}; +use crate::parsing::{ParseTokens, ParseResult}; -/// An optional iterator over the tokens of a function body. -pub type BodyTokens<'a> = Option> + 'a>>; - /// Parser functions. -pub type ParseFunc = dyn Fn(&FuncHeader, BodyTokens<'_>, &Scope) - -> ParseResult>; +pub type ParseFunc = dyn Fn(ParseContext) -> ParseResult>; /// Types that act as functions. /// @@ -24,8 +20,7 @@ pub type ParseFunc = dyn Fn(&FuncHeader, BodyTokens<'_>, &Scope) /// used as functions, that is they fulfill the bounds `Debug + PartialEq + 'static`. pub trait Function: FunctionBounds { /// Parse the function. - fn parse(header: &FuncHeader, tokens: BodyTokens<'_>, scope: &Scope) - -> ParseResult where Self: Sized; + fn parse(context: ParseContext) -> ParseResult where Self: Sized; /// Execute the function and optionally yield a return value. fn typeset(&self, header: &FuncHeader) -> Option; @@ -46,7 +41,7 @@ impl Scope { pub fn add(&mut self, name: &str) { self.parsers.insert( name.to_owned(), - Box::new(|header, tokens, scope| match F::parse(header, tokens, scope) { + Box::new(|context| match F::parse(context) { Ok(func) => Ok(Box::new(func)), Err(err) => Err(err), }) @@ -59,6 +54,16 @@ impl Scope { } } +/// The context for parsing a function. +pub struct ParseContext<'s, 't> { + /// The header of the function to be parsed. + pub header: &'s FuncHeader, + /// Tokens if the function has a body, otherwise nothing. + pub tokens: Option<&'s mut ParseTokens<'t>>, + /// The current scope containing function definitions. + pub scope: &'s Scope, +} + /// A helper trait that describes requirements for types that can implement [`Function`]. /// /// Automatically implemented for all types which fulfill to the bounds -- cgit v1.2.3