bluejay_parser/ast/
directives.rs1use crate::{
2 ast::{Directive, FromTokens, IsMatch, ParseError, Tokens, TryFromTokens},
3 HasSpan, Span,
4};
5use bluejay_core::AsIter;
6
7#[derive(Debug)]
8pub struct Directives<'a, const CONST: bool> {
9 directives: Vec<Directive<'a, CONST>>,
10 span: Option<Span>,
11}
12
13pub type ConstDirectives<'a> = Directives<'a, true>;
14pub type VariableDirectives<'a> = Directives<'a, false>;
15
16impl<'a, const CONST: bool> FromTokens<'a> for Directives<'a, CONST> {
17 #[inline]
18 fn from_tokens(tokens: &mut impl Tokens<'a>) -> Result<Self, ParseError> {
19 let mut directives: Vec<Directive<'a, CONST>> = Vec::new();
20 while let Some(directive) = Directive::try_from_tokens(tokens) {
21 directives.push(directive?);
22 }
23 let span = match directives.as_slice() {
24 [] => None,
25 [first] => Some(first.span().clone()),
26 [first, .., last] => Some(first.span().merge(last.span())),
27 };
28 Ok(Self { directives, span })
29 }
30}
31
32impl<'a, const CONST: bool> IsMatch<'a> for Directives<'a, CONST> {
33 #[inline]
34 fn is_match(tokens: &mut impl Tokens<'a>) -> bool {
35 Directive::<'a, CONST>::is_match(tokens)
36 }
37}
38
39impl<'a, const CONST: bool> bluejay_core::Directives<CONST> for Directives<'a, CONST> {
40 type Directive = Directive<'a, CONST>;
41}
42
43impl<'a, const CONST: bool> AsIter for Directives<'a, CONST> {
44 type Item = Directive<'a, CONST>;
45 type Iterator<'b> = std::slice::Iter<'b, Self::Item> where 'a: 'b;
46
47 fn iter(&self) -> Self::Iterator<'_> {
48 self.directives.iter()
49 }
50}
51
52impl<'a, const CONST: bool> Directives<'a, CONST> {
53 pub(crate) fn span(&self) -> Option<&Span> {
54 self.span.as_ref()
55 }
56}
57
58impl<'a, const CONST: bool> IntoIterator for Directives<'a, CONST> {
59 type Item = Directive<'a, CONST>;
60 type IntoIter = std::vec::IntoIter<Self::Item>;
61
62 fn into_iter(self) -> Self::IntoIter {
63 self.directives.into_iter()
64 }
65}