Skip to content

Commit

Permalink
Merge pull request #295 from KisaragiEffective/refactor/clippy-reduce
Browse files Browse the repository at this point in the history
  • Loading branch information
KisaragiEffective authored Oct 19, 2023
2 parents 577f05e + 475e0f8 commit d3e18a2
Show file tree
Hide file tree
Showing 16 changed files with 86 additions and 107 deletions.
9 changes: 4 additions & 5 deletions package/origlang-cli/src/task/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use origlang_compiler::lexer::Lexer;
use origlang_compiler::parser::{Parser, SimpleErrorWithPos};
use origlang_compiler::type_check::error::TypeCheckError;
use origlang_compiler::type_check::TypeChecker;
use origlang_ir::{IR1, IR2};
use origlang_ir::{IR1, IR2, IntoVerbatimSequencedIR};
use origlang_ir_optimizer::lower::{EachStep, LowerStep, TheTranspiler};
use origlang_ir_optimizer::preset::{NoOptimization, SimpleOptimization};
use crate::args::{EmitPhase, OptimizeLevel, ParseSource};
Expand Down Expand Up @@ -57,15 +57,14 @@ impl Task for UnstableEmit {
}

let checker = TypeChecker::new();
let checked = checker.check(root)?;
let expr = checker.check(root)?;

if self.phase == EmitPhase::TypedAst {
println!("{checked:#?}");
println!("{expr:#?}");
return Ok(())
}

use origlang_ir::IntoVerbatimSequencedIR;
let ir_sequence = checked.into_ir();
let ir_sequence = expr.into_ir();

let optimizer = match optimize_level {
OptimizeLevel::None => &NoOptimization as &dyn EachStep,
Expand Down
22 changes: 0 additions & 22 deletions package/origlang-cli/src/task/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,6 @@ impl ariadne::Cache<()> for Dummy {
pub struct Repl;

impl Repl {
fn type_box_to_final_evaluated_form(tb: &TypeBox) -> String {
match tb {
TypeBox::Int8(i) => i.to_string(),
TypeBox::Int16(i) => i.to_string(),
TypeBox::Int32(i) => i.to_string(),
TypeBox::Int64(i) | TypeBox::NonCoercedInteger(i) => i.to_string(),
TypeBox::Boolean(b) => b.to_string(),
TypeBox::String(s) => format!(r#""{s}""#),
TypeBox::Unit => "()".to_string(),
TypeBox::Tuple(tp) => {
let elements = tp.boxes.iter().map(Self::type_box_to_final_evaluated_form).collect::<Vec<_>>().join(", ");
format!("({elements})")
}
TypeBox::Record(r) => {
let elements = r.values.iter().map(Self::type_box_to_final_evaluated_form).collect::<Vec<_>>().join(", ");
let identifier = r.name.clone();

format!("{identifier} {{{elements}}}")
}
}
}

fn naive_lower(tra: TypedRootAst) -> Vec<IR2> {
let ir = tra.into_ir();
let trans = TheTranspiler::new(&NoOptimization);
Expand Down
2 changes: 2 additions & 0 deletions package/origlang-compiler-entrypoint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ impl TheCompiler {
}
}

#[must_use]
pub fn scanners(mut self, modify: impl FnOnce(&mut ScannerRegistry)) -> Self {
modify(&mut self.scanner);

Expand All @@ -46,6 +47,7 @@ impl TheCompiler {
self
}

#[must_use]
pub fn optimization_preset(mut self, modify: impl FnOnce(&mut OptimizationPresetCollection)) -> Self {
modify(&mut self.optimization_preset);

Expand Down
2 changes: 1 addition & 1 deletion package/origlang-compiler-scanner-example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,6 @@ mod tests {
.register_diagnostic_receiver(Box::new(tdr))
.compile("var foo = 1i32\n".to_string());

assert!(a.is_ok())
assert!(a.is_ok());
}
}
55 changes: 27 additions & 28 deletions package/origlang-compiler/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,18 @@ pub struct Lexer<'src> {

impl<'src> Lexer<'src> {
#[must_use = "Lexer do nothing unless calling parsing function"]
// NOTE: unsafe { NonZeroUsize::new_unchecked(1) } is same as NonZeroUsize::new(1).expect() in
// release mode.
// However, clippy::missing_panics_doc issues that the latter may panic (obviously, it's
// false positive).
pub fn create(source: &'src str) -> Self {
Self {
source_bytes_nth: Cell::new(Utf8CharBoundaryStartByte::new(0)),
source,
line: Cell::new(NonZeroUsize::new(1).unwrap()),
column: Cell::new(NonZeroUsize::new(1).unwrap()),
// SAFETY: 1 != 0
line: Cell::new(unsafe { NonZeroUsize::new_unchecked(1) }),
// SAFETY: 1 != 0
column: Cell::new(unsafe { NonZeroUsize::new_unchecked(1) }),
}
}
}
Expand All @@ -70,18 +76,14 @@ impl Lexer<'_> {
trace!("lexer:try:{s:?}");
let start = self.source_bytes_nth.get();
let end_exclusive = start.as_usize() + s.len();
if let Some(b) = self.source.get((start.as_usize())..end_exclusive) {
if s == b {
match self.set_current_index(Utf8CharBoundaryStartByte::new(end_exclusive)) {
Ok(()) => Ok(Some(s)),
Err(OutOfRangeError { .. }) => Ok(None),
}
} else {
Ok(None)
self.source.get((start.as_usize())..end_exclusive).map_or(Ok(None), |b| if s == b {
match self.set_current_index(Utf8CharBoundaryStartByte::new(end_exclusive)) {
Ok(()) => Ok(Some(s)),
Err(OutOfRangeError { .. }) => Ok(None),
}
} else {
Ok(None)
}
})
}

#[allow(clippy::unnecessary_wraps)]
Expand Down Expand Up @@ -235,6 +237,7 @@ impl Lexer<'_> {

let s = unsafe { this.source.get_unchecked(index..(index + stride.as_usize())) };

#[allow(clippy::or_fun_call)] // latter is fine because it does not cost
let c = s.chars().next().ok_or(this.report_out_of_range_error())?;


Expand Down Expand Up @@ -360,27 +363,30 @@ impl Lexer<'_> {
if old < new {
// forward
let new_line = current_line + src[old..new].bytes().filter(|x| *x == b'\n').count();
let new_col = if let Some(old_relative) = src[old..new].rfind('\n') {
// .......................OLD.................NEW
// |<--------N------>|
new - (old + old_relative)
} else {
let new_col = src[old..new].rfind('\n').map_or_else(|| {
let mut c = self.column.get().get();
c += new - old;

c
};
}, |old_relative| {
new - (old + old_relative)
});

self.line.set(NonZeroUsize::new(new_line).expect("overflow"));
self.column.set(NonZeroUsize::new(new_col).expect("overflow"));
} else {
// back
let new_line = current_line - src[new..old].bytes().filter(|x| *x == b'\n').count();
let new_col = if let Some(new_relative) = src[new..old].find('\n') {
let new_col = src[new..old].find('\n').map_or_else(|| {
let mut c = self.column.get().get();
c += old - new;

c
}, |new_relative| {
// .......................NEW.................OLD
// |<--------N------>|
let nr = new + new_relative;
if let Some(most_recent_nl) = src[..nr].rfind('\n') {
src[..nr].rfind('\n').map_or(nr, |most_recent_nl| {
// ..............NEW.................OLD
// |<--------N------>|
// |<-----MRN-------------->|
Expand All @@ -389,15 +395,8 @@ impl Lexer<'_> {
// cost on runtime.
assert!(most_recent_nl < nr);
nr - most_recent_nl
} else {
nr
}
} else {
let mut c = self.column.get().get();
c += old - new;

c
};
})
});

self.line.set(NonZeroUsize::new(new_line).expect("overflow"));
self.column.set(NonZeroUsize::new(new_col).expect("overflow"));
Expand Down
1 change: 1 addition & 0 deletions package/origlang-compiler/src/lexer/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub enum LexerError {

#[derive(Debug, Error, Eq, PartialEq)]
#[error("lexer index overflow: {current:?} > {max}")]
#[allow(clippy::module_name_repetitions)]
pub struct OutOfRangeError {
pub current: Utf8CharBoundaryStartByte,
pub max: usize,
Expand Down
4 changes: 2 additions & 2 deletions package/origlang-compiler/src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub struct TemporalLexerUnwindToken {
}

impl TemporalLexerUnwindToken {
#[must_use]
pub fn new(reset_to: Utf8CharBoundaryStartByte) -> Self {
#[must_use = "call Self::reset to invoke"]
pub const fn new(reset_to: Utf8CharBoundaryStartByte) -> Self {
Self {
unwind_index: reset_to
}
Expand Down
4 changes: 2 additions & 2 deletions package/origlang-compiler/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,9 +692,9 @@ impl Parser<'_> {
debug!("{:?}", self.lexer.peek().data);
if self.lexer.peek().data != Token::SymComma {
break
} else {
self.lexer.next();
}

self.lexer.next();
}

debug!("type:tuple:accumulator = {vec:?}");
Expand Down
14 changes: 7 additions & 7 deletions package/origlang-compiler/src/type_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl TryIntoTypeCheckedForm for Expression {
type Success = TypedExpression;
type Err = TypeCheckError;

#[allow(clippy::too_many_lines)]
#[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
fn type_check(self, checker: &TypeChecker) -> Result<Self::Success, Self::Err> {
match self {
Self::IntLiteral { value, suffix } => {
Expand Down Expand Up @@ -380,10 +380,10 @@ fn desugar(
}
}

fn extract_pattern(checked: TypedExpression, pattern: &AtomicPattern, type_annotation: Option<TypeSignature>, checker: &TypeChecker) -> Result<Vec<TypedStatement>, TypeCheckError> {
fn extract_pattern(expr: TypedExpression, pattern: &AtomicPattern, type_annotation: Option<TypeSignature>, checker: &TypeChecker) -> Result<Vec<TypedStatement>, TypeCheckError> {
let Some(type_name) = type_annotation else {
// no annotations, just set its type (type-inference) from the expr
return handle_atomic_pattern(checked, pattern, checker)
return handle_atomic_pattern(expr, pattern, checker)
};

let Ok(dest) = checker.lower_type_signature_into_type(&type_name) else {
Expand All @@ -392,19 +392,19 @@ fn extract_pattern(checked: TypedExpression, pattern: &AtomicPattern, type_annot
})
};

match dest.is_assignable(&checked.actual_type()) {
match dest.is_assignable(&expr.actual_type()) {
AssignableQueryAnswer::Yes => {
handle_atomic_pattern(checked, pattern, checker)
handle_atomic_pattern(expr, pattern, checker)
},
AssignableQueryAnswer::PossibleIfCoerceSourceImplicitly => {
Err(TypeCheckError::UnassignableType {
from: checked.actual_type(),
from: expr.actual_type(),
to: dest,
})
}
AssignableQueryAnswer::No => {
Err(TypeCheckError::UnassignableType {
from: checked.actual_type(),
from: expr.actual_type(),
to: dest,
})
}
Expand Down
1 change: 1 addition & 0 deletions package/origlang-ir-optimizer/src/ir0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use origlang_ir::IR0;
pub struct EliminateAfterExit(pub Vec<IR0>);

impl EliminateAfterExit {
#[must_use = "return value is optimized IR, dropping it will waste it"]
pub fn optimize(self) -> Vec<IR0> {
let mut x = self.0.into_iter().take_while(|x| *x != IR0::Exit).collect::<Vec<_>>();
x.push(IR0::Exit);
Expand Down
2 changes: 2 additions & 0 deletions package/origlang-ir-optimizer/src/ir1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ impl FoldBinaryOperatorInvocationWithConstant {
pub struct FoldIfWithConstantCondition(pub Vec<IR1>);

impl FoldIfWithConstantCondition {
#[must_use = "return value is optimized IR, dropping it will waste it"]
pub fn optimize(self) -> Vec<IR1> {
self.0.into_iter().map(|x| {
match x {
Expand Down Expand Up @@ -286,6 +287,7 @@ impl FoldIfWithConstantCondition {
pub struct InlineSimpleBlock(pub Vec<IR1>);

impl InlineSimpleBlock {
#[must_use = "return value is optimized IR, dropping it will waste it"]
pub fn optimize(self) -> Vec<IR1> {
self.0.into_iter().map(|x| match x {
IR1::Output(x) => IR1::Output(Self::walk_expression(x)),
Expand Down
7 changes: 7 additions & 0 deletions package/origlang-ir-optimizer/src/preset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ pub trait OptimizationPreset<IR> {
///
/// # Panics
/// しない。
#[must_use = "return value is optimized IR, dropping it will waste it"]
fn optimize(&self, seq: Vec<IR>) -> Vec<IR>;
}

/// Do not perform optimization at all.
pub struct NoOptimization;

impl OptimizationPreset<IR0> for NoOptimization {
#[allow(clippy::redundant_closure_for_method_calls)]
fn optimize(&self, seq: Vec<IR0>) -> Vec<IR0> {
#[allow(clippy::wildcard_imports)]
use crate::ir0::*;

seq
Expand All @@ -40,7 +43,9 @@ impl OptimizationPreset<IR2> for NoOptimization {
pub struct SimpleOptimization;

impl OptimizationPreset<IR0> for SimpleOptimization {
#[allow(clippy::redundant_closure_for_method_calls)]
fn optimize(&self, seq: Vec<IR0>) -> Vec<IR0> {
#[allow(clippy::wildcard_imports)]
use crate::ir0::*;

seq
Expand All @@ -49,7 +54,9 @@ impl OptimizationPreset<IR0> for SimpleOptimization {
}

impl OptimizationPreset<IR1> for SimpleOptimization {
#[allow(clippy::redundant_closure_for_method_calls)]
fn optimize(&self, seq: Vec<IR1>) -> Vec<IR1> {
#[allow(clippy::wildcard_imports)]
use crate::ir1::*;

seq
Expand Down
11 changes: 2 additions & 9 deletions package/origlang-ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,8 @@ impl IntoVerbatimSequencedIR for TypedStatement {
IR0::Normal(IR1::Output(expression))
]
}
Self::VariableDeclaration { identifier, expression } => {
vec![
IR0::Normal(IR1::UpdateVariable {
ident: identifier,
value: expression,
})
]
}
Self::VariableAssignment { identifier, expression } => {
Self::VariableDeclaration { identifier, expression }
| Self::VariableAssignment { identifier, expression } => {
vec![
IR0::Normal(IR1::UpdateVariable {
ident: identifier,
Expand Down
2 changes: 1 addition & 1 deletion package/origlang-runtime/src/invoke_once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct InvokeOnce<T> {
}

impl<T> InvokeOnce<T> {
pub fn new(value: T) -> Self {
pub const fn new(value: T) -> Self {
Self {
inner: RefCell::new(MaybeUninit::new(value)),
owned: Cell::new(true),
Expand Down
11 changes: 5 additions & 6 deletions package/origlang-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod invoke_once;

use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::fmt::{Debug, Display, Formatter, Write};
use std::fmt::{Debug, Display, Formatter};
use derive_more::{Display, From};
use log::debug;
use tap::Conv;
Expand Down Expand Up @@ -440,11 +440,10 @@ impl CanBeEvaluated for CompiledTypedExpression {
let x = expr.evaluate(runtime)?;
match x {
TypeBox::Tuple(x) => {
if let Some(x) = x.boxes.get(*index) {
Ok(x.clone())
} else {
indicate_type_checker_bug!(context = "tuple_destruction: out of bounds")
}
x.boxes.get(*index).map_or_else(
|| indicate_type_checker_bug!(context = "tuple_destruction: out of bounds"),
|x| Ok(x.clone())
)
}
_other => indicate_type_checker_bug!(context = "must be tuple")
}
Expand Down
Loading

0 comments on commit d3e18a2

Please sign in to comment.