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
use crate::ast;
use crate::parser::Parser;
use crate::token::Kind;
use crate::traits::{Parse, Peek};
use runestick::Span;

/// A declaration.
#[derive(Debug, Clone)]
pub enum Decl {
    /// A use declaration.
    DeclUse(ast::DeclUse),
    /// A function declaration.
    DeclFn(ast::DeclFn),
    /// An enum declaration.
    DeclEnum(ast::DeclEnum),
    /// A struct declaration.
    DeclStruct(ast::DeclStruct),
    /// An impl declaration.
    DeclImpl(ast::DeclImpl),
}

impl Decl {
    /// The span of the declaration.
    pub fn span(&self) -> Span {
        match self {
            Self::DeclUse(decl) => decl.span(),
            Self::DeclFn(decl) => decl.span(),
            Self::DeclEnum(decl) => decl.span(),
            Self::DeclStruct(decl) => decl.span(),
            Self::DeclImpl(decl) => decl.span(),
        }
    }

    /// Indicates if the declaration needs a semi-colon or not.
    pub fn needs_semi_colon(&self) -> bool {
        match self {
            Self::DeclUse(..) => true,
            Self::DeclFn(..) => false,
            Self::DeclEnum(..) => false,
            Self::DeclStruct(decl_struct) => decl_struct.needs_semi_colon(),
            Self::DeclImpl(..) => false,
        }
    }
}

impl Peek for Decl {
    fn peek(t1: Option<crate::Token>, _: Option<crate::Token>) -> bool {
        let t1 = match t1 {
            Some(t1) => t1,
            None => return false,
        };

        match t1.kind {
            Kind::Use => true,
            Kind::Enum => true,
            Kind::Struct => true,
            Kind::Fn => true,
            _ => false,
        }
    }
}

impl Parse for Decl {
    fn parse(parser: &mut Parser) -> crate::Result<Self, crate::ParseError> {
        Ok(match parser.token_peek_eof()?.kind {
            Kind::Use => Self::DeclUse(parser.parse()?),
            Kind::Enum => Self::DeclEnum(parser.parse()?),
            Kind::Struct => Self::DeclStruct(parser.parse()?),
            Kind::Impl => Self::DeclImpl(parser.parse()?),
            _ => Self::DeclFn(parser.parse()?),
        })
    }
}