Cleaned up context argument

pull/2/head
Mark 2023-08-16 22:33:38 -07:00
parent 22935957e2
commit d31fd0b08c
Signed by: Mark
GPG Key ID: AD62BB059C2AAEE4
14 changed files with 115 additions and 111 deletions

View File

@ -44,8 +44,8 @@ fn greeter() -> FormattedText {
#[inline(always)] #[inline(always)]
pub fn do_command( pub fn do_command(
context: &mut Context,
s: &String, s: &String,
context: &mut Context
) -> FormattedText { ) -> FormattedText {
let args: Vec<&str> = s.split(" ").collect(); let args: Vec<&str> = s.split(" ").collect();
let first = args[0]; let first = args[0];
@ -230,7 +230,7 @@ pub fn do_command(
} }
let v = args[1].to_string(); let v = args[1].to_string();
let v = substitute(&v, context); let v = substitute(context, &v);
let r = context.delete(&v); let r = context.delete(&v);
return match r { return match r {

View File

@ -84,10 +84,10 @@ impl Context {
} }
pub fn is_varible(&self, s: &str) -> bool { pub fn is_varible(&self, s: &str) -> bool {
return self.valid_varible(s) && ( return {
self.variables.contains_key(s) || self.valid_varible(s) &&
self.shadow.contains_key(s) (self.variables.contains_key(s) || self.shadow.contains_key(s))
); };
} }
pub fn get_variables(&self) -> &HashMap<String, Expression> { pub fn get_variables(&self) -> &HashMap<String, Expression> {

View File

@ -37,9 +37,9 @@ impl PromptBuffer {
} }
// Same as write_primpt, but pretends there is no cursor // Same as write_primpt, but pretends there is no cursor
pub fn write_prompt_nocursor(&mut self, stdout: &mut RawTerminal<std::io::Stdout>, context: &Context) -> Result<(), std::io::Error> { pub fn write_prompt_nocursor(&mut self, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
// Draw prettyprinted expression // Draw prettyprinted expression
let (_, s) = substitute_cursor(&self.get_contents(), self.buffer.chars().count(), context); let (_, s) = substitute_cursor(context, &self.get_contents(), self.buffer.chars().count());
write!( write!(
stdout, "\r{}{}==>{}{} {}", stdout, "\r{}{}==>{}{} {}",
@ -64,12 +64,12 @@ impl PromptBuffer {
return Ok(()); return Ok(());
} }
pub fn write_prompt(&mut self, stdout: &mut RawTerminal<std::io::Stdout>, context: &Context) -> Result<(), std::io::Error> { pub fn write_prompt(&mut self, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
let l = self.buffer.chars().count(); let l = self.buffer.chars().count();
let i = if l == 0 {0} else {l - self.cursor}; let i = if l == 0 {0} else {l - self.cursor};
// Draw prettyprinted expression // Draw prettyprinted expression
let (display_cursor, s) = substitute_cursor(&self.get_contents(), i, context); let (display_cursor, s) = substitute_cursor(context, &self.get_contents(), i);
write!( write!(
stdout, "\r{}{}==>{}{} {}", stdout, "\r{}{}==>{}{} {}",

View File

@ -24,8 +24,8 @@ pub fn main() -> Result<(), std::io::Error> {
// Handle command-line arguments // Handle command-line arguments
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.iter().any(|s| s == "--help") { if args.iter().any(|s| s == "--help") {
let t = command::do_command(&String::from("help"), &mut context); let t = command::do_command(&mut context, &String::from("help"));
t.write(&mut stdout)?; t.write(&context, &mut stdout)?;
return Ok(()); return Ok(());
} else if args.iter().any(|s| s == "--version") { } else if args.iter().any(|s| s == "--version") {
write!(stdout, "Daisy v{}\r\n", env!("CARGO_PKG_VERSION"))?; write!(stdout, "Daisy v{}\r\n", env!("CARGO_PKG_VERSION"))?;
@ -34,7 +34,7 @@ pub fn main() -> Result<(), std::io::Error> {
'outer: loop { 'outer: loop {
pb.write_prompt(&mut stdout, &context)?; pb.write_prompt(&mut context, &mut stdout)?;
let stdin = stdin(); let stdin = stdin();
for c in stdin.keys() { for c in stdin.keys() {
@ -43,7 +43,7 @@ pub fn main() -> Result<(), std::io::Error> {
'\n' => { '\n' => {
// Print again without cursor, in case we pressed enter // Print again without cursor, in case we pressed enter
// while inside a substitution // while inside a substitution
pb.write_prompt_nocursor(&mut stdout, &context)?; pb.write_prompt_nocursor(&mut context, &mut stdout)?;
let in_str = pb.enter(); let in_str = pb.enter();
write!(stdout, "\r\n")?; write!(stdout, "\r\n")?;
if in_str == "" { break; } if in_str == "" { break; }
@ -51,11 +51,11 @@ pub fn main() -> Result<(), std::io::Error> {
if in_str.trim() == "quit" { if in_str.trim() == "quit" {
break 'outer; break 'outer;
} else { } else {
let r = crate::do_string(&in_str, &mut context); let r = crate::do_string(&mut context, &in_str);
match r { match r {
Ok(t) | Err(t) => { Ok(t) | Err(t) => {
t.write(&mut stdout).unwrap(); t.write(&context, &mut stdout).unwrap();
} }
} }
} }
@ -79,7 +79,7 @@ pub fn main() -> Result<(), std::io::Error> {
}; };
}; };
pb.write_prompt(&mut stdout, &context)?; pb.write_prompt(&mut context, &mut stdout)?;
} }
} }

View File

@ -9,8 +9,8 @@ use super::function::eval_function;
pub fn evaluate( pub fn evaluate(
t: &Expression, context: &mut Context,
context: &mut Context t: &Expression
) -> Result< ) -> Result<
Expression, Expression,
(LineLocation, DaisyError) (LineLocation, DaisyError)
@ -51,7 +51,7 @@ pub fn evaluate(
let new = match g { let new = match g {
Expression::Quantity(_, _) => None, Expression::Quantity(_, _) => None,
Expression::Tuple(_, _) => None, Expression::Tuple(_, _) => None,
Expression::Constant(_, c) => { Some(evaluate(&c.value(), context).unwrap()) }, Expression::Constant(_, c) => { Some(evaluate(context, &c.value()).unwrap()) },
Expression::Variable(l, s) => { Expression::Variable(l, s) => {
// Don't move up, re-evaluate // Don't move up, re-evaluate
// This makes variables containing floating variables work properly // This makes variables containing floating variables work properly
@ -64,7 +64,7 @@ pub fn evaluate(
context.get_variable(&s) context.get_variable(&s)
}, },
Expression::Operator(_, Operator::Function(_), _) => { Some(eval_function(g)?) }, Expression::Operator(_, Operator::Function(_), _) => { Some(eval_function(g)?) },
Expression::Operator(_, _, _) => { eval_operator(g, context)? }, Expression::Operator(_, _, _) => { eval_operator(context, g)? },
}; };
if let Some(mut new) = new { if let Some(mut new) = new {

View File

@ -7,7 +7,7 @@ use crate::errors::DaisyError;
use super::evaluate; use super::evaluate;
pub fn eval_operator(g: &Expression, context: &mut Context) -> Result<Option<Expression>, (LineLocation, DaisyError)> { pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Expression>, (LineLocation, DaisyError)> {
let Expression::Operator(op_loc, op, args) = g else {panic!()}; let Expression::Operator(op_loc, op, args) = g else {panic!()};
@ -52,7 +52,7 @@ pub fn eval_operator(g: &Expression, context: &mut Context) -> Result<Option<Exp
} }
let r = evaluate(&exp, context)?; let r = evaluate(context, &exp)?;
context.clear_shadow(); context.clear_shadow();
return Ok(Some(r)); return Ok(Some(r));

View File

@ -31,7 +31,7 @@ impl FormattedText {
} }
pub fn write(&self, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> { pub fn write(&self, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
if self.text == "[clear]" { if self.text == "[clear]" {
write!( write!(

View File

@ -26,21 +26,21 @@ fn main() -> Result<(), std::io::Error> {
#[inline(always)] #[inline(always)]
pub fn do_string( pub fn do_string(
s: &String, context: &mut Context,
mut context: &mut Context s: &String
) -> Result<FormattedText, FormattedText> { ) -> Result<FormattedText, FormattedText> {
let r: (LineLocation, DaisyError); let r: (LineLocation, DaisyError);
if command::is_command(s) { if command::is_command(s) {
return Ok(command::do_command(s, &mut context)); return Ok(command::do_command(context, s));
} else if s.contains("=") { } else if s.contains("=") {
let x = do_assignment(s, &mut context); let x = do_assignment(context, s);
match x { match x {
Ok(t) => { return Ok(t) }, Ok(t) => { return Ok(t) },
Err(t) => { r = t } Err(t) => { r = t }
}; };
} else { } else {
let x = do_expression(s, &mut context); let x = do_expression(context, s);
match x { match x {
Ok((t, e)) => { context.push_hist(e); return Ok(t) }, Ok((t, e)) => { context.push_hist(e); return Ok(t) },
Err(t) => { r = t } Err(t) => { r = t }
@ -73,14 +73,14 @@ pub fn do_string(
// Returns a FormattedText with output that should be printed. // Returns a FormattedText with output that should be printed.
#[inline(always)] #[inline(always)]
fn do_expression( fn do_expression(
s: &String, context: &mut Context,
context: &mut Context s: &String
) -> Result<(FormattedText, parser::Expression), (LineLocation, DaisyError)> { ) -> Result<(FormattedText, parser::Expression), (LineLocation, DaisyError)> {
let mut output = FormattedText::new("".to_string()); let mut output = FormattedText::new("".to_string());
let g = parser::parse(&s, context)?; let g = parser::parse(context, &s)?;
let g_evaluated = evaluate::evaluate(&g, context)?; let g_evaluated = evaluate::evaluate(context, &g)?;
// Display parsed string // Display parsed string
output.push(&format!( output.push(&format!(
@ -102,8 +102,8 @@ fn do_expression(
// Returns a FormattedText with output that should be printed. // Returns a FormattedText with output that should be printed.
#[inline(always)] #[inline(always)]
fn do_assignment( fn do_assignment(
s: &String, context: &mut Context,
context: &mut Context s: &String
) -> Result<FormattedText, (LineLocation, DaisyError)> { ) -> Result<FormattedText, (LineLocation, DaisyError)> {
let mut output = FormattedText::new("".to_string()); let mut output = FormattedText::new("".to_string());
@ -135,8 +135,8 @@ fn do_assignment(
.unwrap_or_else(|| parts[0].len()); .unwrap_or_else(|| parts[0].len());
let left = substitute(&parts[0].trim().to_string(), &context); let left = substitute(context, &parts[0].trim().to_string());
let right = substitute(&parts[1].trim().to_string(), &context); let right = substitute(context, &parts[1].trim().to_string());
let is_function = left.contains("("); let is_function = left.contains("(");
// The order of methods below is a bit odd. // The order of methods below is a bit odd.
@ -212,7 +212,7 @@ fn do_assignment(
} }
// Parse right hand side // Parse right hand side
let g = parser::parse(&right, context); let g = parser::parse(context, &right);
let Ok(g) = g else { let Ok(g) = g else {
let Err((l, e)) = g else { unreachable!() }; let Err((l, e)) = g else { unreachable!() };
return Err(( return Err((
@ -229,7 +229,7 @@ fn do_assignment(
// Evaluate expression with shadow variables // Evaluate expression with shadow variables
for a in &args { context.add_shadow(a.to_string(), None);} for a in &args { context.add_shadow(a.to_string(), None);}
let g_evaluated = evaluate::evaluate(&g, context); let g_evaluated = evaluate::evaluate(context, &g);
context.clear_shadow(); context.clear_shadow();
let Ok(_g_evaluated) = g_evaluated else { let Ok(_g_evaluated) = g_evaluated else {
let Err((l, e)) = g_evaluated else { unreachable!() }; let Err((l, e)) = g_evaluated else { unreachable!() };
@ -254,7 +254,7 @@ fn do_assignment(
} }
// Parse right hand side // Parse right hand side
let g = parser::parse(&right, context); let g = parser::parse(context, &right);
let Ok(g) = g else { let Ok(g) = g else {
let Err((l, e)) = g else { unreachable!() }; let Err((l, e)) = g else { unreachable!() };
return Err(( return Err((
@ -270,7 +270,7 @@ fn do_assignment(
)); ));
// Evaluate expression // Evaluate expression
let g_evaluated = evaluate::evaluate(&g, context); let g_evaluated = evaluate::evaluate(context, &g);
let Ok(g_evaluated) = g_evaluated else { let Ok(g_evaluated) = g_evaluated else {
let Err((l, e)) = g_evaluated else { unreachable!() }; let Err((l, e)) = g_evaluated else { unreachable!() };
return Err(( return Err((

View File

@ -62,7 +62,7 @@ impl Operator {
} }
#[inline(always)] #[inline(always)]
pub fn from_string(s: &str, context: &Context) -> Option<Operator> { pub fn from_string(context: &Context, s: &str) -> Option<Operator> {
let f = Function::from_string(s); let f = Function::from_string(s);
if let Some(f) = f { if let Some(f) = f {
@ -207,7 +207,11 @@ impl Operator {
let q = &args[1]; let q = &args[1];
if q.is_unitless_integer() && !q.to_string().contains("e") { if {
//context.config.enable_super_powers &&
q.is_unitless_integer() &&
!q.to_string().contains("e")
} {
// Write integer powers as a superscript // Write integer powers as a superscript
let mut b = String::new(); let mut b = String::new();
for c in q.to_string().chars() { for c in q.to_string().chars() {

View File

@ -18,30 +18,30 @@ use crate::context::Context;
use crate::errors::DaisyError; use crate::errors::DaisyError;
pub fn parse( pub fn parse(
s: &String, context: &Context context: &Context, s: &String
) -> Result<Expression, (LineLocation, DaisyError)> { ) -> Result<Expression, (LineLocation, DaisyError)> {
let expressions = stage::tokenize(s, context); let expressions = stage::tokenize(context, s);
let (_, expressions) = stage::find_subs(expressions); let (_, expressions) = stage::find_subs(expressions);
let g = stage::groupify(expressions, context)?; let g = stage::groupify(context, expressions)?;
let g = stage::treeify(g, context)?; let g = stage::treeify(context, g)?;
return Ok(g); return Ok(g);
} }
pub fn parse_no_context(s: &String) -> Result<Expression, (LineLocation, DaisyError)> { pub fn parse_no_context(s: &String) -> Result<Expression, (LineLocation, DaisyError)> {
parse(s, &Context::new()) parse(&Context::new(), s)
} }
pub fn substitute(s: &String, context: &Context) -> String { pub fn substitute(context: &Context, s: &String) -> String {
let (_, s) = substitute_cursor(s, s.chars().count(), context); let (_, s) = substitute_cursor(context, s, s.chars().count());
return s; return s;
} }
pub fn substitute_cursor( pub fn substitute_cursor(
context: &Context,
s: &String, // The string to substitute s: &String, // The string to substitute
c: usize, // Location of the cursor right now c: usize // Location of the cursor right now
context: &Context
) -> ( ) -> (
usize, // Location of cursor in substituted string usize, // Location of cursor in substituted string
String // String with substitutions String // String with substitutions
@ -50,7 +50,7 @@ pub fn substitute_cursor(
let mut new_s = s.clone(); let mut new_s = s.clone();
let l = s.chars().count(); let l = s.chars().count();
let expressions = stage::tokenize(s, context); let expressions = stage::tokenize(context, s);
let (mut subs, _) = stage::find_subs(expressions); let (mut subs, _) = stage::find_subs(expressions);
let mut new_c = l - c; let mut new_c = l - c;

View File

@ -11,8 +11,8 @@ use crate::context::Context;
fn lookback_signs( fn lookback_signs(
g: &mut VecDeque<Token>, context: &Context,
context: &Context g: &mut VecDeque<Token>
) -> Result<(), (LineLocation, DaisyError)> { ) -> Result<(), (LineLocation, DaisyError)> {
// Convert `-` operators to `neg` operators // Convert `-` operators to `neg` operators
@ -44,7 +44,7 @@ fn lookback_signs(
(Token::Operator(_, sa), Token::Operator(l,sb)) (Token::Operator(_, sa), Token::Operator(l,sb))
=> { => {
if { if {
let o = Operator::from_string(sa, context); let o = Operator::from_string(context, sa);
o.is_some() && o.is_some() &&
( (
@ -101,11 +101,11 @@ fn lookback_signs(
// Inserts implicit operators // Inserts implicit operators
fn lookback( fn lookback(
g: &mut VecDeque<Token>, context: &Context,
context: &Context g: &mut VecDeque<Token>
) -> Result<(), (LineLocation, DaisyError)> { ) -> Result<(), (LineLocation, DaisyError)> {
lookback_signs(g, context)?; lookback_signs(context, g)?;
let mut i: usize = 0; let mut i: usize = 0;
while i < g.len() { while i < g.len() {
@ -142,7 +142,7 @@ fn lookback(
=> { => {
let la = la.clone(); let la = la.clone();
let lb = lb.clone(); let lb = lb.clone();
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
g.insert(i-1, b); g.insert(i-1, b);
if o.is_some() { if o.is_some() {
@ -164,7 +164,7 @@ fn lookback(
=> { => {
let la = la.clone(); let la = la.clone();
let lb = lb.clone(); let lb = lb.clone();
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
g.insert(i-1, b); g.insert(i-1, b);
if o.is_some() { if o.is_some() {
@ -196,8 +196,8 @@ fn lookback(
pub fn groupify( pub fn groupify(
mut g: VecDeque<Token>, context: &Context,
context: &Context mut g: VecDeque<Token>
) -> Result< ) -> Result<
Token, Token,
(LineLocation, DaisyError) (LineLocation, DaisyError)
@ -240,7 +240,7 @@ pub fn groupify(
let (_, mut v) = levels.pop().unwrap(); let (_, mut v) = levels.pop().unwrap();
let (_, v_now) = levels.last_mut().unwrap(); let (_, v_now) = levels.last_mut().unwrap();
lookback(&mut v, context)?; lookback(context, &mut v)?;
let q = is_tuple.pop().unwrap(); let q = is_tuple.pop().unwrap();
if q { if q {
@ -275,7 +275,7 @@ pub fn groupify(
let (_, v_now) = levels.last_mut().unwrap(); let (_, v_now) = levels.last_mut().unwrap();
if v.len() == 0 { return Err((l, DaisyError::EmptyGroup)) } if v.len() == 0 { return Err((l, DaisyError::EmptyGroup)) }
lookback(&mut v, context)?; lookback(context, &mut v)?;
let q = is_tuple.pop().unwrap(); let q = is_tuple.pop().unwrap();
if q { if q {
@ -294,7 +294,7 @@ pub fn groupify(
return Err((l, DaisyError::BadTuple)); return Err((l, DaisyError::BadTuple));
} }
lookback(&mut v, context)?; lookback(context, &mut v)?;
return Ok(Token::Group( return Ok(Token::Group(
LineLocation{pos:0, len:last_linelocation.pos + last_linelocation.len}, LineLocation{pos:0, len:last_linelocation.pos + last_linelocation.len},

View File

@ -10,10 +10,10 @@ use super::super::{
// Called whenever a token is finished. // Called whenever a token is finished.
#[inline(always)] #[inline(always)]
fn push_token( fn push_token(
context: &Context,
g: &mut VecDeque<Token>, g: &mut VecDeque<Token>,
t: Option<Token>, t: Option<Token>,
stop_i: usize, stop_i: usize
context: &Context
) { ) {
if t.is_none() { return } if t.is_none() { return }
@ -60,7 +60,7 @@ fn push_token(
// Some operators are written as words. // Some operators are written as words.
if let Token::Word(l, s) = &t { if let Token::Word(l, s) = &t {
if Operator::from_string(s, context).is_some() { if Operator::from_string(context, s).is_some() {
t = Token::Operator(*l, s.clone()); t = Token::Operator(*l, s.clone());
} }
} }
@ -69,7 +69,7 @@ fn push_token(
} }
/// Turns a string into Tokens. First stage of parsing. /// Turns a string into Tokens. First stage of parsing.
pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> { pub fn tokenize(context: &Context, input: &String) -> VecDeque<Token> {
let mut t: Option<Token> = None; // The current token we're reading let mut t: Option<Token> = None; // The current token we're reading
let mut g: VecDeque<Token> = VecDeque::with_capacity(32); let mut g: VecDeque<Token> = VecDeque::with_capacity(32);
@ -88,7 +88,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
// If we're not building a number, finalize // If we're not building a number, finalize
// previous token and start one. // previous token and start one.
_ => { _ => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Quantity(LineLocation{pos: i, len: 0}, String::from(c))); t = Some(Token::Quantity(LineLocation{pos: i, len: 0}, String::from(c)));
} }
}; };
@ -102,7 +102,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
Some(Token::Quantity(_, val)) => { val.push(c); }, Some(Token::Quantity(_, val)) => { val.push(c); },
_ => { _ => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Word(LineLocation{pos: i, len: 0}, String::from(c))); t = Some(Token::Word(LineLocation{pos: i, len: 0}, String::from(c)));
} }
}; };
@ -122,7 +122,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
} else { } else {
// Otherwise, end the number. // Otherwise, end the number.
// We probably have a subtraction. // We probably have a subtraction.
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Operator( t = Some(Token::Operator(
LineLocation{pos: i, len: 1}, LineLocation{pos: i, len: 1},
String::from(c) String::from(c)
@ -134,7 +134,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
// Multi-character operators with - and + are NOT supported! // Multi-character operators with - and + are NOT supported!
// (for example, we can't use -> for unit conversion) // (for example, we can't use -> for unit conversion)
_ => { _ => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Operator( t = Some(Token::Operator(
LineLocation{pos: i, len: 1}, LineLocation{pos: i, len: 1},
String::from(c) String::from(c)
@ -144,7 +144,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
}, },
',' => { ',' => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::TupleDelim(LineLocation{pos: i, len: 1})); t = Some(Token::TupleDelim(LineLocation{pos: i, len: 1}));
}, },
@ -157,7 +157,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
match &mut t { match &mut t {
Some(Token::Operator(_, val)) => { val.push(c); }, Some(Token::Operator(_, val)) => { val.push(c); },
_ => { _ => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Operator(LineLocation{pos: i, len: 0}, String::from(c))); t = Some(Token::Operator(LineLocation{pos: i, len: 0}, String::from(c)));
} }
}; };
@ -165,17 +165,17 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
// Group // Group
'(' => { '(' => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::GroupStart(LineLocation{pos: i, len: 0})); t = Some(Token::GroupStart(LineLocation{pos: i, len: 0}));
}, },
')' => { ')' => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::GroupEnd(LineLocation{pos: i, len: 0})); t = Some(Token::GroupEnd(LineLocation{pos: i, len: 0}));
}, },
// Space. Basic seperator. // Space. Basic seperator.
' ' => { ' ' => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = None; t = None;
} }
@ -185,7 +185,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
Some(Token::Word(_, val)) => { val.push(c); }, Some(Token::Word(_, val)) => { val.push(c); },
_ => { _ => {
push_token(&mut g, t, i, context); push_token(context, &mut g, t, i);
t = Some(Token::Word(LineLocation{pos: i, len: 0}, String::from(c))); t = Some(Token::Word(LineLocation{pos: i, len: 0}, String::from(c)));
} }
}; };
@ -193,7 +193,7 @@ pub fn tokenize(input: &String, context: &Context) -> VecDeque<Token> {
}; };
} }
push_token(&mut g, t, input.chars().count(), context); push_token(context, &mut g, t, input.chars().count());
return g; return g;
} }

View File

@ -10,9 +10,9 @@ use super::super::{
}; };
fn treeify_binary( fn treeify_binary(
context: &Context,
i: usize, i: usize,
g_inner: &mut VecDeque<Token>, g_inner: &mut VecDeque<Token>
context: &Context
) -> Result<bool, (LineLocation, DaisyError)> { ) -> Result<bool, (LineLocation, DaisyError)> {
let this: &Token = &g_inner[i]; let this: &Token = &g_inner[i];
@ -56,7 +56,7 @@ fn treeify_binary(
if let Token::Operator(l, s) = left { if let Token::Operator(l, s) = left {
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string
let o = o.unwrap(); let o = o.unwrap();
@ -72,7 +72,7 @@ fn treeify_binary(
} }
if let Token::Operator(l, s) = right { if let Token::Operator(l, s) = right {
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string
let o = o.unwrap(); let o = o.unwrap();
@ -91,7 +91,7 @@ fn treeify_binary(
// This operator // This operator
let this_op = { let this_op = {
let Token::Operator(l, s) = this else {panic!()}; let Token::Operator(l, s) = this else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // bad operator string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // bad operator string
o.unwrap() o.unwrap()
}; };
@ -99,14 +99,14 @@ fn treeify_binary(
// The operators contesting our arguments // The operators contesting our arguments
let left_op = if i > 1 { let left_op = if i > 1 {
let Token::Operator(l, s) = &g_inner[i-2] else {panic!()}; let Token::Operator(l, s) = &g_inner[i-2] else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad operator string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad operator string
Some(o.unwrap()) Some(o.unwrap())
} else { None }; } else { None };
let right_op = if i < g_inner.len()-2 { let right_op = if i < g_inner.len()-2 {
let Token::Operator(l, s) = &g_inner[i+2] else {panic!()}; let Token::Operator(l, s) = &g_inner[i+2] else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad operator string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad operator string
Some(o.unwrap()) Some(o.unwrap())
} else { None }; } else { None };
@ -122,20 +122,20 @@ fn treeify_binary(
let right_pre = g_inner.remove(i-1).unwrap(); let right_pre = g_inner.remove(i-1).unwrap();
let mut left: Expression; let mut right: Expression; let mut left: Expression; let mut right: Expression;
if let Token::Group(l, _) = right_pre { if let Token::Group(l, _) = right_pre {
right = treeify(right_pre, context)?; right = treeify(context, right_pre)?;
right.set_linelocation(&(right.get_linelocation() + l)); right.set_linelocation(&(right.get_linelocation() + l));
} else if let Token::Tuple(l, _) = right_pre { } else if let Token::Tuple(l, _) = right_pre {
right = treeify(right_pre, context)?; right = treeify(context, right_pre)?;
right.set_linelocation(&(right.get_linelocation() + l)); right.set_linelocation(&(right.get_linelocation() + l));
} else { } else {
right = right_pre.to_expression(context)?; right = right_pre.to_expression(context)?;
} }
if let Token::Group(l, _) = left_pre { if let Token::Group(l, _) = left_pre {
left = treeify(left_pre, context)?; left = treeify(context, left_pre)?;
left.set_linelocation(&(left.get_linelocation() + l)); left.set_linelocation(&(left.get_linelocation() + l));
} else if let Token::Tuple(l, _) = left_pre { } else if let Token::Tuple(l, _) = left_pre {
left = treeify(left_pre, context)?; left = treeify(context, left_pre)?;
left.set_linelocation(&(left.get_linelocation() + l)); left.set_linelocation(&(left.get_linelocation() + l));
} else { } else {
left = left_pre.to_expression(context)?; left = left_pre.to_expression(context)?;
@ -143,7 +143,7 @@ fn treeify_binary(
let (l, o) = { let (l, o) = {
let Token::Operator(l, s) = this_pre else {panic!()}; let Token::Operator(l, s) = this_pre else {panic!()};
let o = Operator::from_string(&s, context); let o = Operator::from_string(context, &s);
if o.is_none() { panic!() } if o.is_none() { panic!() }
(l, o.unwrap()) (l, o.unwrap())
}; };
@ -161,10 +161,10 @@ fn treeify_binary(
} }
fn treeify_unary( fn treeify_unary(
context: &Context,
i: usize, i: usize,
g_inner: &mut VecDeque<Token>, g_inner: &mut VecDeque<Token>,
left_associative: bool, left_associative: bool
context: &Context
) -> Result<bool, (LineLocation, DaisyError)> { ) -> Result<bool, (LineLocation, DaisyError)> {
let this: &Token = &g_inner[i]; let this: &Token = &g_inner[i];
@ -224,7 +224,7 @@ fn treeify_unary(
// This operator // This operator
let this_op = { let this_op = {
let Token::Operator(l, s) = this else {panic!()}; let Token::Operator(l, s) = this else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string
o.unwrap() o.unwrap()
}; };
@ -233,14 +233,14 @@ fn treeify_unary(
let next_op = if left_associative { let next_op = if left_associative {
if i > 1 { if i > 1 {
let Token::Operator(l, s) = &g_inner[i-2] else {panic!()}; let Token::Operator(l, s) = &g_inner[i-2] else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string
Some(o.unwrap()) Some(o.unwrap())
} else { None } } else { None }
} else { } else {
if i < g_inner.len()-2 { if i < g_inner.len()-2 {
let Token::Operator(l, s) = &g_inner[i+2] else {panic!()}; let Token::Operator(l, s) = &g_inner[i+2] else {panic!()};
let o = Operator::from_string(s, context); let o = Operator::from_string(context, s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string if o.is_none() { return Err((*l, DaisyError::Syntax)); } // Bad string
Some(o.unwrap()) Some(o.unwrap())
} else { None } } else { None }
@ -255,10 +255,10 @@ fn treeify_unary(
next_pre = g_inner.remove(i).unwrap(); next_pre = g_inner.remove(i).unwrap();
} }
if let Token::Group(l, _) = next_pre { if let Token::Group(l, _) = next_pre {
next = treeify(next_pre, context)?; next = treeify(context, next_pre)?;
next.set_linelocation(&(next.get_linelocation() + l)); next.set_linelocation(&(next.get_linelocation() + l));
} else if let Token::Tuple(l, _) = next_pre { } else if let Token::Tuple(l, _) = next_pre {
next = treeify(next_pre, context)?; next = treeify(context, next_pre)?;
next.set_linelocation(&(next.get_linelocation() + l)); next.set_linelocation(&(next.get_linelocation() + l));
} else { } else {
next = next_pre.to_expression(context)?; next = next_pre.to_expression(context)?;
@ -267,7 +267,7 @@ fn treeify_unary(
let (l, o) = { let (l, o) = {
let Token::Operator(l, s) = this_pre else {panic!()}; let Token::Operator(l, s) = this_pre else {panic!()};
let o = Operator::from_string(&s, context); let o = Operator::from_string(context, &s);
if o.is_none() { panic!() } if o.is_none() { panic!() }
(l, o.unwrap()) (l, o.unwrap())
}; };
@ -292,8 +292,8 @@ fn treeify_unary(
pub fn treeify( pub fn treeify(
mut g: Token, context: &Context,
context: &Context mut g: Token
) -> Result<Expression, (LineLocation, DaisyError)> { ) -> Result<Expression, (LineLocation, DaisyError)> {
let (l, g_inner): (LineLocation, &mut VecDeque<Token>) = match g { let (l, g_inner): (LineLocation, &mut VecDeque<Token>) = match g {
@ -301,7 +301,7 @@ pub fn treeify(
Token::Tuple(l, parts) => { Token::Tuple(l, parts) => {
let mut t: VecDeque<Expression> = VecDeque::new(); let mut t: VecDeque<Expression> = VecDeque::new();
for p in parts { for p in parts {
t.push_back(treeify(p, context)?); t.push_back(treeify(context, p)?);
}; };
return Ok(Expression::Tuple(l, t)); return Ok(Expression::Tuple(l, t));
@ -332,7 +332,7 @@ pub fn treeify(
// If not an operator, move on. // If not an operator, move on.
let this_op = match &g_inner[i] { let this_op = match &g_inner[i] {
Token::Operator(l, s) => { Token::Operator(l, s) => {
let o = Operator::from_string(&s, context); let o = Operator::from_string(context, &s);
if o.is_none() { return Err((*l, DaisyError::Syntax)); } if o.is_none() { return Err((*l, DaisyError::Syntax)); }
o.unwrap() o.unwrap()
}, },
@ -346,9 +346,9 @@ pub fn treeify(
let mut changed = false; let mut changed = false;
if this_op.is_left_associative() { if this_op.is_left_associative() {
if this_op.is_binary() { if this_op.is_binary() {
changed = treeify_binary(i, g_inner, context)?; changed = treeify_binary(context, i, g_inner)?;
} else { } else {
changed = treeify_unary(i, g_inner, left_associative, context)?; changed = treeify_unary(context, i, g_inner, left_associative)?;
} }
} }
@ -360,9 +360,9 @@ pub fn treeify(
} else { } else {
if !this_op.is_left_associative() { if !this_op.is_left_associative() {
if this_op.is_binary() { if this_op.is_binary() {
treeify_binary(i, g_inner, context)?; treeify_binary(context, i, g_inner)?;
} else { } else {
treeify_unary(i, g_inner, left_associative, context)?; treeify_unary(context, i, g_inner, left_associative)?;
} }
} }
j -= 1 j -= 1
@ -378,7 +378,7 @@ pub fn treeify(
}, },
Token::Tuple(_, _) | Token::Tuple(_, _) |
Token::Group(_,_) => { Token::Group(_,_) => {
treeify(g, context) treeify(context, g)
}, },

View File

@ -10,7 +10,7 @@ fn eval_to_str(s: &str) -> Result<String, ()> {
}; };
//let out_str = g.print(); //let out_str = g.print();
return match evaluate(&g, &mut Context::new()) { return match evaluate(&mut Context::new(), &g) {
Ok(x) => Ok(x.to_string_outer()), Ok(x) => Ok(x.to_string_outer()),
Err(_) => Err(()) Err(_) => Err(())
}; };