1use std::fmt::{self, Display, Formatter};
2
3#[cfg(feature = "ast-json")]
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7use crate::{Ident, Token, TokenKind};
8
9#[derive(Error, Clone, Debug, PartialOrd, Eq, Ord, PartialEq)]
11#[error("Unknown selector `{0}`")]
12pub struct UnknownSelector(pub Token);
13
14fn parse_bracket_selector(s: &str) -> Option<Selector> {
18 let inner = s.strip_prefix(".[")?;
19 let (first, rest) = inner.split_once(']')?;
20
21 if !first.is_empty() && !first.bytes().all(|b| b.is_ascii_digit()) {
22 return None;
23 }
24 let first_idx: Option<usize> = if first.is_empty() {
25 None
26 } else {
27 Some(first.parse().ok()?)
28 };
29
30 if rest.is_empty() {
31 return Some(Selector::List(first_idx, None));
33 }
34
35 let inner2 = rest.strip_prefix('[')?;
36 let (second, tail) = inner2.split_once(']')?;
37 if !tail.is_empty() {
38 return None;
39 }
40 if !second.is_empty() && !second.bytes().all(|b| b.is_ascii_digit()) {
41 return None;
42 }
43 let second_idx: Option<usize> = if second.is_empty() {
44 None
45 } else {
46 Some(second.parse().ok()?)
47 };
48 Some(Selector::Table(first_idx, second_idx))
50}
51
52impl UnknownSelector {
53 pub fn new(token: Token) -> Self {
55 Self(token)
56 }
57}
58
59fn unescape_property_key(s: &str) -> String {
61 let mut result = String::with_capacity(s.len());
62 let mut chars = s.chars();
63 while let Some(c) = chars.next() {
64 if c == '\\' {
65 if let Some(next) = chars.next() {
66 result.push(next);
67 }
68 } else {
69 result.push(c);
70 }
71 }
72 result
73}
74
75fn escape_property_key(key: &str) -> String {
77 let mut result = String::with_capacity(key.len() + 2);
78 for c in key.chars() {
79 match c {
80 '"' => result.push_str("\\\""),
81 '\\' => result.push_str("\\\\"),
82 _ => result.push(c),
83 }
84 }
85 result
86}
87
88#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
93#[derive(PartialEq, PartialOrd, Debug, Eq, Clone)]
94pub enum Selector {
95 Blockquote,
97 Footnote,
99 List(Option<usize>, Option<bool>),
103 Toml,
105 Yaml,
107 Break,
109 InlineCode,
111 InlineMath,
113 Delete,
115 Emphasis,
117 FootnoteRef,
119 Html,
121 Image,
123 ImageRef,
125 MdxJsxTextElement,
127 Link,
129 LinkRef,
131 WikiLink,
133 Callout,
135 Embed,
137 Strong,
139 Code,
141 Math,
143 Heading(Option<u8>),
147 Table(Option<usize>, Option<usize>),
151 TableAlign,
153 Text,
155 HorizontalRule,
157 Definition,
159 MdxFlowExpression,
161 MdxTextExpression,
163 MdxJsEsm,
165 MdxJsxFlowElement,
167 Recursive,
169 Task,
171 Todo,
173 Done,
175 Attr(AttrKind),
177 Property(Ident),
179}
180
181#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
186#[derive(PartialEq, PartialOrd, Debug, Eq, Clone)]
187pub enum AttrKind {
188 Value,
190 Values,
192 Children,
194
195 Lang,
197 Meta,
199 Fence,
201
202 Url,
204 Alt,
206 Title,
208
209 Ident,
211 Label,
213
214 Depth,
216 Level,
218
219 Index,
221 Ordered,
223 Checked,
225
226 Column,
228 Row,
230
231 Align,
233
234 Name,
236 Kind,
238
239 Line,
241 EndLine,
243}
244
245impl Display for AttrKind {
246 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
247 match self {
248 AttrKind::Value => write!(f, ".value"),
249 AttrKind::Values => write!(f, ".values"),
250 AttrKind::Children => write!(f, ".children"),
251 AttrKind::Lang => write!(f, ".lang"),
252 AttrKind::Meta => write!(f, ".meta"),
253 AttrKind::Fence => write!(f, ".fence"),
254 AttrKind::Url => write!(f, ".url"),
255 AttrKind::Alt => write!(f, ".alt"),
256 AttrKind::Title => write!(f, ".title"),
257 AttrKind::Ident => write!(f, ".ident"),
258 AttrKind::Label => write!(f, ".label"),
259 AttrKind::Depth => write!(f, ".depth"),
260 AttrKind::Level => write!(f, ".level"),
261 AttrKind::Index => write!(f, ".index"),
262 AttrKind::Ordered => write!(f, ".ordered"),
263 AttrKind::Checked => write!(f, ".checked"),
264 AttrKind::Column => write!(f, ".column"),
265 AttrKind::Row => write!(f, ".row"),
266 AttrKind::Align => write!(f, ".align"),
267 AttrKind::Name => write!(f, ".name"),
268 AttrKind::Kind => write!(f, ".kind"),
269 AttrKind::Line => write!(f, ".line"),
270 AttrKind::EndLine => write!(f, ".end_line"),
271 }
272 }
273}
274
275macro_rules! selector_table {
278 ($($($name:literal)|+ => $selector:expr,)+) => {
279 pub const SELECTOR_NAMES: &[&str] = &[$($($name),+),+];
281
282 impl Selector {
283 pub fn from_selector_str(s: &str) -> Option<Self> {
287 match s {
288 $($($name)|+ => Some($selector),)+
289 _ => None,
290 }
291 }
292 }
293 };
294}
295
296selector_table! {
297 ".h" | ".heading" => Selector::Heading(None),
298 ".h1" => Selector::Heading(Some(1)),
299 ".h2" => Selector::Heading(Some(2)),
300 ".h3" => Selector::Heading(Some(3)),
301 ".h4" => Selector::Heading(Some(4)),
302 ".h5" => Selector::Heading(Some(5)),
303 ".h6" => Selector::Heading(Some(6)),
304 ".>" | ".blockquote" => Selector::Blockquote,
305 ".^" | ".footnote" => Selector::Footnote,
306 ".<" | ".mdx_jsx_flow_element" => Selector::MdxJsxFlowElement,
307 ".**" | ".emphasis" => Selector::Emphasis,
308 ".$$" | ".math" => Selector::Math,
309 ".horizontal_rule" | ".hr" | ".---" | ".***" | ".___" => Selector::HorizontalRule,
310 ".{}" | ".mdx_text_expression" => Selector::MdxTextExpression,
311 ".[^]" | ".footnote_ref" => Selector::FootnoteRef,
312 ".definition" => Selector::Definition,
313 ".break" | ".br" => Selector::Break,
314 ".delete" => Selector::Delete,
315 ".<>" | ".html" => Selector::Html,
316 ".image" => Selector::Image,
317 ".image_ref" => Selector::ImageRef,
318 ".code_inline" | ".inline_code" => Selector::InlineCode,
319 ".math_inline" | ".inline_math" => Selector::InlineMath,
320 ".link" => Selector::Link,
321 ".link_ref" => Selector::LinkRef,
322 ".wikilink" => Selector::WikiLink,
323 ".callout" => Selector::Callout,
324 ".embed" => Selector::Embed,
325 ".[]" | ".list" | ".li" => Selector::List(None, None),
326 ".task" => Selector::Task,
327 ".todo" => Selector::Todo,
328 ".done" => Selector::Done,
329 ".toml" => Selector::Toml,
330 ".strong" => Selector::Strong,
331 ".yaml" => Selector::Yaml,
332 ".code" | ".code_block" => Selector::Code,
333 ".mdx_js_esm" => Selector::MdxJsEsm,
334 ".mdx_jsx_text_element" => Selector::MdxJsxTextElement,
335 ".mdx_flow_expression" => Selector::MdxFlowExpression,
336 ".text" | ".p" | ".paragraph" => Selector::Text,
337 ".[][]" | ".table" => Selector::Table(None, None),
338 ".table_align" => Selector::TableAlign,
339 ".." => Selector::Recursive,
340 ".value" => Selector::Attr(AttrKind::Value),
341 ".values" => Selector::Attr(AttrKind::Values),
342 ".children" | ".cn" => Selector::Attr(AttrKind::Children),
343 ".lang" => Selector::Attr(AttrKind::Lang),
344 ".meta" => Selector::Attr(AttrKind::Meta),
345 ".fence" => Selector::Attr(AttrKind::Fence),
346 ".url" => Selector::Attr(AttrKind::Url),
347 ".alt" => Selector::Attr(AttrKind::Alt),
348 ".title" => Selector::Attr(AttrKind::Title),
349 ".ident" => Selector::Attr(AttrKind::Ident),
350 ".label" => Selector::Attr(AttrKind::Label),
351 ".depth" => Selector::Attr(AttrKind::Depth),
352 ".level" => Selector::Attr(AttrKind::Level),
353 ".index" => Selector::Attr(AttrKind::Index),
354 ".ordered" => Selector::Attr(AttrKind::Ordered),
355 ".checked" => Selector::Attr(AttrKind::Checked),
356 ".column" => Selector::Attr(AttrKind::Column),
357 ".row" => Selector::Attr(AttrKind::Row),
358 ".align" => Selector::Attr(AttrKind::Align),
359 ".name" => Selector::Attr(AttrKind::Name),
360 ".kind" => Selector::Attr(AttrKind::Kind),
361 ".line" => Selector::Attr(AttrKind::Line),
362 ".end_line" => Selector::Attr(AttrKind::EndLine),
363}
364
365impl TryFrom<&Token> for Selector {
366 type Error = UnknownSelector;
367
368 fn try_from(token: &Token) -> Result<Self, Self::Error> {
369 if let TokenKind::Selector(s) = &token.kind {
370 if let Some(sel) = Self::from_selector_str(s.as_str()) {
371 return Ok(sel);
372 }
373 if let Some(sel) = parse_bracket_selector(s.as_str()) {
374 return Ok(sel);
375 }
376 if let Some(quoted) = s.strip_prefix(".\"").and_then(|r| r.strip_suffix('"')) {
378 return Ok(Selector::Property(Ident::new(&unescape_property_key(quoted))));
379 }
380 Err(UnknownSelector(token.clone()))
381 } else {
382 Err(UnknownSelector(token.clone()))
383 }
384 }
385}
386
387impl Display for Selector {
388 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
389 match self {
390 Selector::Heading(None) => write!(f, ".h"),
391 Selector::Heading(Some(1)) => write!(f, ".h1"),
392 Selector::Heading(Some(2)) => write!(f, ".h2"),
393 Selector::Heading(Some(3)) => write!(f, ".h3"),
394 Selector::Heading(Some(4)) => write!(f, ".h4"),
395 Selector::Heading(Some(5)) => write!(f, ".h5"),
396 Selector::Heading(Some(6)) => write!(f, ".h6"),
397 Selector::Heading(Some(n)) => write!(f, ".h{}", n),
398 Selector::Blockquote => write!(f, ".blockquote"),
399 Selector::Footnote => write!(f, ".footnote"),
400 Selector::List(None, None) => write!(f, ".list"),
401 Selector::List(Some(idx), None) => write!(f, ".[{}]", idx),
402 Selector::List(Some(idx), _) => write!(f, ".[{}]", idx),
403 Selector::List(None, _) => write!(f, ".[]"),
404 Selector::Toml => write!(f, ".toml"),
405 Selector::Yaml => write!(f, ".yaml"),
406 Selector::Break => write!(f, ".break"),
407 Selector::InlineCode => write!(f, ".code_inline"),
408 Selector::InlineMath => write!(f, ".math_inline"),
409 Selector::Delete => write!(f, ".delete"),
410 Selector::Emphasis => write!(f, ".emphasis"),
411 Selector::FootnoteRef => write!(f, ".footnote_ref"),
412 Selector::Html => write!(f, ".html"),
413 Selector::Image => write!(f, ".image"),
414 Selector::ImageRef => write!(f, ".image_ref"),
415 Selector::MdxJsxTextElement => write!(f, ".mdx_jsx_text_element"),
416 Selector::Link => write!(f, ".link"),
417 Selector::LinkRef => write!(f, ".link_ref"),
418 Selector::WikiLink => write!(f, ".wikilink"),
419 Selector::Callout => write!(f, ".callout"),
420 Selector::Embed => write!(f, ".embed"),
421 Selector::Strong => write!(f, ".strong"),
422 Selector::Code => write!(f, ".code"),
423 Selector::Math => write!(f, ".math"),
424 Selector::Table(None, None) => write!(f, ".table"),
425 Selector::Table(Some(row), None) => write!(f, ".[{}][]", row),
426 Selector::Table(Some(row), Some(col)) => write!(f, ".[{}][{}]", row, col),
427 Selector::Table(None, Some(col)) => write!(f, ".[][{}]", col),
428 Selector::TableAlign => write!(f, ".table_align"),
429 Selector::Text => write!(f, ".text"),
430 Selector::HorizontalRule => write!(f, ".horizontal_rule"),
431 Selector::Definition => write!(f, ".definition"),
432 Selector::MdxFlowExpression => write!(f, ".mdx_flow_expression"),
433 Selector::MdxTextExpression => write!(f, ".mdx_text_expression"),
434 Selector::MdxJsEsm => write!(f, ".mdx_js_esm"),
435 Selector::MdxJsxFlowElement => write!(f, ".mdx_jsx_flow_element"),
436 Selector::Recursive => write!(f, ".."),
437 Selector::Task => write!(f, ".task"),
438 Selector::Todo => write!(f, ".todo"),
439 Selector::Done => write!(f, ".done"),
440 Selector::Attr(attr) => write!(f, "{}", attr),
441 Selector::Property(property) => property.resolve_with(|s| write!(f, ".\"{}\"", escape_property_key(s))),
442 }
443 }
444}
445
446impl Selector {
447 pub fn is_attribute_selector(&self) -> bool {
449 matches!(self, Selector::Attr(_))
450 }
451
452 pub fn name(&self) -> String {
454 self.to_string().trim_start_matches('.').to_string()
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use crate::{
461 ArenaId, Position, Range, Token, TokenKind,
462 selector::{AttrKind, Selector, UnknownSelector},
463 };
464 use rstest::rstest;
465 use smol_str::SmolStr;
466
467 #[rstest]
468 #[case::heading(".h", Selector::Heading(None), ".h")]
470 #[case::heading_h1(".h1", Selector::Heading(Some(1)), ".h1")]
471 #[case::heading_h2(".h2", Selector::Heading(Some(2)), ".h2")]
472 #[case::heading_h3(".h3", Selector::Heading(Some(3)), ".h3")]
473 #[case::heading_h4(".h4", Selector::Heading(Some(4)), ".h4")]
474 #[case::heading_h5(".h5", Selector::Heading(Some(5)), ".h5")]
475 #[case::heading_h6(".h6", Selector::Heading(Some(6)), ".h6")]
476 #[case::blockquote(".blockquote", Selector::Blockquote, ".blockquote")]
478 #[case::blockquote_alias(".>", Selector::Blockquote, ".blockquote")]
479 #[case::footnote(".footnote", Selector::Footnote, ".footnote")]
481 #[case::footnote_alias(".^", Selector::Footnote, ".footnote")]
482 #[case::mdx_jsx_flow_element(".mdx_jsx_flow_element", Selector::MdxJsxFlowElement, ".mdx_jsx_flow_element")]
484 #[case::mdx_jsx_flow_element_alias(".<", Selector::MdxJsxFlowElement, ".mdx_jsx_flow_element")]
485 #[case::emphasis(".emphasis", Selector::Emphasis, ".emphasis")]
487 #[case::emphasis_alias(".**", Selector::Emphasis, ".emphasis")]
488 #[case::math(".math", Selector::Math, ".math")]
490 #[case::math_alias(".$$", Selector::Math, ".math")]
491 #[case::horizontal_rule(".horizontal_rule", Selector::HorizontalRule, ".horizontal_rule")]
493 #[case::horizontal_rule_alias_hr(".hr", Selector::HorizontalRule, ".horizontal_rule")]
494 #[case::horizontal_rule_alias_dash(".---", Selector::HorizontalRule, ".horizontal_rule")]
495 #[case::horizontal_rule_alias_star(".***", Selector::HorizontalRule, ".horizontal_rule")]
496 #[case::horizontal_rule_alias_underscore(".___", Selector::HorizontalRule, ".horizontal_rule")]
497 #[case::mdx_text_expression(".mdx_text_expression", Selector::MdxTextExpression, ".mdx_text_expression")]
499 #[case::mdx_text_expression_alias(".{}", Selector::MdxTextExpression, ".mdx_text_expression")]
500 #[case::footnote_ref(".footnote_ref", Selector::FootnoteRef, ".footnote_ref")]
502 #[case::footnote_ref_alias(".[^]", Selector::FootnoteRef, ".footnote_ref")]
503 #[case::definition(".definition", Selector::Definition, ".definition")]
505 #[case::break_selector(".break", Selector::Break, ".break")]
507 #[case::break_alias_br(".br", Selector::Break, ".break")]
508 #[case::delete(".delete", Selector::Delete, ".delete")]
510 #[case::html(".html", Selector::Html, ".html")]
512 #[case::html_alias(".<>", Selector::Html, ".html")]
513 #[case::image(".image", Selector::Image, ".image")]
515 #[case::image_ref(".image_ref", Selector::ImageRef, ".image_ref")]
517 #[case::code_inline(".code_inline", Selector::InlineCode, ".code_inline")]
519 #[case::inline_code_alias(".inline_code", Selector::InlineCode, ".code_inline")]
520 #[case::math_inline(".math_inline", Selector::InlineMath, ".math_inline")]
522 #[case::inline_math_alias(".inline_math", Selector::InlineMath, ".math_inline")]
523 #[case::link(".link", Selector::Link, ".link")]
525 #[case::link_ref(".link_ref", Selector::LinkRef, ".link_ref")]
527 #[case::wikilink(".wikilink", Selector::WikiLink, ".wikilink")]
529 #[case::list(".list", Selector::List(None, None), ".list")]
531 #[case::list_bracket(".[]", Selector::List(None, None), ".list")]
532 #[case::list_alias_li(".li", Selector::List(None, None), ".list")]
533 #[case::list_with_index(".[1]", Selector::List(Some(1), None), ".[1]")]
534 #[case::task(".task", Selector::Task, ".task")]
536 #[case::task(".todo", Selector::Todo, ".todo")]
537 #[case::task(".done", Selector::Done, ".done")]
538 #[case::toml(".toml", Selector::Toml, ".toml")]
540 #[case::strong(".strong", Selector::Strong, ".strong")]
542 #[case::yaml(".yaml", Selector::Yaml, ".yaml")]
544 #[case::code(".code", Selector::Code, ".code")]
546 #[case::code_block_alias(".code_block", Selector::Code, ".code")]
547 #[case::mdx_js_esm(".mdx_js_esm", Selector::MdxJsEsm, ".mdx_js_esm")]
549 #[case::mdx_jsx_text_element(".mdx_jsx_text_element", Selector::MdxJsxTextElement, ".mdx_jsx_text_element")]
551 #[case::mdx_flow_expression(".mdx_flow_expression", Selector::MdxFlowExpression, ".mdx_flow_expression")]
553 #[case::text(".text", Selector::Text, ".text")]
555 #[case::text_alias_p(".p", Selector::Text, ".text")]
556 #[case::text_alias_paragraph(".paragraph", Selector::Text, ".text")]
557 #[case::table(".table", Selector::Table(None, None), ".table")]
559 #[case::table_bracket(".[][]", Selector::Table(None, None), ".table")]
560 #[case::table_row_any(".[1][]", Selector::Table(Some(1), None), ".[1][]")]
561 #[case::table_row_col(".[1][2]", Selector::Table(Some(1), Some(2)), ".[1][2]")]
562 #[case::table_any_col(".[][2]", Selector::Table(None, Some(2)), ".[][2]")]
563 #[case::table_align(".table_align", Selector::TableAlign, ".table_align")]
565 #[case::recursive("..", Selector::Recursive, "..")]
567 #[case::attr_value(".value", Selector::Attr(AttrKind::Value), ".value")]
569 #[case::attr_values(".values", Selector::Attr(AttrKind::Values), ".values")]
570 #[case::attr_children(".children", Selector::Attr(AttrKind::Children), ".children")]
571 #[case::attr_lang(".lang", Selector::Attr(AttrKind::Lang), ".lang")]
573 #[case::attr_meta(".meta", Selector::Attr(AttrKind::Meta), ".meta")]
574 #[case::attr_fence(".fence", Selector::Attr(AttrKind::Fence), ".fence")]
575 #[case::attr_url(".url", Selector::Attr(AttrKind::Url), ".url")]
577 #[case::attr_alt(".alt", Selector::Attr(AttrKind::Alt), ".alt")]
578 #[case::attr_title(".title", Selector::Attr(AttrKind::Title), ".title")]
579 #[case::attr_ident(".ident", Selector::Attr(AttrKind::Ident), ".ident")]
581 #[case::attr_label(".label", Selector::Attr(AttrKind::Label), ".label")]
582 #[case::attr_depth(".depth", Selector::Attr(AttrKind::Depth), ".depth")]
584 #[case::attr_level(".level", Selector::Attr(AttrKind::Level), ".level")]
585 #[case::attr_index(".index", Selector::Attr(AttrKind::Index), ".index")]
587 #[case::attr_ordered(".ordered", Selector::Attr(AttrKind::Ordered), ".ordered")]
588 #[case::attr_checked(".checked", Selector::Attr(AttrKind::Checked), ".checked")]
589 #[case::attr_column(".column", Selector::Attr(AttrKind::Column), ".column")]
591 #[case::attr_row(".row", Selector::Attr(AttrKind::Row), ".row")]
592 #[case::attr_align(".align", Selector::Attr(AttrKind::Align), ".align")]
594 #[case::attr_name(".name", Selector::Attr(AttrKind::Name), ".name")]
596 #[case::attr_line(".line", Selector::Attr(AttrKind::Line), ".line")]
598 #[case::attr_end_line(".end_line", Selector::Attr(AttrKind::EndLine), ".end_line")]
599 #[case::property_quoted_h1(".\"h1\"", Selector::Property("h1".into()), ".\"h1\"")]
601 #[case::property_quoted_url(".\"url\"", Selector::Property("url".into()), ".\"url\"")]
602 #[case::property_quoted_with_space(".\"my key\"", Selector::Property("my key".into()), ".\"my key\"")]
603 #[case::property_quoted_escaped_quote(".\"my\\\"key\"", Selector::Property("my\"key".into()), ".\"my\\\"key\"")]
604 #[case::property_quoted_escaped_backslash(".\"my\\\\key\"", Selector::Property("my\\key".into()), ".\"my\\\\key\"")]
605 #[case::property_quoted_empty(".\"\"", Selector::Property("".into()), ".\"\"")]
606 fn test_selector_try_from_and_display(
607 #[case] input: &str,
608 #[case] expected_selector: Selector,
609 #[case] expected_display: &str,
610 ) {
611 let selector = Selector::try_from(&Token {
613 kind: TokenKind::Selector(SmolStr::new(input)),
614 range: Range {
615 start: Position::new(0, 0),
616 end: Position::new(0, 0),
617 },
618 module_id: ArenaId::new(0),
619 })
620 .expect("Should parse valid selector");
621 assert_eq!(selector, expected_selector);
622
623 assert_eq!(selector.to_string(), expected_display);
625 }
626
627 #[rstest]
628 #[case(".")]
629 #[case(".mykey")]
630 #[case(".my_key")]
631 #[case(".unknown")]
632 #[case(".hedaing")]
633 fn test_selector_try_from_invalid(#[case] input: &str) {
634 let token = Token {
635 kind: TokenKind::Selector(SmolStr::new(input)),
636 range: Range {
637 start: Position::new(0, 0),
638 end: Position::new(0, 0),
639 },
640 module_id: ArenaId::new(0),
641 };
642 let result = Selector::try_from(&token);
643 assert!(result.is_err());
644 if let Err(e) = result {
645 assert_eq!(e, UnknownSelector(token));
646 }
647 }
648}