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

[ast][ir] Introduce unary operator #1190

Merged
merged 2 commits into from
Mar 31, 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
28 changes: 27 additions & 1 deletion crates/samlang-ast/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ pub struct ClosureTypeDefinition {
pub function_type: FunctionType,
}

fn name_with_tparams(heap: &samlang_heap::Heap, name: TypeName, tparams: &Vec<PStr>) -> String {
fn name_with_tparams(heap: &samlang_heap::Heap, name: TypeName, tparams: &[PStr]) -> String {
if tparams.is_empty() {
name.pretty_print(heap)
} else {
Expand Down Expand Up @@ -179,6 +179,11 @@ impl TypeDefinition {
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UnaryOperator {
Not,
IsPointer,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BinaryOperator {
Expand Down Expand Up @@ -345,6 +350,11 @@ impl Callee {

#[derive(Debug, Clone)]
pub enum Statement {
Unary {
name: PStr,
operator: UnaryOperator,
operand: Expression,
},
Binary {
name: PStr,
operator: BinaryOperator,
Expand Down Expand Up @@ -412,6 +422,22 @@ impl Statement {
collector: &mut Vec<String>,
) {
match self {
Statement::Unary { name, operator: UnaryOperator::Not, operand } => {
collector.push(format!(
"{}let {} = !{};\n",
" ".repeat(level),
name.as_str(heap),
operand.debug_print(heap),
));
}
Statement::Unary { name, operator: UnaryOperator::IsPointer, operand } => {
collector.push(format!(
"{}let {} = is_pointer({});\n",
" ".repeat(level),
name.as_str(heap),
operand.debug_print(heap),
));
}
Statement::Binary { name, operator, e1, e2 } => {
collector.push(format!(
"{}let {} = {} {} {};\n",
Expand Down
16 changes: 16 additions & 0 deletions crates/samlang-ast/src/hir_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ mod tests {
let heap = &mut Heap::new();

assert!(ZERO.as_int_literal().is_some());
Type::new_id(PStr::UPPER_A, vec![INT_TYPE, Type::new_id_no_targs(PStr::UPPER_B)]).as_id();
Type::new_id(PStr::UPPER_A, vec![INT_TYPE, Type::new_id_no_targs(PStr::UPPER_B)]).is_int();
assert!(INT_TYPE.is_int());
assert!(INT_TYPE.as_id().is_none());
format!(
"{:?}",
Expression::var_name(
Expand Down Expand Up @@ -310,6 +314,16 @@ mod tests {
},
],
s2: vec![
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::Not,
operand: ZERO,
},
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::IsPointer,
operand: ZERO,
},
Statement::Binary {
name: heap.alloc_str_for_test("dd"),
operator: BinaryOperator::PLUS,
Expand Down Expand Up @@ -425,6 +439,8 @@ if 0 {
}
bar = (b1: int);
} else {
let dd = !0;
let dd = is_pointer(0);
let dd = 0 + 0;
let dd = 0 - 0;
let dd = 0 - -2147483648;
Expand Down
25 changes: 24 additions & 1 deletion crates/samlang-ast/src/lir.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::hir;

use super::{
hir::{BinaryOperator, GlobalVariable},
hir::{BinaryOperator, GlobalVariable, UnaryOperator},
mir::{FunctionName, SymbolTable, TypeNameId},
};
use enum_as_inner::EnumAsInner;
Expand Down Expand Up @@ -131,6 +133,11 @@ pub struct GenenalLoopVariable {
}

pub enum Statement {
Unary {
name: PStr,
operator: UnaryOperator,
operand: Expression,
},
Binary {
name: PStr,
operator: BinaryOperator,
Expand Down Expand Up @@ -232,6 +239,22 @@ impl Statement {
collector: &mut String,
) {
match self {
Statement::Unary { name, operator: hir::UnaryOperator::Not, operand } => {
Self::append_spaces(collector, level);
collector.push_str("let ");
collector.push_str(name.as_str(heap));
collector.push_str(" = !");
operand.pretty_print(collector, heap, table);
collector.push_str(";\n");
}
Statement::Unary { name, operator: hir::UnaryOperator::IsPointer, operand } => {
Self::append_spaces(collector, level);
collector.push_str("let ");
collector.push_str(name.as_str(heap));
collector.push_str(" = typeof ");
operand.pretty_print(collector, heap, table);
collector.push_str(" === 'object';\n");
}
Statement::Binary { name, operator, e1, e2 } => {
Self::append_spaces(collector, level);
collector.push_str("let ");
Expand Down
14 changes: 13 additions & 1 deletion crates/samlang-ast/src/lir_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
mod tests {
use super::super::lir::*;
use crate::{
hir::{BinaryOperator, GlobalVariable},
hir::{BinaryOperator, GlobalVariable, UnaryOperator},
mir::{FunctionName, SymbolTable},
};
use pretty_assertions::assert_eq;
Expand Down Expand Up @@ -159,6 +159,16 @@ mod tests {
},
],
s2: vec![
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::Not,
operand: ZERO,
},
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::IsPointer,
operand: ZERO,
},
Statement::binary(heap.alloc_str_for_test("dd"), BinaryOperator::PLUS, ZERO, ZERO),
Statement::binary(heap.alloc_str_for_test("dd"), BinaryOperator::MINUS, ZERO, ZERO),
Statement::binary(
Expand Down Expand Up @@ -287,6 +297,8 @@ function __$f(v1: (t0: number) => number): number {{
}}
bar = b1;
}} else {{
let dd = !0;
let dd = typeof 0 === 'object';
let dd = 0 + 0;
let dd = 0 + 0;
let dd = 0 - -2147483648;
Expand Down
23 changes: 23 additions & 0 deletions crates/samlang-ast/src/mir.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::hir;

use super::hir::{BinaryOperator, GlobalVariable};
use enum_as_inner::EnumAsInner;
use itertools::Itertools;
Expand Down Expand Up @@ -470,6 +472,11 @@ impl GenenalLoopVariable {

#[derive(Debug, Clone, EnumAsInner)]
pub enum Statement {
Unary {
name: PStr,
operator: hir::UnaryOperator,
operand: Expression,
},
Binary(Binary),
IndexedAccess {
name: PStr,
Expand Down Expand Up @@ -621,6 +628,22 @@ impl Statement {
collector: &mut Vec<String>,
) {
match self {
Statement::Unary { name, operator: hir::UnaryOperator::Not, operand } => {
collector.push(format!(
"{}let {} = !{};\n",
" ".repeat(level),
name.as_str(heap),
operand.debug_print(heap, table),
));
}
Statement::Unary { name, operator: hir::UnaryOperator::IsPointer, operand } => {
collector.push(format!(
"{}let {} = is_pointer({});\n",
" ".repeat(level),
name.as_str(heap),
operand.debug_print(heap, table),
));
}
Statement::Binary(s) => {
let e1 = s.e1.debug_print(heap, table);
let e2 = s.e2.debug_print(heap, table);
Expand Down
18 changes: 17 additions & 1 deletion crates/samlang-ast/src/mir_tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[cfg(test)]
mod tests {
use super::super::hir::{BinaryOperator, GlobalVariable};
use super::super::hir::{BinaryOperator, GlobalVariable, UnaryOperator};
use super::super::mir::*;
use pretty_assertions::assert_eq;
use samlang_heap::{Heap, ModuleReference, PStr};
Expand All @@ -14,6 +14,10 @@ mod tests {
assert!(INT_TYPE <= INT_TYPE);
format!("{:?}", INT_TYPE.cmp(&INT_TYPE));
assert!(ZERO.as_int_literal().is_some());
Type::Id(table.create_type_name_for_test(PStr::UPPER_A)).as_id();
Type::Id(table.create_type_name_for_test(PStr::UPPER_A)).is_int();
assert!(INT_TYPE.is_int());
assert!(INT_TYPE.as_id().is_none());
format!(
"{:?}",
Expression::var_name(PStr::LOWER_A, Type::Id(table.create_type_name_for_test(PStr::UPPER_A)))
Expand Down Expand Up @@ -203,6 +207,16 @@ mod tests {
},
],
s2: vec![
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::Not,
operand: ZERO,
},
Statement::Unary {
name: heap.alloc_str_for_test("dd"),
operator: UnaryOperator::IsPointer,
operand: ZERO,
},
Statement::binary(heap.alloc_str_for_test("dd"), BinaryOperator::PLUS, ZERO, ZERO),
Statement::binary(heap.alloc_str_for_test("dd"), BinaryOperator::MINUS, ZERO, ZERO),
Statement::binary(
Expand Down Expand Up @@ -293,6 +307,8 @@ if 0 {
}
bar = (b1: int);
} else {
let dd = !0;
let dd = is_pointer(0);
let dd = 0 + 0;
let dd = 0 + 0;
let dd = 0 - -2147483648;
Expand Down
6 changes: 4 additions & 2 deletions crates/samlang-checker/src/type_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ impl TypeParameterSignature {
self.to_description().pretty_print(heap)
}

pub fn pretty_print_list(list: &Vec<TypeParameterSignature>, heap: &Heap) -> String {
pub fn pretty_print_list(list: &[TypeParameterSignature], heap: &Heap) -> String {
if list.is_empty() {
"".to_string()
} else {
Expand Down Expand Up @@ -685,7 +685,9 @@ mod type_tests {
builder.int_type().as_generic();
builder.int_type().as_fn();
builder.simple_nominal_type(Heap::new().alloc_str_for_test("")).as_nominal();
builder.simple_nominal_type(Heap::new().alloc_str_for_test("")).as_generic();
builder.fun_type(vec![], builder.int_type()).as_fn();
builder.fun_type(vec![], builder.int_type()).as_generic();
}

#[test]
Expand Down Expand Up @@ -791,7 +793,7 @@ mod type_tests {
.pretty_print(&heap)
);

assert_eq!("", TypeParameterSignature::pretty_print_list(&vec![], &heap));
assert_eq!("", TypeParameterSignature::pretty_print_list(&[], &heap));
assert_eq!(
"<A : B, C>",
TypeParameterSignature::pretty_print_list(
Expand Down
9 changes: 4 additions & 5 deletions crates/samlang-compiler/src/hir_lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,10 @@ impl<'a> ExpressionLoweringManager<'a> {
self.lower(&expression.argument);
let value_name = self.allocate_temp_variable();
statements.push(match expression.operator {
source::expr::UnaryOperator::NOT => hir::Statement::Binary {
source::expr::UnaryOperator::NOT => hir::Statement::Unary {
name: value_name,
operator: hir::BinaryOperator::XOR,
e1: result_expr,
e2: hir::ONE,
operator: hir::UnaryOperator::Not,
operand: result_expr,
},
source::expr::UnaryOperator::NEG => hir::Statement::Binary {
name: value_name,
Expand Down Expand Up @@ -1771,7 +1770,7 @@ return 0;"#,
argument: Box::new(dummy_source_this(heap)),
}),
heap,
"let _t1 = (_this: DUMMY_Dummy) ^ 1;\nreturn (_t1: int);",
"let _t1 = !(_this: DUMMY_Dummy);\nreturn (_t1: int);",
);
let heap = &mut Heap::new();
assert_expr_correctly_lowered(
Expand Down
11 changes: 10 additions & 1 deletion crates/samlang-compiler/src/lir_lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ impl<'a> LoweringManager<'a> {

fn lower_stmt(&mut self, stmt: mir::Statement) -> Vec<lir::Statement> {
match stmt {
mir::Statement::Unary { name, operator, operand } => {
vec![lir::Statement::Unary { name, operator, operand: lower_expression(operand) }]
}
mir::Statement::Binary(mir::Binary { name, operator, e1, e2 }) => {
vec![lir::Statement::Binary {
name,
Expand Down Expand Up @@ -738,7 +741,7 @@ pub fn compile_mir_to_lir(heap: &mut Heap, sources: mir::Sources) -> lir::Source
mod tests {
use pretty_assertions::assert_eq;
use samlang_ast::{
hir::BinaryOperator,
hir::{BinaryOperator, UnaryOperator},
lir,
mir::{
Callee, ClosureTypeDefinition, EnumTypeDefinition, Expression, Function, FunctionName,
Expand Down Expand Up @@ -896,6 +899,11 @@ mod tests {
parameters: vec![],
type_: Type::new_fn_unwrapped(vec![], INT_TYPE),
body: vec![
Statement::Unary {
name: heap.alloc_str_for_test("v1"),
operator: UnaryOperator::Not,
operand: ZERO,
},
Statement::binary(heap.alloc_str_for_test("v1"), BinaryOperator::PLUS, ZERO, ZERO),
Statement::StructInit {
struct_variable_name: heap.alloc_str_for_test("O"),
Expand Down Expand Up @@ -1066,6 +1074,7 @@ function __$cc(): number {{
return 0;
}}
function __$main(): number {{
let v1 = !0;
let v1 = 0 + 0;
let _t3 = obj as unknown as any;
__$inc_ref(_t3);
Expand Down
8 changes: 8 additions & 0 deletions crates/samlang-compiler/src/lir_unused_name_elimination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ fn collect_used_names_from_statement(
statement: &Statement,
) {
match statement {
Statement::Unary { name: _, operator: _, operand } => {
collect_used_names_from_expression(str_name_set, fn_name_set, type_set, operand);
}
Statement::Binary { name: _, operator: _, e1, e2 } => {
collect_used_names_from_expression(str_name_set, fn_name_set, type_set, e1);
collect_used_names_from_expression(str_name_set, fn_name_set, type_set, e2);
Expand Down Expand Up @@ -308,6 +311,11 @@ mod tests {
return_type: INT_TYPE,
return_collector: None,
},
Statement::Unary {
name: PStr::LOWER_A,
operator: hir::UnaryOperator::Not,
operand: ZERO,
},
Statement::IfElse {
condition: ZERO,
s1: vec![Statement::binary(
Expand Down
Loading
Loading