From 90d533e03132bab1032adde78fae3c10903d05cc Mon Sep 17 00:00:00 2001 From: bnewbold Date: Mon, 16 Jan 2017 14:41:46 -0800 Subject: refactor repr/transpile names --- src/bin/mt-tool.rs | 4 +- src/bin/mt-webface.rs | 6 +-- src/lib.rs | 2 +- src/repr_latex.rs | 99 +++++++++++++++++++++++++++++++++++++++++++++++++ src/transpile_js.rs | 18 ++++----- src/transpile_latex.rs | 99 ------------------------------------------------- src/transpile_scheme.rs | 20 +++++----- 7 files changed, 124 insertions(+), 124 deletions(-) create mode 100644 src/repr_latex.rs delete mode 100644 src/transpile_latex.rs diff --git a/src/bin/mt-tool.rs b/src/bin/mt-tool.rs index e554636..f45c739 100644 --- a/src/bin/mt-tool.rs +++ b/src/bin/mt-tool.rs @@ -76,12 +76,12 @@ fn run() -> Result<()> { ("transpile_scheme", Some(subm)) => { let dir = Path::new(subm.value_of("DIR").unwrap()); let me = try!(modelthing::load_model_entry(dir)); - println!("{}", try!(me.ast.repr_scheme())); + println!("{}", try!(me.ast.transpile_scheme())); }, ("transpile_js", Some(subm)) => { let dir = Path::new(subm.value_of("DIR").unwrap()); let me = try!(modelthing::load_model_entry(dir)); - println!("{}", try!(me.ast.repr_js())); + println!("{}", try!(me.ast.transpile_js())); }, ("list", Some(subm)) => { let dir = Path::new(subm.value_of("DIR").unwrap_or("examples")); diff --git a/src/bin/mt-webface.rs b/src/bin/mt-webface.rs index ed0cacb..b9e3cad 100644 --- a/src/bin/mt-webface.rs +++ b/src/bin/mt-webface.rs @@ -21,7 +21,7 @@ use pencil::method::{Get, Post}; use regex::Regex; use modelthing::transpile_scheme::TranspileScheme; use modelthing::transpile_js::TranspileJS; -use modelthing::transpile_latex::TranspileLaTeX; +use modelthing::repr_latex::ReprLaTeX; /* This command doesn't use error_chain (or raise errors in general) because the @@ -108,8 +108,8 @@ fn model_repr(r: &mut Request) -> PencilResult { match modelthing::load_model_entry(model_path.as_path()) { Ok(me) => { match format { - "scheme" => Ok(Response::from(me.ast.repr_scheme().unwrap())), - "javascript" => Ok(Response::from(me.ast.repr_js().unwrap())), + "scheme" => Ok(Response::from(me.ast.transpile_scheme().unwrap())), + "javascript" => Ok(Response::from(me.ast.transpile_js().unwrap())), "latex" => Ok(Response::from(me.ast.repr_latex().unwrap())), _ => abort(403), } diff --git a/src/lib.rs b/src/lib.rs index cf88d3b..a83975a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,7 +11,7 @@ pub extern crate modelica_parser; pub mod modelica_model; pub mod transpile_scheme; pub mod transpile_js; -pub mod transpile_latex; +pub mod repr_latex; use std::path::Path; use std::fs; diff --git a/src/repr_latex.rs b/src/repr_latex.rs new file mode 100644 index 0000000..4c4e34c --- /dev/null +++ b/src/repr_latex.rs @@ -0,0 +1,99 @@ + +extern crate modelica_parser; + +use self::modelica_parser::*; +use errors::Result; + +pub trait ReprLaTeX { + fn repr_latex(&self) -> Result; +} + + +impl ReprLaTeX for ModelicaModel { + fn repr_latex(&self) -> Result { + + let mut result = r#"\begin{array}{rcl}"#.to_string() + "\n"; + + for eq in &self.equations { + result += &format!(" {} & = & {} \\\\\n", + try!(eq.lhs.repr_latex()), + try!(eq.rhs.repr_latex())); + } + result += "\n"; + result += r#"\end{array}"#; + Ok(result) + } +} + +fn is_latexy_ident(s: &str) -> bool { + let latexy_idents = [ + "alpha", "Alpha", "beta", "gamma", "Gamma", "delta", "Delta", + "epsilon", "zeta", "eta", "theta", "Theta", "iota", "kappa", "lambda", + "Lambda", "mu", "nu", "xi", "Xi", "omicron", "pi", "Pi", "rho", + "sigma", "Sigma", "tau", "upsilon", "phi", "Phi", "chi", "psi", "Psi", + "omega", "Omega"]; + latexy_idents.contains(&s) +} + +impl ReprLaTeX for Expr { + fn repr_latex(&self) -> Result { + use modelica_parser::Expr::*; + use modelica_parser::MathUnaryFunc::*; + use modelica_parser::BinOperator::*; + match *self { + Integer(e) => Ok(format!("{}", e)), + Float(e) => Ok(format!("{}", e)), + Boolean(true) => Ok(format!("true")), + Boolean(false) => Ok(format!("false")), + StringLiteral(ref s) => Ok(format!("\\text{{ {} }}", s)), + // Tries to do script for simple cases ("M_1") + Ident(ref e) => { + if e.contains('_') { + let split: Vec<&str> = e.splitn(2, '_').collect(); + Ok(format!(r"{}{}_{{ {}{} }}", + if is_latexy_ident(split[0]) { "\\" } else { "" }, + split[0], + if is_latexy_ident(split[1]) { "\\" } else { "" }, + split[1])) + } else { + Ok(format!("{}{}", + if is_latexy_ident(e) { "\\" } else { "" }, + e)) + } + }, + // Treate simple derivatives (common case) differently from complex + // (destructuring with 'box' keyword is still unstable) + Der(ref e) => + if let &Ident(_) = e.as_ref() { + Ok(format!("\\frac{{ d {} }}{{ dt }}", try!(e.repr_latex()))) + } else { + Ok(format!("\\frac{{ d }}{{ dt }} {}", try!(e.repr_latex()))) + }, + Sign(ref e) => Ok(format!("\\sign{{ {} }}", try!(e.repr_latex()))), + // LaTeX depends on the unary + MathUnaryExpr(Abs, ref e) => Ok(format!("\\left\\|{}\\right\\|", try!(e.repr_latex()))), + MathUnaryExpr(Sqrt, ref e) => Ok(format!("\\sqrt{{ {} }}", try!(e.repr_latex()))), + MathUnaryExpr(Log10, ref e) => Ok(format!("\\log_{{10}}{{ {} }} ", try!(e.repr_latex()))), + MathUnaryExpr(func, ref e) => Ok(format!("\\{:?}{{ {} }}", func, try!(e.repr_latex()))), + // LaTeX depends on binexpr + BinExpr(Divide, ref l, ref r) => + Ok(format!("\\frac{{ {} }}{{ {} }}", + try!(l.repr_latex()), + try!(r.repr_latex()))), + BinExpr(Multiply, ref l, ref r) => + Ok(format!("{} \\cdot {}", + try!(l.repr_latex()), + try!(r.repr_latex()))), + BinExpr(Exponentiate, ref l, ref r) => + Ok(format!("{}^{{ {} }}", + try!(l.repr_latex()), + try!(r.repr_latex()))), + BinExpr(op, ref l, ref r) => + Ok(format!("\\left({} {:?} {}\\right)", + try!(l.repr_latex()), + op, + try!(r.repr_latex()))), + Array(_) => unimplemented!(), + } + } +} diff --git a/src/transpile_js.rs b/src/transpile_js.rs index 4150b12..219364a 100644 --- a/src/transpile_js.rs +++ b/src/transpile_js.rs @@ -5,23 +5,23 @@ use self::modelica_parser::*; use errors::Result; pub trait TranspileJS { - fn repr_js(&self) -> Result; + fn transpile_js(&self) -> Result; } impl TranspileJS for ModelicaModel { - fn repr_js(&self) -> Result { + fn transpile_js(&self) -> Result { let mut constants = vec![]; for (c, e) in self.get_constant_vars() { if let Some(v) = e { - constants.push(format!("var {} = {};", c, try!(v.repr_js()))); + constants.push(format!("var {} = {};", c, try!(v.transpile_js()))); } } let mut binds = vec![]; let mut outputs = vec![]; for eq in self.equations.iter() { if let Expr::Ident(ref symb) = eq.lhs { - binds.push(format!("var {} = {};", symb, try!(eq.rhs.repr_js()))); + binds.push(format!("var {} = {};", symb, try!(eq.rhs.transpile_js()))); outputs.push(symb.to_string()); } else { bail!("Expected an identifier on LHS (in this partial implementation)") @@ -42,7 +42,7 @@ impl TranspileJS for ModelicaModel { } impl TranspileJS for Expr { - fn repr_js(&self) -> Result { + fn transpile_js(&self) -> Result { use modelica_parser::Expr::*; match *self { Integer(e) => Ok(format!("{}", e)), @@ -51,11 +51,11 @@ impl TranspileJS for Expr { Boolean(false) => Ok(format!("false")), StringLiteral(ref s) => Ok(format!("\"{}\"", s)), Ident(ref e) => Ok(format!("{}", e)), - Der(ref e) => Ok(format!("der({})", try!(e.repr_js()))), - Sign(ref e) => Ok(format!("sign({})", try!(e.repr_js()))), - MathUnaryExpr(func, ref e) => Ok(format!("{:?}({})", func, try!(e.repr_js()))), + Der(ref e) => Ok(format!("der({})", try!(e.transpile_js()))), + Sign(ref e) => Ok(format!("sign({})", try!(e.transpile_js()))), + MathUnaryExpr(func, ref e) => Ok(format!("{:?}({})", func, try!(e.transpile_js()))), BinExpr(op, ref l, ref r) => { - Ok(format!("({} {:?} {})", try!(l.repr_js()), op, try!(r.repr_js()))) + Ok(format!("({} {:?} {})", try!(l.transpile_js()), op, try!(r.transpile_js()))) } Array(_) => unimplemented!(), } diff --git a/src/transpile_latex.rs b/src/transpile_latex.rs deleted file mode 100644 index 1c777d2..0000000 --- a/src/transpile_latex.rs +++ /dev/null @@ -1,99 +0,0 @@ - -extern crate modelica_parser; - -use self::modelica_parser::*; -use errors::Result; - -pub trait TranspileLaTeX { - fn repr_latex(&self) -> Result; -} - - -impl TranspileLaTeX for ModelicaModel { - fn repr_latex(&self) -> Result { - - let mut result = r#"\begin{array}{rcl}"#.to_string() + "\n"; - - for eq in &self.equations { - result += &format!(" {} & = & {} \\\\\n", - try!(eq.lhs.repr_latex()), - try!(eq.rhs.repr_latex())); - } - result += "\n"; - result += r#"\end{array}"#; - Ok(result) - } -} - -fn is_latexy_ident(s: &str) -> bool { - let latexy_idents = [ - "alpha", "Alpha", "beta", "gamma", "Gamma", "delta", "Delta", - "epsilon", "zeta", "eta", "theta", "Theta", "iota", "kappa", "lambda", - "Lambda", "mu", "nu", "xi", "Xi", "omicron", "pi", "Pi", "rho", - "sigma", "Sigma", "tau", "upsilon", "phi", "Phi", "chi", "psi", "Psi", - "omega", "Omega"]; - latexy_idents.contains(&s) -} - -impl TranspileLaTeX for Expr { - fn repr_latex(&self) -> Result { - use modelica_parser::Expr::*; - use modelica_parser::MathUnaryFunc::*; - use modelica_parser::BinOperator::*; - match *self { - Integer(e) => Ok(format!("{}", e)), - Float(e) => Ok(format!("{}", e)), - Boolean(true) => Ok(format!("true")), - Boolean(false) => Ok(format!("false")), - StringLiteral(ref s) => Ok(format!("\\text{{ {} }}", s)), - // Tries to do script for simple cases ("M_1") - Ident(ref e) => { - if e.contains('_') { - let split: Vec<&str> = e.splitn(2, '_').collect(); - Ok(format!(r"{}{}_{{ {}{} }}", - if is_latexy_ident(split[0]) { "\\" } else { "" }, - split[0], - if is_latexy_ident(split[1]) { "\\" } else { "" }, - split[1])) - } else { - Ok(format!("{}{}", - if is_latexy_ident(e) { "\\" } else { "" }, - e)) - } - }, - // Treate simple derivatives (common case) differently from complex - // (destructuring with 'box' keyword is still unstable) - Der(ref e) => - if let &Ident(_) = e.as_ref() { - Ok(format!("\\frac{{ d {} }}{{ dt }}", try!(e.repr_latex()))) - } else { - Ok(format!("\\frac{{ d }}{{ dt }} {}", try!(e.repr_latex()))) - }, - Sign(ref e) => Ok(format!("\\sign{{ {} }}", try!(e.repr_latex()))), - // LaTeX depends on the unary - MathUnaryExpr(Abs, ref e) => Ok(format!("\\left\\|{}\\right\\|", try!(e.repr_latex()))), - MathUnaryExpr(Sqrt, ref e) => Ok(format!("\\sqrt{{ {} }}", try!(e.repr_latex()))), - MathUnaryExpr(Log10, ref e) => Ok(format!("\\log_{{10}}{{ {} }} ", try!(e.repr_latex()))), - MathUnaryExpr(func, ref e) => Ok(format!("\\{:?}{{ {} }}", func, try!(e.repr_latex()))), - // LaTeX depends on binexpr - BinExpr(Divide, ref l, ref r) => - Ok(format!("\\frac{{ {} }}{{ {} }}", - try!(l.repr_latex()), - try!(r.repr_latex()))), - BinExpr(Multiply, ref l, ref r) => - Ok(format!("{} \\cdot {}", - try!(l.repr_latex()), - try!(r.repr_latex()))), - BinExpr(Exponentiate, ref l, ref r) => - Ok(format!("{}^{{ {} }}", - try!(l.repr_latex()), - try!(r.repr_latex()))), - BinExpr(op, ref l, ref r) => - Ok(format!("\\left({} {:?} {}\\right)", - try!(l.repr_latex()), - op, - try!(r.repr_latex()))), - Array(_) => unimplemented!(), - } - } -} diff --git a/src/transpile_scheme.rs b/src/transpile_scheme.rs index b206123..e29a422 100644 --- a/src/transpile_scheme.rs +++ b/src/transpile_scheme.rs @@ -5,23 +5,23 @@ use self::modelica_parser::*; use errors::Result; pub trait TranspileScheme { - fn repr_scheme(&self) -> Result; + fn transpile_scheme(&self) -> Result; } impl TranspileScheme for ModelicaModel { - fn repr_scheme(&self) -> Result { + fn transpile_scheme(&self) -> Result { let mut constants = vec![]; for (c, e) in self.get_constant_vars() { if let Some(v) = e { - constants.push(format!("({} {})", c, try!(v.repr_scheme()))); + constants.push(format!("({} {})", c, try!(v.transpile_scheme()))); } } let mut binds = vec![]; let mut outputs = vec![]; for eq in self.equations.iter() { if let Expr::Ident(ref symb) = eq.lhs { - binds.push(format!("({} {})", symb, try!(eq.rhs.repr_scheme()))); + binds.push(format!("({} {})", symb, try!(eq.rhs.transpile_scheme()))); outputs.push(symb.to_string()); } else { bail!("Expected an identifier on LHS (in this partial implementation)") @@ -40,7 +40,7 @@ impl TranspileScheme for ModelicaModel { } impl TranspileScheme for Expr { - fn repr_scheme(&self) -> Result { + fn transpile_scheme(&self) -> Result { use modelica_parser::Expr::*; match *self { Integer(e) => Ok(format!("{}", e)), @@ -49,14 +49,14 @@ impl TranspileScheme for Expr { Boolean(false) => Ok(format!("#f")), StringLiteral(ref s) => Ok(format!("\"{}\"", s)), Ident(ref e) => Ok(format!("{}", e)), - Der(ref e) => Ok(format!("(der {})", try!(e.repr_scheme()))), - Sign(ref e) => Ok(format!("(sign {})", try!(e.repr_scheme()))), - MathUnaryExpr(func, ref e) => Ok(format!("({:?} {})", func, try!(e.repr_scheme()))), + Der(ref e) => Ok(format!("(der {})", try!(e.transpile_scheme()))), + Sign(ref e) => Ok(format!("(sign {})", try!(e.transpile_scheme()))), + MathUnaryExpr(func, ref e) => Ok(format!("({:?} {})", func, try!(e.transpile_scheme()))), BinExpr(op, ref l, ref r) => { Ok(format!("({:?} {} {})", op, - try!(l.repr_scheme()), - try!(r.repr_scheme()))) + try!(l.transpile_scheme()), + try!(r.transpile_scheme()))) } Array(_) => unimplemented!(), } -- cgit v1.2.3