Compare commits

..

No commits in common. "a6c3ffa68dfe9d79f532e1c985eadfd4f1858c26" and "9ea1990f3c118775215bb1773ec8111d5598c053" have entirely different histories.

21 changed files with 217 additions and 396 deletions

2
Cargo.lock generated
View File

@ -28,7 +28,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "daisycalc" name = "daisycalc"
version = "1.0.1" version = "1.0.0"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"rug", "rug",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "daisycalc" name = "daisycalc"
version = "1.0.1" version = "1.0.0"
edition = "2021" edition = "2021"
build = "buildscript/main.rs" build = "buildscript/main.rs"
license = "GPL-3.0-only" license = "GPL-3.0-only"

View File

@ -5,7 +5,6 @@ A high-precision scientific calculator with support for units, derivatives, and
Many features are missing, this is still under development. Many features are missing, this is still under development.
# 📦 Installation # 📦 Installation
- **Cargo:** `cargo install daisycalc`
- **Arch:** `yay -S daisy` - **Arch:** `yay -S daisy`
- **Debian:** coming soon - **Debian:** coming soon

View File

@ -27,6 +27,11 @@
- Optional history file - Optional history file
- daisyrc file - daisyrc file
- Compile to WASM, publish a webapp - Compile to WASM, publish a webapp
- Options:
- disable replacement
- disable special characters
- 1/ as -1 power toggle
- powers as superscripts toggle
- evaluate straight from command line - evaluate straight from command line
- Auto-push to crates.io - Auto-push to crates.io
- Package for debian - Package for debian

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];
@ -170,7 +170,7 @@ pub fn do_command(
t.push(&format!( t.push(&format!(
" {key}{padding} = [c]{v}[n]\n", " {key}{padding} = [c]{v}[n]\n",
v = value.display(context), v = value.to_string(),
)); ));
} }
} }
@ -184,7 +184,7 @@ pub fn do_command(
t.push(&format!( t.push(&format!(
" {s}{padding} = [c]{v}[n]\n", " {s}{padding} = [c]{v}[n]\n",
v = exp.display(context), v = exp.to_string(),
)); ));
} }
} }
@ -230,7 +230,7 @@ pub fn do_command(
} }
let v = args[1].to_string(); let v = args[1].to_string();
let v = substitute(context, &v); let v = substitute(&v, context);
let r = context.delete(&v); let r = context.delete(&v);
return match r { return match r {

View File

@ -3,68 +3,7 @@ use crate::quantity::freeunit_from_string;
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug)] #[derive(Debug)]
#[derive(Clone)]
pub struct Config {
// How to color terminal text.
// 0: No colors
// 1: ANSI-compatible, 8 colors
// 2: Full 256 color and special styles
pub term_color_type: u8,
// Should we accept input and print in unicode?
//pub enable_unicode: bool,
// Should we replace certain strings (like "pi")
// with prettier unicode alternatives?
//
// Automatically disabled if enable_unicode is off.
//pub enable_substituion: bool,
// Should we print simple powers
// as unicode superscript chars?
//
// Automatically disables if enable_unicode is off.
pub enable_super_powers: bool,
// Should we write "one-over" fractions
// as -1 powers?
//
// Automatically disabled if enable_super_powers is off.
pub enable_one_over_power: bool,
}
impl Config {
pub fn new() -> Config {
Config{
term_color_type: 2,
//enable_substituion: true,
//enable_unicode: true,
enable_super_powers: true,
enable_one_over_power: true
}
}
pub fn check(&mut self) {
//if !self.enable_unicode {
// self.enable_substituion = false;
// self.enable_super_powers = false;
//}
if !self.enable_super_powers {
self.enable_one_over_power = false
}
}
}
#[derive(Debug)]
#[derive(Clone)]
pub struct Context { pub struct Context {
pub config: Config,
history: Vec<Expression>, history: Vec<Expression>,
variables: HashMap<String, Expression>, variables: HashMap<String, Expression>,
functions: HashMap<String, (Vec<String>, Expression)>, functions: HashMap<String, (Vec<String>, Expression)>,
@ -77,7 +16,6 @@ pub struct Context {
impl Context { impl Context {
pub fn new() -> Context { pub fn new() -> Context {
Context{ Context{
config: Config::new(),
history: Vec::new(), history: Vec::new(),
variables: HashMap::new(), variables: HashMap::new(),
functions: HashMap::new(), functions: HashMap::new(),
@ -146,10 +84,10 @@ impl Context {
} }
pub fn is_varible(&self, s: &str) -> bool { pub fn is_varible(&self, s: &str) -> bool {
return { return self.valid_varible(s) && (
self.valid_varible(s) && self.variables.contains_key(s) ||
(self.variables.contains_key(s) || self.shadow.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, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> { pub fn write_prompt_nocursor(&mut self, stdout: &mut RawTerminal<std::io::Stdout>, context: &Context) -> Result<(), std::io::Error> {
// Draw prettyprinted expression // Draw prettyprinted expression
let (_, s) = substitute_cursor(context, &self.get_contents(), self.buffer.chars().count()); let (_, s) = substitute_cursor(&self.get_contents(), self.buffer.chars().count(), context);
write!( write!(
stdout, "\r{}{}==>{}{} {}", stdout, "\r{}{}==>{}{} {}",
@ -64,12 +64,12 @@ impl PromptBuffer {
return Ok(()); return Ok(());
} }
pub fn write_prompt(&mut self, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> { pub fn write_prompt(&mut self, stdout: &mut RawTerminal<std::io::Stdout>, context: &Context) -> 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(context, &self.get_contents(), i); let (display_cursor, s) = substitute_cursor(&self.get_contents(), i, context);
write!( write!(
stdout, "\r{}{}==>{}{} {}", stdout, "\r{}{}==>{}{} {}",

View File

@ -1,3 +1,4 @@
use std::io::Write;
use std::io::stdout; use std::io::stdout;
use std::io::stdin; use std::io::stdin;
use std::env; use std::env;
@ -5,63 +6,35 @@ use std::env;
use termion::{ use termion::{
event::Key, event::Key,
input::TermRead, input::TermRead,
raw::IntoRawMode, raw::IntoRawMode
color::DetectColors
}; };
use super::promptbuffer::PromptBuffer; use super::promptbuffer::PromptBuffer;
use crate::command; use crate::command;
use crate::context::Context; use crate::context::Context;
use crate::FormattedText;
#[inline(always)] #[inline(always)]
pub fn main() -> Result<(), std::io::Error> { pub fn main() -> Result<(), std::io::Error> {
let mut stdout = stdout().into_raw_mode().unwrap(); let mut stdout = stdout().into_raw_mode().unwrap();
let mut pb: PromptBuffer = PromptBuffer::new(64); let mut pb: PromptBuffer = PromptBuffer::new(64);
let mut context = Context::new(); let mut context: Context = Context::new();
// Set color compatibilty
let term_colors = stdout.available_colors().unwrap_or(0);
if term_colors >= 256 {
context.config.term_color_type = 2
} else if term_colors >= 8 {
context.config.term_color_type = 1
} else {
context.config.term_color_type = 0
}
context.config.check();
// 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(&mut context, &String::from("help")); let t = command::do_command(&String::from("help"), &mut context);
t.write(&context, &mut stdout)?; t.write(&mut stdout)?;
return Ok(()); return Ok(());
} else if args.iter().any(|s| s == "--version") { } else if args.iter().any(|s| s == "--version") {
let t = FormattedText::new(format!( write!(stdout, "Daisy v{}\r\n", env!("CARGO_PKG_VERSION"))?;
"Daisy v{}\n", env!("CARGO_PKG_VERSION")
));
t.write(&context, &mut stdout)?;
return Ok(());
} else if args.iter().any(|s| s == "--debug") {
let t = FormattedText::new(format!(
concat!(
"Daisy v{}\n",
"Your terminal supports {} colors.\n"
),
env!("CARGO_PKG_VERSION"),
term_colors
));
t.write(&context, &mut stdout)?;
return Ok(()); return Ok(());
} }
'outer: loop { 'outer: loop {
pb.write_prompt(&mut context, &mut stdout)?; pb.write_prompt(&mut stdout, &context)?;
let stdin = stdin(); let stdin = stdin();
for c in stdin.keys() { for c in stdin.keys() {
@ -70,19 +43,19 @@ 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 context, &mut stdout)?; pb.write_prompt_nocursor(&mut stdout, &context)?;
let in_str = pb.enter(); let in_str = pb.enter();
FormattedText::newline(&mut stdout)?; write!(stdout, "\r\n")?;
if in_str == "" { break; } if in_str == "" { break; }
if in_str.trim() == "quit" { if in_str.trim() == "quit" {
break 'outer; break 'outer;
} else { } else {
let r = crate::do_string(&mut context, &in_str); let r = crate::do_string(&in_str, &mut context);
match r { match r {
Ok(t) | Err(t) => { Ok(t) | Err(t) => {
t.write(&context, &mut stdout).unwrap(); t.write(&mut stdout).unwrap();
} }
} }
} }
@ -106,10 +79,10 @@ pub fn main() -> Result<(), std::io::Error> {
}; };
}; };
pb.write_prompt(&mut context, &mut stdout)?; pb.write_prompt(&mut stdout, &context)?;
} }
} }
FormattedText::newline(&mut stdout)?; write!(stdout, "\r\n")?;
return Ok(()); return Ok(());
} }

View File

@ -9,8 +9,8 @@ use super::function::eval_function;
pub fn evaluate( pub fn evaluate(
context: &mut Context, t: &Expression,
t: &Expression context: &mut Context
) -> 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(context, &c.value()).unwrap()) }, Expression::Constant(_, c) => { Some(evaluate(&c.value(), context).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(context, g)? }, Expression::Operator(_, _, _) => { eval_operator(g, context)? },
}; };
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(context: &mut Context, g: &Expression) -> Result<Option<Expression>, (LineLocation, DaisyError)> { pub fn eval_operator(g: &Expression, context: &mut Context) -> 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(context: &mut Context, g: &Expression) -> Result<Option<Exp
} }
let r = evaluate(context, &exp)?; let r = evaluate(&exp, context)?;
context.clear_shadow(); context.clear_shadow();
return Ok(Some(r)); return Ok(Some(r));
@ -78,8 +78,8 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(
a.convert_to_base().unit.display(context), a.convert_to_base().unit.to_string(),
b.convert_to_base().unit.display(context) b.convert_to_base().unit.to_string()
) )
)); ));
} }
@ -101,8 +101,8 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(
a.convert_to_base().unit.display(context), a.convert_to_base().unit.to_string(),
b.convert_to_base().unit.display(context) b.convert_to_base().unit.to_string()
) )
)); ));
} }
@ -179,8 +179,8 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(
va.convert_to_base().unit.display(context), va.convert_to_base().unit.to_string(),
vb.convert_to_base().unit.display(context) vb.convert_to_base().unit.to_string()
) )
)); ));
} }

View File

@ -5,7 +5,6 @@ use termion::style;
use termion::clear; use termion::clear;
use termion::cursor; use termion::cursor;
use std::ops::Add; use std::ops::Add;
use crate::context::Context;
#[derive(Debug)] #[derive(Debug)]
@ -19,92 +18,8 @@ impl ToString for FormattedText {
} }
fn format_map_none(c: char) -> Option<String> {
Some(match c {
'n'|'i'|'t'|'a'|
'e'|'c'|'s'|'r'
=> { "".to_string() },
_ => { return None }
})
}
fn format_map_ansi(c: char) -> Option<String> {
Some(match c {
'n' => { // Normal text
format!("{}{}", color::Fg(color::Reset), color::Bg(color::Reset))
},
'i' => { // Normal italic text
format!("{}{}", color::Fg(color::Reset), color::Bg(color::Reset))
},
't' => { // Title text
format!("{}{}", color::Fg(color::AnsiValue(6)), color::Bg(color::Reset))
},
'a' => { // Colored text
format!("{}{}", color::Fg(color::AnsiValue(5)), color::Bg(color::Reset))
},
'e' => { // Error titles
format!("{}{}", color::Fg(color::AnsiValue(1)), color::Bg(color::Reset))
},
'c' => { // Console text
format!("{}{}", color::Fg(color::AnsiValue(0)), color::Bg(color::AnsiValue(7)))
},
's' => { // Repeat prompt (how => is styled)
format!("{}{}", color::Fg(color::AnsiValue(2)), color::Bg(color::Reset))
},
'r' => { // Result prompt (how = is styled)
format!("{}{}", color::Fg(color::AnsiValue(4)), color::Bg(color::Reset))
},
_ => { return None }
})
}
fn format_map_full(c: char) -> Option<String> {
Some(match c {
'n' => { // Normal text
format!("{}{}", color::Fg(color::Reset), style::Reset)
},
'i' => { // Normal italic text
format!("{}{}", color::Fg(color::Reset), style::Italic)
},
't' => { // Title text
format!("{}{}", color::Fg(color::Magenta), style::Bold)
},
'a' => { // Colored text
format!("{}{}", color::Fg(color::Magenta), style::Reset)
},
'e' => { // Error titles
format!("{}{}", color::Fg(color::Red), style::Bold)
},
'c' => { // Console text
format!("{}{}", color::Fg(color::LightBlack), style::Italic)
},
's' => { // Repeat prompt (how => is styled)
format!("{}{}", color::Fg(color::Magenta), style::Bold)
},
'r' => { // Result prompt (how = is styled)
format!("{}{}", color::Fg(color::Green), style::Bold)
},
_ => { return None }
})
}
impl FormattedText { impl FormattedText {
pub fn newline(stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
write!(
stdout,
"\r\n",
)?;
return Ok(());
}
}
impl FormattedText {
pub fn new(s: String) -> FormattedText { pub fn new(s: String) -> FormattedText {
return FormattedText { return FormattedText {
text: s text: s
@ -116,7 +31,7 @@ impl FormattedText {
} }
pub fn write(&self, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> { pub fn write(&self, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
if self.text == "[clear]" { if self.text == "[clear]" {
write!( write!(
@ -143,22 +58,30 @@ impl FormattedText {
let b = chars.next().unwrap(); let b = chars.next().unwrap();
match (a, b) { match (a, b) {
(c, ']') => { // Normal text ('n', ']') => { // Normal text
s.push_str(&format!("{}{}", color::Fg(color::Reset), style::Reset));
},
('i', ']') => { // Normal italic text
s.push_str(&format!("{}{}", color::Fg(color::Reset), style::Italic));
},
('t', ']') => { // Title text
s.push_str(&format!("{}{}", color::Fg(color::Magenta), style::Bold));
},
('a', ']') => { // Colored text
s.push_str(&format!("{}{}", color::Fg(color::Magenta), style::Reset));
},
('e', ']') => { // Error titles
s.push_str(&format!("{}{}", color::Fg(color::Red), style::Bold));
},
('c', ']') => { // Console text
s.push_str(&format!("{}{}", color::Fg(color::LightBlack), style::Italic));
},
let q = match context.config.term_color_type { ('s', ']') => { // Repeat prompt (how => is styled)
0 => format_map_none(c), s.push_str(&format!("{}{}", color::Fg(color::Magenta), style::Bold));
1 => format_map_ansi(c), },
2 => format_map_full(c), ('r', ']') => { // Result prompt (how = is styled)
_ => unreachable!("Invalid term_color_type") s.push_str(&format!("{}{}", color::Fg(color::Green), style::Bold));
};
if q.is_some() {
s.push_str(&q.unwrap());
} else {
s.push('[');
s.push(a);
s.push(b);
}
}, },
_ => { _ => {

View File

@ -26,21 +26,21 @@ fn main() -> Result<(), std::io::Error> {
#[inline(always)] #[inline(always)]
pub fn do_string( pub fn do_string(
context: &mut Context, s: &String,
s: &String mut context: &mut Context
) -> 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(context, s)); return Ok(command::do_command(s, &mut context));
} else if s.contains("=") { } else if s.contains("=") {
let x = do_assignment(context, s); let x = do_assignment(s, &mut context);
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(context, s); let x = do_expression(s, &mut context);
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,25 +73,25 @@ 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(
context: &mut Context, s: &String,
s: &String context: &mut Context
) -> 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(context, &s)?; let g = parser::parse(&s, context)?;
let g_evaluated = evaluate::evaluate(context, &g)?; let g_evaluated = evaluate::evaluate(&g, context)?;
// Display parsed string // Display parsed string
output.push(&format!( output.push(&format!(
" [s]=>[n] {}\n\n", " [s]=>[n] {}\n\n",
g.display(context) g.to_string()
)); ));
// Display result // Display result
output.push(&format!( output.push(&format!(
" [r]=[n] {}\n\n", " [r]=[n] {}\n\n",
g_evaluated.display_outer(context), g_evaluated.to_string_outer(),
)); ));
return Ok((output, g_evaluated)); return Ok((output, g_evaluated));
@ -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(
context: &mut Context, s: &String,
s: &String context: &mut Context
) -> 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(context, &parts[0].trim().to_string()); let left = substitute(&parts[0].trim().to_string(), &context);
let right = substitute(context, &parts[1].trim().to_string()); let right = substitute(&parts[1].trim().to_string(), &context);
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(context, &right); let g = parser::parse(&right, context);
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((
@ -224,12 +224,12 @@ fn do_assignment(
// Display parsed string // Display parsed string
output.push(&format!( output.push(&format!(
" [s]=>[n] {left} = {}\n\n", " [s]=>[n] {left} = {}\n\n",
g.display(context) g.to_string()
)); ));
// 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(context, &g); let g_evaluated = evaluate::evaluate(&g, context);
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(context, &right); let g = parser::parse(&right, context);
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((
@ -266,11 +266,11 @@ fn do_assignment(
// Display parsed string // Display parsed string
output.push(&format!( output.push(&format!(
" [t]=>[n] {left} = {}\n\n", " [t]=>[n] {left} = {}\n\n",
g.display(context) g.to_string()
)); ));
// Evaluate expression // Evaluate expression
let g_evaluated = evaluate::evaluate(context, &g); let g_evaluated = evaluate::evaluate(&g, context);
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

@ -1,6 +1,5 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use crate::quantity::Quantity; use crate::quantity::Quantity;
use crate::context::Context;
use super::Operator; use super::Operator;
use super::Constant; use super::Constant;
@ -18,17 +17,17 @@ pub enum Expression {
Tuple(LineLocation, VecDeque<Expression>), Tuple(LineLocation, VecDeque<Expression>),
} }
impl Expression { impl ToString for Expression {
pub fn display(&self, context: &Context) -> String { fn to_string(&self) -> String {
match self { match self {
Expression::Quantity(_, v) => v.display(context), Expression::Quantity(_, v) => v.to_string(),
Expression::Constant(_, c) => c.to_string(), Expression::Constant(_, c) => c.to_string(),
Expression::Variable(_, s) => s.clone(), Expression::Variable(_, s) => s.clone(),
Expression::Operator(_, o,a) => o.display(context, a), Expression::Operator(_, o,a) => o.print(a),
Expression::Tuple(_, v) => { Expression::Tuple(_, v) => {
format!("({})", format!("({})",
v.iter() v.iter()
.map(|x| x.display(context)) .map(|x| x.to_string())
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
) )
@ -40,16 +39,16 @@ impl Expression {
impl Expression { impl Expression {
// This is called only when this is the outermost Expression. // This is called only when this is the outermost Expression.
// This sometimes leads to different--usually more verbose--behavior. // This sometimes leads to different--usually more verbose--behavior.
pub fn display_outer(&self, context: &Context) -> String { pub fn to_string_outer(&self) -> String {
match self { match self {
Expression::Quantity(_, v) => v.display_outer(context), Expression::Quantity(_, v) => v.to_string_outer(),
Expression::Constant(_, c) => c.to_string(), Expression::Constant(_, c) => c.to_string(),
Expression::Variable(_, s) => s.clone(), Expression::Variable(_, s) => s.clone(),
Expression::Operator(_, o,a) => o.display(context, a), Expression::Operator(_, o,a) => o.print(a),
Expression::Tuple(_, v) => { Expression::Tuple(_, v) => {
format!("({})", format!("({})",
v.iter() v.iter()
.map(|x| x.display(context)) .map(|x| x.to_string())
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
) )

View File

@ -62,7 +62,7 @@ impl Operator {
} }
#[inline(always)] #[inline(always)]
pub fn from_string(context: &Context, s: &str) -> Option<Operator> { pub fn from_string(s: &str, context: &Context) -> Option<Operator> {
let f = Function::from_string(s); let f = Function::from_string(s);
if let Some(f) = f { if let Some(f) = f {
@ -128,8 +128,8 @@ impl Operator {
} }
#[inline(always)] #[inline(always)]
fn add_parens_to_arg(&self, context: &Context, arg: &Expression) -> String { fn add_parens_to_arg(&self, arg: &Expression) -> String {
let mut astr: String = arg.display(context); let mut astr: String = arg.to_string();
if let Expression::Operator(_, o,_) = arg { if let Expression::Operator(_, o,_) = arg {
if o.print_map() < self.print_map() { if o.print_map() < self.print_map() {
astr = format!("({})", astr); astr = format!("({})", astr);
@ -139,8 +139,8 @@ impl Operator {
} }
#[inline(always)] #[inline(always)]
fn add_parens_to_arg_strict(&self, context: &Context, arg: &Expression) -> String { fn add_parens_to_arg_strict(&self, arg: &Expression) -> String {
let mut astr: String = arg.display(context); let mut astr: String = arg.to_string();
if let Expression::Operator(_, o,_) = arg { if let Expression::Operator(_, o,_) = arg {
if o.print_map() <= self.print_map() { if o.print_map() <= self.print_map() {
astr = format!("({})", astr); astr = format!("({})", astr);
@ -150,56 +150,56 @@ impl Operator {
} }
pub fn display(&self, context: &Context, args: &VecDeque<Expression>) -> String { pub fn print(&self, args: &VecDeque<Expression>) -> String {
match self { match self {
Operator::Negative => { Operator::Negative => {
return format!("-{}", self.add_parens_to_arg(context, &args[0])); return format!("-{}", self.add_parens_to_arg(&args[0]));
}, },
Operator::Sqrt => { Operator::Sqrt => {
return format!( return format!(
"√{}", "√{}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
); );
}, },
Operator::ModuloLong => { Operator::ModuloLong => {
return format!( return format!(
"{} mod {}", "{} mod {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
Operator::DivideLong => { Operator::DivideLong => {
return format!( return format!(
"{} per {}", "{} per {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
Operator::UnitConvert => { Operator::UnitConvert => {
return format!( return format!(
"{} to {}", "{} to {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
Operator::Modulo => { Operator::Modulo => {
return format!( return format!(
"{} % {}", "{} % {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
Operator::Subtract => { Operator::Subtract => {
return format!( return format!(
"{} - {}", "{} - {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
@ -207,14 +207,10 @@ impl Operator {
let q = &args[1]; let q = &args[1];
if { if q.is_unitless_integer() && !q.to_string().contains("e") {
context.config.enable_super_powers &&
q.is_unitless_integer() &&
!q.display(context).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.display(context).chars() { for c in q.to_string().chars() {
b.push(match c { b.push(match c {
'-' => '⁻', '-' => '⁻',
'0' => '⁰', '0' => '⁰',
@ -233,27 +229,27 @@ impl Operator {
return format!( return format!(
"{}{}", "{}{}",
self.add_parens_to_arg_strict(context, &args[0]), self.add_parens_to_arg_strict(&args[0]),
b b
); );
} else { } else {
return format!( return format!(
"{}^{}", "{}^{}",
self.add_parens_to_arg_strict(context, &args[0]), self.add_parens_to_arg_strict(&args[0]),
self.add_parens_to_arg_strict(context, &args[1]) self.add_parens_to_arg_strict(&args[1])
); );
} }
}, },
Operator::Factorial => { Operator::Factorial => {
return format!("{}!", self.add_parens_to_arg(context, &args[0])); return format!("{}!", self.add_parens_to_arg(&args[0]));
}, },
Operator::Add => { Operator::Add => {
return format!( return format!(
"{} + {}", "{} + {}",
self.add_parens_to_arg(context, &args[0]), self.add_parens_to_arg(&args[0]),
self.add_parens_to_arg(context, &args[1]) self.add_parens_to_arg(&args[1])
); );
}, },
@ -283,26 +279,26 @@ impl Operator {
if let Expression::Quantity(_, u) = b { if let Expression::Quantity(_, u) = b {
if u.unit.no_space() { if u.unit.no_space() {
return format!("{}{}", return format!("{}{}",
self.add_parens_to_arg_strict(context, a), self.add_parens_to_arg_strict(a),
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
} else { } else {
return format!("{} {}", return format!("{} {}",
self.add_parens_to_arg_strict(context, a), self.add_parens_to_arg_strict(a),
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
} }
} else { } else {
return format!("{}{}", return format!("{}{}",
self.add_parens_to_arg_strict(context, a), self.add_parens_to_arg_strict(a),
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
}; };
} else { } else {
return format!("{} × {}", return format!("{} × {}",
self.add_parens_to_arg_strict(context, a), self.add_parens_to_arg_strict(a),
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
} }
}, },
@ -313,25 +309,25 @@ impl Operator {
if let Expression::Quantity(_, q) = a { if let Expression::Quantity(_, q) = a {
if q.is_one() && context.config.enable_one_over_power { if q.is_one() {
return format!("{}⁻¹", return format!("{}⁻¹",
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
} }
} }
return format!("{} ÷ {}", return format!("{} ÷ {}",
self.add_parens_to_arg_strict(context, a), self.add_parens_to_arg_strict(a),
self.add_parens_to_arg_strict(context, b) self.add_parens_to_arg_strict(b)
); );
}, },
Operator::Function(s) => { Operator::Function(s) => {
return format!("{}({})", s.to_string(), args[0].display(context)); return format!("{}({})", s.to_string(), args[0].to_string());
}, },
Operator::UserFunction(s) => { Operator::UserFunction(s) => {
return format!("{}({})", s, args[0].display(context)); return format!("{}({})", s.to_string(), args[0].to_string());
} }
}; };
} }

View File

@ -18,30 +18,30 @@ use crate::context::Context;
use crate::errors::DaisyError; use crate::errors::DaisyError;
pub fn parse( pub fn parse(
context: &Context, s: &String s: &String, context: &Context
) -> Result<Expression, (LineLocation, DaisyError)> { ) -> Result<Expression, (LineLocation, DaisyError)> {
let expressions = stage::tokenize(context, s); let expressions = stage::tokenize(s, context);
let (_, expressions) = stage::find_subs(expressions); let (_, expressions) = stage::find_subs(expressions);
let g = stage::groupify(context, expressions)?; let g = stage::groupify(expressions, context)?;
let g = stage::treeify(context, g)?; let g = stage::treeify(g, context)?;
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(&Context::new(), s) parse(s, &Context::new())
} }
pub fn substitute(context: &Context, s: &String) -> String { pub fn substitute(s: &String, context: &Context) -> String {
let (_, s) = substitute_cursor(context, s, s.chars().count()); let (_, s) = substitute_cursor(s, s.chars().count(), context);
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(context, s); let expressions = stage::tokenize(s, context);
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(
context: &Context, g: &mut VecDeque<Token>,
g: &mut VecDeque<Token> context: &Context
) -> 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(context, sa); let o = Operator::from_string(sa, context);
o.is_some() && o.is_some() &&
( (
@ -101,11 +101,11 @@ fn lookback_signs(
// Inserts implicit operators // Inserts implicit operators
fn lookback( fn lookback(
context: &Context, g: &mut VecDeque<Token>,
g: &mut VecDeque<Token> context: &Context
) -> Result<(), (LineLocation, DaisyError)> { ) -> Result<(), (LineLocation, DaisyError)> {
lookback_signs(context, g)?; lookback_signs(g, context)?;
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(
context: &Context, mut g: VecDeque<Token>,
mut g: VecDeque<Token> context: &Context
) -> 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(context, &mut v)?; lookback(&mut v, context)?;
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(context, &mut v)?; lookback(&mut v, context)?;
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(context, &mut v)?; lookback(&mut v, context)?;
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(context, s).is_some() { if Operator::from_string(s, context).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(context: &Context, input: &String) -> VecDeque<Token> { pub fn tokenize(input: &String, context: &Context) -> 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(context: &Context, input: &String) -> 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(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
Some(Token::Quantity(_, val)) => { val.push(c); }, Some(Token::Quantity(_, val)) => { val.push(c); },
_ => { _ => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
} else { } else {
// Otherwise, end the number. // Otherwise, end the number.
// We probably have a subtraction. // We probably have a subtraction.
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> 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(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
}, },
',' => { ',' => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
match &mut t { match &mut t {
Some(Token::Operator(_, val)) => { val.push(c); }, Some(Token::Operator(_, val)) => { val.push(c); },
_ => { _ => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
// Group // Group
'(' => { '(' => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
t = Some(Token::GroupStart(LineLocation{pos: i, len: 0})); t = Some(Token::GroupStart(LineLocation{pos: i, len: 0}));
}, },
')' => { ')' => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context, &mut g, t, i); push_token(&mut g, t, i, context);
t = None; t = None;
} }
@ -185,7 +185,7 @@ pub fn tokenize(context: &Context, input: &String) -> VecDeque<Token> {
Some(Token::Word(_, val)) => { val.push(c); }, Some(Token::Word(_, val)) => { val.push(c); },
_ => { _ => {
push_token(context, &mut g, t, i); push_token(&mut g, t, i, context);
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(context: &Context, input: &String) -> VecDeque<Token> {
}; };
} }
push_token(context, &mut g, t, input.chars().count()); push_token(&mut g, t, input.chars().count(), context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, right_pre)?; right = treeify(right_pre, context)?;
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(context, right_pre)?; right = treeify(right_pre, context)?;
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(context, left_pre)?; left = treeify(left_pre, context)?;
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(context, left_pre)?; left = treeify(left_pre, context)?;
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(context, &s); let o = Operator::from_string(&s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, s); let o = Operator::from_string(s, context);
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(context, next_pre)?; next = treeify(next_pre, context)?;
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(context, next_pre)?; next = treeify(next_pre, context)?;
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(context, &s); let o = Operator::from_string(&s, context);
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(
context: &Context, mut g: Token,
mut g: Token context: &Context
) -> 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(context, p)?); t.push_back(treeify(p, context)?);
}; };
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(context, &s); let o = Operator::from_string(&s, context);
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(context, i, g_inner)?; changed = treeify_binary(i, g_inner, context)?;
} else { } else {
changed = treeify_unary(context, i, g_inner, left_associative)?; changed = treeify_unary(i, g_inner, left_associative, context)?;
} }
} }
@ -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(context, i, g_inner)?; treeify_binary(i, g_inner, context)?;
} else { } else {
treeify_unary(context, i, g_inner, left_associative)?; treeify_unary(i, g_inner, left_associative, context)?;
} }
} }
j -= 1 j -= 1
@ -378,7 +378,7 @@ pub fn treeify(
}, },
Token::Tuple(_, _) | Token::Tuple(_, _) |
Token::Group(_,_) => { Token::Group(_,_) => {
treeify(context, g) treeify(g, context)
}, },

View File

@ -7,7 +7,6 @@ use std::ops::{
}; };
use std::cmp::Ordering; use std::cmp::Ordering;
use crate::context::Context;
use crate::quantity::Unit; use crate::quantity::Unit;
use crate::quantity::FreeUnit; use crate::quantity::FreeUnit;
@ -22,12 +21,12 @@ pub struct Quantity {
impl Quantity { impl ToString for Quantity {
pub fn display(&self, context: &Context) -> String { fn to_string(&self) -> String {
let n = self.scalar.to_string(); let n = self.scalar.to_string();
if self.unitless() { return n; } if self.unitless() { return n; }
let u = self.unit.display(context); let u = self.unit.to_string();
if self.is_one() { return u; }; if self.is_one() { return u; };
if self.unit.no_space() { if self.unit.no_space() {
@ -39,11 +38,11 @@ impl Quantity {
} }
impl Quantity { impl Quantity {
pub fn display_outer(&self, context: &Context) -> String { pub fn to_string_outer(&self) -> String {
let n = self.scalar.to_string(); let n = self.scalar.to_string();
if self.unitless() { return n; } if self.unitless() { return n; }
let u = self.unit.display(context); let u = self.unit.to_string();
if self.unit.no_space() { if self.unit.no_space() {
return format!("{n}{u}"); return format!("{n}{u}");
} else { } else {

View File

@ -4,7 +4,6 @@ use std::ops::{
MulAssign, DivAssign MulAssign, DivAssign
}; };
use crate::context::Context;
use crate::quantity::Scalar; use crate::quantity::Scalar;
use crate::quantity::Quantity; use crate::quantity::Quantity;
use super::FreeUnit; use super::FreeUnit;
@ -17,8 +16,8 @@ pub struct Unit {
pub val: HashMap<FreeUnit, Scalar> pub val: HashMap<FreeUnit, Scalar>
} }
impl Unit { impl ToString for Unit {
pub fn display(&self, context: &Context) -> String { fn to_string(&self) -> String {
if self.unitless() { return String::new(); }; if self.unitless() { return String::new(); };
@ -38,11 +37,7 @@ impl Unit {
if *p == Scalar::new_rational(1f64).unwrap() { if *p == Scalar::new_rational(1f64).unwrap() {
t.push_str(&format!("{c}·")); t.push_str(&format!("{c}·"));
} else if { } else if p.is_int() && !p.to_string().contains("e"){
context.config.enable_super_powers &&
p.is_int() &&
!p.to_string().contains("e")
} {
t.push_str(&c); t.push_str(&c);
for c in p.to_string().chars() { for c in p.to_string().chars() {
t.push( match c { t.push( match c {
@ -79,11 +74,7 @@ impl Unit {
bottom_count += 1; bottom_count += 1;
if t.len() != 0 && *p == Scalar::new_rational(-1f64).unwrap() { if t.len() != 0 && *p == Scalar::new_rational(-1f64).unwrap() {
b.push_str(&format!("{c}·")); b.push_str(&format!("{c}·"));
} else if { } else if p.is_int() && !p.to_string().contains("e") {
context.config.enable_super_powers &&
p.is_int() &&
!p.to_string().contains("e")
} {
b.push_str(&c); b.push_str(&c);
for c in p.to_string().chars() { for c in p.to_string().chars() {
if c == '-' && t.len() != 0 { continue; } if c == '-' && t.len() != 0 { continue; }

View File

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