Commit 6b6c745e authored by Michael Aaron Murphy's avatar Michael Aaron Murphy
Browse files

Apply rustfmt

parent 33253fd2
...@@ -4,7 +4,11 @@ ...@@ -4,7 +4,11 @@
// const MIN_VERSION: &'static str = "1.19.0"; // const MIN_VERSION: &'static str = "1.19.0";
use std::{ use std::{
env, fs::File, io::{self, Read, Write}, path::Path, process::Command, env,
fs::File,
io::{self, Read, Write},
path::Path,
process::Command,
}; };
fn main() { fn main() {
......
extern crate permutate; extern crate permutate;
extern crate smallvec;
extern crate small; extern crate small;
extern crate smallvec;
use permutate::Permutator; use permutate::Permutator;
use smallvec::SmallVec; use smallvec::SmallVec;
......
use calculate::{eval, eval_polish, CalcError, Value}; use calculate::{eval, eval_polish, CalcError, Value};
use std::io::{self, Write};
use small; use small;
use std::io::{self, Write};
const REPL_GUIDE: &'static str = r#"ion-calc const REPL_GUIDE: &'static str = r#"ion-calc
Type in expressions to have them evaluated. Type in expressions to have them evaluated.
......
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
use std::io::{self, Write};
use small; use small;
use std::io::{self, Write};
#[allow(unused_must_use)] #[allow(unused_must_use)]
fn rand_list(args: &[small::String]) -> Result<(), small::String> { fn rand_list(args: &[small::String]) -> Result<(), small::String> {
......
...@@ -114,8 +114,7 @@ AUTHOR ...@@ -114,8 +114,7 @@ AUTHOR
Written by Michael Murphy. Written by Michael Murphy.
"#; "#;
const QUICK_GUIDE: &'static str = const QUICK_GUIDE: &'static str = r#"Usage: test [EXPRESSION]
r#"Usage: test [EXPRESSION]
Try 'test --help' for more information."#; Try 'test --help' for more information."#;
pub fn test(args: &[small::String]) -> Result<bool, small::String> { pub fn test(args: &[small::String]) -> Result<bool, small::String> {
...@@ -223,7 +222,10 @@ fn get_modified_file_time(filename: &str) -> Option<SystemTime> { ...@@ -223,7 +222,10 @@ fn get_modified_file_time(filename: &str) -> Option<SystemTime> {
} }
/// Attempt to parse a &str as a usize. /// Attempt to parse a &str as a usize.
fn parse_integers(left: &str, right: &str) -> Result<(Option<isize>, Option<isize>), small::String> { fn parse_integers(
left: &str,
right: &str,
) -> Result<(Option<isize>, Option<isize>), small::String> {
let parse_integer = |input: &str| -> Result<Option<isize>, small::String> { let parse_integer = |input: &str| -> Result<Option<isize>, small::String> {
match input match input
.parse::<isize>() .parse::<isize>()
...@@ -385,18 +387,13 @@ fn test_strings() { ...@@ -385,18 +387,13 @@ fn test_strings() {
fn test_empty_str() { fn test_empty_str() {
let eval = |args: Vec<small::String>| evaluate_arguments(&args); let eval = |args: Vec<small::String>| evaluate_arguments(&args);
assert_eq!(eval(vec!["".into()]), Ok(false)); assert_eq!(eval(vec!["".into()]), Ok(false));
assert_eq!( assert_eq!(eval(vec!["c".into(), "=".into(), "".into()]), Ok(false));
eval(vec!["c".into(), "=".into(), "".into()]),
Ok(false)
);
} }
#[test] #[test]
fn test_integers_arguments() { fn test_integers_arguments() {
fn vec_string(args: &[&str]) -> Vec<small::String> { fn vec_string(args: &[&str]) -> Vec<small::String> {
args.iter() args.iter().map(|s| (*s).into()).collect()
.map(|s| (*s).into())
.collect()
} }
// Equal To // Equal To
assert_eq!( assert_eq!(
......
use std::fmt::{self, Display, Formatter};
use super::Primitive; use super::Primitive;
use std::fmt::{self, Display, Formatter};
/// Keys are used in assignments to define which variable will be set, and whether the correct /// Keys are used in assignments to define which variable will be set, and whether the correct
/// types are being assigned. /// types are being assigned.
...@@ -64,7 +64,9 @@ impl<'a> KeyIterator<'a> { ...@@ -64,7 +64,9 @@ impl<'a> KeyIterator<'a> {
loop { loop {
let mut eol = self.read + 1 >= self.data.len(); let mut eol = self.read + 1 >= self.data.len();
if self.data.as_bytes()[self.read] == b']' && (eol || self.data.as_bytes()[self.read + 1] == b' ') { if self.data.as_bytes()[self.read] == b']'
&& (eol || self.data.as_bytes()[self.read + 1] == b' ')
{
let kind = match &self.data[index_ident_start..self.read] { let kind = match &self.data[index_ident_start..self.read] {
"" => Primitive::AnyArray, "" => Primitive::AnyArray,
s => Primitive::Indexed(s.to_owned(), Box::new(Primitive::Any)), s => Primitive::Indexed(s.to_owned(), Box::new(Primitive::Any)),
...@@ -72,7 +74,9 @@ impl<'a> KeyIterator<'a> { ...@@ -72,7 +74,9 @@ impl<'a> KeyIterator<'a> {
self.read += 1; self.read += 1;
break Ok(Key { name, kind }); break Ok(Key { name, kind });
} else if self.data.as_bytes()[self.read] == b']' && self.data.as_bytes()[self.read + 1] == b':' { } else if self.data.as_bytes()[self.read] == b']'
&& self.data.as_bytes()[self.read + 1] == b':'
{
let index_ident_end = self.read; let index_ident_end = self.read;
self.read += 2; self.read += 2;
...@@ -86,8 +90,12 @@ impl<'a> KeyIterator<'a> { ...@@ -86,8 +90,12 @@ impl<'a> KeyIterator<'a> {
"" => Primitive::AnyArray, "" => Primitive::AnyArray,
s => match Primitive::parse(&self.data[index_ident_end + 2..self.read]) { s => match Primitive::parse(&self.data[index_ident_end + 2..self.read]) {
Some(kind) => Primitive::Indexed(s.to_owned(), Box::new(kind)), Some(kind) => Primitive::Indexed(s.to_owned(), Box::new(kind)),
None => break Err(TypeError::Invalid(self.data[index_ident_end + 1..self.read].into())), None => {
} break Err(TypeError::Invalid(
self.data[index_ident_end + 1..self.read].into(),
))
}
},
}; };
break Ok(Key { name, kind }); break Ok(Key { name, kind });
...@@ -164,11 +172,11 @@ mod tests { ...@@ -164,11 +172,11 @@ mod tests {
#[test] #[test]
fn key_parsing() { fn key_parsing() {
let mut parser = KeyIterator::new("a:int b[] c:bool d e:int[] \ let mut parser = KeyIterator::new(
f[0] g[$index] h[1]:int \ "a:int b[] c:bool d e:int[] f[0] g[$index] h[1]:int i:hmap[] j:hmap[float] \
i:hmap[] j:hmap[float] k:hmap[int[]] l:hmap[hmap[bool[]]] \ k:hmap[int[]] l:hmap[hmap[bool[]]] m:bmap[] n:bmap[int] o:bmap[float[]] \
m:bmap[] n:bmap[int] o:bmap[float[]] p:bmap[hmap[bool]] \ p:bmap[hmap[bool]] d:a",
d:a"); );
assert_eq!( assert_eq!(
parser.next().unwrap(), parser.next().unwrap(),
Ok(Key { Ok(Key {
...@@ -250,7 +258,9 @@ mod tests { ...@@ -250,7 +258,9 @@ mod tests {
parser.next().unwrap(), parser.next().unwrap(),
Ok(Key { Ok(Key {
name: "l", name: "l",
kind: Primitive::HashMap(Box::new(Primitive::HashMap(Box::new(Primitive::BooleanArray)))), kind: Primitive::HashMap(Box::new(Primitive::HashMap(Box::new(
Primitive::BooleanArray
)))),
},) },)
); );
assert_eq!( assert_eq!(
...@@ -278,7 +288,9 @@ mod tests { ...@@ -278,7 +288,9 @@ mod tests {
parser.next().unwrap(), parser.next().unwrap(),
Ok(Key { Ok(Key {
name: "p", name: "p",
kind: Primitive::BTreeMap(Box::new(Primitive::HashMap(Box::new(Primitive::Boolean)))), kind: Primitive::BTreeMap(Box::new(Primitive::HashMap(Box::new(
Primitive::Boolean
)))),
},) },)
); );
assert_eq!(parser.next().unwrap(), Err(TypeError::Invalid("a".into()))); assert_eq!(parser.next().unwrap(), Err(TypeError::Invalid("a".into())));
......
...@@ -2,13 +2,17 @@ mod keys; ...@@ -2,13 +2,17 @@ mod keys;
mod operator; mod operator;
mod primitive; mod primitive;
pub use self::keys::{Key, KeyBuf, KeyIterator, TypeError}; pub use self::{
pub use self::operator::Operator; keys::{Key, KeyBuf, KeyIterator, TypeError},
pub use self::primitive::Primitive; operator::Operator,
primitive::Primitive,
};
/// Given an valid assignment expression, this will split it into `keys`, /// Given an valid assignment expression, this will split it into `keys`,
/// `operator`, `values`. /// `operator`, `values`.
pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Operator>, Option<&'a str>) { pub fn assignment_lexer<'a>(
statement: &'a str,
) -> (Option<&'a str>, Option<Operator>, Option<&'a str>) {
let statement = statement.trim(); let statement = statement.trim();
if statement.is_empty() { if statement.is_empty() {
return (None, None, None); return (None, None, None);
...@@ -35,7 +39,7 @@ pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Oper ...@@ -35,7 +39,7 @@ pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Oper
operator = Some(op); operator = Some(op);
start = read; start = read;
read = found; read = found;
break break;
} }
} }
} }
...@@ -59,10 +63,10 @@ pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Oper ...@@ -59,10 +63,10 @@ pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Oper
fn find_operator(bytes: &[u8], read: usize) -> Option<(Operator, usize)> { fn find_operator(bytes: &[u8], read: usize) -> Option<(Operator, usize)> {
if bytes.len() <= read + 3 { if bytes.len() <= read + 3 {
None None
} else if bytes[read+1] == b'=' { } else if bytes[read + 1] == b'=' {
Operator::parse_single(bytes[read]).map(|op| (op, read + 2)) Operator::parse_single(bytes[read]).map(|op| (op, read + 2))
} else if bytes[read+2] == b'=' { } else if bytes[read + 2] == b'=' {
Operator::parse_double(&bytes[read..read+2]).map(|op| (op, read + 3)) Operator::parse_double(&bytes[read..read + 2]).map(|op| (op, read + 3))
} else { } else {
None None
} }
...@@ -74,14 +78,8 @@ mod tests { ...@@ -74,14 +78,8 @@ mod tests {
#[test] #[test]
fn assignment_splitting() { fn assignment_splitting() {
assert_eq!( assert_eq!(assignment_lexer(""), (None, None, None));
assignment_lexer(""), assert_eq!(assignment_lexer("abc"), (Some("abc"), None, None));
(None, None, None)
);
assert_eq!(
assignment_lexer("abc"),
(Some("abc"), None, None)
);
assert_eq!( assert_eq!(
assignment_lexer("abc+=def"), assignment_lexer("abc+=def"),
......
...@@ -21,35 +21,39 @@ impl Operator { ...@@ -21,35 +21,39 @@ impl Operator {
b'-' => Some(Operator::Subtract), b'-' => Some(Operator::Subtract),
b'/' => Some(Operator::Divide), b'/' => Some(Operator::Divide),
b'*' => Some(Operator::Multiply), b'*' => Some(Operator::Multiply),
_ => None, _ => None,
} }
} }
pub(crate) fn parse_double(data: &[u8]) -> Option<Operator> { pub(crate) fn parse_double(data: &[u8]) -> Option<Operator> {
match data { match data {
b"//" => Some(Operator::IntegerDivide), b"//" => Some(Operator::IntegerDivide),
b"**" => Some(Operator::Exponent), b"**" => Some(Operator::Exponent),
b"++" => Some(Operator::Concatenate), b"++" => Some(Operator::Concatenate),
b"::" => Some(Operator::ConcatenateHead), b"::" => Some(Operator::ConcatenateHead),
b"\\\\" => Some(Operator::Filter), b"\\\\" => Some(Operator::Filter),
_ => None, _ => None,
} }
} }
} }
impl Display for Operator { impl Display for Operator {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", match *self { write!(
Operator::Add => "+=", f,
Operator::Concatenate => "++=", "{}",
Operator::ConcatenateHead => "::=", match *self {
Operator::Filter => "\\\\=", Operator::Add => "+=",
Operator::Divide => "/=", Operator::Concatenate => "++=",
Operator::Equal => "=", Operator::ConcatenateHead => "::=",
Operator::Exponent => "**=", Operator::Filter => "\\\\=",
Operator::IntegerDivide => "//=", Operator::Divide => "/=",
Operator::Multiply => "*=", Operator::Equal => "=",
Operator::Subtract => "-=", Operator::Exponent => "**=",
}) Operator::IntegerDivide => "//=",
Operator::Multiply => "*=",
Operator::Subtract => "-=",
}
)
} }
} }
...@@ -34,22 +34,26 @@ impl Primitive { ...@@ -34,22 +34,26 @@ impl Primitive {
fn parse_inner_hash_map(inner: &str) -> Option<Primitive> { fn parse_inner_hash_map(inner: &str) -> Option<Primitive> {
match inner { match inner {
"" => Some(Primitive::HashMap(Box::new(Primitive::Any))), "" => Some(Primitive::HashMap(Box::new(Primitive::Any))),
_ => Primitive::parse(inner).map(|p| Primitive::HashMap(Box::new(p))) _ => Primitive::parse(inner).map(|p| Primitive::HashMap(Box::new(p))),
} }
} }
fn parse_inner_btree_map(inner: &str) -> Option<Primitive> { fn parse_inner_btree_map(inner: &str) -> Option<Primitive> {
match inner { match inner {
"" => Some(Primitive::BTreeMap(Box::new(Primitive::Any))), "" => Some(Primitive::BTreeMap(Box::new(Primitive::Any))),
_ => Primitive::parse(inner).map(|p| Primitive::BTreeMap(Box::new(p))) _ => Primitive::parse(inner).map(|p| Primitive::BTreeMap(Box::new(p))),
} }
} }
let res = if kind.starts_with("hmap[") { let res = if kind.starts_with("hmap[") {
let kind = &kind[5..]; let kind = &kind[5..];
kind.rfind(']').map(|found| &kind[..found]).and_then(parse_inner_hash_map) kind.rfind(']')
.map(|found| &kind[..found])
.and_then(parse_inner_hash_map)
} else if kind.starts_with("bmap[") { } else if kind.starts_with("bmap[") {
let kind = &kind[5..]; let kind = &kind[5..];
kind.rfind(']').map(|found| &kind[..found]).and_then(parse_inner_btree_map) kind.rfind(']')
.map(|found| &kind[..found])
.and_then(parse_inner_btree_map)
} else { } else {
None None
}; };
...@@ -77,18 +81,14 @@ impl Display for Primitive { ...@@ -77,18 +81,14 @@ impl Display for Primitive {
Primitive::Integer => write!(f, "int"), Primitive::Integer => write!(f, "int"),
Primitive::IntegerArray => write!(f, "int[]"), Primitive::IntegerArray => write!(f, "int[]"),
Primitive::StrArray => write!(f, "str[]"), Primitive::StrArray => write!(f, "str[]"),
Primitive::HashMap(ref kind) => { Primitive::HashMap(ref kind) => match **kind {
match **kind { Primitive::Any | Primitive::Str => write!(f, "hmap[]"),
Primitive::Any | Primitive::Str => write!(f, "hmap[]"), ref kind => write!(f, "hmap[{}]", kind),
ref kind => write!(f, "hmap[{}]", kind), },
} Primitive::BTreeMap(ref kind) => match **kind {
} Primitive::Any | Primitive::Str => write!(f, "bmap[]"),
Primitive::BTreeMap(ref kind) => { ref kind => write!(f, "bmap[{}]", kind),
match **kind { },
Primitive::Any | Primitive::Str => write!(f, "bmap[]"),
ref kind => write!(f, "bmap[{}]", kind),
}
}
Primitive::Indexed(_, ref kind) => write!(f, "{}", kind), Primitive::Indexed(_, ref kind) => write!(f, "{}", kind),
} }
} }
......
#[macro_use] #[macro_use]
extern crate bitflags; extern crate bitflags;
pub mod assignments;
pub mod arguments; pub mod arguments;
pub mod assignments;
pub mod designators; pub mod designators;
pub use self::{assignments::*, arguments::*, designators::*}; pub use self::{arguments::*, assignments::*, designators::*};
...@@ -122,7 +122,9 @@ fn char_range<'a>( ...@@ -122,7 +122,9 @@ fn char_range<'a>(
} }
stepped_range_chars(start, end, char_step) stepped_range_chars(start, end, char_step)
} else { } else {
Some(Box::new(Some((start as char).to_string().into()).into_iter())) Some(Box::new(
Some((start as char).to_string().into()).into_iter(),
))
} }
} }
......
...@@ -2,9 +2,8 @@ extern crate libc; ...@@ -2,9 +2,8 @@ extern crate libc;
extern crate syscall; extern crate syscall;
use std::{ use std::{
env::{split_paths, remove_var, var, vars}, env::{remove_var, split_paths, var, vars},
io, io, mem,
mem,
os::unix::{ffi::OsStrExt, io::RawFd}, os::unix::{ffi::OsStrExt, io::RawFd},
path::PathBuf, path::PathBuf,
process::exit, process::exit,
...@@ -288,12 +287,7 @@ pub mod variables { ...@@ -288,12 +287,7 @@ pub mod variables {
} }
pub mod env { pub mod env {
use std::{ use std::{env, path::PathBuf};
env,
path::PathBuf,
};
pub fn home_dir() -> Option<PathBuf> { pub fn home_dir() -> Option<PathBuf> { env::var_os("HOME").map(PathBuf::from) }
env::var_os("HOME").map(PathBuf::from)
}
} }
...@@ -38,10 +38,22 @@ pub const STDIN_FILENO: i32 = libc::STDIN_FILENO; ...@@ -38,10 +38,22 @@ pub const STDIN_FILENO: i32 = libc::STDIN_FILENO;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn errno() -> i32 { unsafe { *libc::__errno_location() } } fn errno() -> i32 { unsafe { *libc::__errno_location() } }
#[cfg(any(target_os = "openbsd", target_os = "bitrig", target_os = "android"))] #[cfg(
any(
target_os = "openbsd",
target_os = "bitrig",
target_os = "android"
)
)]
fn errno() -> i32 { unsafe { *libc::__errno() } } fn errno() -> i32 { unsafe { *libc::__errno() } }
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] #[cfg(
any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd"
)
)]
fn errno() -> i32 { unsafe { *libc::__error() } } fn errno() -> i32 { unsafe { *libc::__error() } }
#[cfg(target_os = "dragonfly")] #[cfg(target_os = "dragonfly")]
...@@ -393,17 +405,27 @@ pub mod env { ...@@ -393,17 +405,27 @@ pub mod env {
}; };
pub fn home_dir() -> Option<PathBuf> { pub fn home_dir() -> Option<PathBuf> {
return env::var_os("HOME").or_else(|| unsafe { return env::var_os("HOME")
fallback() .or_else(|| unsafe { fallback() })
}).map(PathBuf::from); .map(PathBuf::from);
#[cfg(any(target_os = "android", #[cfg(
target_os = "ios", any(
target_os = "emscripten"))] target_os = "android",
target_os = "ios",
target_os = "emscripten"
)
)]
unsafe fn fallback() -> Option<OsString> { None } unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android", #[cfg(
target_os = "ios", not(
target_os = "emscripten")))] any(
target_os = "android",
target_os = "ios",
target_os = "emscripten"
)
)
)]
unsafe fn fallback() -> Option<OsString> { unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {