1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//! Representation of the AST.
//!
//! This follows [`rowan::ast`](https://docs.rs/rowan/latest/rowan/ast/index.html).
//! The basic idea is to try to "cast" the nodes
//! of the concrete syntax tree (CST) to AST nodes based on their `SyntaxKind`.
//! This is achieved with the [`AstNode`] and [`AstToken`] traits in this module.
pub mod constants;
pub use constants::*;

pub mod bindings;
pub use bindings::*;

pub mod declarations;
pub use declarations::*;

pub mod expressions;
pub use expressions::*;

pub mod identifiers;
pub use identifiers::*;

pub mod matches;
pub use matches::*;

pub mod patterns;
pub use patterns::*;

pub mod type_expressions;
pub use type_expressions::*;

use crate::language::{SyntaxNode, SyntaxToken};
pub use rowan::ast::AstNode;

pub trait AstToken {
    fn cast(token: SyntaxToken) -> Option<Self>
    where
        Self: Sized;

    fn syntax(&self) -> &SyntaxToken;
}

pub type AstPtr<N> = rowan::ast::AstPtr<N>;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct File {
    syntax: SyntaxNode,
}

crate::impl_ast_node!(File, FILE);

impl File {
    pub fn declarations(&self) -> impl Iterator<Item = crate::ast::Dec> {
        rowan::ast::support::children(self.syntax())
    }
}

#[macro_export]
macro_rules! impl_ast_node {
    ($target:ty, $kind:ident) => {
        impl $crate::AstNode for $target {
            type Language = $crate::language::SML;

            fn can_cast(kind: <Self::Language as rowan::Language>::Kind) -> bool
            where
                Self: Sized,
            {
                use $crate::SyntaxKind::*;
                kind == $kind
            }

            fn cast(node: $crate::language::SyntaxNode) -> Option<Self>
            where
                Self: Sized,
            {
                use $crate::SyntaxKind::*;
                match node.kind() {
                    $kind => Some(Self { syntax: node }),
                    _ => None,
                }
            }

            fn syntax(&self) -> &$crate::language::SyntaxNode {
                &self.syntax
            }
        }

        impl std::fmt::Display for $target {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", <Self as $crate::AstNode>::syntax(self))
            }
        }
    };
}

#[macro_export]
macro_rules! impl_ast_token {
    ($target:ty, $kind:ident) => {
        impl $crate::AstToken for $target {
            fn cast(node: $crate::language::SyntaxToken) -> Option<Self>
            where
                Self: Sized,
            {
                use $crate::SyntaxKind::*;
                match node.kind() {
                    $kind => Some(Self { syntax: node }),
                    _ => None,
                }
            }

            fn syntax(&self) -> &$crate::language::SyntaxToken {
                &self.syntax
            }
        }

        impl std::fmt::Display for $target {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", <Self as $crate::AstToken>::syntax(self))
            }
        }
    };
}

pub mod support {
    use crate::{
        language::{SyntaxElement, SyntaxNode, SML},
        AstNode, AstToken,
    };

    pub use rowan::ast::support::{child, token};

    pub fn tokens<N: AstToken>(parent: &SyntaxNode) -> impl Iterator<Item = N> {
        parent.children_with_tokens().filter_map(|c| match c {
            SyntaxElement::Token(token) => N::cast(token),
            _ => None,
        })
    }

    pub fn children<N: AstNode<Language = SML>>(parent: &SyntaxNode) -> impl Iterator<Item = N> {
        rowan::ast::support::children(parent)
    }
}

mod util {
    #[macro_export]
    macro_rules! impl_from {
        ($target:ty, $x:ident, $t:ty) => {
            impl From<$t> for $target {
                fn from(x: $t) -> Self {
                    Self::$x(x)
                }
            }
        };
    }
}

#[cfg(test)]
mod tests {
    use expect_test::{expect, Expect};

    fn check(should_error: bool, src: &str, expect: Expect) {
        use crate::{ast::File, AstNode, Parser};
        let parser = Parser::new(src);
        let tree = parser.parse();
        let file = File::cast(tree.syntax()).unwrap();

        let actual: String = file
            .declarations()
            .map(|d| format!("{}", d))
            .collect::<Vec<String>>()
            .join("; ");
        expect.assert_eq(&actual);

        assert_eq!(tree.has_errors(), should_error);
    }

    #[test]
    fn file_test() {
        check(
            false,
            "val a = b; fun f a = g a; type int = d",
            expect!["val a = b; fun f a = g a; type int = d"],
        )
    }
}