diff --git a/docs/concepts/datatypes.md b/docs/concepts/datatypes.md index 405712f..a3c1d19 100644 --- a/docs/concepts/datatypes.md +++ b/docs/concepts/datatypes.md @@ -54,3 +54,45 @@ Banana Apple Pineapple ``` + +## The Any type + +`any` can be used to specify that any type can be used in this place. This should be used with caution, as it might cause undefined behavior. + +``` +fn main() { + + print_anything(5) + print_anything("Hello") +} + +fn print_anything(x: any) { + println(x) +} +``` + +``` +$ sabre run main.sb +5 +Hello +``` + +`any` can also be used in conjunction with the array notation to allow a mixture of types within an array. + +``` +fn main() { + + let arr = [1, "Two", 3] + + for x in arr { + println(x) + } +} +``` + +``` +$ sabre run main.sb +1 +Two +3 +``` diff --git a/examples/playground.sb b/examples/playground.sb index 7d6dc27..41575ae 100644 --- a/examples/playground.sb +++ b/examples/playground.sb @@ -1,8 +1,8 @@ fn main() { - let x = add_one(2) - println(x) -} -fn add_one(x: int): int { - return x + 1 + let arr = [1, "Two", 3] + + for x in arr { + println(x) + } } \ No newline at end of file diff --git a/src/generator/c.rs b/src/generator/c.rs index 7b1ba2f..9b64e61 100644 --- a/src/generator/c.rs +++ b/src/generator/c.rs @@ -53,6 +53,7 @@ pub(super) fn generate_type(t: Either>) -> String { Some(t) => match t { Type::Int => "int".into(), Type::Str => "char *".into(), + Type::Any => "void *".into(), Type::Bool => "bool".into(), Type::Array(_) => match name { Some(n) => format!( diff --git a/src/parser/node_type.rs b/src/parser/node_type.rs index e341184..e6f038c 100644 --- a/src/parser/node_type.rs +++ b/src/parser/node_type.rs @@ -59,6 +59,7 @@ pub struct Variable { #[derive(Debug, Eq, PartialEq, Clone)] pub enum Type { + Any, Int, Str, Bool, @@ -71,6 +72,7 @@ impl TryFrom for Type { match s.as_ref() { "int" => Ok(Self::Int), "string" => Ok(Self::Str), + "any" => Ok(Self::Any), "bool" => Ok(Self::Bool), _ => Err("Unknown Type".into()), } diff --git a/tests/type_any.sb b/tests/type_any.sb new file mode 100644 index 0000000..e7c40e0 --- /dev/null +++ b/tests/type_any.sb @@ -0,0 +1,8 @@ +fn main() { + print_any(5) + print_any("Test") +} + +fn print_any(x: any) { + println(x) +} \ No newline at end of file