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

Apply rustfmt

parent 33253fd2
......@@ -4,7 +4,11 @@
// const MIN_VERSION: &'static str = "1.19.0";
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() {
......
extern crate permutate;
extern crate smallvec;
extern crate small;
extern crate smallvec;
use permutate::Permutator;
use smallvec::SmallVec;
......
use calculate::{eval, eval_polish, CalcError, Value};
use std::io::{self, Write};
use small;
use std::io::{self, Write};
const REPL_GUIDE: &'static str = r#"ion-calc
Type in expressions to have them evaluated.
......
use rand::{thread_rng, Rng};
use std::io::{self, Write};
use small;
use std::io::{self, Write};
#[allow(unused_must_use)]
fn rand_list(args: &[small::String]) -> Result<(), small::String> {
......
......@@ -114,8 +114,7 @@ AUTHOR
Written by Michael Murphy.
"#;
const QUICK_GUIDE: &'static str =
r#"Usage: test [EXPRESSION]
const QUICK_GUIDE: &'static str = r#"Usage: test [EXPRESSION]
Try 'test --help' for more information."#;
pub fn test(args: &[small::String]) -> Result<bool, small::String> {
......@@ -223,7 +222,10 @@ fn get_modified_file_time(filename: &str) -> Option<SystemTime> {
}
/// 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> {
match input
.parse::<isize>()
......@@ -385,18 +387,13 @@ fn test_strings() {
fn test_empty_str() {
let eval = |args: Vec<small::String>| evaluate_arguments(&args);
assert_eq!(eval(vec!["".into()]), Ok(false));
assert_eq!(
eval(vec!["c".into(), "=".into(), "".into()]),
Ok(false)
);
assert_eq!(eval(vec!["c".into(), "=".into(), "".into()]), Ok(false));
}
#[test]
fn test_integers_arguments() {
fn vec_string(args: &[&str]) -> Vec<small::String> {
args.iter()
.map(|s| (*s).into())
.collect()
args.iter().map(|s| (*s).into()).collect()
}
// Equal To
assert_eq!(
......
use std::fmt::{self, Display, Formatter};
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
/// types are being assigned.
......@@ -64,7 +64,9 @@ impl<'a> KeyIterator<'a> {
loop {
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] {
"" => Primitive::AnyArray,
s => Primitive::Indexed(s.to_owned(), Box::new(Primitive::Any)),
......@@ -72,7 +74,9 @@ impl<'a> KeyIterator<'a> {
self.read += 1;
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;
self.read += 2;
......@@ -86,8 +90,12 @@ impl<'a> KeyIterator<'a> {
"" => Primitive::AnyArray,
s => match Primitive::parse(&self.data[index_ident_end + 2..self.read]) {
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 });
......@@ -164,11 +172,11 @@ mod tests {
#[test]
fn key_parsing() {
let mut parser = KeyIterator::new("a:int b[] c:bool d e:int[] \
f[0] g[$index] h[1]:int \
i:hmap[] j:hmap[float] k:hmap[int[]] l:hmap[hmap[bool[]]] \
m:bmap[] n:bmap[int] o:bmap[float[]] p:bmap[hmap[bool]] \
d:a");
let mut parser = KeyIterator::new(
"a:int b[] c:bool d e:int[] f[0] g[$index] h[1]:int i:hmap[] j:hmap[float] \
k:hmap[int[]] l:hmap[hmap[bool[]]] m:bmap[] n:bmap[int] o:bmap[float[]] \
p:bmap[hmap[bool]] d:a",
);
assert_eq!(
parser.next().unwrap(),
Ok(Key {
......@@ -250,7 +258,9 @@ mod tests {
parser.next().unwrap(),
Ok(Key {
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!(
......@@ -278,7 +288,9 @@ mod tests {
parser.next().unwrap(),
Ok(Key {
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())));
......
......@@ -2,13 +2,17 @@ mod keys;
mod operator;
mod primitive;
pub use self::keys::{Key, KeyBuf, KeyIterator, TypeError};
pub use self::operator::Operator;
pub use self::primitive::Primitive;
pub use self::{
keys::{Key, KeyBuf, KeyIterator, TypeError},
operator::Operator,
primitive::Primitive,
};
/// Given an valid assignment expression, this will split it into `keys`,
/// `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();
if statement.is_empty() {
return (None, None, None);
......@@ -35,7 +39,7 @@ pub fn assignment_lexer<'a>(statement: &'a str) -> (Option<&'a str>, Option<Oper
operator = Some(op);
start = read;
read = found;
break
break;
}
}
}
......@@ -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)> {
if bytes.len() <= read + 3 {
None
} else if bytes[read+1] == b'=' {
} else if bytes[read + 1] == b'=' {
Operator::parse_single(bytes[read]).map(|op| (op, read + 2))
} else if bytes[read+2] == b'=' {
Operator::parse_double(&bytes[read..read+2]).map(|op| (op, read + 3))
} else if bytes[read + 2] == b'=' {
Operator::parse_double(&bytes[read..read + 2]).map(|op| (op, read + 3))
} else {
None
}
......@@ -74,14 +78,8 @@ mod tests {
#[test]
fn assignment_splitting() {
assert_eq!(
assignment_lexer(""),
(None, None, None)
);
assert_eq!(
assignment_lexer("abc"),
(Some("abc"), None, None)
);
assert_eq!(assignment_lexer(""), (None, None, None));
assert_eq!(assignment_lexer("abc"), (Some("abc"), None, None));
assert_eq!(
assignment_lexer("abc+=def"),
......
......@@ -21,35 +21,39 @@ impl Operator {
b'-' => Some(Operator::Subtract),
b'/' => Some(Operator::Divide),
b'*' => Some(Operator::Multiply),
_ => None,
_ => None,
}
}
pub(crate) fn parse_double(data: &[u8]) -> Option<Operator> {
match data {
b"//" => Some(Operator::IntegerDivide),
b"**" => Some(Operator::Exponent),
b"++" => Some(Operator::Concatenate),
b"::" => Some(Operator::ConcatenateHead),
b"//" => Some(Operator::IntegerDivide),
b"**" => Some(Operator::Exponent),
b"++" => Some(Operator::Concatenate),
b"::" => Some(Operator::ConcatenateHead),
b"\\\\" => Some(Operator::Filter),
_ => None,
_ => None,
}
}
}
impl Display for Operator {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", match *self {
Operator::Add => "+=",
Operator::Concatenate => "++=",
Operator::ConcatenateHead => "::=",
Operator::Filter => "\\\\=",
Operator::Divide => "/=",
Operator::Equal => "=",
Operator::Exponent => "**=",
Operator::IntegerDivide => "//=",
Operator::Multiply => "*=",
Operator::Subtract => "-=",
})
write!(
f,
"{}",
match *self {
Operator::Add => "+=",
Operator::Concatenate => "++=",
Operator::ConcatenateHead => "::=",
Operator::Filter => "\\\\=",
Operator::Divide => "/=",
Operator::Equal => "=",
Operator::Exponent => "**=",
Operator::IntegerDivide => "//=",
Operator::Multiply => "*=",
Operator::Subtract => "-=",
}
)
}
}
......@@ -34,22 +34,26 @@ impl Primitive {
fn parse_inner_hash_map(inner: &str) -> Option<Primitive> {
match inner {
"" => 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> {
match inner {
"" => 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 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[") {
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 {
None
};
......@@ -77,18 +81,14 @@ impl Display for Primitive {
Primitive::Integer => write!(f, "int"),
Primitive::IntegerArray => write!(f, "int[]"),
Primitive::StrArray => write!(f, "str[]"),
Primitive::HashMap(ref kind) => {
match **kind {
Primitive::Any | Primitive::Str => write!(f, "hmap[]"),
ref kind => write!(f, "hmap[{}]", kind),
}
}
Primitive::BTreeMap(ref kind) => {
match **kind {
Primitive::Any | Primitive::Str => write!(f, "bmap[]"),
ref kind => write!(f, "bmap[{}]", kind),
}
}
Primitive::HashMap(ref kind) => match **kind {
Primitive::Any | Primitive::Str => write!(f, "hmap[]"),
ref kind => write!(f, "hmap[{}]", kind),
},
Primitive::BTreeMap(ref kind) => match **kind {
Primitive::Any | Primitive::Str => write!(f, "bmap[]"),
ref kind => write!(f, "bmap[{}]", kind),
},
Primitive::Indexed(_, ref kind) => write!(f, "{}", kind),
}
}
......
#[macro_use]
extern crate bitflags;
pub mod assignments;
pub mod arguments;
pub mod assignments;
pub mod designators;
pub use self::{assignments::*, arguments::*, designators::*};
pub use self::{arguments::*, assignments::*, designators::*};
......@@ -122,7 +122,9 @@ fn char_range<'a>(
}
stepped_range_chars(start, end, char_step)
} 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;
extern crate syscall;
use std::{
env::{split_paths, remove_var, var, vars},
io,
mem,
env::{remove_var, split_paths, var, vars},
io, mem,
os::unix::{ffi::OsStrExt, io::RawFd},
path::PathBuf,
process::exit,
......@@ -288,12 +287,7 @@ pub mod variables {
}
pub mod env {
use std::{
env,
path::PathBuf,
};
use std::{env, path::PathBuf};
pub fn home_dir() -> Option<PathBuf> {
env::var_os("HOME").map(PathBuf::from)
}
pub fn home_dir() -> Option<PathBuf> { env::var_os("HOME").map(PathBuf::from) }
}
......@@ -38,10 +38,22 @@ pub const STDIN_FILENO: i32 = libc::STDIN_FILENO;
#[cfg(target_os = "linux")]
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() } }
#[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() } }
#[cfg(target_os = "dragonfly")]
......@@ -393,17 +405,27 @@ pub mod env {
};
pub fn home_dir() -> Option<PathBuf> {
return env::var_os("HOME").or_else(|| unsafe {
fallback()
}).map(PathBuf::from);
#[cfg(any(target_os = "android",
target_os = "ios",
target_os = "emscripten"))]
return env::var_os("HOME")
.or_else(|| unsafe { fallback() })
.map(PathBuf::from);
#[cfg(
any(
target_os = "android",
target_os = "ios",
target_os = "emscripten"
)
)]
unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android",
target_os = "ios",
target_os = "emscripten")))]
#[cfg(
not(
any(
target_os = "android",
target_os = "ios",
target_os = "emscripten"
)
)
)]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512 as usize,
......@@ -412,13 +434,18 @@ pub mod env {
let mut buf = Vec::with_capacity(amt);
let mut passwd: libc::passwd = mem::zeroed();
let mut result = ptr::null_mut();
match libc::getpwuid_r(libc::getuid(), &mut passwd, buf.as_mut_ptr(),
buf.capacity(), &mut result) {
match libc::getpwuid_r(
libc::getuid(),
&mut passwd,
buf.as_mut_ptr(),
buf.capacity(),
&mut result,
) {
0 if !result.is_null() => {
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
Some(OsStringExt::from_vec(bytes))
},
}
_ => None,
}
}
......
use builtins::man_pages::*;
use shell::{status::*, flow_control::Function, Shell};
use shell::{flow_control::Function, status::*, Shell};
use small;
use sys;
use types;
......@@ -22,7 +22,7 @@ pub(crate) fn which(args: &[small::String], shell: &mut Shell) -> Result<i32, ()
match c_type.as_ref() {
"alias" => if let Some(alias) = shell.variables.get::<types::Alias>(&**command) {
println!("{}: alias to {}", command, &*alias);
}
},
"function" => println!("{}: function", command),
"builtin" => println!("{}: built-in shell command", command),
_path => println!("{}", _path),
......@@ -47,7 +47,7 @@ pub(crate) fn find_type(args: &[small::String], shell: &mut Shell) -> Result<i32
match c_type.as_ref() {
"alias" => if let Some(alias) = shell.variables.get::<types::Alias>(&**command) {
println!("{} is aliased to `{}`", command, &*alias);
}
},
// TODO Make it print the function.
"function" => println!("{} is a function", command),
"builtin" => println!("{} is a shell builtin", command),
......
use builtins::man_pages::{check_help, MAN_EXEC};
use small;
use shell::Shell;
use small;
use std::error::Error;
use sys::execve;
......
use std::{fs, os::unix::fs::PermissionsExt};
#[cfg(test)]
use shell::{
self,
flow_control::Statement,
};
use shell::{
flow_control::Function,
Shell,
};
use shell::{self, flow_control::Statement};
use shell::{flow_control::Function, Shell};
use small;
use types;
......@@ -157,27 +151,43 @@ fn test_evaluate_arguments() {
assert_eq!(evaluate_arguments(&[], &shell), Ok(false));
// multiple arguments
// ignores all but the first argument
assert_eq!(evaluate_arguments(&["foo".into(), "bar".into()], &shell), Ok(true));
assert_eq!(
evaluate_arguments(&["foo".into(), "bar".into()], &shell),
Ok(true)
);
// check `exists STRING`
assert_eq!(evaluate_arguments(&["".into()], &shell), Ok(false));
assert_eq!(evaluate_arguments(&["string".into()], &shell), Ok(true));
assert_eq!(evaluate_arguments(&["string with space".into()], &shell), Ok(true));
assert_eq!(evaluate_arguments(&["-startswithdash".into()], &shell), Ok(true));
assert_eq!(
evaluate_arguments(&["string with space".into()], &shell),
Ok(true)
);
assert_eq!(
evaluate_arguments(&["-startswithdash".into()], &shell),
Ok(true)
);
// check `exists -a`
// no argument means we treat it as a string
assert_eq!(evaluate_arguments(&["-a".into()], &shell), Ok(true));
shell
.variables
.set("emptyarray", types::Array::new());
assert_eq!(evaluate_arguments(&["-a".into(), "emptyarray".into()], &shell), Ok(false));
shell.variables.set("emptyarray", types::Array::new());
assert_eq!(
evaluate_arguments(&["-a".into(), "emptyarray".into()], &shell),
Ok(false)
);
let mut array = types::Array::new();
array.push("element".into());
shell.variables.set("array", array);
assert_eq!(evaluate_arguments(&["-a".into(), "array".into()], &shell), Ok(true));
assert_eq!(
evaluate_arguments(&["-a".into(), "array".into()], &shell),
Ok(true)
);
shell.variables.remove_variable("array");
assert_eq!(evaluate_arguments(&["-a".into(), "array".into()], &shell), Ok(false));
assert_eq!(
evaluate_arguments(&["-a".into(), "array".into()], &shell),
Ok(false)
);
// check `exists -b`
// TODO: see test_binary_is_in_path()
......@@ -190,7 +200,10 @@ fn test_evaluate_arguments() {
evaluate_arguments(&["-b".into(), "executable_file".into()], &shell),
Ok(true)
);
assert_eq!(evaluate_arguments(&["-b".into(), "empty_file".into()], &shell), Ok(false));
assert_eq!(
evaluate_arguments(&["-b".into(), "empty_file".into()], &shell),
Ok(false)
);
assert_eq!(
evaluate_arguments(&["-b".into(), "file_does_not_exist".into()], &shell),
Ok(false)
......@@ -203,7 +216,10 @@ fn test_evaluate_arguments() {
// check `exists -d`
// no argument means we treat it as a string
assert_eq!(evaluate_arguments(&["-d".into()], &shell), Ok(true));
assert_eq!(evaluate_arguments(&["-d".into(), "testing/".into()], &shell), Ok(true));
assert_eq!(