Skip to content

Commit

Permalink
Merge pull request #490 from KisaragiEffective/cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
KisaragiEffective authored Jun 25, 2024
2 parents 26d4aed + 4fc7ed9 commit 1a2a75a
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 101 deletions.
1 change: 0 additions & 1 deletion package/origlang-ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ impl Identifier {
}

#[must_use = "If you don't use it, it will drop entire String"]
#[allow(clippy::missing_const_for_fn)] // see https://github.com/rust-lang/rust-clippy/issues/10617
pub fn name(self) -> String {
self.0
}
Expand Down
2 changes: 0 additions & 2 deletions package/origlang-cli/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// clap issue?: https://github.com/clap-rs/clap/issues/4733
#![warn(clippy::almost_swapped)]

use std::fs::File;
use std::io::{BufReader, Read};
use std::path::PathBuf;
use std::string::FromUtf8Error;
use clap::{Parser, Subcommand};
Expand Down
17 changes: 0 additions & 17 deletions package/origlang-ir-optimizer/src/ir1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,6 @@ impl<T: PartialOrd + PartialEq + CastFrom<Ordering>> OutputCompareResultAsSelf f
}
}

trait Continue<T> {
fn continue_value(self) -> Option<T>;
}

impl<T> Continue<T> for Option<T> {
#[allow(clippy::use_self)]
fn continue_value(self) -> Option<T> {
self
}
}

impl Continue<Self> for bool {
fn continue_value(self) -> Option<Self> {
self.then_some(true)
}
}

/// 二項演算子についての定数畳み込みを行う。
// TODO: 左端以外に畳み込みが行える定数項があっても、それらの項が畳み込まれない。
// すなわち、オーバーフローがないものとして`a * 2 / 2`を最適化するとき、`a`に最適化出来ない。
Expand Down
6 changes: 0 additions & 6 deletions package/origlang-lexer/src/boundary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,3 @@ impl From<char> for Utf8CharStride {
}
}
}

#[derive(Error, Debug)]
#[error("invalid value for UTF-8 codepoint stride: {given_value}")]
pub struct InvalidUtf8CharStrideError {
given_value: u8
}
38 changes: 19 additions & 19 deletions package/origlang-parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub enum TokenKind {
}

impl TokenKind {
fn only(token: Token) -> Self {
fn only(token: &Token) -> Self {
Self::Only(token.display())
}
}
Expand Down Expand Up @@ -142,7 +142,7 @@ impl Parser {
unmatch: aliased.data
}, aliased.position)) };

self.read_and_consume_or_report_unexpected_token(Token::SymEq)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymEq)?;
let Ok(replace_with) = self.lexer.parse_fallible(|| self.parse_type()) else {
let p = self.lexer.peek_cloned();
return Err(ParserError::new(ParserErrorInner::UnexpectedToken {
Expand Down Expand Up @@ -218,7 +218,7 @@ impl Parser {
Ok(expr_tuple)
} else {
let inner_expression = self.parse_lowest_precedence_expression()?;
self.read_and_consume_or_report_unexpected_token(Token::SymRightPar)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymRightPar)?;
Ok(inner_expression)
}
}
Expand Down Expand Up @@ -582,7 +582,7 @@ impl Parser {

debug!("type:tuple:accumulator = {vec:?}");

self.read_and_consume_or_report_unexpected_token(Token::SymRightPar)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymRightPar)?;

if vec.len() < 2 {
let l = vec.len();
Expand All @@ -609,7 +609,7 @@ impl Parser {

fn parse_variable_declaration(&self) -> Result<Statement, ParserError> {
debug!("decl:var");
self.read_and_consume_or_report_unexpected_token(Token::VarKeyword)?;
self.read_and_consume_or_report_unexpected_token(&Token::VarKeyword)?;
let pattern = self.parse_atomic_pattern()?;

// optionally, allow type annotation
Expand All @@ -631,7 +631,7 @@ impl Parser {

debug!("decl:var:annotation: {type_annotation:?}");

self.read_and_consume_or_report_unexpected_token(Token::SymEq)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymEq)?;
debug!("decl:var:expr");
let expression = self.parse_lowest_precedence_expression()?;

Expand All @@ -651,7 +651,7 @@ impl Parser {
pat: TokenKind::Identifier,
unmatch: ident_token.data }, ident_token.position))
};
self.read_and_consume_or_report_unexpected_token(Token::SymEq)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymEq)?;
debug!("assign:var:expr");
let expression = self.parse_lowest_precedence_expression()?;
Ok(Statement::VariableAssignment {
Expand All @@ -670,9 +670,9 @@ impl Parser {
if self.lexer.peek().ok_or_else(|| ParserError::new(ParserErrorInner::EndOfFileError, self.lexer.last_position))?.data == Token::KeywordIf {
self.lexer.next();
let condition = self.parse_lowest_precedence_expression()?;
self.read_and_consume_or_report_unexpected_token(Token::KeywordThen)?;
self.read_and_consume_or_report_unexpected_token(&Token::KeywordThen)?;
let then_clause_value = self.parse_lowest_precedence_expression()?;
self.read_and_consume_or_report_unexpected_token(Token::KeywordElse)?;
self.read_and_consume_or_report_unexpected_token(&Token::KeywordElse)?;
let else_clause_value = self.parse_lowest_precedence_expression()?;
Ok(Expression::If {
condition: Box::new(condition),
Expand All @@ -686,7 +686,7 @@ impl Parser {

fn parse_block_scope(&self) -> Result<Statement, ParserError> {
debug!("statement:block");
self.read_and_consume_or_report_unexpected_token(Token::KeywordBlock)?;
self.read_and_consume_or_report_unexpected_token(&Token::KeywordBlock)?;
if self.lexer.peek().ok_or_else(|| ParserError::new(ParserErrorInner::EndOfFileError, self.lexer.last_position))?.data == Token::NewLine {
self.lexer.next();
}
Expand All @@ -695,7 +695,7 @@ impl Parser {
while let Ok(v) = self.parse_statement() {
statements.push(v);
}
self.read_and_consume_or_report_unexpected_token(Token::KeywordEnd)?;
self.read_and_consume_or_report_unexpected_token(&Token::KeywordEnd)?;

Ok(Statement::Block {
inner_statements: (statements),
Expand All @@ -706,7 +706,7 @@ impl Parser {
debug!("expr:block");
if self.lexer.peek().ok_or_else(|| ParserError::new(ParserErrorInner::EndOfFileError, self.lexer.last_position))?.data == Token::KeywordBlock {
self.lexer.next();
self.read_and_consume_or_report_unexpected_token(Token::NewLine)?;
self.read_and_consume_or_report_unexpected_token(&Token::NewLine)?;
let mut statements = vec![];
while let Ok(v) = self.parse_statement() {
statements.push(v);
Expand All @@ -715,7 +715,7 @@ impl Parser {
if self.lexer.peek().ok_or_else(|| ParserError::new(ParserErrorInner::EndOfFileError, self.lexer.last_position))?.data == Token::NewLine {
self.lexer.next();
}
self.read_and_consume_or_report_unexpected_token(Token::KeywordEnd)?;
self.read_and_consume_or_report_unexpected_token(&Token::KeywordEnd)?;
Ok(Expression::Block {
intermediate_statements: statements,
final_expression
Expand All @@ -727,7 +727,7 @@ impl Parser {

fn parse_tuple_destruct_pattern(&self) -> Result<AtomicPattern, ParserError> {
debug!("pattern:tuple");
self.read_and_consume_or_report_unexpected_token(Token::SymLeftPar)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymLeftPar)?;

let mut v = vec![];

Expand All @@ -740,10 +740,10 @@ impl Parser {
break
}

self.read_and_consume_or_report_unexpected_token(Token::SymComma)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymComma)?;
}

self.read_and_consume_or_report_unexpected_token(Token::SymRightPar)?;
self.read_and_consume_or_report_unexpected_token(&Token::SymRightPar)?;

Ok(AtomicPattern::Tuple(v))
}
Expand Down Expand Up @@ -774,11 +774,11 @@ impl Parser {
}

/// 現在のトークンが指定されたトークンならそのトークンをそのまま返した上でレキサーを1個進める。そうではないなら[`ParseError::UnexpectedToken`]を返す。
fn read_and_consume_or_report_unexpected_token(&self, token: Token) -> Result<Token, ParserError> {
fn read_and_consume_or_report_unexpected_token(&self, token: &Token) -> Result<(), ParserError> {
let peek = self.lexer.peek().ok_or_else(|| ParserError::new(ParserErrorInner::EndOfFileError, self.lexer.last_position))?;
if peek.data == token {
if &peek.data == token {
self.lexer.next();
Ok(token)
Ok(())
} else {
Err(ParserError::new(ParserErrorInner::UnexpectedToken {
pat: TokenKind::only(token),
Expand Down
85 changes: 44 additions & 41 deletions package/origlang-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,6 @@ impl Runtime {
}

/// Start runtime. Never returns until execution is completed.
#[allow(dead_code)]
pub fn start<'s: 'o, 'o>(&'s self, seq: &[IR2]) -> &'o RefCell<dyn OutputAccumulator> {
// info!("{ast:?}", ast = &ast);
let x = seq;
Expand Down Expand Up @@ -342,6 +341,49 @@ macro_rules! indicate_type_checker_bug {
};
}

fn evaluate_bin_op(runtime: &Runtime, lhs: &CompiledTypedExpression, rhs: &CompiledTypedExpression, operator: &BinaryOperatorKind) -> EvaluateResult {
let lhs = lhs.evaluate(runtime)?;
let rhs = rhs.evaluate(runtime)?;
if matches!(operator, BinaryOperatorKind::Equal | BinaryOperatorKind::NotEqual) {
return if lhs.get_type() == rhs.get_type() {
let ret = match operator {
BinaryOperatorKind::Equal => lhs == rhs,
BinaryOperatorKind::NotEqual => lhs != rhs,
_ => unreachable!(),
};
Ok(ret.into())
} else {
indicate_type_checker_bug!(context = "type checker must deny equality check between different types")
}
}

match (lhs, rhs) {
(TypeBox::NonCoercedInteger(lhs), TypeBox::NonCoercedInteger(rhs)) => {
f!(lhs, operator, rhs as NonCoerced)
},
(TypeBox::Int8(lhs), TypeBox::Int8(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int16(lhs), TypeBox::Int16(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int32(lhs), TypeBox::Int32(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int64(lhs), TypeBox::Int64(rhs)) => {
f!(lhs, operator, rhs as Coerced)
},
(TypeBox::String(lhs), TypeBox::String(rhs)) => {
let mut ret = lhs;
// give hint to compiler
ret.reserve_exact(rhs.len());
ret += rhs.as_str();
Ok(ret.into())
}
_ => indicate_type_checker_bug!(context = "type checker must deny operator application between different type")
}
}

impl CanBeEvaluated for CompiledTypedExpression {
fn evaluate(&self, runtime: &Runtime) -> EvaluateResult {
match self {
Expand All @@ -361,46 +403,7 @@ impl CanBeEvaluated for CompiledTypedExpression {
.ok_or(RuntimeError::UndefinedVariable { identifier: ident.clone() })
},
Self::BinaryOperator { lhs, rhs, operator, return_type: _ } => {
let lhs = lhs.as_ref().evaluate(runtime)?;
let rhs = rhs.as_ref().evaluate(runtime)?;
if matches!(operator, BinaryOperatorKind::Equal | BinaryOperatorKind::NotEqual) {
return if lhs.get_type() == rhs.get_type() {
let ret = match operator {
BinaryOperatorKind::Equal => lhs == rhs,
BinaryOperatorKind::NotEqual => lhs != rhs,
_ => unreachable!(),
};
Ok(ret.into())
} else {
indicate_type_checker_bug!(context = "type checker must deny equality check between different types")
}
}

return match (lhs, rhs) {
(TypeBox::NonCoercedInteger(lhs), TypeBox::NonCoercedInteger(rhs)) => {
f!(lhs, operator, rhs as NonCoerced)
},
(TypeBox::Int8(lhs), TypeBox::Int8(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int16(lhs), TypeBox::Int16(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int32(lhs), TypeBox::Int32(rhs)) => {
f!(lhs, operator, rhs)
},
(TypeBox::Int64(lhs), TypeBox::Int64(rhs)) => {
f!(lhs, operator, rhs as Coerced)
},
(TypeBox::String(lhs), TypeBox::String(rhs)) => {
let mut ret = lhs;
// give hint to compiler
ret.reserve_exact(rhs.len());
ret += rhs.as_str();
Ok(ret.into())
}
_ => indicate_type_checker_bug!(context = "type checker must deny operator application between different type")
};
evaluate_bin_op(runtime, lhs, rhs, operator)
}
Self::If { condition, then: then_clause_value, els: else_clause_value, return_type: _ } => {
let ret = condition.as_ref().evaluate(runtime)?;
Expand Down
17 changes: 2 additions & 15 deletions package/origlang-typecheck/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
#![deny(clippy::all)]
#![warn(clippy::pedantic, clippy::nursery)]
pub mod type_check;

pub fn add(left: usize, right: usize) -> usize {
left + right
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
// TODO: lift up
pub mod type_check;
2 changes: 2 additions & 0 deletions package/origlang-typecheck/src/type_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,8 @@ impl TypeChecker {
}
}

#[must_use]
#[allow(clippy::missing_panics_doc)] // do not panic
pub fn make_fresh_identifier(&self) -> Identifier {
// TODO: this implementation is poor. choice more elegant algorithm.
let hello = RandomState::new().hash_one(());
Expand Down

0 comments on commit 1a2a75a

Please sign in to comment.