Skip to content
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

perf: reduce register pressure #637

Merged
merged 2 commits into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion package/origlang-ast/src/after_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub enum Expression {
/// 真偽値リテラル
BooleanLiteral(bool),
/// 文字列リテラル
StringLiteral(String),
StringLiteral(Box<str>),
/// ユニットリテラル
UnitLiteral,
/// 変数
Expand Down
12 changes: 6 additions & 6 deletions package/origlang-ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,20 @@ pub enum Statement {

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Comment {
pub content: String,
pub content: Box<str>,
}

#[derive(Eq, PartialEq, Clone, Debug, Hash)]
pub struct Identifier(String);
pub struct Identifier(Box<str>);

impl Identifier {
#[must_use = "If you don't use it, it will drop entire String"]
pub const fn new(s: String) -> Self {
#[must_use = "If you don't use it, it will drop entire string"]
pub const fn new(s: Box<str>) -> Self {
Self(s)
}

#[must_use = "If you don't use it, it will drop entire String"]
pub fn name(self) -> String {
#[must_use = "If you don't use it, it will drop entire string"]
pub fn name(self) -> Box<str> {
self.0
}

Expand Down
4 changes: 2 additions & 2 deletions package/origlang-compiler-entrypoint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ impl TheCompiler {
self
}

pub fn compile(&self, source: String) -> Result<Vec<IR1>, PartialCompilation> {
let x = Parser::create(&source);
pub fn compile(&self, source: &str) -> Result<Vec<IR1>, PartialCompilation> {
let x = Parser::create(source);
let root = x.parse()?;
let typeck = TypeChecker::new().check(root)?;
let ir0_seq = typeck.into_ir();
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 @@ -77,7 +77,7 @@ mod tests {
s.ir1_scanner.push(PreOrPost::Pre(Box::new(MyScanner)));
})
.register_diagnostic_receiver(Box::new(tdr))
.compile("var foo = 1i32\n".to_string());
.compile("var foo = 1i32\n");

assert!(a.is_ok());
}
Expand Down
3 changes: 2 additions & 1 deletion package/origlang-interop/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ struct PseudoStdout;

impl OutputAccumulator for PseudoStdout {
fn output(&mut self, tb: TypeBox) {
// TODO: this shall be Box<str> whenever possible.
let s: String = match tb {
TypeBox::NonCoercedInteger(x) => x.to_string(),
TypeBox::Int8(i) => i.to_string(),
Expand All @@ -44,7 +45,7 @@ impl OutputAccumulator for PseudoStdout {
TypeBox::Float32(f) => f.to_string(),
TypeBox::Float64(f) => f.to_string(),
TypeBox::Boolean(i) => i.to_string(),
TypeBox::String(s) => s,
TypeBox::String(s) => s.to_string(),
TypeBox::Unit => "()".to_string(),
TypeBox::Tuple(t) => t.to_string(),
TypeBox::Record(r) => r.to_string(),
Expand Down
2 changes: 1 addition & 1 deletion package/origlang-ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ pub enum CompiledTypedExpression {
IntLiteral(TypedIntLiteral),
BooleanLiteral(bool),
FloatLiteral(TypedFloatLiteral),
StringLiteral(String),
StringLiteral(Box<str>),
UnitLiteral,
Variable {
ident: Identifier,
Expand Down
8 changes: 4 additions & 4 deletions package/origlang-lexer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl Lexer<'_> {
"type" => Token::KeywordType,
"_" => Token::SymUnderscore,
other => Token::Reserved {
matched: other.to_string(),
matched: other.to_string().into_boxed_str(),
},
}
} else {
Expand Down Expand Up @@ -275,7 +275,7 @@ impl Lexer<'_> {
.unwrap_or(self.source.len() - start);
self.advance_bytes(rel_pos + 1);

let s = self.source[start..(start + rel_pos)].to_string();
let s = self.source[start..(start + rel_pos)].to_string().into_boxed_str();
Token::StringLiteral(s)
}

Expand Down Expand Up @@ -353,7 +353,7 @@ impl Lexer<'_> {
let rel_pos = self.source[start..].find('\n').unwrap_or(self.source.len());
self.advance_bytes(rel_pos);

let content = self.source[start..(start + rel_pos)].to_string();
let content = self.source[start..(start + rel_pos)].into();
Token::Comment {
content: Comment { content },
}
Expand Down Expand Up @@ -435,7 +435,7 @@ impl Lexer<'_> {

debug!("lexer:identifier: length of {plus}");
let start = self.source_bytes_nth.get().as_usize();
let s = Identifier::new(self.source[start..(start + plus)].to_string());
let s = Identifier::new(self.source[start..(start + plus)].into());
self.advance_bytes(plus);

Ok(Some(s))
Expand Down
8 changes: 4 additions & 4 deletions package/origlang-lexer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ fn test(str_lit: &str) {
assert_eq!(
p.next().data,
Token::Identifier {
inner: Identifier::new("x".to_string()),
inner: Identifier::new("x".to_string().into_boxed_str()),
}
);
assert_eq!(p.next().data, Token::SymEq);
assert_eq!(p.next().data, Token::StringLiteral(str_lit.to_string()));
assert_eq!(p.next().data, Token::StringLiteral(str_lit.to_string().into_boxed_str()));
}

#[test]
Expand Down Expand Up @@ -117,7 +117,7 @@ fn token_location() {
lexer.next(),
Pointed {
data: Token::Identifier {
inner: Identifier::new("x".to_string())
inner: Identifier::new("x".to_string().into_boxed_str())
},
position: SourcePosition::try_new((1, 5)).unwrap()
}
Expand Down Expand Up @@ -162,7 +162,7 @@ fn token_location() {
lexer.next(),
Pointed {
data: Token::Identifier {
inner: Identifier::new("y".to_string())
inner: Identifier::new("y".to_string().into_boxed_str())
},
position: SourcePosition::try_new((2, 5)).unwrap()
}
Expand Down
4 changes: 2 additions & 2 deletions package/origlang-lexer/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,10 @@ pub enum Token {
Comment {
content: Comment,
},
StringLiteral(String),
StringLiteral(Box<str>),
/// reserved for future use.
Reserved {
matched: String,
matched: Box<str>,
},
/// `_`
SymUnderscore,
Expand Down
8 changes: 4 additions & 4 deletions package/origlang-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub enum TypeBox {
Boolean(bool),
#[display(fmt = "{_0}")]
#[from]
String(String),
String(Box<str>),
#[display(fmt = "()")]
#[from]
Unit,
Expand Down Expand Up @@ -406,11 +406,11 @@ fn evaluate_bin_op(
f!(lhs, operator, rhs as Coerced)
}
(TypeBox::String(lhs), TypeBox::String(rhs)) => {
let mut ret = lhs;
let mut ret = lhs.to_string();
// give hint to compiler
ret.reserve_exact(rhs.len());
ret += rhs.as_str();
Ok(ret.into())
ret += rhs.as_ref();
Ok(ret.into_boxed_str().into())
}
_ => indicate_type_checker_bug!(
context = "type checker must deny operator application between different type"
Expand Down
18 changes: 9 additions & 9 deletions package/origlang-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod display {
#[test]
fn empty() {
let x = DisplayRecordValue {
name: Identifier::new("abcdef".to_string()),
name: Identifier::new("abcdef".to_string().into_boxed_str()),
values: vec![],
};

Expand All @@ -17,9 +17,9 @@ mod display {
#[test]
fn one() {
let x = DisplayRecordValue {
name: Identifier::new("abcdef".to_string()),
name: Identifier::new("abcdef".to_string().into_boxed_str()),
values: vec![
TypeBox::String("defg".to_string())
TypeBox::String("defg".to_string().into_boxed_str())
],
};

Expand All @@ -30,11 +30,11 @@ mod display {
#[test]
fn many() {
let x = DisplayRecordValue {
name: Identifier::new("abcdef".to_string()),
name: Identifier::new("abcdef".to_string().into_boxed_str()),
values: vec![
TypeBox::String("abcdef".to_string()),
TypeBox::String("ghijkl".to_string()),
TypeBox::String("alice".to_string())
TypeBox::String("abcdef".to_string().into_boxed_str()),
TypeBox::String("ghijkl".to_string().into_boxed_str()),
TypeBox::String("alice".to_string().into_boxed_str())
],
};

Expand All @@ -59,7 +59,7 @@ mod display {
#[test]
fn one() {
let x = DisplayTupleValue {
boxes: Box::new([TypeBox::String("abcd".to_string())]),
boxes: Box::new([TypeBox::String("abcd".to_string().into_boxed_str())]),
};

let x = format!("{x}");
Expand All @@ -69,7 +69,7 @@ mod display {
#[test]
fn many() {
let x = DisplayTupleValue {
boxes: Box::new([TypeBox::String("abcd".to_string()), TypeBox::String("defg".to_string())]),
boxes: Box::new([TypeBox::String("abcd".to_string().into_boxed_str()), TypeBox::String("defg".to_string().into_boxed_str())]),
};

let x = format!("{x}");
Expand Down
3 changes: 2 additions & 1 deletion package/origlang-slice-in-box/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::alloc::{alloc, Layout};
use std::mem::MaybeUninit;

pub type BoxedSlice<I> = Box<[I]>;
Expand Down Expand Up @@ -26,4 +27,4 @@ unsafe fn assume_every_elements_are_initialized<I>(half_baked_slice_in_box: Boxe
let slice = ptr as *mut [I];

unsafe { Box::from_raw(slice) }
}
}
22 changes: 11 additions & 11 deletions package/origlang-testsuite/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,15 +454,15 @@ impl Test {
fn test_string_literal() {
assert_eq!(
Self::evaluated_expressions("print \"123\"\n").expect("properly parsed and typed"),
type_boxes!("123".to_string() => String)
type_boxes!("123".to_string().into_boxed_str() => String)
);
}

fn test_string_concat() {
assert_eq!(
Self::evaluated_expressions("print \"123\" + \"456\"\n")
.expect("properly parsed and typed"),
type_boxes!("123456".to_string() => String)
type_boxes!("123456".to_string().into_boxed_str() => String)
);
}

Expand Down Expand Up @@ -633,7 +633,7 @@ print a
.expect("properly parsed")
.statement,
[Statement::VariableDeclaration {
pattern: AtomicPattern::Bind(Identifier::new("a".to_string())),
pattern: AtomicPattern::Bind(Identifier::new("a".into())),
expression: Expression::Tuple {
expressions: vec![
Expression::IntLiteral {
Expand All @@ -647,8 +647,8 @@ print a
],
},
type_annotation: Some(TypeSignature::Tuple(vec![
TypeSignature::Simple(Identifier::new("Int32".to_string())),
TypeSignature::Simple(Identifier::new("Int32".to_string())),
TypeSignature::Simple(Identifier::new("Int32".into())),
TypeSignature::Simple(Identifier::new("Int32".into())),
])),
}]
);
Expand All @@ -667,7 +667,7 @@ print 1
statement: vec![
Statement::Comment {
content: Comment {
content: "Hello, World!".to_string()
content: "Hello, World!".into()
},
},
Statement::Print {
Expand Down Expand Up @@ -696,7 +696,7 @@ print 1
},
Statement::Comment {
content: Comment {
content: "Hello, World!".to_string()
content: "Hello, World!".into()
},
},
]
Expand Down Expand Up @@ -745,8 +745,8 @@ print 1
.expect("properly parsed")
.statement,
[Statement::TypeAliasDeclaration {
new_name: Identifier::new("Ik".to_string()),
replace_with: TypeSignature::Simple(Identifier::new("Int32".to_string()))
new_name: Identifier::new("Ik".into()),
replace_with: TypeSignature::Simple(Identifier::new("Int32".into()))
}]
);
assert_eq!(
Expand All @@ -764,7 +764,7 @@ print 1
assert_eq!(
Self::ast("var a = 1 << 2\n").expect("fail").statement,
[Statement::VariableDeclaration {
pattern: AtomicPattern::Bind(Identifier::new("a".to_owned())),
pattern: AtomicPattern::Bind(Identifier::new("a".into())),
expression: Expression::BinaryOperator {
lhs: Box::new(Expression::IntLiteral {
value: 1,
Expand All @@ -788,7 +788,7 @@ print 1
assert_eq!(
Self::ast("var a = 4 >> 2\n").expect("fail").statement,
[Statement::VariableDeclaration {
pattern: AtomicPattern::Bind(Identifier::new("a".to_owned())),
pattern: AtomicPattern::Bind(Identifier::new("a".into())),
expression: Expression::BinaryOperator {
lhs: Box::new(Expression::IntLiteral {
value: 4,
Expand Down
6 changes: 3 additions & 3 deletions package/origlang-typecheck/src/type_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ impl TryIntoTypeCheckedForm for Expression {
}
} else {
Err(TypeCheckError::GenericTypeMismatch {
context: "The condition of if-expression".to_string(),
context: "The condition of if-expression".to_string().into_boxed_str(),
expected_type: Type::Boolean,
actual_type: cond_type,
})
Expand Down Expand Up @@ -490,7 +490,7 @@ impl TryIntoTypeCheckedForm for Statement {
}])
} else {
Err(TypeCheckError::GenericTypeMismatch {
context: "variable assignment".to_string(),
context: "variable assignment".to_string().into_boxed_str(),
expected_type,
actual_type: checked.actual_type(),
})
Expand Down Expand Up @@ -597,7 +597,7 @@ impl TypeChecker {
m[7].clamp(b'a', b'z'),
];

Identifier::new(core::str::from_utf8(&m).expect("not panic").to_owned())
Identifier::new(core::str::from_utf8(&m).expect("not panic").into())
}
}

Expand Down
2 changes: 1 addition & 1 deletion package/origlang-typecheck/src/type_check/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub enum TypeCheckError {
},
#[error("{context} must be {expected_type}, got {actual_type}")]
GenericTypeMismatch {
context: String,
context: Box<str>,
expected_type: Type,
actual_type: Type,
},
Expand Down
2 changes: 1 addition & 1 deletion package/origlang-typesystem-model/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ pub enum TypedExpression {
IntLiteral(TypedIntLiteral),
BooleanLiteral(bool),
FloatLiteral(TypedFloatLiteral),
StringLiteral(String),
StringLiteral(Box<str>),
UnitLiteral,
Variable {
ident: Identifier,
Expand Down