asciidoc_parser/attributes/
element_attribute.rs

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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use crate::{
    span::MatchedItem,
    warnings::{MatchAndWarnings, Warning, WarningType},
    HasSpan, Span,
};

/// This struct represents a single element attribute.
///
/// Element attributes define the built-in and user-defined settings and
/// metadata that can be applied to an individual block element or inline
/// element in a document (including macros). Although the include directive is
/// not technically an element, element attributes can also be defined on an
/// include directive.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ElementAttribute<'src> {
    name: Option<Span<'src>>,
    shorthand_items: Vec<Span<'src>>,
    value: Span<'src>,
    source: Span<'src>,
}

impl<'src> ElementAttribute<'src> {
    pub(crate) fn parse(
        source: Span<'src>,
    ) -> MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>> {
        Self::parse_internal(source, false)
    }

    pub(crate) fn parse_with_shorthand(
        source: Span<'src>,
    ) -> MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>> {
        Self::parse_internal(source, true)
    }

    fn parse_internal(
        source: Span<'src>,
        parse_shorthand: bool,
    ) -> MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>> {
        let mut warnings: Vec<Warning<'src>> = vec![];

        let (name, after): (Option<Span>, Span) = match source.take_attr_name() {
            Some(name) => {
                let space = name.after.take_whitespace();
                match space.after.take_prefix("=") {
                    Some(equals) => {
                        let space = equals.after.take_whitespace();
                        if space.after.is_empty() || space.after.starts_with(',') {
                            // TO DO: Is this a warning? Possible spec ambiguity.
                            (None, source)
                        } else {
                            (Some(name.item), space.after)
                        }
                    }
                    None => (None, source),
                }
            }
            None => (None, source),
        };

        let value = match after.data().chars().next() {
            Some('\'') | Some('"') => match after.take_quoted_string() {
                Some(v) => v,
                None => {
                    warnings.push(Warning {
                        source: after,
                        warning: WarningType::AttributeValueMissingTerminatingQuote,
                    });

                    return MatchAndWarnings {
                        item: None,
                        warnings,
                    };
                }
            },
            _ => after.take_while(|c| c != ','),
        };

        if value.item.is_empty() {
            return MatchAndWarnings {
                item: None,
                warnings,
            };
        }

        let source = source.trim_remainder(value.after);

        let shorthand_items = if name.is_none() && parse_shorthand {
            parse_shorthand_items(source, &mut warnings)
        } else {
            vec![]
        };

        MatchAndWarnings {
            item: Some(MatchedItem {
                item: Self {
                    name,
                    shorthand_items,
                    value: value.item,
                    source,
                },
                after: value.after,
            }),
            warnings,
        }
    }

    /// Return a [`Span`] describing the attribute name.
    pub fn name(&'src self) -> &'src Option<Span<'src>> {
        &self.name
    }

    /// Return the shorthand items, if parsed via `parse_with_shorthand`.
    pub fn shorthand_items(&'src self) -> &'src Vec<Span<'src>> {
        &self.shorthand_items
    }

    /// Return the block style name from shorthand syntax.
    pub fn block_style(&'src self) -> Option<Span<'src>> {
        self.shorthand_items
            .first()
            .filter(|span| span.position(is_shorthand_delimiter).is_none())
            .copied()
    }

    /// Return the id attribute from shorthand syntax.
    ///
    /// If multiple id attributes were specified, only the first
    /// match is returned. (Multiple ids are not supported.)
    pub fn id(&'src self) -> Option<Span<'src>> {
        self.shorthand_items
            .iter()
            .find(|span| span.starts_with('#'))
            .map(|span| span.discard(1))
    }

    /// Return any role attributes that were found in shorthand syntax.
    pub fn roles(&'src self) -> Vec<Span<'src>> {
        self.shorthand_items
            .iter()
            .filter(|span| span.starts_with('.'))
            .map(|span| span.discard(1))
            .collect()
    }

    /// Return any option attributes that were found in shorthand syntax.
    pub fn options(&'src self) -> Vec<Span<'src>> {
        self.shorthand_items
            .iter()
            .filter(|span| span.starts_with('%'))
            .map(|span| span.discard(1))
            .collect()
    }

    /// Return the attribute's raw value.
    pub fn raw_value(&'src self) -> Span<'src> {
        self.value
    }

    //-/ Return the attribute's interpolated value.
    // pub fn value(&'src self) -> AttributeValue<'src> {
    //     self.value.as_attribute_value()
    // }
}

impl<'src> HasSpan<'src> for ElementAttribute<'src> {
    fn span(&'src self) -> &'src Span<'src> {
        &self.source
    }
}

fn parse_shorthand_items<'src>(
    mut span: Span<'src>,
    warnings: &mut Vec<Warning<'src>>,
) -> Vec<Span<'src>> {
    let mut shorthand_items: Vec<Span<'src>> = vec![];

    // Look for block style selector.
    if let Some(block_style_pr) = span.split_at_match_non_empty(is_shorthand_delimiter) {
        shorthand_items.push(block_style_pr.item);
        span = block_style_pr.after;
    }

    while !span.is_empty() {
        // Assumption: First character is a delimiter.
        let after_delimiter = span.discard(1);
        match after_delimiter.position(is_shorthand_delimiter) {
            None => {
                if after_delimiter.is_empty() {
                    warnings.push(Warning {
                        source: span,
                        warning: WarningType::EmptyShorthandItem,
                    });
                    span = after_delimiter;
                } else {
                    shorthand_items.push(span);
                    span = span.discard_all();
                }
            }
            Some(0) => {
                warnings.push(Warning {
                    source: span.trim_remainder(after_delimiter),
                    warning: WarningType::EmptyShorthandItem,
                });
                span = after_delimiter;
            }
            Some(index) => {
                let mi: MatchedItem<Span> = span.into_parse_result(index + 1);
                shorthand_items.push(mi.item);
                span = mi.after;
            }
        }
    }

    shorthand_items
}

fn is_shorthand_delimiter(c: char) -> bool {
    c == '#' || c == '%' || c == '.'
}