Compare commits

...

5 Commits

Author SHA1 Message Date
Mark edc859dc01
Updated TODO 2023-08-20 17:24:39 -07:00
Mark 77c357c2f3
All style definitions in one place 2023-08-20 16:49:35 -07:00
Mark 3ae5383eed
Minor cleanup 2023-08-20 16:49:05 -07:00
Mark 4055c08217
Fixed incompatible messages when one unit is a scalar 2023-08-20 16:33:34 -07:00
Mark 6969d17cce
Added substitution config switch 2023-08-20 16:19:57 -07:00
8 changed files with 197 additions and 144 deletions

View File

@ -14,6 +14,7 @@
- Tuple operations - Tuple operations
- we don't need vectors as arguments to operators - we don't need vectors as arguments to operators
- Assignment tests - Assignment tests
- Color check is too slow
## Parser ## Parser
- Better error when `sin = 2` - Better error when `sin = 2`

View File

@ -19,7 +19,7 @@ pub struct Config {
// with prettier unicode alternatives? // with prettier unicode alternatives?
// //
// Automatically disabled if enable_unicode is off. // Automatically disabled if enable_unicode is off.
//pub enable_substituion: bool, pub enable_substituion: bool,
// Should we print simple powers // Should we print simple powers
// as unicode superscript chars? // as unicode superscript chars?
@ -38,7 +38,7 @@ impl Config {
pub fn new() -> Config { pub fn new() -> Config {
Config{ Config{
term_color_type: 2, term_color_type: 2,
//enable_substituion: true, enable_substituion: true,
//enable_unicode: true, //enable_unicode: true,
enable_super_powers: true, enable_super_powers: true,
enable_one_over_power: true enable_one_over_power: true

View File

@ -1,11 +1,12 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use std::io::Write; use std::io::Write;
use termion::raw::RawTerminal; use termion::raw::RawTerminal;
use termion::color; use crate::formattedtext;
use termion::style;
use crate::parser::substitute_cursor; use crate::parser::substitute_cursor;
use crate::context::Context; use crate::context::Context;
const PROMPT_STR: &str = "==> ";
#[derive(Debug)] #[derive(Debug)]
pub struct PromptBuffer { pub struct PromptBuffer {
// History // History
@ -38,30 +39,11 @@ 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, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
// Draw prettyprinted expression let tmp = self.cursor;
let (_, s) = substitute_cursor(context, &self.get_contents(), self.buffer.chars().count()); self.cursor = 0;
let r = self.write_prompt(context, stdout);
write!( self.cursor = tmp;
stdout, "\r{}{}==>{}{} {}", return r;
style::Bold,
color::Fg(color::Blue),
color::Fg(color::Reset),
style::Reset,
s
)?;
// If this string is shorter, clear the remaining old one.
if s.chars().count() < self.last_print_len {
write!(
stdout, "{}{}",
" ".repeat(self.last_print_len - s.chars().count()),
termion::cursor::Left((self.last_print_len - s.chars().count()) as u16)
)?;
}
self.last_print_len = s.chars().count();
stdout.flush()?;
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, context: &Context, stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
@ -69,38 +51,30 @@ impl PromptBuffer {
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_c, s) = substitute_cursor(context, &self.get_contents(), i);
write!( write!(
stdout, "\r{}{}==>{}{} {}", stdout, "\r{}{PROMPT_STR}{}{}",
style::Bold, formattedtext::format_map('p', context).unwrap(),
color::Fg(color::Blue), formattedtext::format_map('n', context).unwrap(),
color::Fg(color::Reset),
style::Reset,
s s
)?; )?;
// If this string is shorter, clear the remaining old one. // If this string is shorter, clear the remaining old one.
if s.chars().count() < self.last_print_len { if s.chars().count() < self.last_print_len {
write!(
stdout, "{}{}",
" ".repeat(self.last_print_len - s.chars().count()),
termion::cursor::Left((self.last_print_len - s.chars().count()) as u16)
)?;
}
// Move cursor to correct position
if display_cursor != 0 {
write!( write!(
stdout, "{}", stdout, "{}",
termion::cursor::Left(display_cursor as u16) " ".repeat(self.last_print_len - s.chars().count()),
)?; )?;
stdout.flush()?;
} }
self.last_print_len = s.chars().count();
write!(
stdout, "\r{}",
termion::cursor::Right((display_c + PROMPT_STR.chars().count()) as u16)
)?;
stdout.flush()?; stdout.flush()?;
self.last_print_len = s.chars().count();
return Ok(()); return Ok(());
} }

View File

@ -23,11 +23,11 @@ pub fn main() -> Result<(), std::io::Error> {
// Set color compatibilty // Set color compatibilty
let term_colors = stdout.available_colors().unwrap_or(0); let term_colors = stdout.available_colors().unwrap_or(0);
if term_colors >= 256 { if term_colors >= 256 {
context.config.term_color_type = 2 context.config.term_color_type = 2;
} else if term_colors >= 8 { } else if term_colors >= 8 {
context.config.term_color_type = 1 context.config.term_color_type = 1;
} else { } else {
context.config.term_color_type = 0 context.config.term_color_type = 0;
} }
context.config.check(); context.config.check();

View File

@ -75,12 +75,26 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
if let Expression::Quantity(la, a) = a { if let Expression::Quantity(la, a) = a {
if let Expression::Quantity(lb, b) = b { if let Expression::Quantity(lb, b) = b {
if !a.unit.compatible_with(&b.unit) { if !a.unit.compatible_with(&b.unit) {
let a = a.convert_to_base().unit;
let b = b.convert_to_base().unit;
let a_s: String;
let b_s: String;
if a.unitless() {
a_s = String::from("scalar");
} else {
a_s = a.display(context);
}
if b.unitless() {
b_s = String::from("scalar");
} else {
b_s = b.display(context);
}
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(a_s, b_s)
a.convert_to_base().unit.display(context),
b.convert_to_base().unit.display(context)
)
)); ));
} }
return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, a.clone() + b.clone()))); return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, a.clone() + b.clone())));
@ -98,12 +112,24 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
if let Expression::Quantity(la, a) = a { if let Expression::Quantity(la, a) = a {
if let Expression::Quantity(lb, b) = b { if let Expression::Quantity(lb, b) = b {
if !a.unit.compatible_with(&b.unit) { if !a.unit.compatible_with(&b.unit) {
let a_s: String;
let b_s: String;
if a.unitless() {
a_s = String::from("scalar");
} else {
a_s = a.display(context);
}
if b.unitless() {
b_s = String::from("scalar");
} else {
b_s = b.display(context);
}
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(a_s, b_s)
a.convert_to_base().unit.display(context),
b.convert_to_base().unit.display(context)
)
)); ));
} }
return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, a.clone() - b.clone()))); return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, a.clone() - b.clone())));
@ -181,12 +207,26 @@ pub fn eval_operator(context: &mut Context, g: &Expression) -> Result<Option<Exp
if let Expression::Quantity(lb, vb) = b { if let Expression::Quantity(lb, vb) = b {
let n = va.clone().convert_to(vb.clone()); let n = va.clone().convert_to(vb.clone());
if n.is_none() { if n.is_none() {
let va = va.convert_to_base().unit;
let vb = vb.convert_to_base().unit;
let a_s: String;
let b_s: String;
if va.unitless() {
a_s = String::from("scalar");
} else {
a_s = a.display(context);
}
if vb.unitless() {
b_s = String::from("scalar");
} else {
b_s = b.display(context);
}
return Err(( return Err((
*la + *lb + *op_loc, *la + *lb + *op_loc,
DaisyError::IncompatibleUnits( DaisyError::IncompatibleUnits(a_s, b_s)
va.convert_to_base().unit.display(context),
vb.convert_to_base().unit.display(context)
)
)); ));
} }
return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, n.unwrap()))); return Ok(Some(Expression::Quantity(*la + *lb + *op_loc, n.unwrap())));

View File

@ -22,7 +22,8 @@ impl ToString for FormattedText {
fn format_map_none(c: char) -> Option<String> { fn format_map_none(c: char) -> Option<String> {
Some(match c { Some(match c {
'n'|'i'|'t'|'a'| 'n'|'i'|'t'|'a'|
'e'|'c'|'s'|'r' 'e'|'c'|'s'|'r'|
'p'
=> { "".to_string() }, => { "".to_string() },
_ => { return None } _ => { return None }
}) })
@ -37,24 +38,27 @@ fn format_map_ansi(c: char) -> Option<String> {
'i' => { // Normal italic text 'i' => { // Normal italic text
format!("{}{}", color::Fg(color::Reset), color::Bg(color::Reset)) format!("{}{}", color::Fg(color::Reset), color::Bg(color::Reset))
}, },
't' => { // Title text 't' => { // Title text (should be cyan)
format!("{}{}", color::Fg(color::AnsiValue(6)), color::Bg(color::Reset)) format!("{}{}", color::Fg(color::AnsiValue(6)), color::Bg(color::Reset))
}, },
'a' => { // Colored text 'a' => { // Colored text (should be pink)
format!("{}{}", color::Fg(color::AnsiValue(5)), color::Bg(color::Reset)) format!("{}{}", color::Fg(color::AnsiValue(5)), color::Bg(color::Reset))
}, },
'e' => { // Error titles 'e' => { // Error titles (should be red)
format!("{}{}", color::Fg(color::AnsiValue(1)), color::Bg(color::Reset)) format!("{}{}", color::Fg(color::AnsiValue(1)), color::Bg(color::Reset))
}, },
'c' => { // Console text 'c' => { // Console text (inverted black on white)
format!("{}{}", color::Fg(color::AnsiValue(0)), color::Bg(color::AnsiValue(7))) format!("{}{}", color::Fg(color::AnsiValue(0)), color::Bg(color::AnsiValue(7)))
}, },
's' => { // Repeat prompt (how => is styled) 'p' => { // Input prompt (how ==> is styled) (should be blue)
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)) format!("{}{}", color::Fg(color::AnsiValue(4)), color::Bg(color::Reset))
}, },
's' => { // Repeat prompt (how => is styled) (should be pink)
format!("{}{}", color::Fg(color::AnsiValue(5)), color::Bg(color::Reset))
},
'r' => { // Result prompt (how = is styled) (should be green)
format!("{}{}", color::Fg(color::AnsiValue(2)), color::Bg(color::Reset))
},
_ => { return None } _ => { return None }
}) })
@ -83,6 +87,9 @@ fn format_map_full(c: char) -> Option<String> {
'c' => { // Console text 'c' => { // Console text
format!("{}{}", color::Fg(color::LightBlack), style::Italic) format!("{}{}", color::Fg(color::LightBlack), style::Italic)
}, },
'p' => { // Input prompt (how ==> is styled)
format!("{}{}", color::Fg(color::Blue), style::Bold)
},
's' => { // Repeat prompt (how => is styled) 's' => { // Repeat prompt (how => is styled)
format!("{}{}", color::Fg(color::Magenta), style::Bold) format!("{}{}", color::Fg(color::Magenta), style::Bold)
}, },
@ -90,17 +97,24 @@ fn format_map_full(c: char) -> Option<String> {
format!("{}{}", color::Fg(color::Green), style::Bold) format!("{}{}", color::Fg(color::Green), style::Bold)
}, },
_ => { return None } _ => { return None }
}) })
} }
pub fn format_map(c: char, context: &Context) -> Option<String> {
match context.config.term_color_type {
0 => format_map_none(c),
1 => format_map_ansi(c),
2 => format_map_full(c),
_ => unreachable!("Invalid term_color_type")
}
}
impl FormattedText { impl FormattedText {
pub fn newline(stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> { pub fn newline(stdout: &mut RawTerminal<std::io::Stdout>) -> Result<(), std::io::Error> {
write!( write!(stdout, "\n")?;
stdout,
"\r\n",
)?;
return Ok(()); return Ok(());
} }
} }
@ -147,12 +161,7 @@ impl FormattedText {
match (a, b) { match (a, b) {
(c, ']') => { // Normal text (c, ']') => { // Normal text
let q = match context.config.term_color_type { let q = format_map(c, context);
0 => format_map_none(c),
1 => format_map_ansi(c),
2 => format_map_full(c),
_ => unreachable!("Invalid term_color_type")
};
if q.is_some() { if q.is_some() {
s.push_str(&q.unwrap()); s.push_str(&q.unwrap());
@ -175,7 +184,7 @@ impl FormattedText {
} }
} }
write!(stdout, "{}", s)?; write!(stdout, "\r{}", s)?;
return Ok(()); return Ok(());
} }
} }

View File

@ -21,8 +21,10 @@ pub fn parse(
context: &Context, s: &String context: &Context, s: &String
) -> Result<Expression, (LineLocation, DaisyError)> { ) -> Result<Expression, (LineLocation, DaisyError)> {
let expressions = stage::tokenize(context, s); let mut expressions = stage::tokenize(context, s);
let (_, expressions) = stage::find_subs(expressions); if context.config.enable_substituion {
(_, expressions) = stage::find_subs(expressions);
}
let g = stage::groupify(context, expressions)?; let g = stage::groupify(context, expressions)?;
let g = stage::treeify(context, g)?; let g = stage::treeify(context, g)?;
@ -34,6 +36,7 @@ pub fn parse_no_context(s: &String) -> Result<Expression, (LineLocation, DaisyEr
} }
pub fn substitute(context: &Context, s: &String) -> String { pub fn substitute(context: &Context, s: &String) -> String {
if !context.config.enable_substituion { return s.clone(); }
let (_, s) = substitute_cursor(context, s, s.chars().count()); let (_, s) = substitute_cursor(context, s, s.chars().count());
return s; return s;
} }
@ -43,34 +46,45 @@ pub fn substitute_cursor(
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
) -> ( ) -> (
usize, // Location of cursor in substituted string usize, // New cursor
String // String with substitutions String // String with substitutions
) { ) {
if !context.config.enable_substituion { return (c, s.clone()); }
if s == "" { return (c, s.clone()) } if s == "" { return (c, s.clone()) }
let mut new_s = s.clone(); let mut new_s = s.clone();
let l = s.chars().count();
let expressions = stage::tokenize(context, s); 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 = c.clone();
while subs.len() > 0 { while subs.len() > 0 {
let r = subs.pop_back().unwrap();
// Apply substitutions in reverse order // Apply substitutions in reverse order
// r is the current substitution: (linelocation, string)
let r = subs.pop_back().unwrap();
if { // Don't substitute if our cursor is inside the substitution if { // Don't substitute if our cursor is inside the substitution
c >= r.0.pos && c >= r.0.pos &&
c < r.0.pos+r.0.len c < r.0.pos+r.0.len
} { continue; } } { continue; }
if c < r.0.pos { // If this substitution is before our cursor,
let ct = r.1.chars().count(); // we need to adjust our cursor's position.
if ct >= r.0.len { if c > r.0.pos {
if new_c >= ct - r.0.len { let c_o = r.0.len; // Old length
new_c += ct - r.0.len let c_n = r.1.chars().count(); // New length
}
} else { if c_n > c_o {
new_c -= r.0.len - ct // Move cursor right by difference
new_c += c_n - c_o;
} else if c_n < c_o {
// Move cursor left by difference
if new_c >= c_o - c_n {
new_c -= c_o - c_n;
} else { new_c = 0; }
} }
} }

View File

@ -6,6 +6,64 @@ use super::super::{
}; };
fn sub_string(s: &str) -> Option<&'static str> {
let r = match s {
/* Only found in operator tokens */
"*" => "×",
"/" => "÷",
"sqrt" => "",
"rt" => "",
/* Only found in word tokens */
// Greek letters
"alpha" => "α",
"beta" => "β",
"gamma" => "γ",
"delta" => "δ",
"epsilon" => "ε",
"zeta" => "ζ",
"eta" => "η",
"theta" => "θ",
//"iota" => {Some("ι")}, // looks just like i
//"kappa" => {Some("κ")}, // looks just like k
"lambda" => "λ",
"mu" => "μ",
//"nu" => {Some("ν")}, // looks just like v
"xi" => "ξ",
//"omicron" => {Some("ο")}, // looks exactly like o
"pi" => "π",
"rho" => "ρ",
"sigma" => "σ",
"tau" => "τ",
//"upsilon" => {Some("υ")}, // looks just like u
"phi" => "φ",
"chi" => "χ",
//"psi" => {Some("ψ")}, Conflict with pound / square inch
"omega" => "ω",
// Constants
"epsilon_zero" => "ε₀",
"eps_zero" => "ε₀",
"g_zero" => "g₀",
"mu_zero" => "μ₀",
"h_bar" => "",
// Misc
"deg" => "°",
_ => { return None; }
};
return Some(r);
}
pub fn find_subs( pub fn find_subs(
mut g: VecDeque<Token>, mut g: VecDeque<Token>,
) -> ( ) -> (
@ -24,62 +82,19 @@ pub fn find_subs(
while g.len() > 0 { while g.len() > 0 {
let mut t = g.pop_front().unwrap(); let mut t = g.pop_front().unwrap();
let target: Option<&str> = match &mut t { let target: Option<&str> = match &mut t {
Token::Operator(_, s) => { Token::Operator(_, s) => {
let target = match &s[..] { let target = sub_string(s);
"*" => {Some("×")},
"/" => {Some("÷")},
"sqrt" => {Some("")},
"rt" => {Some("")},
_ => {None}
};
// Update token contents too. // Update token contents too.
// This makes sure that errors also contain the updated text. // This makes errors and printouts use the updated string.
if target.is_some() { *s = String::from(target.unwrap()); } if target.is_some() { *s = String::from(target.unwrap()); }
target target
}, },
Token::Word(_, s) => { Token::Word(_, s) => {
let target = match &s[..] { let target = sub_string(s);
// Greek letters
"alpha" => {Some("α")},
"beta" => {Some("β")},
"gamma" => {Some("γ")},
"delta" => {Some("δ")},
"epsilon" => {Some("ε")},
"zeta" => {Some("ζ")},
"eta" => {Some("η")},
"theta" => {Some("θ")},
//"iota" => {Some("ι")},
//"kappa" => {Some("κ")},
"lambda" => {Some("λ")},
"mu" => {Some("μ")},
//"nu" => {Some("ν")},
"xi" => {Some("ξ")},
//"omicron" => {Some("ο")},
"pi" => {Some("π")},
"rho" => {Some("ρ")},
"sigma" => {Some("σ")},
"tau" => {Some("τ")},
//"upsilon" => {Some("υ")},
"phi" => {Some("φ")},
"chi" => {Some("χ")},
//"psi" => {Some("ψ")}, Conflict with pound / square inch
"omega" => {Some("ω")},
// Constants
"epsilon_zero" => {Some("ε₀")},
"eps_zero" => {Some("ε₀")},
"g_zero" => {Some("g₀")},
"mu_zero" => {Some("μ₀")},
"h_bar" => {Some("")},
// Misc
"deg" => {Some("°")}
_ => {None}
};
if target.is_some() { *s = String::from(target.unwrap()); } if target.is_some() { *s = String::from(target.unwrap()); }
target target
}, },