Skip to content

Commit 7940459

Browse files
committed
chore: run cargo fmt and apply clippy lints
1 parent e566d42 commit 7940459

10 files changed

Lines changed: 68 additions & 85 deletions

File tree

kitc/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ fn main() -> Result<(), Error> {
6969

7070
fn compile(source: &PathBuf, libs: &[String], measure: bool) -> Result<PathBuf, String> {
7171
let init = time::Instant::now();
72-
fs::read_to_string(source).map_err(|_| format!("couldn't read {:?}", source))?;
72+
fs::read_to_string(source).map_err(|_| format!("couldn't read {}", source.display()))?;
7373

7474
let ext = if cfg!(windows) { "exe" } else { "" };
7575
let exe_path = source.with_extension(ext);
@@ -92,7 +92,7 @@ fn compile(source: &PathBuf, libs: &[String], measure: bool) -> Result<PathBuf,
9292
fn run_executable(exe_path: &PathBuf) -> Result<(), String> {
9393
let status = Command::new(exe_path)
9494
.status()
95-
.map_err(|e| format!("failed to launch executable: {}", e))?;
95+
.map_err(|e| format!("failed to launch executable: {e}"))?;
9696

9797
if !status.success() {
9898
std::process::exit(status.code().unwrap_or(1));

kitc/tests/examples.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ fn run_example_test(
2323
.ok_or("couldn't get workspace root")?;
2424

2525
let examples_dir = workspace_root.join("examples");
26-
let example_file = examples_dir.join(format!("{}.kit", example_name));
27-
let expected_file = examples_dir.join(format!("{}.kit.expected", example_name));
26+
let example_file = examples_dir.join(format!("{example_name}.kit"));
27+
let expected_file = examples_dir.join(format!("{example_name}.kit.expected"));
2828

2929
assert!(
3030
example_file.exists(),
@@ -39,8 +39,7 @@ fn run_example_test(
3939
);
4040

4141
log::info!(
42-
"Running example {} in {} (path: {}). Expected file is at {}",
43-
example_name,
42+
"Running example {example_name} in {} (path: {}). Expected file is at {}",
4443
workspace_root.display(),
4544
example_file.display(),
4645
expected_file.display()

kitlang/src/codegen/ast.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::codegen::types::*;
1+
use crate::codegen::types::{AssignmentOperator, BinaryOperator, Type, TypeId, UnaryOperator};
22

33
use std::collections::HashSet;
44

@@ -169,15 +169,16 @@ pub enum Literal {
169169

170170
impl Literal {
171171
/// Converts the literal to its C representation string.
172+
#[must_use]
172173
pub fn to_c(&self) -> String {
173174
match self {
174175
Literal::Int(i) => i.to_string(),
175176
Literal::Float(f) => {
176177
// Ensure float literals have 'f' suffix in C
177178
if f.fract() == 0.0 {
178-
format!("{}.0f", f)
179+
format!("{f}.0f")
179180
} else {
180-
format!("{}f", f)
181+
format!("{f}f")
181182
}
182183
}
183184
Literal::String(s) => {
@@ -192,7 +193,7 @@ impl Literal {
192193
_ => c.to_string(),
193194
})
194195
.collect();
195-
format!("\"{}\"", escaped)
196+
format!("\"{escaped}\"")
196197
}
197198
Literal::Bool(b) => b.to_string(),
198199
Literal::Null => "NULL".to_string(),

kitlang/src/codegen/compiler.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ impl Toolchain {
146146
match self {
147147
Toolchain::Gcc | Toolchain::Clang => {
148148
let flags = ["-std=c99", "-Wall", "-Wextra", "-pedantic"];
149-
flags.iter().map(|s| s.to_string()).collect()
149+
flags.iter().map(ToString::to_string).collect()
150150
}
151151
#[cfg(windows)]
152152
Toolchain::Msvc => {
@@ -181,7 +181,7 @@ pub struct CompilerOptions {
181181
pub link_opts: Vec<String>,
182182
}
183183

184-
#[derive(Debug, Clone)]
184+
#[derive(Debug, Clone, Copy)]
185185
pub struct CompilerMeta(pub Toolchain);
186186

187187
impl CompilerOptions {
@@ -256,9 +256,10 @@ impl CompilerOptions {
256256

257257
/// Build the compiler invocation used to spawn `Command`.
258258
///
259-
/// Returns (path_to_compiler_executable, args_vec).
259+
/// Returns (`path_to_compiler_executable`, `args_vec`).
260+
///
261+
/// # Errors
260262
///
261-
/// Errors:
262263
/// - if `sources` is empty
263264
/// - if `output` is not set
264265
/// - if no system compiler can be found and no `enforced_toolchain` is usable

kitlang/src/codegen/frontend.rs

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
use crate::{KitParser, Rule, error::CompilationError};
21
use crate::error::CompileResult;
2+
use crate::{KitParser, Rule, error::CompilationError};
33
use pest::Parser;
44

55
use std::collections::HashSet;
6+
use std::fmt::Write;
67
use std::path::{Path, PathBuf};
78
use std::process::Command;
89

9-
use crate::codegen::ast::*;
10+
use crate::codegen::ast::{Block, Expr, Function, Include, Program, Stmt};
1011
use crate::codegen::compiler::{CompilerMeta, CompilerOptions, Toolchain};
1112
use crate::codegen::inference::TypeInferencer;
1213
use crate::codegen::parser::Parser as CodeParser;
@@ -60,7 +61,7 @@ impl Compiler {
6061
}
6162
}
6263

63-
self.includes = includes.clone();
64+
self.includes.clone_from(&includes);
6465

6566
Ok(Program {
6667
includes,
@@ -70,10 +71,10 @@ impl Compiler {
7071
}
7172

7273
/// Generate C code from the AST and write it to the output path
73-
fn transpile_with_program(&mut self, prog: Program) {
74-
let c_code = self.generate_c_code(&prog);
74+
fn transpile_with_program(&mut self, prog: &Program) {
75+
let c_code = self.generate_c_code(prog);
7576
if let Err(e) = std::fs::write(&self.c_output, c_code) {
76-
panic!("Failed to write output: {}", e);
77+
panic!("Failed to write output: {e}");
7778
}
7879
}
7980

@@ -134,7 +135,7 @@ impl Compiler {
134135

135136
// emit unique headers
136137
for hdr in seen_headers {
137-
out.push_str(&format!("#include {}\n", hdr));
138+
writeln!(out, "#include {hdr}").unwrap();
138139
}
139140
out.push('\n');
140141

@@ -213,16 +214,15 @@ impl Compiler {
213214
.inferencer
214215
.store
215216
.resolve(*inferred)
216-
.map(|t| t.to_c_repr().name)
217-
.unwrap_or_else(|_| "auto".to_string());
217+
.map_or_else(|_| "auto".to_string(), |t| t.to_c_repr().name);
218218

219219
match init {
220220
Some(expr) => {
221221
let init_str = self.transpile_expr(expr);
222-
format!("{} {} = {};\n", ty_str, name, init_str)
222+
format!("{ty_str} {name} = {init_str};\n")
223223
}
224224
None => {
225-
format!("{} {};\n", ty_str, name)
225+
format!("{ty_str} {name};\n")
226226
}
227227
}
228228
}
@@ -260,16 +260,12 @@ impl Compiler {
260260
let mut s = if let Expr::RangeLiteral { start, end } = iter {
261261
let start_str = self.transpile_expr(start);
262262
let end_str = self.transpile_expr(end);
263-
format!(
264-
"for (int {} = {}; {} < {}; ++{}) ",
265-
var, start_str, var, end_str, var
266-
)
263+
format!("for (int {var} = {start_str}; {var} < {end_str}; ++{var}) ")
267264
} else {
268265
let iter_str = self.transpile_expr(iter);
269-
format!("for (int {} = 0; {} < {}; ++{}) ", var, var, iter_str, var)
266+
format!("for (int {var} = 0; {var} < {iter_str}; ++{var}) ")
270267
};
271268
s.push_str(&self.transpile_block(body));
272-
s.push('\n');
273269
s
274270
}
275271
Stmt::Break => "break;\n".to_string(),
@@ -300,7 +296,7 @@ impl Compiler {
300296
.map(|a| self.transpile_expr(a))
301297
.collect::<Vec<_>>()
302298
.join(", ");
303-
format!("{}({})", callee, args_str)
299+
format!("{callee}({args_str})")
304300
}
305301
Expr::UnaryOp { op, expr, ty: _ } => {
306302
let expr_str = self.transpile_expr(expr);
@@ -314,7 +310,7 @@ impl Compiler {
314310
} => {
315311
let left_str = self.transpile_expr(left);
316312
let right_str = self.transpile_expr(right);
317-
format!("({} {} {})", left_str, op.to_c_str(), right_str)
313+
format!("({left_str} {} {right_str})", op.to_c_str())
318314
}
319315
Expr::Assign {
320316
op,
@@ -324,7 +320,7 @@ impl Compiler {
324320
} => {
325321
let left_str = self.transpile_expr(left);
326322
let right_str = self.transpile_expr(right);
327-
format!("{} {} {}", left_str, op.to_c_str(), right_str)
323+
format!("{left_str} {} {right_str}", op.to_c_str())
328324
}
329325
Expr::If {
330326
cond,
@@ -335,7 +331,7 @@ impl Compiler {
335331
let cond_str = self.transpile_expr(cond);
336332
let then_str = self.transpile_expr(then_branch);
337333
let else_str = self.transpile_expr(else_branch);
338-
format!("({} ? {} : {})", cond_str, then_str, else_str)
334+
format!("({cond_str} ? {then_str} : {else_str})")
339335
}
340336
Expr::RangeLiteral { .. } => {
341337
// Should technically not be used alone, but return something safe to avoid panic
@@ -348,7 +344,7 @@ impl Compiler {
348344
let mut prog = self.parse()?;
349345

350346
self.inferencer.infer_program(&mut prog)?;
351-
self.transpile_with_program(prog);
347+
self.transpile_with_program(&prog);
352348

353349
let detected = Toolchain::executable_path().ok_or(CompilationError::ToolchainNotFound)?;
354350

kitlang/src/codegen/inference.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::ast::*;
1+
use super::ast::{Block, Expr, Function, Literal, Program, Stmt};
22
use super::symbols::SymbolTable;
33
use super::types::{BinaryOperator, Type, TypeId, TypeStore, UnaryOperator};
44
use crate::error::{CompilationError, CompileResult};
@@ -169,8 +169,7 @@ impl TypeInferencer {
169169
.map_err(CompilationError::TypeError)?;
170170
if iter_resolved != Type::Int && iter_resolved != Type::Void {
171171
return Err(CompilationError::TypeError(format!(
172-
"For loop iterator must be Int or Range, found {:?}",
173-
iter_resolved
172+
"For loop iterator must be Int or Range, found {iter_resolved:?}"
174173
)));
175174
}
176175

@@ -187,12 +186,12 @@ impl TypeInferencer {
187186
Ok(())
188187
}
189188

190-
/// Infer types for an expression.
189+
/// Infer types for an expression
191190
fn infer_expr(&mut self, expr: &mut Expr) -> Result<TypeId, CompilationError> {
192191
let ty = match expr {
193192
Expr::Identifier(name, ty_id) => {
194193
let var_ty = self.symbols.lookup_var(name).ok_or_else(|| {
195-
CompilationError::TypeError(format!("Use of undeclared variable '{}'", name))
194+
CompilationError::TypeError(format!("Use of undeclared variable '{name}'"))
196195
})?;
197196
*ty_id = var_ty;
198197
var_ty
@@ -268,8 +267,7 @@ impl TypeInferencer {
268267
self.store.new_known(*inner_ty)
269268
} else {
270269
return Err(CompilationError::TypeError(format!(
271-
"Cannot dereference non-pointer type: {:?}",
272-
resolved
270+
"Cannot dereference non-pointer type: {resolved:?}"
273271
)));
274272
}
275273
}

kitlang/src/codegen/parser.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ impl Parser {
285285
Rule::unary_op => {
286286
let op_str = first_pair.as_str();
287287
let op = UnaryOperator::from_str(op_str)
288-
.map_err(|_| parse_error!("invalid unary operation: {}", op_str))?;
288+
.map_err(|()| parse_error!("invalid unary operation: {op_str}"))?;
289289

290290
// SAFETY: Grammar guarantees expression after unary op
291291
let expr = self.parse_expr(inner_pairs.next().unwrap())?;
@@ -306,7 +306,7 @@ impl Parser {
306306
})
307307
}
308308
Rule::primary => self.parse_expr(first_pair),
309-
_other => Err(parse_error!("Unexpected rule in unary: {:?}", _other)),
309+
other => Err(parse_error!("Unexpected rule in unary: {other:?}")),
310310
}
311311
}
312312
Rule::identifier => Ok(Expr::Identifier(
@@ -396,21 +396,21 @@ impl Parser {
396396
// Otherwise, unwrap and parse the inner rule
397397
let inner_pair = inner.next().unwrap();
398398
match inner_pair.as_rule() {
399-
Rule::literal => self.parse_expr(inner_pair),
400399
Rule::identifier => Ok(Expr::Identifier(
401400
inner_pair.as_str().to_string(),
402401
TypeId::default(),
403402
)),
404-
Rule::function_call_expr
403+
Rule::literal
404+
| Rule::function_call_expr
405405
| Rule::array_literal
406406
| Rule::struct_init
407407
| Rule::union_init
408408
| Rule::tuple_literal
409409
| Rule::if_expr
410410
| Rule::range_expr
411411
| Rule::string
412-
| Rule::expr => self.parse_expr(inner_pair),
413-
Rule::unary => self.parse_expr(inner_pair),
412+
| Rule::expr
413+
| Rule::unary => self.parse_expr(inner_pair),
414414
_ => Err(parse_error!(
415415
"Unexpected primary inner rule: {:?}",
416416
inner_pair.as_rule()
@@ -429,8 +429,7 @@ impl Parser {
429429
})
430430
}
431431
other => Err(CompilationError::ParseError(format!(
432-
"Unexpected expr rule: {:?}",
433-
other
432+
"Unexpected expr rule: {other:?}"
434433
))),
435434
}
436435
}

kitlang/src/codegen/symbols.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ use std::collections::HashMap;
44
/// Symbol table for tracking variable and function types during inference.
55
///
66
/// Currently uses a flat scope (no nesting). Variables and functions are tracked
7-
/// by their names and their TypeIds.
7+
/// by their names and their `TypeId`s.
88
pub struct SymbolTable {
9-
/// Maps variable names to their inferred TypeIds.
9+
/// Maps variable names to their inferred `TypeId`s.
1010
vars: HashMap<String, TypeId>,
1111

1212
/// Maps function names to their signatures (parameter types, return type).

0 commit comments

Comments
 (0)