Browse Source

feat: add any type

github-actions
Garrit Franke 3 years ago
parent
commit
4a4634e2d7
  1. 42
      docs/concepts/datatypes.md
  2. 10
      examples/playground.sb
  3. 1
      src/generator/c.rs
  4. 2
      src/parser/node_type.rs
  5. 8
      tests/type_any.sb

42
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
```

10
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)
}
}

1
src/generator/c.rs

@ -53,6 +53,7 @@ pub(super) fn generate_type(t: Either<Variable, Option<Type>>) -> 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!(

2
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<String> 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()),
}

8
tests/type_any.sb

@ -0,0 +1,8 @@
fn main() {
print_any(5)
print_any("Test")
}
fn print_any(x: any) {
println(x)
}
Loading…
Cancel
Save