Skip to content

Fix 1 #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix lint issues
  • Loading branch information
iacore committed Oct 21, 2022
commit 20ffe348bacefd5cd29000d5c8521dc45200c891
42 changes: 21 additions & 21 deletions src/bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
use crate::{parser::Literal, error, Result};
use std::fmt::{self, Formatter, Display};

#[derive(PartialEq, Copy, Clone, Debug)]
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum OpCode {
LoadConst(u16), // (const_id)
LoadSym(u16), // (sym_id)
Expand Down Expand Up @@ -126,13 +126,13 @@ impl OpCode {
}
}

#[derive(PartialEq, Clone, Debug)]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Chunk {
pub instructions: Vec<OpCode>,
pub reference: Vec<u16>,
}

#[derive(PartialEq, Clone, Debug)]
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum BytecodePattern {
Var(u16), // (sym_idx)
Constr(u16, Vec<u16>), // (constr_id, [pat_idx])
Expand Down Expand Up @@ -174,7 +174,7 @@ impl Bytecode {
let mut ptr = 5; // Skip timestamp
let sym_length = len(&mut ptr, bytes)?;
println!("Sym length.");
let mut symbols = (0..sym_length).map(|_| string(&mut ptr, bytes)).collect::<Result<Vec<String>>>()?;
let symbols = (0..sym_length).map(|_| string(&mut ptr, bytes)).collect::<Result<Vec<String>>>()?;
println!("Syms.");
let consts_length = len(&mut ptr, bytes)?;
println!("Consts length.");
Expand Down Expand Up @@ -263,14 +263,14 @@ impl Bytecode {
println!("Matches length.");
let matches = (0..matches_length).map(|_| {
let match_length = len(&mut ptr, bytes)?;
Ok((0..match_length).map(|_| {
(0..match_length).map(|_| {
let idx = len(&mut ptr, bytes)?;
let instrs_len = len(&mut ptr, bytes)?;
let instrs = (0..instrs_len).map(|_| {
OpCode::deserialize(&mut ptr, bytes)
}).collect::<Result<Vec<OpCode>>>()?;
Ok((idx, instrs))
}).collect::<Result<Vec<(u16, Vec<OpCode>)>>>()?)
}).collect::<Result<Vec<(u16, Vec<OpCode>)>>>()
}).collect::<Result<Vec<Vec<(u16, Vec<OpCode>)>>>>()?;
println!("Matches.");

Expand Down Expand Up @@ -334,17 +334,17 @@ impl Bytecode {
to_ret.extend(&link.to_be_bytes());
});

let serialized = chunk.instructions.iter().map(|instr| {
let serialized = chunk.instructions.iter().flat_map(|instr| {
instr.serialize()
}).flatten();
});
to_ret.extend(&(chunk.instructions.len() as u16).to_be_bytes());
to_ret.extend(serialized)
});

// Instructions
let serialized = self.instructions.iter().map(|instr| {
let serialized = self.instructions.iter().flat_map(|instr| {
instr.serialize()
}).flatten();
});
to_ret.extend(&(self.instructions.len() as u16).to_be_bytes());
to_ret.extend(serialized);

Expand All @@ -359,7 +359,7 @@ impl Bytecode {

// Patterns
to_ret.extend(&(self.patterns.len() as u16).to_be_bytes());
to_ret.extend(self.patterns.iter().map(|p| {
to_ret.extend(self.patterns.iter().flat_map(|p| {
match p {
BytecodePattern::Var(idx) => {
let mut to_ret = vec![0];
Expand All @@ -370,17 +370,17 @@ impl Bytecode {
let mut to_ret = vec![1];
to_ret.extend(&id.to_be_bytes());
to_ret.extend(&(pats.len() as u16).to_be_bytes());
to_ret.extend(pats.into_iter().map(|p| {
to_ret.extend(pats.iter().flat_map(|p| {
p.to_be_bytes().to_vec()
}).flatten());
}));
to_ret
}
BytecodePattern::Tuple(pats) => {
let mut to_ret = vec![2];
to_ret.extend(&(pats.len() as u16).to_be_bytes());
to_ret.extend(pats.into_iter().map(|p| {
to_ret.extend(pats.iter().flat_map(|p| {
p.to_be_bytes().to_vec()
}).flatten());
}));
to_ret
}
BytecodePattern::Literal(idx) => {
Expand All @@ -390,20 +390,20 @@ impl Bytecode {
}
BytecodePattern::Any => vec![4],
}
}).flatten());
}));

// Matches
to_ret.extend(&(self.matches.len() as u16).to_be_bytes());
to_ret.extend(self.matches.iter().map(|patterns| {
to_ret.extend(self.matches.iter().flat_map(|patterns| {
let mut to_ret = (patterns.len() as u16).to_be_bytes().to_vec();
to_ret.extend(patterns.into_iter().map(|(idx, instrs)| {
to_ret.extend(patterns.iter().flat_map(|(idx, instrs)| {
let mut to_ret = idx.to_be_bytes().to_vec();
to_ret.extend(&(instrs.len() as u16).to_be_bytes());
to_ret.extend(instrs.into_iter().map(|instr| instr.serialize()).flatten());
to_ret.extend(instrs.iter().flat_map(|instr| instr.serialize()));
to_ret
}).flatten());
}));
to_ret
}).flatten());
}));
to_ret
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
use clap::{App, Arg};
use rustyline::{error::ReadlineError, Editor};
use std::{rc::Rc, time::Instant, path::Path, fs, io::Write};
use crate::{Result, print_err, error, lexer::{Lexer, Token}, parser::{Parser, Expr}, bytecode::Bytecode, compiler::{Compiler, Macro}, vm::{VM, Value}};
use crate::{Result, print_err, error, lexer::{Lexer}, parser::{Parser}, bytecode::Bytecode, compiler::{Compiler}, vm::{VM, Value}};

fn repl(dbg_level: u8, lib: String) -> Result<()> {
println!(
Expand Down Expand Up @@ -111,7 +111,7 @@ env!("CARGO_PKG_VERSION")
let top = &vm.stack.iter().nth(match vm.stack.len() as isize - 1 {
x if x < 0 => 0,
x => x as usize,
}).and_then(|v| Some((**v).clone()));
}).map(|v| (**v).clone());
if let Some(Value::Tuple(v)) = top {
if !v.is_empty() {
println!("=> {}", vm.display_value(Rc::new(top.clone().unwrap()), true))
Expand Down Expand Up @@ -184,7 +184,7 @@ pub fn cli() -> Result<()> {
let lib = match matches.value_of("lib") {
Some(l) => l.to_string(),
None => match env::var("ORION_LIB") {
Ok(v) => v.to_string(),
Ok(v) => v,
Err(_) => return error!(=> "No such environment variable: ORION_LIB."),
}
};
Expand Down
14 changes: 6 additions & 8 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Compiler {
&name,
self.constructors
.iter()
.position(|var| var.to_string() == name)
.position(|var| *var == name)
.unwrap()
)
} else {
Expand All @@ -126,7 +126,7 @@ impl Compiler {
let idx = self
.constructors
.iter()
.position(|variant| name == variant.to_string())
.position(|variant| name == *variant)
.unwrap();
Ok((self.output.constructors[idx].0, idx as u16))
} else {
Expand Down Expand Up @@ -386,7 +386,7 @@ impl Compiler {
.builtins
.iter()
.position(|builtin| builtin.0 == name)
.map_or(error!(self.file, expr.line => "No such builtin: {}.", name), |i| Ok(i))?;
.map_or(error!(self.file, expr.line => "No such builtin: {}.", name), Ok)?;
let impure_builtin = self.builtins[idx as usize].1;
if !impure && impure_builtin {
return error!(self.file, expr.line => "Impure builtin used out of an `impure` function: {}.", name);
Expand All @@ -397,12 +397,10 @@ impl Compiler {
ExprT::Enum(name, constructors) => {
let start = self.output.constructors.len() as u16;
constructors
.into_iter()
.map(|(k, v)| {
.into_iter().try_for_each(|(k, v)| {
symbols = self.register_constructor(k, symbols.clone(), v, expr.line)?;
Ok(())
})
.collect::<Result<()>>()?;
})?;
let end = self.output.constructors.len() as u16 - 1;
self.output.types.push((name, start, end));
Ok((vec![], symbols))
Expand Down Expand Up @@ -457,7 +455,7 @@ impl Compiler {
Ok((to_ret, symbols))
}
ExprT::Match(expr, patterns) => {
let (mut compiled, mut symbols) = self.compile_expr(*expr.clone(), symbols, impure)?;
let (mut compiled, mut symbols) = self.compile_expr(*expr, symbols, impure)?;
let match_content = patterns.into_iter().map(|(pat, expr)| {
let (pat_id, new_symbols) = self.declare_pat(pat, symbols.clone(), impure, expr.line)?;
symbols = new_symbols;
Expand Down
2 changes: 1 addition & 1 deletion src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ macro_rules! error {
let _file = std::option::Option::Some($file.to_string());
let _line = std::option::Option::Some($line);
)?
std::result::Result::Err(crate::errors::OrionError(_file, _line, format_args!($($arg)*).to_string()))
std::result::Result::Err($crate::errors::OrionError(_file, _line, format_args!($($arg)*).to_string()))

}
}
Expand Down
20 changes: 9 additions & 11 deletions src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub struct Lexer {
impl Lexer {
pub fn new(input: impl ToString, file: impl ToString) -> Self {
Self {
input: input.to_string().replace("λ", "\\").to_string(),
input: input.to_string().replace('λ', "\\"),
output: vec![],
current: 0,
line: 1,
Expand Down Expand Up @@ -161,11 +161,9 @@ impl Lexer {
} else if !self.is_at_end() && self.peek() == '|' {
self.advance();
while !self.is_at_end() {
if self.peek() == '|' {
if !self.is_at_end() && self.peek() == '#' {
self.advance();
break;
}
if self.peek() == '|' && !self.is_at_end() && self.peek() == '#' {
self.advance();
break;
}
self.advance();
}
Expand All @@ -179,7 +177,7 @@ impl Lexer {
}
}
_ => {
if c.is_digit(10) {
if c.is_ascii_digit() {
self.number();
} else {
self.identifier();
Expand All @@ -193,15 +191,15 @@ impl Lexer {
self.builtins.push(builtin.to_string());
}
fn number(&mut self) {
while !self.is_at_end() && self.peek().is_digit(10) {
while !self.is_at_end() && self.peek().is_ascii_digit() {
self.advance();
}

if !self.is_at_end() && self.peek() == '.' {
self.advance(); // Decimal part delimiter
}

while !self.is_at_end() && self.peek().is_digit(10) {
while !self.is_at_end() && self.peek().is_ascii_digit() {
self.advance();
}

Expand Down Expand Up @@ -280,7 +278,7 @@ fn apply_ansi_codes(input: &str) -> String {
.replace("\\t", "\t")
.replace("\\0", "\0")
.replace("\\\\", "\\")
.to_string()

}

#[cfg(test)]
Expand Down Expand Up @@ -317,7 +315,7 @@ mod test {
let ttypes = get_ttypes(Lexer::new("42 3.1415926535897932", "").proc_tokens()?);
assert_eq!(
ttypes,
vec![TType::Number(42), TType::Float(3.1415926535897932)]
vec![TType::Number(42), TType::Float(3.141_592_7)]
);
Ok(())
}
Expand Down
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@
* You should have received a copy of the GNU General Public License
* along with Orion. If not, see <https://www.gnu.org/licenses/>.
*/

mod bytecode;
mod compiler;
mod errors;
#[allow(clippy::approx_constant)]
mod lexer;
#[allow(clippy::approx_constant)]
mod parser;
#[allow(clippy::approx_constant)]
mod vm;
mod cli;

Expand Down
17 changes: 6 additions & 11 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pub enum Pattern {
Literal(Literal),
}
fn first_char(s: impl ToString) -> char {
s.to_string().chars().nth(0).unwrap()
s.to_string().chars().next().unwrap()
}

pub struct Parser {
Expand Down Expand Up @@ -143,8 +143,7 @@ impl Parser {
fn peek(&self) -> Option<Token> {
self.input
.iter()
.nth(self.current)
.and_then(|t| Some(t.clone()))
.nth(self.current).cloned()
}
fn is_at_end(&self) -> bool {
self.input.len() != 1 && self.current >= self.input.len()
Expand Down Expand Up @@ -266,7 +265,7 @@ impl Parser {
while !self.is_at_end() && self.peek().unwrap().ttype != TType::RBracket {
exprs.push(self.parse_expr()?);
}
let constr = if exprs.len() >= 1 {
let constr = if !exprs.is_empty() {
exprs.into_iter().rev().fold(ExprT::Constr("Nil".to_string(), vec![]), |acc, e| ExprT::Constr("Cons".to_string(), vec![e, Expr::new(acc).line(root.line)]))
} else {
ExprT::Constr("Nil".to_string(), vec![])
Expand Down Expand Up @@ -323,14 +322,10 @@ impl Parser {
}
TType::Def => {
let impure =
if self.peek().and_then(|t| Some(t.ttype)) == Some(TType::Quote) {
if self.peek().map(|t| t.ttype) == Some(TType::Quote) {
self.advance(TType::Quote)?;
let got = self.advance(TType::Ident("".to_string()))?;
if got.ttype == TType::Ident("impure".to_string()) {
true
} else {
false
}
got.ttype == TType::Ident("impure".to_string())
} else {
false
};
Expand Down Expand Up @@ -556,7 +551,7 @@ mod test {
vec![
Expr::new(ExprT::Literal(Literal::String("foo".to_string()))).line(1),
Expr::new(ExprT::Literal(Literal::Integer(42))).line(1),
Expr::new(ExprT::Literal(Literal::Single(3.1415926535897932))).line(1),
Expr::new(ExprT::Literal(Literal::Single(3.141_592_7))).line(1),
]
);

Expand Down
2 changes: 1 addition & 1 deletion src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl<const STACK_SIZE: usize> VM<STACK_SIZE> {
Ok(Rc::new(Value::String(if i < 0 {
"".to_string()
} else {
s.chars().nth(i as usize).and_then(|c| Some(format!("{}", c))).unwrap_or("".to_string())
s.chars().nth(i as usize).map(|c| format!("{}", c)).unwrap_or("".to_string())
})))
} else {
error!(=> "Expected a String, found a {}.", self.val_type(&string)?)
Expand Down
Loading