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
use std::sync::Arc;

use gramatika::{Parse, ParseStreamer, Span, Spanned, SpannedError, Token as _};

use crate::{
	common::{AttributeList, TypeDecl},
	stmt::BlockStmt,
	token::{brace, keyword, operator, punct, Token, TokenKind},
	ParseStream,
};

use super::Decl;

#[derive(Clone, DebugLisp)]
pub struct FunctionDecl {
	pub attributes: Option<AttributeList>,
	pub storage: Token,
	pub storage_modifier: Option<Token>,
	pub name: Token,
	pub params: Arc<[Decl]>,
	pub return_ty: Option<TypeDecl>,
	pub body: BlockStmt,
}

#[derive(Clone, DebugLisp)]
pub struct ParamDecl {
	pub attributes: Option<AttributeList>,
	pub name: Token,
	pub ty: TypeDecl,
}

impl Parse for FunctionDecl {
	type Stream = ParseStream;

	fn parse(input: &mut Self::Stream) -> gramatika::Result<Self> {
		use TokenKind::*;

		let storage = input.consume(keyword![fn])?;
		let storage_modifier = if input.check(operator![<]) {
			input.consume(operator![<])?;
			let modifier = input.consume_kind(TokenKind::Keyword)?;
			input.consume(operator![>])?;

			Some(modifier)
		} else {
			None
		};
		let name = input.consume_as(TokenKind::Ident, Token::function)?;
		input.consume(brace!["("])?;

		let mut params = vec![];
		while !input.check(brace![")"]) {
			match input.peek() {
				Some(token) => match token.as_matchable() {
					(Punct, "@", _) | (Ident, _, _) => {
						let param = input.parse::<ParamDecl>()?;
						params.push(Decl::Param(param));
					}
					(Punct, ",", _) => input.discard(),
					(_, _, span) => {
						return Err(SpannedError {
							message: "Expected parameter, `,`, or `)`".into(),
							span: Some(span),
							source: input.source(),
						})
					}
				},
				None => {
					return Err(SpannedError {
						message: "Unexpected end of input".into(),
						source: input.source(),
						span: None,
					})
				}
			};
		}

		input.consume(brace![")"])?;
		let return_ty = if input.check(operator![->]) {
			Some(input.parse::<TypeDecl>()?)
		} else {
			None
		};

		let body = input.parse::<BlockStmt>()?;

		Ok(Self {
			attributes: None,
			storage,
			storage_modifier,
			name,
			params: params.into(),
			return_ty,
			body,
		})
	}
}

impl Spanned for FunctionDecl {
	fn span(&self) -> Span {
		self.storage.span().through(self.body.brace_close.span())
	}
}

impl Parse for ParamDecl {
	type Stream = ParseStream;

	fn parse(input: &mut Self::Stream) -> gramatika::Result<Self> {
		let attributes = if input.check(punct!["@"]) {
			Some(input.parse::<AttributeList>()?)
		} else {
			None
		};
		let name = input.consume_kind(TokenKind::Ident)?;
		let ty = input.parse::<TypeDecl>()?;

		Ok(Self {
			attributes,
			name,
			ty,
		})
	}
}

impl Spanned for ParamDecl {
	fn span(&self) -> Span {
		let span_start = self
			.attributes
			.as_ref()
			.and_then(|attrs| attrs.attributes.first().map(|attr| &attr.at_sign))
			.unwrap_or(&self.name)
			.span();

		span_start.through(self.ty.span())
	}
}