Merge pull request #67 from mist-go/syntax-philosphy-rewrite

Syntax philosphy rewrite
This commit is contained in:
2026-06-05 20:25:37 +02:00
committed by GitHub
22 changed files with 317 additions and 349 deletions
+41 -41
View File
@@ -156,18 +156,6 @@ impl GetRust for Path {
} }
} }
impl GetRust for TypePostfix {
fn get_rust(&self) -> String {
match self {
TypePostfix::Ref => format!("&"),
TypePostfix::RefMut => format!("&mut "),
TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
TypePostfix::Dyn => format!("dyn "),
}
}
}
impl GetRust for Visibility { impl GetRust for Visibility {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
match self { match self {
@@ -186,12 +174,47 @@ impl GetRust for Identifier {
impl GetRust for TypeExpr { impl GetRust for TypeExpr {
fn get_rust(&self) -> String { fn get_rust(&self) -> String {
self.1 match self {
.iter() // TypePostfix::Ref => format!("&"),
.map(TypePostfix::get_rust) // TypePostfix::RefMut => format!("&mut "),
.rev() // TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
.collect::<String>() // TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
+ &self.0.get_rust() // TypePostfix::Dyn => format!("dyn "),
Self::Path(path, generics) => {
if let Some(generics) = generics {
format!("{}{}", get_static_type_path(path), generics.get_rust())
} else {
get_static_type_path(path)
}
}
Self::Lifetime(name) => format!("'{}", name.get_rust()),
Self::Tuple(types) => format!(
"({})",
types
.into_iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", ")
),
Self::Ref {
lifetime,
mutable,
ty,
} => {
let mutable = if *mutable { "mut " } else { "" };
if let Some(lifetime) = lifetime {
format!("&'{} {mutable}{}", lifetime.get_rust(), ty.get_rust())
} else {
format!("&{mutable}{}", ty.get_rust())
}
}
Self::Dyn(ty) => {
format!("dyn {}", ty.get_rust())
}
}
} }
} }
@@ -205,29 +228,6 @@ pub fn get_static_type_path(path: &Path) -> String {
} }
} }
impl GetRust for TypeExprKind {
fn get_rust(&self) -> String {
match self {
TypeExprKind::Path(path, generics) => {
if let Some(generics) = generics {
format!("{}{}", get_static_type_path(path), generics.get_rust())
} else {
get_static_type_path(path)
}
}
TypeExprKind::Lifetime(name) => format!("'{}", name.get_rust()),
TypeExprKind::Tuple(types) => format!(
"({})",
types
.into_iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GenRust for Pattern { impl GenRust for Pattern {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) { fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self { match self {
+14 -10
View File
@@ -88,8 +88,11 @@ impl GenRust for FunctionDecl {
param.gen_rust(ctx, cg); param.gen_rust(ctx, cg);
} }
cg.add(") -> "); cg.add(") ");
cg.add(&self.return_type.get_rust()); if let Some(return_type) = &self.return_type {
cg.add("-> ");
cg.add(&return_type.get_rust());
}
if let Some(body) = &self.body { if let Some(body) = &self.body {
cg.add(" "); cg.add(" ");
@@ -234,10 +237,14 @@ impl GenRust for (&Vec<Spanned<FieldDeclStmt>>, &Spanned<ClassConstructor>) {
let mut constructor_params = vec![VarDecl { let mut constructor_params = vec![VarDecl {
name: Pattern::Path(false, Path(vec![Identifier(String::from("self"))])), name: Pattern::Path(false, Path(vec![Identifier(String::from("self"))])),
type_: Some(TypeExpr( type_: Some(TypeExpr::Ref {
TypeExprKind::Path(Path(vec![Identifier(String::from("Self"))]), None), lifetime: None,
vec![TypePostfix::RefMut], mutable: true,
ty: Box::new(TypeExpr::Path(
Path(vec![Identifier(String::from("Self"))]),
None,
)), )),
}),
}]; }];
constructor_params.append(&mut self.1.item.params.0.clone()); constructor_params.append(&mut self.1.item.params.0.clone());
@@ -250,7 +257,7 @@ impl GenRust for (&Vec<Spanned<FieldDeclStmt>>, &Spanned<ClassConstructor>) {
name: Identifier(String::from("constructor")), name: Identifier(String::from("constructor")),
generics: self.1.item.generics.clone(), generics: self.1.item.generics.clone(),
params: ParamList(constructor_params), params: ParamList(constructor_params),
return_type: TypeExpr::no_px(TypeExprKind::Tuple(Vec::new())), return_type: Some(TypeExpr::Tuple(Vec::new())),
body: Some(self.1.item.body.clone()), body: Some(self.1.item.body.clone()),
}, },
} }
@@ -423,10 +430,7 @@ impl GenRust for TopLevelKind {
let mut impl_ = impl_.clone(); let mut impl_ = impl_.clone();
impl_.item.trait_ = Some(impl_.item.target); impl_.item.trait_ = Some(impl_.item.target);
impl_.item.target = TypeExpr( impl_.item.target = TypeExpr::Path(Path(vec![name.clone()]), None);
TypeExprKind::Path(Path(vec![name.clone()]), None),
Vec::new(),
);
impl_.gen_rust(ctx, cg); impl_.gen_rust(ctx, cg);
} }
+8 -23
View File
@@ -18,19 +18,13 @@ pub struct Identifier(pub String);
pub struct ParamList(pub Vec<VarDecl>); pub struct ParamList(pub Vec<VarDecl>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>); pub enum TypeExpr {
Ref {
#[derive(Debug, Clone, Serialize)] lifetime: Option<Identifier>,
pub enum TypePostfix { mutable: bool,
Ref, ty: Box<TypeExpr>,
RefMut, },
RefLifetime(Identifier), Dyn(Box<TypeExpr>),
RefMutLifetime(Identifier),
Dyn,
}
#[derive(Debug, Clone, Serialize)]
pub enum TypeExprKind {
Path(Path, Option<Generics>), Path(Path, Option<Generics>),
Tuple(Vec<TypeExpr>), Tuple(Vec<TypeExpr>),
Lifetime(Identifier), Lifetime(Identifier),
@@ -43,20 +37,11 @@ pub struct Spanned<T> {
pub item: T, pub item: T,
} }
impl TypeExpr {
pub fn no_px(kind: TypeExprKind) -> Self {
Self(kind, Vec::new())
}
}
impl From<GenericDecl> for Generic { impl From<GenericDecl> for Generic {
fn from(value: GenericDecl) -> Self { fn from(value: GenericDecl) -> Self {
match value { match value {
GenericDecl::Lifetime(life) => Generic::Lifetime(life), GenericDecl::Lifetime(life) => Generic::Lifetime(life),
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr( GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
TypeExprKind::Path(Path(vec![ty]), None),
Vec::new(),
)),
} }
} }
} }
+1 -1
View File
@@ -97,7 +97,7 @@ pub struct FunctionDecl {
pub name: Identifier, pub name: Identifier,
pub generics: GenericsDecl, pub generics: GenericsDecl,
pub params: ParamList, pub params: ParamList,
pub return_type: TypeExpr, pub return_type: Option<TypeExpr>,
pub body: Option<Block>, pub body: Option<Block>,
} }
+17 -11
View File
@@ -31,6 +31,7 @@ keyword = {
| "dyn" | "dyn"
| "loop" | "loop"
| "fn" | "fn"
| "unsafe"
} }
identifier = @{ identifier = @{
@@ -76,7 +77,6 @@ program = {
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? } visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
mutable = { "mut" } mutable = { "mut" }
let_kw = { "let" }
// ====================================================== // ======================================================
// GENERICS // GENERICS
@@ -100,15 +100,15 @@ path_type = {
} }
ref_type = { ref_type = {
mutable? ~ lifetime? ~ "*" "*" ~ lifetime? ~ mutable? ~ type_expr
} }
dyn_type = { dyn_type = {
"dyn" "dyn" ~ type_expr
} }
type_expr = { type_expr = {
(path_type | tuple_type) ~ (ref_type | dyn_type)* (path_type | tuple_type | ref_type | dyn_type)
} }
lifetime = { lifetime = {
@@ -192,11 +192,15 @@ attributes = {
// DECLARATION HELPERS // DECLARATION HELPERS
// ====================================================== // ======================================================
var_decl = { var_decl = {
(let_kw | type_expr) ~ pattern "let" ~ pattern ~ type_expr?
} }
field = { field = {
visibility? ~ type_expr ~ identifier visibility? ~ identifier ~ type_expr
}
param = {
pattern ~ type_expr?
} }
field_list = { field_list = {
@@ -204,7 +208,7 @@ field_list = {
} }
param_list = { param_list = {
(var_decl ~ ("," ~ var_decl)* ~ ","?)? (param ~ ("," ~ param)* ~ ","?)?
} }
// ====================================================== // ======================================================
@@ -274,7 +278,7 @@ class_field = {
} }
self_param = { self_param = {
"self" ~ mutable? ~ deref_px? (deref_px ~ lifetime?)? ~ mutable? ~ "self"
} }
method_args = _{ method_args = _{
@@ -319,7 +323,7 @@ trait_decl = {
// ====================================================== // ======================================================
function_decl = { function_decl = {
visibility? ~ type_expr ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ (block | semicolon) visibility? ~ "fn" ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ type_expr? ~ (block | semicolon)
} }
// ====================================================== // ======================================================
@@ -449,7 +453,10 @@ match_stmt = {
// CLOSURES // CLOSURES
// ------------------------------------------------------ // ------------------------------------------------------
closure = { type_expr? ~ "fn" ~ "(" ~ param_list ~ ")" ~ expr } closure = {
"fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ block
| "fn" ~ "(" ~ param_list ~ ")" ~ type_expr? ~ "->" ~ expr
}
// ------------------------------------------------------ // ------------------------------------------------------
// TUPLES & ARRAYS // TUPLES & ARRAYS
@@ -628,4 +635,3 @@ bin_op = {
expr = { term ~ (bin_op ~ term)* } expr = { term ~ (bin_op ~ term)* }
term = { prefix* ~ primary ~ postfix* } term = { prefix* ~ primary ~ postfix* }
+13 -18
View File
@@ -2,7 +2,7 @@ use crate::{
Rule, Rule,
ast::*, ast::*,
ast_expr, ast_expr,
error::{AstError, IntoErr}, error::{AstError, IntoErr, collect_recovered},
}; };
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt { impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
@@ -48,25 +48,12 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() { match pair.as_rule() {
Rule::var_decl => { Rule::var_decl | Rule::param => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let type_ = inner
.next()
.and_then(|pair| {
if pair.as_rule() == Rule::let_kw {
None
} else {
Some(TypeExpr::try_from(pair))
}
})
.transpose();
let name = Pattern::try_from(inner.next().unwrap());
ast_expr!(VarDecl { ast_expr!(VarDecl {
type_: type_, name: Pattern::try_from(inner.next().unwrap()),
name: name, type_: inner.next().map(TypeExpr::try_from).transpose(),
}) })
} }
@@ -85,8 +72,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
ast_expr!(FieldDecl { ast_expr!(FieldDecl {
visibility: Visibility::try_from(&mut inner), visibility: Visibility::try_from(&mut inner),
type_: TypeExpr::try_from(inner.next().unwrap()),
name: Identifier::try_from(inner.next().unwrap()), name: Identifier::try_from(inner.next().unwrap()),
type_: TypeExpr::try_from(inner.next().unwrap()),
}) })
} }
@@ -94,3 +81,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
} }
} }
} }
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
}
}
+2 -2
View File
@@ -77,10 +77,10 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
Rule::closure => { Rule::closure => {
ast_expr!(Expression::Closure { ast_expr!(Expression::Closure {
params: collect_recovered(inner.next().unwrap().into_inner()),
return_type: consume_rule(&mut inner, Rule::type_expr) return_type: consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from) .map(TypeExpr::try_from)
.transpose(), .transpose(),
params: collect_recovered(inner.next().unwrap().into_inner()),
body: Expression::try_from(inner.next().unwrap()).map(Box::new), body: Expression::try_from(inner.next().unwrap()).map(Box::new),
}) })
} }
@@ -109,7 +109,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
)), )),
} }
} }
Rule::statement | Rule::basic_stmt | Rule::control_flow => ast_expr!( Rule::statement | Rule::basic_stmt | Rule::control_flow | Rule::block => ast_expr!(
Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new)) Expression::Statement(pair.try_into().get_map(Box::new).map(Box::new))
), ),
+27 -65
View File
@@ -2,67 +2,10 @@ use crate::{
Rule, Rule,
ast::*, ast::*,
ast_ensure, ast_expr, ast_ensure, ast_expr,
error::{AstError, IntoErr, collect_recovered}, error::{AstError, AstResult, IntoErr, collect_recovered},
parser::{consume_rule, listen_rule}, parser::{consume_rule, listen_rule},
}; };
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::ref_type => {
let mutable = listen_rule(&mut inner, Rule::mutable);
let lifetime = consume_rule(&mut inner, Rule::lifetime)
.map(|pair| Identifier::try_from(pair.into_inner().next().unwrap()))
.transpose()
.get()?;
Ok(if mutable {
if let Some(lifetime) = lifetime {
TypePostfix::RefMutLifetime(lifetime)
} else {
TypePostfix::RefMut
}
} else {
if let Some(lifetime) = lifetime {
TypePostfix::RefLifetime(lifetime)
} else {
TypePostfix::Ref
}
})
}
Rule::dyn_type => Ok(TypePostfix::Dyn),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExprKind {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::tuple_type => ast_expr!(TypeExprKind::Tuple(collect_recovered(inner))),
Rule::path_type => {
ast_expr!(TypeExprKind::Path(
Path::try_from(inner.next().unwrap()),
inner.next().map(Generics::try_from).transpose()
))
}
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr { impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
type Error = AstError<'a, Self>; type Error = AstError<'a, Self>;
@@ -72,13 +15,32 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
match rule { match rule {
Rule::generic => Self::try_from(inner.next().unwrap()), Rule::generic => Self::try_from(inner.next().unwrap()),
Rule::type_expr => ast_expr!(TypeExpr( Rule::type_expr => inner.next().unwrap().try_into(),
inner.next().unwrap().try_into(), Rule::lifetime => ast_expr!(TypeExpr::Lifetime(inner.next().unwrap().try_into())),
collect_recovered(inner),
)), Rule::tuple_type => ast_expr!(TypeExpr::Tuple(collect_recovered(inner))),
Rule::lifetime => ast_expr!(TypeExprKind::Lifetime(inner.next().unwrap().try_into())) Rule::path_type => {
.get_map(TypeExpr::no_px) ast_expr!(TypeExpr::Path(
.map(TypeExpr::no_px), Path::try_from(inner.next().unwrap()),
inner.next().map(Generics::try_from).transpose()
))
}
Rule::ref_type => {
ast_expr!(TypeExpr::Ref {
lifetime: consume_rule(&mut inner, Rule::lifetime)
.map(|v| v.into_inner().next().map(Identifier::try_from))
.unwrap_or_default()
.transpose(),
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<bool>,
ty: TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
})
}
Rule::dyn_type => {
ast_expr!(TypeExpr::Dyn(
TypeExpr::try_from(inner.next().unwrap()).map(Box::new),
))
}
_ => AstError::bug_unimplemented(pair), _ => AstError::bug_unimplemented(pair),
} }
+19 -22
View File
@@ -2,7 +2,7 @@ use crate::{
Rule, Rule,
ast::*, ast::*,
ast_ensure, ast_expr, ast_ensure, ast_expr,
error::{AstError, AstResult, IntoErr, collect_recovered}, error::{AstError, AstResult, IntoErr},
parser::{consume_rule, listen_rule}, parser::{consume_rule, listen_rule},
}; };
@@ -13,7 +13,6 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
ast_ensure!(pair, Rule::function_decl => { ast_ensure!(pair, Rule::function_decl => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let visibility = Visibility::try_from(&mut inner); let visibility = Visibility::try_from(&mut inner);
let return_type = TypeExpr::try_from(inner.next().unwrap());
let name = Identifier::try_from(inner.next().unwrap()); let name = Identifier::try_from(inner.next().unwrap());
let generics = consume_rule(&mut inner, Rule::generics_decl) let generics = consume_rule(&mut inner, Rule::generics_decl)
@@ -23,24 +22,26 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| { let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
let mut param_inner = param.into_inner(); let mut param_inner = param.into_inner();
let mutable = listen_rule(&mut param_inner, Rule::mutable);
let is_ref = listen_rule(&mut param_inner, Rule::deref_px); let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
let lifetime = consume_rule(&mut param_inner, Rule::lifetime);
let mutable = listen_rule(&mut param_inner, Rule::mutable);
let name = Pattern::Path(mutable && !is_ref, Path(vec![Identifier(String::from("self"))])); let name = Pattern::Path(mutable && !is_ref, Path(vec![Identifier(String::from("self"))]));
let self_ty = TypeExpr::Path(Path(vec![Identifier(String::from("Self"))]), None);
VarDecl { VarDecl {
name: name.clone(), name: name.clone(),
type_: Some(TypeExpr( type_: Some(if is_ref {
TypeExprKind::Path(Path(vec![Identifier("Self".to_string())]), None), TypeExpr::Ref {
if is_ref { lifetime:
vec![if mutable { lifetime.map(|v| Identifier::try_from(v.into_inner().next().unwrap()))
TypePostfix::RefMut .transpose()
.expect("Failed to get lifetime identifier"),
mutable,
ty: Box::new(self_ty)
}
} else { } else {
TypePostfix::Ref self_ty
}] }),
} else {
Vec::new()
},
)),
} }
}); });
@@ -57,6 +58,10 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
}) })
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect()))); .unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
let return_type = consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose();
let body = inner.next().map(Block::try_from).transpose(); let body = inner.next().map(Block::try_from).transpose();
ast_expr!(Self { ast_expr!(Self {
@@ -70,11 +75,3 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
}) })
} }
} }
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
}
}
+21
View File
@@ -0,0 +1,21 @@
#[derive(Debug)]
pub struct Debuggable {
value i32,
}
pub fn test_derive_attribute() {
let d = Debuggable { value: 42 };
assert_eq!(d.value, 42);
}
#[allow(unused_variables)]
pub fn test_allow_attribute() {
let x = 42;
let y = "unused";
assert_eq!(x, 42);
}
pub fn run_tests() {
test_derive_attribute();
test_allow_attribute();
}
+19 -19
View File
@@ -1,42 +1,42 @@
pub void test_let_basic() { pub fn test_let_basic() {
let x = 42; let x = 42;
assert_eq!(x, 42); assert_eq!(x, 42);
} }
pub void test_let_typed() { pub fn test_let_typed() {
i32 x = 42; let x i32 = 42;
assert_eq!(x, 42); assert_eq!(x, 42);
str* s = "hello"; let s *str = "hello";
assert_eq!(s, "hello"); assert_eq!(s, "hello");
bool b = true; let b bool = true;
assert_eq!(b, true); assert_eq!(b, true);
f64 f = 3.14; let f f64 = 3.14;
assert_eq!(f, 3.14); assert_eq!(f, 3.14);
} }
pub void test_let_mut() { pub fn test_let_mut() {
let mut x = 42; let mut _x = 42;
x = 100; _x = 100;
assert_eq!(x, 100); assert_eq!(_x, 100);
} }
pub void test_let_tuple_destructure() { pub fn test_let_tuple_destructure() {
let [a, b] = (10, "hello"); let [a, b] = (10, "hello");
assert_eq!(a, 10); assert_eq!(a, 10);
assert_eq!(b, "hello"); assert_eq!(b, "hello");
} }
pub void test_let_nested_tuple() { pub fn test_let_nested_tuple() {
let [a, [b, c]] = (1, (2, 3)); let [a, [b, c]] = (1, (2, 3));
assert_eq!(a, 1); assert_eq!(a, 1);
assert_eq!(b, 2); assert_eq!(b, 2);
assert_eq!(c, 3); assert_eq!(c, 3);
} }
pub void test_let_pattern_irrefutable() { pub fn test_let_pattern_irrefutable() {
let x = 5; let x = 5;
let [y, z] = (1, 2); let [y, z] = (1, 2);
assert_eq!(x, 5); assert_eq!(x, 5);
@@ -44,30 +44,30 @@ pub void test_let_pattern_irrefutable() {
assert_eq!(z, 2); assert_eq!(z, 2);
} }
pub void test_multiple_decls() { pub fn test_multiple_decls() {
let a = 1; let a = 1;
let b = 2; let b = 2;
let c = 3; let c = 3;
assert_eq!(a + b + c, 6); assert_eq!(a + b + c, 6);
} }
pub void test_let_with_type_and_init() { pub fn test_let_with_type_and_init() {
f64 x = 10.0; let x f64 = 10.0;
assert_eq!(x, 10.0); assert_eq!(x, 10.0);
} }
pub void test_string_literal() { pub fn test_string_literal() {
let s = "hello, world!"; let s = "hello, world!";
assert_eq!(s.len(), 13); assert_eq!(s.len(), 13);
} }
pub void test_let_bool() { pub fn test_let_bool() {
let t = true; let t = true;
let f = false; let f = false;
assert_eq!(t, !f); assert_eq!(t, !f);
} }
pub void run_tests() { pub fn run_tests() {
test_let_basic(); test_let_basic();
test_let_typed(); test_let_typed();
test_let_mut(); test_let_mut();
+19 -21
View File
@@ -1,6 +1,4 @@
use std::cmp; pub fn test_literals() {
pub void test_literals() {
assert_eq!(42, 42); assert_eq!(42, 42);
assert_eq!(3.14, 3.14); assert_eq!(3.14, 3.14);
assert_eq!(true, true); assert_eq!(true, true);
@@ -8,28 +6,28 @@ pub void test_literals() {
assert_eq!("hello", "hello"); assert_eq!("hello", "hello");
} }
pub void test_tuples() { pub fn test_tuples() {
let t = (1, true, "three"); let t = (1, true, "three");
assert_eq!(t.0, 1); assert_eq!(t.0, 1);
assert_eq!(t.1, true); assert_eq!(t.1, true);
assert_eq!(t.2, "three"); assert_eq!(t.2, "three");
} }
pub void test_arrays() { pub fn test_arrays() {
let arr = [1, 2, 3]; let arr = [1, 2, 3];
assert_eq!(arr[0], 1); assert_eq!(arr[0], 1);
assert_eq!(arr[1], 2); assert_eq!(arr[1], 2);
assert_eq!(arr[2], 3); assert_eq!(arr[2], 3);
} }
pub void test_array_repeat() { pub fn test_array_repeat() {
let arr = [0; 5]; let arr = [0; 5];
assert_eq!(arr[0], 0); assert_eq!(arr[0], 0);
assert_eq!(arr[4], 0); assert_eq!(arr[4], 0);
assert_eq!(arr.len(), 5); assert_eq!(arr.len(), 5);
} }
pub void test_binary_arith() { pub fn test_binary_arith() {
assert_eq!(10 + 5, 15); assert_eq!(10 + 5, 15);
assert_eq!(10 - 5, 5); assert_eq!(10 - 5, 5);
assert_eq!(10 * 5, 50); assert_eq!(10 * 5, 50);
@@ -37,7 +35,7 @@ pub void test_binary_arith() {
assert_eq!(10 % 3, 1); assert_eq!(10 % 3, 1);
} }
pub void test_binary_cmp() { pub fn test_binary_cmp() {
assert_eq!(5 < 10, true); assert_eq!(5 < 10, true);
assert_eq!(10 <= 10, true); assert_eq!(10 <= 10, true);
assert_eq!(10 > 5, true); assert_eq!(10 > 5, true);
@@ -46,14 +44,14 @@ pub void test_binary_cmp() {
assert_eq!(5 != 10, true); assert_eq!(5 != 10, true);
} }
pub void test_binary_logic() { pub fn test_binary_logic() {
assert_eq!(true && true, true); assert_eq!(true && true, true);
assert_eq!(true && false, false); assert_eq!(true && false, false);
assert_eq!(true || false, true); assert_eq!(true || false, true);
assert_eq!(false || false, false); assert_eq!(false || false, false);
} }
pub void test_binary_bit() { pub fn test_binary_bit() {
assert_eq!(5 & 3, 1); assert_eq!(5 & 3, 1);
assert_eq!(5 | 3, 7); assert_eq!(5 | 3, 7);
assert_eq!(5 ^ 3, 6); assert_eq!(5 ^ 3, 6);
@@ -61,20 +59,20 @@ pub void test_binary_bit() {
assert_eq!(4 >> 1, 2); assert_eq!(4 >> 1, 2);
} }
pub void test_prefix() { pub fn test_prefix() {
let x = 42; let x = 42;
assert_eq!(-x, -42); assert_eq!(-x, -42);
assert_eq!(!true, false); assert_eq!(!true, false);
assert_eq!(!false, true); assert_eq!(!false, true);
} }
pub void test_ref_deref() { pub fn test_ref_deref() {
let x = 42; let x = 42;
let r = &x; let r = &x;
assert_eq!(*r, 42); assert_eq!(*r, 42);
} }
pub void test_postfix_inc_dec() { pub fn test_postfix_inc_dec() {
let mut x = 5; let mut x = 5;
x++; x++;
assert_eq!(x, 6); assert_eq!(x, 6);
@@ -82,17 +80,17 @@ pub void test_postfix_inc_dec() {
assert_eq!(x, 5); assert_eq!(x, 5);
} }
pub void test_as_cast() { pub fn test_as_cast() {
let x = 42; let x = 42;
assert_eq!(x as f64, 42.0); assert_eq!(x as f64, 42.0);
} }
pub void test_closure() { pub fn test_closure() {
let add = fn(let a, let b) a + b; let add = fn(a, b) -> a + b;
assert_eq!(add(2, 3), 5); assert_eq!(add(2, 3), 5);
} }
pub void test_block_expr() { pub fn test_block_expr() {
let x = { let x = {
let y = 10; let y = 10;
y + 5 y + 5
@@ -100,7 +98,7 @@ pub void test_block_expr() {
assert_eq!(x, 15); assert_eq!(x, 15);
} }
pub void test_if_expr() { pub fn test_if_expr() {
let x = if (true) { 1 } else { 2 }; let x = if (true) { 1 } else { 2 };
assert_eq!(x, 1); assert_eq!(x, 1);
@@ -108,7 +106,7 @@ pub void test_if_expr() {
assert_eq!(y, 2); assert_eq!(y, 2);
} }
pub void test_range_expr() { pub fn test_range_expr() {
let r = 0..5; let r = 0..5;
let mut count = 0; let mut count = 0;
for (i : r) { for (i : r) {
@@ -117,7 +115,7 @@ pub void test_range_expr() {
assert_eq!(count, 5); assert_eq!(count, 5);
} }
pub void test_binary_assign() { pub fn test_binary_assign() {
let mut x = 10; let mut x = 10;
x += 5; x += 5;
assert_eq!(x, 15); assert_eq!(x, 15);
@@ -131,7 +129,7 @@ pub void test_binary_assign() {
assert_eq!(x, 2); assert_eq!(x, 2);
} }
pub void run_tests() { pub fn run_tests() {
test_literals(); test_literals();
test_tuples(); test_tuples();
test_arrays(); test_arrays();
+20 -20
View File
@@ -1,21 +1,21 @@
pub void test_var_decl() { pub fn test_var_decl() {
let x = 42; let x = 42;
assert_eq!(x, 42); assert_eq!(x, 42);
i32 y = 10; let y i32 = 10;
assert_eq!(y, 10); assert_eq!(y, 10);
str* name = "mist"; let name *str = "mist";
assert_eq!(name, "mist"); assert_eq!(name, "mist");
} }
pub void test_var_decl_with_init() { pub fn test_var_decl_with_init() {
let mut x = 0; let mut x = 0;
x = 5; x = 5;
assert_eq!(x, 5); assert_eq!(x, 5);
} }
pub void test_if_statement() { pub fn test_if_statement() {
let mut x = 0; let mut x = 0;
if (true) { if (true) {
@@ -31,7 +31,7 @@ pub void test_if_statement() {
assert_eq!(x, 3); assert_eq!(x, 3);
} }
pub void test_if_else_if() { pub fn test_if_else_if() {
let mut x = 0; let mut x = 0;
if (x == 1) { if (x == 1) {
@@ -44,7 +44,7 @@ pub void test_if_else_if() {
assert_eq!(x, 20); assert_eq!(x, 20);
} }
pub void test_while_loop() { pub fn test_while_loop() {
let mut count = 0; let mut count = 0;
while (count < 5) { while (count < 5) {
@@ -53,7 +53,7 @@ pub void test_while_loop() {
assert_eq!(count, 5); assert_eq!(count, 5);
} }
pub void test_for_loop() { pub fn test_for_loop() {
let mut sum = 0; let mut sum = 0;
for (i : 0..4) { for (i : 0..4) {
@@ -62,7 +62,7 @@ pub void test_for_loop() {
assert_eq!(sum, 6); assert_eq!(sum, 6);
} }
pub void test_loop_stmt() { pub fn test_loop_stmt() {
let mut count = 0; let mut count = 0;
loop { loop {
@@ -74,7 +74,7 @@ pub void test_loop_stmt() {
assert_eq!(count, 3); assert_eq!(count, 3);
} }
pub void test_break_continue() { pub fn test_break_continue() {
let mut sum = 0; let mut sum = 0;
for (i : 0..10) { for (i : 0..10) {
@@ -89,11 +89,11 @@ pub void test_break_continue() {
assert_eq!(sum, 1 + 3 + 5); assert_eq!(sum, 1 + 3 + 5);
} }
pub i32 test_return_from_fn() { pub fn test_return_from_fn() i32 {
return 42; return 42;
} }
pub void test_block_scope() { pub fn test_block_scope() {
let x = { let x = {
let inner = 10; let inner = 10;
inner + 5 inner + 5
@@ -101,9 +101,9 @@ pub void test_block_scope() {
assert_eq!(x, 15); assert_eq!(x, 15);
} }
pub void test_match_literal() { pub fn test_match_literal() {
let x = 2; let x = 2;
let mut result = 0; let result;
match (x) { match (x) {
1 => { result = 10; } 1 => { result = 10; }
@@ -114,9 +114,9 @@ pub void test_match_literal() {
assert_eq!(result, 20); assert_eq!(result, 20);
} }
pub void test_match_or_pattern() { pub fn test_match_or_pattern() {
let x = 1; let x = 1;
let mut result = 0; let result i32;
match (x) { match (x) {
1 | 2 => { result = 100; } 1 | 2 => { result = 100; }
@@ -126,9 +126,9 @@ pub void test_match_or_pattern() {
assert_eq!(result, 100); assert_eq!(result, 100);
} }
pub void test_match_default() { pub fn test_match_default() {
let x = 99; let x = 99;
let mut result = 0; let result;
match (x) { match (x) {
1 => { result = 10; } 1 => { result = 10; }
@@ -137,7 +137,7 @@ pub void test_match_default() {
assert_eq!(result, 99); assert_eq!(result, 99);
} }
pub void test_for_with_pattern_destructure() { pub fn test_for_with_pattern_destructure() {
let pairs = [(1, "a"), (2, "b")]; let pairs = [(1, "a"), (2, "b")];
let mut keys = 0; let mut keys = 0;
@@ -147,7 +147,7 @@ pub void test_for_with_pattern_destructure() {
assert_eq!(keys, 3); assert_eq!(keys, 3);
} }
pub void run_tests() { pub fn run_tests() {
test_var_decl(); test_var_decl();
test_var_decl_with_init(); test_var_decl_with_init();
test_if_statement(); test_if_statement();
+20 -20
View File
@@ -1,56 +1,56 @@
pub void test_integer_type() { pub fn test_integer_type() {
i32 x = 42; let x i32 = 42;
assert_eq!(x, 42); assert_eq!(x, 42);
} }
pub void test_float_type() { pub fn test_float_type() {
f64 x = 3.14; let x f64 = 3.14;
assert_eq!(x, 3.14); assert_eq!(x, 3.14);
} }
pub void test_bool_type() { pub fn test_bool_type() {
bool x = true; let x bool = true;
assert_eq!(x, true); assert_eq!(x, true);
bool y = false; let y bool = false;
assert_eq!(y, false); assert_eq!(y, false);
} }
pub void test_string_type() { pub fn test_string_type() {
str* s = "hello"; let s *str = "hello";
assert_eq!(s, "hello"); assert_eq!(s, "hello");
} }
pub void test_tuple_type() { pub fn test_tuple_type() {
[i32, str*] t = (42, "answer"); let t [i32, *str] = (42, "answer");
assert_eq!(t.0, 42); assert_eq!(t.0, 42);
assert_eq!(t.1, "answer"); assert_eq!(t.1, "answer");
} }
pub void test_ref_type() { pub fn test_ref_type() {
i32 x = 42; let x i32 = 42;
i32* r = &x; let r *i32 = &x;
assert_eq!(*r, 42); assert_eq!(*r, 42);
} }
pub void test_mut_ref_type() { pub fn test_mut_ref_type() {
let mut x = 42; let mut x = 42;
i32 mut* r = &mut x; let r *mut i32 = &mut x;
*r = 100; *r = 100;
assert_eq!(x, 100); assert_eq!(x, 100);
} }
pub void test_void_type() {} pub fn test_void_type() {}
i32 add(i32 a, i32 b) { fn add(a i32, b i32) i32 {
a + b a + b
} }
pub void test_fn_return_type() { pub fn test_fn_return_type() {
assert_eq!(add(3, 4), 7); assert_eq!(add(3, 4), 7);
} }
pub void run_tests() { pub fn run_tests() {
test_integer_type(); test_integer_type();
test_float_type(); test_float_type();
test_bool_type(); test_bool_type();
+4 -4
View File
@@ -1,21 +1,21 @@
#[derive(Debug)] #[derive(Debug)]
pub struct Debuggable { pub struct Debuggable {
i32 value, value i32,
} }
pub void test_derive_attribute() { pub fn test_derive_attribute() {
let d = Debuggable { value: 42 }; let d = Debuggable { value: 42 };
assert_eq!(d.value, 42); assert_eq!(d.value, 42);
} }
#[allow(unused_variables)] #[allow(unused_variables)]
pub void test_allow_attribute() { pub fn test_allow_attribute() {
let x = 42; let x = 42;
let y = "unused"; let y = "unused";
assert_eq!(x, 42); assert_eq!(x, 42);
} }
pub void run_tests() { pub fn run_tests() {
test_derive_attribute(); test_derive_attribute();
test_allow_attribute(); test_allow_attribute();
} }
+12 -12
View File
@@ -1,56 +1,56 @@
pub class Counter { pub class Counter {
pub i32 count; pub count i32;
pub constructor(i32 start) { pub constructor(start i32) {
self.count = start; self.count = start;
} }
pub void increment(self mut*) { pub fn increment(*mut self) {
self.count++; self.count++;
} }
pub i32 get(self*) { pub fn get(*self) i32 {
self.count self.count
} }
} }
pub void test_class_create() { pub fn test_class_create() {
let c = Counter::new(0); let c = Counter::new(0);
assert_eq!(c.get(), 0); assert_eq!(c.get(), 0);
} }
pub void test_class_method() { pub fn test_class_method() {
let mut c = Counter::new(5); let mut c = Counter::new(5);
c.increment(); c.increment();
assert_eq!(c.get(), 6); assert_eq!(c.get(), 6);
} }
pub void test_class_field_access() { pub fn test_class_field_access() {
let c = Counter::new(42); let c = Counter::new(42);
assert_eq!(c.count, 42); assert_eq!(c.count, 42);
} }
class NamedCounter : Counter { class NamedCounter : Counter {
pub String name; pub name String;
pub constructor(i32 start, String name) { pub constructor(start i32, name String) {
self._super = Counter::new(start); self._super = Counter::new(start);
self.name = name; self.name = name;
} }
pub String get_name(self*) { pub fn get_name(*self) String {
self.name.clone() self.name.clone()
} }
} }
pub void test_class_inherit() { pub fn test_class_inherit() {
let nc = NamedCounter::new(10, "test".to_string()); let nc = NamedCounter::new(10, "test".to_string());
assert_eq!(nc.get_name(), "test"); assert_eq!(nc.get_name(), "test");
assert_eq!(nc.count, 10); assert_eq!(nc.count, 10);
} }
pub void run_tests() { pub fn run_tests() {
test_class_create(); test_class_create();
test_class_method(); test_class_method();
test_class_field_access(); test_class_field_access();
+7 -7
View File
@@ -3,7 +3,7 @@ enum OptionInt {
Some[i32], Some[i32],
} }
pub void test_enum_named() { pub fn test_enum_named() {
let x = OptionInt::None; let x = OptionInt::None;
match (x) { match (x) {
OptionInt::None => { assert_eq!(1, 1); } OptionInt::None => { assert_eq!(1, 1); }
@@ -11,7 +11,7 @@ pub void test_enum_named() {
} }
} }
pub void test_enum_tuple() { pub fn test_enum_tuple() {
let x = OptionInt::Some(42); let x = OptionInt::Some(42);
match (x) { match (x) {
OptionInt::None => { assert_eq!(0, 1); } OptionInt::None => { assert_eq!(0, 1); }
@@ -20,11 +20,11 @@ pub void test_enum_tuple() {
} }
enum Shape { enum Shape {
Circle { i32 radius }, Circle { radius i32 },
Rect { i32 w, i32 h }, Rect { w i32, h i32 },
} }
pub void test_enum_struct() { pub fn test_enum_struct() {
let c = Shape::Circle { radius: 5 }; let c = Shape::Circle { radius: 5 };
match (c) { match (c) {
Shape::Circle { radius } => { assert_eq!(radius, 5); } Shape::Circle { radius } => { assert_eq!(radius, 5); }
@@ -44,7 +44,7 @@ enum Color {
Blue, Blue,
} }
pub void test_enum_eq() { pub fn test_enum_eq() {
let c = Color::Red; let c = Color::Red;
match (c) { match (c) {
Color::Red => { assert_eq!(1, 1); } Color::Red => { assert_eq!(1, 1); }
@@ -52,7 +52,7 @@ pub void test_enum_eq() {
} }
} }
pub void run_tests() { pub fn run_tests() {
test_enum_named(); test_enum_named();
test_enum_tuple(); test_enum_tuple();
test_enum_struct(); test_enum_struct();
+15 -15
View File
@@ -1,58 +1,58 @@
void greet() { fn greet() {
let mut x = 1; let mut x = 1;
x++; x++;
} }
pub void test_basic_function() { pub fn test_basic_function() {
greet(); greet();
} }
i32 add(i32 a, i32 b) { fn add(a i32, b i32) i32 {
a + b a + b
} }
pub void test_fn_params() { pub fn test_fn_params() {
assert_eq!(add(2, 3), 5); assert_eq!(add(2, 3), 5);
} }
pub i32 test_fn_return() { pub fn test_fn_return() i32 {
42 42
} }
pub i32 test_fn_early_return() { pub fn test_fn_early_return() i32 {
return 100; return 100;
0 0
} }
pub i32 test_fn_mut_param(i32 mut x) { pub fn test_fn_mut_param(mut x i32) i32 {
x = x + 10; x = x + 10;
x x
} }
pub void test_method_call() { pub fn test_method_call() {
str* s = "hello"; let s = "hello";
assert_eq!(s.len(), 5); assert_eq!(s.len(), 5);
assert_eq!(s.to_uppercase(), "HELLO"); assert_eq!(s.to_uppercase(), "HELLO");
} }
i32 triple(i32 x) { fn triple(x i32) i32 {
add(x, add(x, x)) add(x, add(x, x))
} }
pub void test_nested_fn_calls() { pub fn test_nested_fn_calls() {
assert_eq!(triple(5), 15); assert_eq!(triple(5), 15);
} }
i32 factorial(i32 n) { fn factorial(n i32) i32 {
if (n <= 1) 1 if (n <= 1) 1
else (n) * (factorial(n - 1)) else n * factorial(n - 1)
} }
pub void test_recursive_fn() { pub fn test_recursive_fn() {
assert_eq!(factorial(5), 120); assert_eq!(factorial(5), 120);
} }
pub void run_tests() { pub fn run_tests() {
test_basic_function(); test_basic_function();
test_fn_params(); test_fn_params();
assert_eq!(test_fn_return(), 42); assert_eq!(test_fn_return(), 42);
+10 -10
View File
@@ -1,37 +1,37 @@
struct Vector2 { struct Vector2 {
i32 x, x i32,
i32 y, y i32,
} }
impl Vector2 { impl Vector2 {
pub i32 magnitude(self*) { pub fn magnitude(*self) i32 {
self.x * self.x + self.y * self.y self.x * self.x + self.y * self.y
} }
} }
pub void test_inherent_impl() { pub fn test_inherent_impl() {
let v = Vector2 { x: 3, y: 4 }; let v = Vector2 { x: 3, y: 4 };
assert_eq!(v.magnitude(), 25); assert_eq!(v.magnitude(), 25);
} }
trait Display { trait Display {
String display(self*); fn display(*self) String;
} }
impl Display for Vector2 { impl Display for Vector2 {
String display(self*) { fn display(*self) String {
format!("({}, {})", self.x, self.y) format!("({}, {})", self.x, self.y)
} }
} }
pub void test_trait_impl_block() { pub fn test_trait_impl_block() {
let v = Vector2 { x: 1, y: 2 }; let v = Vector2 { x: 1, y: 2 };
let s = v.display(); let s = v.display();
assert_eq!(s.len() > 0, true); assert_eq!(s.len() > 0, true);
} }
impl Vector2 { impl Vector2 {
pub Vector2 add(self*, Vector2 other) { pub fn add(*self, other Vector2) Vector2 {
Vector2 { Vector2 {
x: self.x + other.x, x: self.x + other.x,
y: self.y + other.y, y: self.y + other.y,
@@ -39,7 +39,7 @@ impl Vector2 {
} }
} }
pub void test_multiple_impls() { pub fn test_multiple_impls() {
let a = Vector2 { x: 1, y: 2 }; let a = Vector2 { x: 1, y: 2 };
let b = Vector2 { x: 3, y: 4 }; let b = Vector2 { x: 3, y: 4 };
let c = a.add(b); let c = a.add(b);
@@ -47,7 +47,7 @@ pub void test_multiple_impls() {
assert_eq!(c.y, 6); assert_eq!(c.y, 6);
} }
pub void run_tests() { pub fn run_tests() {
test_inherent_impl(); test_inherent_impl();
test_trait_impl_block(); test_trait_impl_block();
test_multiple_impls(); test_multiple_impls();
+9 -9
View File
@@ -1,21 +1,21 @@
struct Point { struct Point {
i32 x, x i32,
i32 y, y i32,
} }
pub void test_struct_create_access() { pub fn test_struct_create_access() {
let p = Point { x: 10, y: 20 }; let p = Point { x: 10, y: 20 };
assert_eq!(p.x, 10); assert_eq!(p.x, 10);
assert_eq!(p.y, 20); assert_eq!(p.y, 20);
} }
pub void test_struct_mut_field() { pub fn test_struct_mut_field() {
let mut p = Point { x: 1, y: 2 }; let mut p = Point { x: 1, y: 2 };
p.x = 100; p.x = 100;
assert_eq!(p.x, 100); assert_eq!(p.x, 100);
} }
pub void test_struct_destructure() { pub fn test_struct_destructure() {
let p = Point { x: 3, y: 4 }; let p = Point { x: 3, y: 4 };
let Point { x, y } = p; let Point { x, y } = p;
assert_eq!(x, 3); assert_eq!(x, 3);
@@ -23,11 +23,11 @@ pub void test_struct_destructure() {
} }
struct Line { struct Line {
Point start, start Point,
Point end, end Point,
} }
pub void test_struct_nested() { pub fn test_struct_nested() {
let l = Line { let l = Line {
start: Point { x: 0, y: 0 }, start: Point { x: 0, y: 0 },
end: Point { x: 5, y: 10 }, end: Point { x: 5, y: 10 },
@@ -36,7 +36,7 @@ pub void test_struct_nested() {
assert_eq!(l.end.y, 10); assert_eq!(l.end.y, 10);
} }
pub void run_tests() { pub fn run_tests() {
test_struct_create_access(); test_struct_create_access();
test_struct_mut_field(); test_struct_mut_field();
test_struct_destructure(); test_struct_destructure();
+15 -15
View File
@@ -1,39 +1,39 @@
trait Speak { trait Speak {
String speak(self*); fn speak(*self) String;
}
trait Greet : Speak {
fn greet(*self) String;
} }
struct Dog { struct Dog {
String name, name String,
} }
impl Speak for Dog { impl Speak for Dog {
String speak(self*) { fn speak(*self) String {
"woof".to_string() "woof".to_string()
} }
} }
pub void test_trait_impl() {
let d = Dog { name: "Rex".to_string() };
assert_eq!(d.speak(), "woof");
}
trait Greet : Speak {
String greet(self*);
}
impl Greet for Dog { impl Greet for Dog {
String greet(self*) { fn greet(*self) String {
"hello".to_string() "hello".to_string()
} }
} }
pub void test_trait_with_requirement() { pub fn test_trait_impl() {
let d = Dog { name: "Rex".to_string() };
assert_eq!(d.speak(), "woof");
}
pub fn test_trait_with_requirement() {
let d = Dog { name: "Buddy".to_string() }; let d = Dog { name: "Buddy".to_string() };
assert_eq!(d.speak(), "woof"); assert_eq!(d.speak(), "woof");
assert_eq!(d.greet(), "hello"); assert_eq!(d.greet(), "hello");
} }
pub void run_tests() { pub fn run_tests() {
test_trait_impl(); test_trait_impl();
test_trait_with_requirement(); test_trait_with_requirement();
} }
+1 -1
View File
@@ -1,4 +1,4 @@
void main() { fn main() {
println!("running common tests..."); println!("running common tests...");
common::expr_test::run_tests(); common::expr_test::run_tests();
common::statement_test::run_tests(); common::statement_test::run_tests();