Skip to content

Commit

Permalink
fix clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
sezna committed Jun 22, 2024
1 parent 46c8d60 commit bf64008
Show file tree
Hide file tree
Showing 14 changed files with 69 additions and 55 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"petr-parse",
"petr-fmt",
Expand Down
11 changes: 7 additions & 4 deletions pete/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::{fs, path::PathBuf};
use std::{
fs,
path::{Path, PathBuf},
};

use clap::Parser as ClapParser;
use petr_ir::Lowerer;
Expand Down Expand Up @@ -200,16 +203,16 @@ fn main() {
}
}

fn load_project_and_dependencies(path: &PathBuf) -> (petr_pkg::Lockfile, Vec<(PathBuf, String)>, BuildPlan) {
let manifest = petr_pkg::manifest::find_manifest(Some(path.clone())).expect("Failed to find manifest");
fn load_project_and_dependencies(path: &Path) -> (petr_pkg::Lockfile, Vec<(PathBuf, String)>, BuildPlan) {
let manifest = petr_pkg::manifest::find_manifest(Some(path.to_path_buf())).expect("Failed to find manifest");
let dependencies = manifest.dependencies;
let (lockfile, build_plan) = petr_pkg::load_dependencies(dependencies);

let files = load_files(path);
(lockfile, files, build_plan)
}

fn load_files(path: &PathBuf) -> Vec<(PathBuf, String)> {
fn load_files(path: &Path) -> Vec<(PathBuf, String)> {
let mut buf = Vec::new();

fn read_petr_files(
Expand Down
13 changes: 8 additions & 5 deletions petr-ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,15 @@ pub enum Literal {
String(Rc<str>),
}

impl ToString for Literal {
fn to_string(&self) -> String {
impl std::fmt::Display for Literal {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
match self {
Literal::Integer(i) => i.to_string(),
Literal::Boolean(b) => b.to_string(),
Literal::String(s) => format!("\"{s}\""),
Literal::Integer(i) => write!(f, "{}", i),
Literal::Boolean(b) => write!(f, "{}", b),
Literal::String(s) => write!(f, "\"{}\"", s),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion petr-bind/src/binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ impl Binder {
&self,
scope: ScopeId,
) -> impl Iterator<Item = (&SymbolId, &Item)> {
self.scopes.get(scope).items.iter().map(|(k, v)| (k, v))
self.scopes.get(scope).items.iter()
}
}

Expand Down
2 changes: 1 addition & 1 deletion petr-fmt/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl FormatterContext {
config: FormatterConfig,
f: impl Fn(&mut FormatterContext) -> crate::FormattedLines,
) -> crate::FormattedLines {
let old_config = self.config.clone();
let old_config = self.config;
self.config = config;
let res = f(self);
self.config = old_config;
Expand Down
4 changes: 2 additions & 2 deletions petr-fmt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ impl Formattable for ExpressionWithBindings {
let mut buf = if is_first { "let ".to_string() } else { " ".to_string() };

let name = ctx.interner.get(binding.name.id);
buf.push_str(&*name);
buf.push_str(&name);
buf.push_str(" = ");
let expr_lines = ctx.indented(|ctx| binding.val.format(ctx).lines);

Expand Down Expand Up @@ -634,7 +634,7 @@ pub trait Formattable {
];

for config in &configs {
let result = self.try_config(ctx, config.clone());
let result = self.try_config(ctx, *config);
if result.max_length() < ctx.config.max_line_length() {
return result;
}
Expand Down
6 changes: 3 additions & 3 deletions petr-ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,12 @@ impl Lowerer {
lit: &petr_typecheck::Literal,
) -> DataLabel {
use petr_typecheck::Literal::*;
let label = self.data_section.insert(match lit {

self.data_section.insert(match lit {
Integer(val) => DataSectionEntry::Int64(*val),
Boolean(val) => DataSectionEntry::Bool(*val),
String(val) => DataSectionEntry::String(val.clone()),
});
label
})
}

// convert a polytype type to an `IrTy`
Expand Down
28 changes: 15 additions & 13 deletions petr-parse/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,14 @@ impl ParseErrorKind {

fn format_toks(toks: &[Token]) -> String {
let mut buf = toks.iter().take(toks.len() - 1).map(|t| format!("{}", t)).collect::<Vec<_>>().join(", ");
if toks.len() == 2 {
buf.push_str(&format!(" or {}", toks.last().unwrap()));
} else if toks.len() > 2 {
buf.push_str(&format!(", or {}", toks.last().unwrap()));
match toks.len() {
2 => {
buf.push_str(&format!(" or {}", toks.last().unwrap()));
},
x if x > 2 => {
buf.push_str(&format!(", or {}", toks.last().unwrap()));
},
_ => (),
}
buf
}
Expand Down Expand Up @@ -136,11 +140,9 @@ impl Parser {
return self.errors.push(err.map(|err| err.into_err()));
}
let mut help_text = Vec::with_capacity(self.help.len());
let mut indentation = 0;
for help in &self.help {
for (indentation, help) in self.help.iter().enumerate() {
let text = format!("{}{}{help}", " ".repeat(indentation), if indentation == 0 { "" } else { "↪ " });
help_text.push(text);
indentation += 1;
}
let err = err.map(|err| err.into_err().with_help(Some(help_text.join("\n"))));
self.errors.push(err);
Expand Down Expand Up @@ -171,7 +173,7 @@ impl Parser {
}
}

pub fn new<'a>(sources: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>) -> Self {
pub fn new(sources: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>) -> Self {
// TODO we hold two copies of the source for now: one in source_maps, and one outside the parser
// for the lexer to hold on to and not have to do self-referential pointers.
let sources = sources
Expand Down Expand Up @@ -206,6 +208,7 @@ impl Parser {
}

/// consume tokens until a node is produced
#[allow(clippy::type_complexity)]
pub fn into_result(
mut self
) -> (
Expand Down Expand Up @@ -308,9 +311,8 @@ impl Parser {

pub fn advance(&mut self) -> SpannedItem<Token> {
if self.file_barrier {
match self.peek().item() {
Token::NewFile(_) => return self.lexer.span().with_item(Token::Eof),
_ => (),
if let Token::NewFile(_) = self.peek().item() {
return self.lexer.span().with_item(Token::Eof);
}
}
if let Some(tok) = self.peek.take() {
Expand Down Expand Up @@ -423,15 +425,15 @@ impl Parser {
let res = f(self);
match res {
Some(res) => Ok(res),
None => return Err(self.restore_checkpoint(checkpoint)),
None => Err(self.restore_checkpoint(checkpoint)),
}
}

fn checkpoint(&self) -> Checkpoint {
Checkpoint {
errors: self.errors.len(),
lexer: self.lexer.clone(),
peek: self.peek.clone(),
peek: self.peek,
}
}

Expand Down
5 changes: 1 addition & 4 deletions petr-parse/src/parser/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,7 @@ pub enum Token {
impl Token {
pub(crate) fn is_operator(&self) -> bool {
use Token::*;
match self {
Plus | Minus | Slash | Star => true,
_ => false,
}
matches!(self, Plus | Minus | Slash | Star)
}
}

Expand Down
24 changes: 12 additions & 12 deletions petr-pkg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ fn order_dependencies(deps: Vec<LoadDependencyResult>) -> BuildPlan {
let mut graph: BTreeMap<DependencyKey, Vec<DependencyKey>> = BTreeMap::new();

for dep in &deps {
graph.entry(dep.key.clone()).or_insert(vec![]);
for (_, top_level_dependency) in &dep.lock.depends_on {
graph.entry(dep.key.clone()).or_default();
for top_level_dependency in dep.lock.depends_on.values() {
let key = match top_level_dependency {
Dependency::Git(git_dep) => git_dep.git.clone(),
Dependency::Path(path_dep) => path_dep.path.clone(),
};
graph.entry(dep.key.clone()).or_insert(vec![]).push(key);
graph.entry(dep.key.clone()).or_default().push(key);

// Recursively include transient dependencies
fn add_transient_dependencies(
Expand All @@ -102,10 +102,10 @@ fn order_dependencies(deps: Vec<LoadDependencyResult>) -> BuildPlan {
Dependency::Git(git_dep) => git_dep.git.clone(),
Dependency::Path(path_dep) => path_dep.path.clone(),
};
graph.entry(dep_key.clone()).or_insert(vec![]).push(key.clone());
graph.entry(dep_key.clone()).or_default().push(key.clone());

if let Some(dep) = deps.iter().find(|d| d.key == key) {
for (_, trans_dependency) in &dep.lock.depends_on {
for trans_dependency in dep.lock.depends_on.values() {
add_transient_dependencies(graph, &key, trans_dependency, deps);
}
}
Expand All @@ -116,12 +116,12 @@ fn order_dependencies(deps: Vec<LoadDependencyResult>) -> BuildPlan {
}

for dep in &deps {
for (_, dependency) in &dep.lock.depends_on {
for dependency in dep.lock.depends_on.values() {
let dep_key = match dependency {
Dependency::Git(git_dep) => git_dep.git.parse().unwrap(),
Dependency::Path(path_dep) => path_dep.path.parse().unwrap(),
};
graph.entry(dep_key).or_insert(vec![]).push(dep.key.clone());
graph.entry(dep_key).or_default().push(dep.key.clone());
}
}

Expand Down Expand Up @@ -159,7 +159,7 @@ fn order_dependencies(deps: Vec<LoadDependencyResult>) -> BuildPlan {
// then sort them by the order of the `sorted_keys`
let mut all_deps = deps.clone();
for dep in &deps {
for (_, dependency) in &dep.lock.depends_on {
for dependency in dep.lock.depends_on.values() {
let key = match dependency {
Dependency::Git(git_dep) => git_dep.git.clone(),
Dependency::Path(path_dep) => path_dep.path.clone(),
Expand All @@ -177,15 +177,15 @@ fn order_dependencies(deps: Vec<LoadDependencyResult>) -> BuildPlan {
let items = sorted_keys
.into_iter()
.map(|key| {
let dep = all_deps.iter().find(|x| &x.key == &key).unwrap();
let dep = all_deps.iter().find(|x| x.key == key).unwrap();
let path = Path::new(&dep.lock.name);
BuildableItem {
path_to_source: path.to_path_buf(),
depends_on: dep
.lock
.depends_on
.iter()
.map(|(_, dep)| match dep {
.values()
.map(|dep| match dep {
Dependency::Git(git_dep) => git_dep.git.clone(),
Dependency::Path(path_dep) => path_dep.path.clone(),
})
Expand Down Expand Up @@ -218,7 +218,7 @@ fn load_git_dependency(dep: &GitDependency) -> LoadDependencyResult {
fs::create_dir_all(&petr_dir).expect("Failed to create .petr directory");
}

let repo_dir = petr_dir.join(&dep.git.replace("/", "_"));
let repo_dir = petr_dir.join(dep.git.replace("/", "_"));

if !repo_dir.exists() {
let _ = git2::Repository::clone(&dep.git, &repo_dir).expect("Failed to clone Git repository");
Expand Down
2 changes: 1 addition & 1 deletion petr-resolve/src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ impl Resolve for Expression {
for binding in &bound_expression.bindings {
let rhs = binding.val.resolve(resolver, binder, scope_id)?;
bindings.push(Binding {
name: binding.name.clone(),
name: binding.name,
expression: rhs,
});
}
Expand Down
6 changes: 3 additions & 3 deletions petr-typecheck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ impl TypeChecker {

let mut ty = Type::arrow(tys[0].clone(), tys[1].clone());

for i in 2..tys.len() {
ty = Type::arrow(ty, tys[i].clone());
for item in tys.iter().skip(2) {
ty = Type::arrow(ty, item.clone());
}

ty
Expand Down Expand Up @@ -329,7 +329,7 @@ impl TypeCheck for Expr {
) -> Self::Output {
match &self.kind {
ExprKind::Literal(lit) => {
let ty = ctx.convert_literal_to_type(&lit);
let ty = ctx.convert_literal_to_type(lit);
TypedExpr::Literal { value: lit.clone(), ty }
},
ExprKind::List(exprs) => {
Expand Down
14 changes: 11 additions & 3 deletions petr-utils/src/index_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ impl<K, V> IndexMap<K, V> {
pub fn len(&self) -> usize {
self.entries.len()
}

pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}

impl<K, V> Default for IndexMap<K, V>
Expand Down Expand Up @@ -83,6 +87,10 @@ where
.expect("IDs are handed out by insertion, so this should never fail")
}

// converting this into an IntoIter trait is kind of a pain in the butt...but should be done
// eventually.
// see https://github.com/sezna/petr/issues/39
#[allow(clippy::should_implement_trait)]
pub fn into_iter(self) -> impl Iterator<Item = (K, V)> {
self.entries.into_iter().enumerate().map(|(i, v)| (i.into(), v))
}
Expand Down Expand Up @@ -115,9 +123,9 @@ macro_rules! idx_map_key {
}
}

impl Into<usize> for $name {
fn into(self) -> usize {
self.0
impl From<$name> for usize {
fn from(value: $name) -> usize {
value.0
}
}

Expand Down
6 changes: 3 additions & 3 deletions petr-vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,23 +150,23 @@ impl Vm {
let str = &self.state.memory[ptr + 1..ptr + 1 + len];
let str = str.iter().flat_map(|num| num.to_ne_bytes()).collect::<Vec<u8>>();
// convert vec of usizes to string
let string: String = str.iter().map(|&c| c as u8 as char).collect();
let string: String = str.iter().map(|&c| c as char).collect();
println!("{}", string);
},
};
Ok(Continue)
},
IrOpcode::FunctionLabel(_) => Ok(Continue),
IrOpcode::LoadImmediate(dest, imm) => {
self.set_register(dest, Value(imm as u64));
self.set_register(dest, Value(imm));
Ok(Continue)
},
IrOpcode::Copy(dest, src) => {
let val = self.get_register(src)?;
self.set_register(dest, val);
Ok(Continue)
},
IrOpcode::TerminateExecution() => return Ok(Terminate),
IrOpcode::TerminateExecution() => Ok(Terminate),
IrOpcode::Jump(_) => todo!(),
IrOpcode::Label(_) => todo!(),
IrOpcode::Return() => {
Expand Down

0 comments on commit bf64008

Please sign in to comment.