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

feat: union types #466

Draft
wants to merge 19 commits into
base: staging
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 7 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
70 changes: 63 additions & 7 deletions src/modules/types.rs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function try_parse_type could be simply extended with a recursive approach. Here is a code block that illustrates how can it be achieved without introducing new functions:

    if token(meta, "|").is_ok() {
        // We're parsing this function recursively
        match (res, try_parse_type(meta)) {
            // And we flatten the result into a single union
            (Ok(lhs), Ok(rhs)) => return Ok(Type::Union([&[lhs], &rhs[..]].concat()))
            (Err(_), _) => error!(meta, tok, "Expected type before '|'.")
            (_, Err(_)) => error!(meta, tok, "Expected type after '|'.")
        }
    }

Here is the full function for a reference:

Full implementation of try_parse_type
// Tries to parse the type - if it fails, it fails quietly
pub fn try_parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
    let tok = meta.get_current_token();
    let res = match tok.clone() {
        Some(matched_token) => {
            match matched_token.word.as_ref() {
                "Text" => {
                    meta.increment_index();
                    Ok(Type::Text)
                },
                "Bool" => {
                    meta.increment_index();
                    Ok(Type::Bool)
                },
                "Num" => {
                    meta.increment_index();
                    Ok(Type::Num)
                },
                "Null" => {
                    meta.increment_index();
                    Ok(Type::Null)
                },
                "[" => {
                    let index = meta.get_index();
                    meta.increment_index();
                    if token(meta, "]").is_ok() {
                        Ok(Type::Array(Box::new(Type::Generic)))
                    } else {
                        match try_parse_type(meta) {
                            Ok(Type::Array(_)) => error!(meta, tok, "Arrays cannot be nested due to the Bash limitations"),
                            Ok(result_type) => {
                                token(meta, "]")?;
                                Ok(Type::Array(Box::new(result_type)))
                            },
                            Err(_) => {
                                meta.set_index(index);
                                Err(Failure::Quiet(PositionInfo::at_eof(meta)))
                            }
                        }
                    }
                },
                // Error messages to help users of other languages understand the syntax
                text @ ("String" | "Char") => {
                    error!(meta, tok, format!("'{text}' is not a valid data type. Did you mean 'Text'?"))
                },
                number @ ("Number" | "Int" | "Float" | "Double") => {
                    error!(meta, tok, format!("'{number}' is not a valid data type. Did you mean 'Num'?"))
                },
                "Boolean" => {
                    error!(meta, tok, "'Boolean' is not a valid data type. Did you mean 'Bool'?")
                },
                array @ ("List" | "Array") => {
                    error!(meta, tok => {
                        message: format!("'{array}'<T> is not a valid data type. Did you mean '[T]'?"),
                        comment: "Where 'T' is the type of the array elements"
                    })
                },
                // The quiet error
                _ => Err(Failure::Quiet(PositionInfo::at_eof(meta)))
            }
        },
        None => {
            Err(Failure::Quiet(PositionInfo::at_eof(meta)))
        }
    };

    if token(meta, "?").is_ok() {
        res = Ok(res.map(|t| Type::Failable(Box::new(t))));
    }
    
    if token(meta, "|").is_ok() {
        // We're parsing this function recursively
        match (res, try_parse_type(meta)) {
            // And we flatten the result into a single union
            (Ok(lhs), Ok(rhs)) => return Ok(Type::Union([&[lhs], &rhs[..]].concat()))
            (Err(_), _) => error!(meta, tok, "Expected type before '|'.")
            (_, Err(_)) => error!(meta, tok, "Expected type after '|'.")
        }
    }

    res
}

Original file line number Diff line number Diff line change
@@ -1,26 +1,59 @@
use std::fmt::Display;

use heraclitus_compiler::prelude::*;
use itertools::Itertools;
use crate::utils::ParserMetadata;

#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[derive(Debug, Clone, Eq, Default)]
pub enum Type {
#[default] Null,
Text,
Bool,
Num,
Union(Vec<Type>),
Array(Box<Type>),
Failable(Box<Type>),
Generic
}

impl Type {
fn eq_union_normal(one: &[Type], other: &Type) -> bool {
one.iter().any(|x| (*x).to_string() == other.to_string())
}

fn eq_unions(one: &[Type], other: &[Type]) -> bool {
one.iter().any(|x| {
Self::eq_union_normal(other, x)
})
}
}

impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
if let Type::Union(union) = self {
if let Type::Union(other) = other {
return Type::eq_unions(union, other);
} else {
return Type::eq_union_normal(union, other);
}
}

if let Type::Union(other) = other {
Type::eq_union_normal(other, self)
} else {
self.to_string() == other.to_string()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While a good workaround, I don't think it is optimal performance-wise to compare types by stringifying them.

FYI, the optimal yet broken way would be to use the std::mem::discriminant function to compare enum variants. The issue is that it doesn't care about the nested data, see #300 (comment).

}
}
}

impl Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Type::Text => write!(f, "Text"),
Type::Bool => write!(f, "Bool"),
Type::Num => write!(f, "Num"),
Type::Null => write!(f, "Null"),
Type::Union(types) => write!(f, "{}", types.iter().map(|x| format!("{x}")).join(" | ")),
Type::Array(t) => write!(f, "[{}]", t),
Type::Failable(t) => write!(f, "{}?", t),
Type::Generic => write!(f, "Generic")
Expand All @@ -39,10 +72,8 @@ pub fn parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
.map_err(|_| Failure::Loud(Message::new_err_at_token(meta, tok).message("Expected a data type")))
}

// Tries to parse the type - if it fails, it fails quietly
pub fn try_parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
let tok = meta.get_current_token();
let res = match tok.clone() {
fn parse_type_tok(meta: &mut ParserMetadata, tok: Option<Token>) -> Result<Type, Failure> {
match tok.clone() {
Some(matched_token) => {
match matched_token.word.as_ref() {
"Text" => {
Expand Down Expand Up @@ -99,10 +130,35 @@ pub fn try_parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
None => {
Err(Failure::Quiet(PositionInfo::at_eof(meta)))
}
};
}
}

fn parse_one_type(meta: &mut ParserMetadata, tok: Option<Token>) -> Result<Type, Failure> {
let res = parse_type_tok(meta, tok)?;
if token(meta, "?").is_ok() {
return res.map(|t| Type::Failable(Box::new(t)))
return Ok(Type::Failable(Box::new(res)))
}
Ok(res)
}

// Tries to parse the type - if it fails, it fails quietly
pub fn try_parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
let tok = meta.get_current_token();
let res = parse_one_type(meta, tok);

if token(meta, "|").is_ok() {
// is union type
let mut unioned = vec![ res? ];
loop {
match parse_one_type(meta, meta.get_current_token()) {
Err(err) => return Err(err),
Ok(t) => unioned.push(t)
};
if token(meta, "|").is_err() {
break;
}
}
return Ok(Type::Union(unioned))
}

res
Expand Down
2 changes: 2 additions & 0 deletions src/tests/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::test_amber;

mod unions;

#[test]
#[should_panic(expected = "ERROR: Return type does not match function return type")]
fn function_with_wrong_typed_return() {
Expand Down
32 changes: 32 additions & 0 deletions src/tests/errors/unions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::tests::test_amber;

#[test]
#[should_panic(expected = "ERROR: 1st argument 'param' of function 'abc' expects type 'Text | Null', but 'Num' was given")]
fn invalid_union_type_eq_normal_type() {
let code = r#"
fun abc(param: Text | Null) {}
abc("")
abc(123)
"#;
test_amber(code, "");
}

#[test]
#[should_panic(expected = "ERROR: 1st argument 'param' of function 'abc' expects type 'Text | Null', but 'Num | [Text]' was given")]
fn invalid_two_unions() {
let code = r#"
fun abc(param: Text | Null) {}
abc(123 as Num | [Text])
"#;
test_amber(code, "");
}

#[test]
#[should_panic(expected = "ERROR: 1st argument 'param' of function 'abc' expects type 'Text | Num | Text? | Num? | [Null]', but 'Null' was given")]
fn big_union() {
let code = r#"
fun abc(param: Text | Num | Text? | Num? | [Null]) {}
abc(null)
"#;
test_amber(code, "");
}
10 changes: 10 additions & 0 deletions src/tests/validity/function_with_union_types.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Output
// abc
// 123

fun check(thing: Text | Num): Null {
echo thing
}

check("abc")
check(123)
7 changes: 7 additions & 0 deletions src/tests/validity/union_types.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Output
// 123

let thingy = "abc" as Text | Num;
thingy = 123;

echo thingy;
19 changes: 19 additions & 0 deletions src/tests/validity/union_types_if.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Output
// is text
// abc
// is num
// 123

fun check(thing: Text | Num): Null {
if thing is Text {
echo "is text"
echo thing
}
if thing is Num {
echo "is num"
echo thing
}
}

check("abc")
check(123)
Loading