1use crate::Problem;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct Pos {
8 pub line: u32,
10 pub col: u32,
12}
13
14#[derive(Debug, Clone, PartialEq)]
16pub struct File {
17 pub imports: Vec<Import>,
19 pub root: Element,
21 pub next_id: u32,
24}
25
26#[derive(Debug, Clone, PartialEq)]
29pub struct Import {
30 pub name: String,
32 pub path: String,
34 pub pos: Pos,
36}
37
38#[derive(Debug, Clone, PartialEq)]
40pub struct Element {
41 pub id: u32,
45 pub name: String,
47 pub attrs: Vec<Attr>,
49 pub children: Vec<Child>,
51 pub pos: Pos,
53}
54
55#[derive(Debug, Clone, PartialEq)]
57pub enum Child {
58 Element(Element),
60 Text(Vec<TextPart>, Pos),
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub enum TextPart {
68 Literal(String),
70 Prop(String),
72 Theme(String, Pos),
75}
76
77#[derive(Debug, Clone, PartialEq)]
79pub struct Attr {
80 pub name: String,
82 pub value: Value,
84 pub pos: Pos,
86}
87
88#[derive(Debug, Clone, PartialEq)]
90pub enum Value {
91 Str(String, Pos),
94 Num(f64),
96 Bool(bool),
98 Array(Vec<Value>),
100 Object(Vec<(String, Value)>),
102 Prop(String),
104 Theme(String, Pos),
107 Themed {
113 light: String,
114 dark: String,
115 written: String,
116 },
117}
118
119pub fn parse(source: &str) -> Result<File, Problem> {
121 let mut p = Parser {
122 chars: source.chars().collect(),
123 at: 0,
124 line: 1,
125 col: 1,
126 depth: 0,
127 };
128 let mut imports = Vec::new();
129 p.skip_space();
130 while p.peek_word("import") {
131 let pos = p.pos();
132 p.expect_word("import")?;
133 p.skip_space();
134 let name = p.ident()?;
135 p.skip_space();
136 p.expect_word("from")?;
137 p.skip_space();
138 let path = p.string()?;
139 imports.push(Import { name, path, pos });
140 p.skip_space();
141 }
142 if p.peek() != Some('<') {
143 return Err(p.problem("expected an import or the root element"));
144 }
145 let root = p.element()?;
146 p.skip_space();
147 if p.peek().is_some() {
148 return Err(p.problem("expected nothing after the root element"));
149 }
150 let mut root = root;
151 let mut next_id = 0;
152 number_all(&mut root, &mut next_id);
153 Ok(File {
154 imports,
155 root,
156 next_id,
157 })
158}
159
160pub(crate) fn number_all(el: &mut Element, next: &mut u32) {
162 el.id = *next;
163 *next += 1;
164 for child in &mut el.children {
165 if let Child::Element(e) = child {
166 number_all(e, next);
167 }
168 }
169}
170
171struct Parser {
173 chars: Vec<char>,
175 at: usize,
177 line: u32,
179 col: u32,
181 depth: usize,
183}
184
185pub const MAX_DEPTH: usize = 256;
188
189pub const THEME: &str = "theme";
192
193pub const MAX_NUMBER: f64 = 1_000_000.0;
196
197impl Parser {
198 fn pos(&self) -> Pos {
200 Pos {
201 line: self.line,
202 col: self.col,
203 }
204 }
205
206 fn problem(&self, message: &str) -> Problem {
209 Problem {
210 file: String::new(),
211 pos: self.pos(),
212 message: message.to_string(),
213 }
214 }
215
216 fn peek(&self) -> Option<char> {
218 self.chars.get(self.at).copied()
219 }
220
221 fn peek_at(&self, n: usize) -> Option<char> {
223 self.chars.get(self.at + n).copied()
224 }
225
226 fn bump(&mut self) -> Option<char> {
229 let c = self.peek()?;
230 self.at += 1;
231 if c == '\n' {
232 self.line += 1;
233 self.col = 1;
234 } else {
235 self.col += 1;
236 }
237 Some(c)
238 }
239
240 fn skip_space(&mut self) {
242 loop {
243 match self.peek() {
244 Some(c) if c.is_whitespace() => {
245 self.bump();
246 }
247 Some('/') if self.peek_at(1) == Some('/') => {
248 while !matches!(self.peek(), None | Some('\n')) {
249 self.bump();
250 }
251 }
252 _ => return,
253 }
254 }
255 }
256
257 fn peek_word(&self, word: &str) -> bool {
259 word.chars()
260 .enumerate()
261 .all(|(i, c)| self.peek_at(i) == Some(c))
262 && !self
263 .peek_at(word.len())
264 .is_some_and(|c| c.is_alphanumeric() || c == '_')
265 }
266
267 fn expect_word(&mut self, word: &str) -> Result<(), Problem> {
269 if !self.peek_word(word) {
270 return Err(self.problem(&format!("expected `{word}`")));
271 }
272 for _ in 0..word.len() {
273 self.bump();
274 }
275 Ok(())
276 }
277
278 fn expect(&mut self, c: char) -> Result<(), Problem> {
280 if self.peek() != Some(c) {
281 return Err(self.problem(&format!("expected `{c}`")));
282 }
283 self.bump();
284 Ok(())
285 }
286
287 fn ident(&mut self) -> Result<String, Problem> {
290 let mut s = String::new();
291 while let Some(c) = self.peek() {
292 if c.is_alphanumeric() || c == '_' || (c == '-' && !s.is_empty()) {
293 s.push(c);
294 self.bump();
295 } else {
296 break;
297 }
298 }
299 if s.is_empty() || s.starts_with(|c: char| c.is_ascii_digit()) {
300 return Err(self.problem("expected a name"));
301 }
302 Ok(s)
303 }
304
305 fn deeper(&mut self) -> Result<(), Problem> {
307 self.depth += 1;
308 if self.depth > MAX_DEPTH {
309 return Err(self.problem(&format!("nested more than {MAX_DEPTH} deep")));
310 }
311 Ok(())
312 }
313
314 fn string(&mut self) -> Result<String, Problem> {
317 let quote = match self.peek() {
318 Some(q @ ('"' | '\'')) => q,
319 _ => return Err(self.problem("expected a string")),
320 };
321 let open = self.problem("unterminated string");
323 self.bump();
324 let mut s = String::new();
325 loop {
326 match self.bump() {
327 None | Some('\n') => return Err(open),
328 Some(c) if c == quote => return Ok(s),
329 Some(c) => s.push(c),
330 }
331 }
332 }
333
334 fn element(&mut self) -> Result<Element, Problem> {
336 let pos = self.pos();
337 self.deeper()?;
338 let element = self.element_inner(pos);
339 self.depth -= 1;
340 element
341 }
342
343 fn element_inner(&mut self, pos: Pos) -> Result<Element, Problem> {
346 self.expect('<')?;
347 let name = self.ident()?;
348 let mut attrs = Vec::new();
349 loop {
350 self.skip_space();
351 match self.peek() {
352 Some('/') => {
353 self.bump();
354 self.expect('>')?;
355 return Ok(Element {
356 id: 0,
357 name,
358 attrs,
359 children: Vec::new(),
360 pos,
361 });
362 }
363 Some('>') => {
364 self.bump();
365 break;
366 }
367 _ => {
368 let pos = self.pos();
369 let attr = self.ident()?;
370 self.skip_space();
371 let value = if self.peek() == Some('=') {
372 self.bump();
373 self.skip_space();
374 self.attr_value()?
375 } else {
376 Value::Bool(true)
377 };
378 attrs.push(Attr {
379 name: attr,
380 value,
381 pos,
382 });
383 }
384 }
385 }
386 let children = self.children(&name)?;
387 Ok(Element {
388 id: 0,
389 name,
390 attrs,
391 children,
392 pos,
393 })
394 }
395
396 fn children(&mut self, parent: &str) -> Result<Vec<Child>, Problem> {
399 let mut children = Vec::new();
400 let mut text: Vec<TextPart> = Vec::new();
401 let mut text_pos = self.pos();
402 let mut literal = String::new();
403 loop {
404 match self.peek() {
405 None => return Err(self.problem(&format!("`<{parent}>` is never closed"))),
406 Some('<') => {
407 flush_text(&mut literal, &mut text, &mut children, text_pos);
408 if self.peek_at(1) == Some('/') {
409 self.bump();
410 self.bump();
411 let name = self.ident()?;
412 if name != parent {
413 return Err(self.problem(&format!("`</{name}>` closes `<{parent}>`")));
414 }
415 self.skip_space();
416 self.expect('>')?;
417 return Ok(children);
418 }
419 children.push(Child::Element(self.element()?));
420 text_pos = self.pos();
421 }
422 Some('{') => {
423 if text.is_empty() && literal.trim().is_empty() {
424 text_pos = self.pos();
425 }
426 if !literal.is_empty() {
427 text.push(TextPart::Literal(std::mem::take(&mut literal)));
428 }
429 self.bump();
430 self.skip_space();
431 let pos = self.pos();
432 let name = self.ident()?;
433 let part = if name == THEME && self.peek() == Some('.') {
434 self.bump();
435 TextPart::Theme(self.ident()?, pos)
436 } else {
437 TextPart::Prop(name)
438 };
439 self.skip_space();
440 self.expect('}')?;
441 text.push(part);
442 }
443 Some(c) => {
444 if text.is_empty() && literal.trim().is_empty() && !c.is_whitespace() {
445 text_pos = self.pos();
446 }
447 literal.push(c);
448 self.bump();
449 }
450 }
451 }
452 }
453
454 fn attr_value(&mut self) -> Result<Value, Problem> {
456 match self.peek() {
457 Some('"' | '\'') => {
458 let pos = self.pos();
459 Ok(Value::Str(self.string()?, pos))
460 }
461 Some('{') => {
462 self.bump();
463 self.skip_space();
464 let value = self.value()?;
465 self.skip_space();
466 self.expect('}')?;
467 Ok(value)
468 }
469 _ => Err(self.problem("expected a string or a value in braces")),
470 }
471 }
472
473 fn value(&mut self) -> Result<Value, Problem> {
475 let nests = matches!(self.peek(), Some('[' | '{'));
477 if nests {
478 self.deeper()?;
479 }
480 let value = self.value_inner();
481 if nests {
482 self.depth -= 1;
483 }
484 value
485 }
486
487 fn value_inner(&mut self) -> Result<Value, Problem> {
490 match self.peek() {
491 Some('"' | '\'') => {
492 let pos = self.pos();
493 Ok(Value::Str(self.string()?, pos))
494 }
495 Some('[') => {
496 self.bump();
497 let mut items = Vec::new();
498 loop {
499 self.skip_space();
500 if self.peek() == Some(']') {
501 self.bump();
502 return Ok(Value::Array(items));
503 }
504 items.push(self.value()?);
505 self.skip_space();
506 match self.peek() {
507 Some(',') => {
508 self.bump();
509 }
510 Some(']') => {}
511 _ => return Err(self.problem("expected `,` or `]`")),
512 }
513 }
514 }
515 Some('{') => {
516 self.bump();
517 let mut fields = Vec::new();
518 loop {
519 self.skip_space();
520 if self.peek() == Some('}') {
521 self.bump();
522 return Ok(Value::Object(fields));
523 }
524 let key = self.ident()?;
525 self.skip_space();
526 self.expect(':')?;
527 self.skip_space();
528 fields.push((key, self.value()?));
529 self.skip_space();
530 match self.peek() {
531 Some(',') => {
532 self.bump();
533 }
534 Some('}') => {}
535 _ => return Err(self.problem("expected `,` or `}`")),
536 }
537 }
538 }
539 Some(c) if c.is_ascii_digit() || c == '-' || c == '.' => {
540 let mut s = String::new();
541 while let Some(c) = self.peek() {
542 if c.is_ascii_digit() || c == '-' || c == '.' {
543 s.push(c);
544 self.bump();
545 } else {
546 break;
547 }
548 }
549 number(&s)
550 .map(Value::Num)
551 .map_err(|message| self.problem(&message))
552 }
553 _ => {
554 let pos = self.pos();
555 let name = self.ident()?;
556 Ok(match name.as_str() {
557 "true" => Value::Bool(true),
558 "false" => Value::Bool(false),
559 THEME if self.peek() == Some('.') => {
560 self.bump();
561 Value::Theme(self.ident()?, pos)
562 }
563 _ => Value::Prop(name),
564 })
565 }
566 }
567 }
568}
569
570pub fn number(s: &str) -> Result<f64, String> {
574 if !s
575 .chars()
576 .all(|c| c.is_ascii_digit() || c == '-' || c == '.')
577 {
578 return Err(format!("`{s}` is not a number"));
579 }
580 in_range(
581 s,
582 s.parse::<f64>()
583 .map_err(|_| format!("`{s}` is not a number"))?,
584 )
585}
586
587pub fn in_range(s: &str, n: f64) -> Result<f64, String> {
589 if n.abs() <= MAX_NUMBER {
590 Ok(n)
591 } else if n.is_nan() {
592 Err(format!("`{s}` is not a number"))
593 } else if n < 0.0 {
594 Err(format!(
595 "`{s}` is too small: numbers go down to -{MAX_NUMBER}"
596 ))
597 } else {
598 Err(format!("`{s}` is too large: numbers go up to {MAX_NUMBER}"))
599 }
600}
601
602fn flush_text(literal: &mut String, text: &mut Vec<TextPart>, children: &mut Vec<Child>, pos: Pos) {
606 if !literal.is_empty() {
607 text.push(TextPart::Literal(std::mem::take(literal)));
608 }
609 let mut parts = Vec::new();
610 for part in text.drain(..) {
611 match part {
612 TextPart::Literal(s) => {
613 let s = collapse(&s);
614 if !s.is_empty() {
615 parts.push(TextPart::Literal(s));
616 }
617 }
618 prop => parts.push(prop),
619 }
620 }
621 if !parts.is_empty() {
622 children.push(Child::Text(parts, pos));
623 }
624}
625
626fn collapse(s: &str) -> String {
629 let lines: Vec<&str> = s.split('\n').collect();
630 if lines.len() == 1 {
631 return s.to_string();
632 }
633 lines
634 .iter()
635 .map(|l| l.trim())
636 .filter(|l| !l.is_empty())
637 .collect::<Vec<_>>()
638 .join(" ")
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644
645 #[test]
646 fn imports_attributes_and_text_with_props() {
647 let file = parse(
648 r##"// a comment
649import Button from "./button.design"
650
651<Frame width={390} padding={[12, 20]} shadow={{ y: 4, color: "#0002" }} clip>
652 <Text size={16}>Hi, {name}</Text>
653 <Button label="Pay" />
654</Frame>"##,
655 )
656 .unwrap();
657 assert_eq!(file.imports[0].name, "Button");
658 assert_eq!(file.imports[0].path, "./button.design");
659 let root = &file.root;
660 assert_eq!(root.attrs[0].value, Value::Num(390.0));
661 assert_eq!(
662 root.attrs[1].value,
663 Value::Array(vec![Value::Num(12.0), Value::Num(20.0)])
664 );
665 assert!(matches!(root.attrs[2].value, Value::Object(ref f) if f.len() == 2));
666 assert_eq!(root.attrs[3].value, Value::Bool(true));
667 let Child::Element(text) = &root.children[0] else {
668 panic!()
669 };
670 assert_eq!(
671 text.children,
672 vec![Child::Text(
673 vec![
674 TextPart::Literal("Hi, ".into()),
675 TextPart::Prop("name".into())
676 ],
677 Pos { line: 5, col: 19 }
678 )]
679 );
680 assert_eq!(root.children.len(), 2);
681 }
682
683 #[test]
684 fn a_problem_has_its_place() {
685 let problem = parse("<Frame>\n <Text>hi</Frame>").unwrap_err();
686 assert_eq!(problem.pos, Pos { line: 2, col: 18 });
687 assert_eq!(problem.message, "`</Frame>` closes `<Text>`");
688 }
689
690 #[test]
691 fn every_syntax_error_has_its_place() {
692 let cases = [
693 ("", "1:1: expected an import or the root element"),
694 (
695 "<Frame />\n<Frame />",
696 "2:1: expected nothing after the root element",
697 ),
698 ("import \"./a.design\"", "1:8: expected a name"),
699 ("import A \"./a.design\"", "1:10: expected `from`"),
700 ("import A from ./a.design", "1:15: expected a string"),
701 ("<Frame name=\"x\n/>", "1:13: unterminated string"),
702 (
703 "<Frame>\n <Text>hi</Text>",
704 "2:18: `<Frame>` is never closed",
705 ),
706 (
707 "<Frame gap=4 />",
708 "1:12: expected a string or a value in braces",
709 ),
710 ("<Frame padding={[1 2]} />", "1:20: expected `,` or `]`"),
711 ("<Frame shadow={{ y 4 }} />", "1:20: expected `:`"),
712 (
713 "<Frame shadow={{ y: 4 x: 1 }} />",
714 "1:23: expected `,` or `}`",
715 ),
716 ("<Frame gap={1.2.3} />", "1:18: `1.2.3` is not a number"),
717 ("<Frame gap={4 />", "1:15: expected `}`"),
718 ("<Frame><Text>{ }</Text></Frame>", "1:16: expected a name"),
719 (
720 "<Frame><Text>hi</Frame>",
721 "1:23: `</Frame>` closes `<Text>`",
722 ),
723 ("<Frame / >", "1:9: expected `>`"),
724 ];
725 for (source, expected) in cases {
726 let problem = parse(source).unwrap_err();
727 assert_eq!(
728 format!(
729 "{}:{}: {}",
730 problem.pos.line, problem.pos.col, problem.message
731 ),
732 expected,
733 "{source:?}"
734 );
735 }
736 }
737
738 #[test]
739 fn strings_bare_attributes_and_names_follow_jsx() {
740 let file = parse(r#"<Frame name='it\s "quoted"' aria-label="a\nb" clip data-x={false} />"#)
741 .unwrap();
742 let attrs = &file.root.attrs;
743 assert_eq!(
745 attrs[0].value,
746 Value::Str(r#"it\s "quoted""#.into(), Pos { line: 1, col: 13 })
747 );
748 assert_eq!(attrs[1].name, "aria-label");
749 assert_eq!(
750 attrs[1].value,
751 Value::Str(r"a\nb".into(), Pos { line: 1, col: 40 })
752 );
753 assert_eq!(attrs[2].value, Value::Bool(true));
755 assert_eq!(attrs[3].name, "data-x");
756 assert_eq!(attrs[3].value, Value::Bool(false));
757 }
758
759 #[test]
760 fn nesting_and_numbers_have_limits() {
761 let deep = "<Frame>".repeat(MAX_DEPTH + 1) + &"</Frame>".repeat(MAX_DEPTH + 1);
762 let problem = parse(&deep).unwrap_err();
763 assert_eq!(
764 problem.message,
765 format!("nested more than {MAX_DEPTH} deep")
766 );
767 let deep = format!("<Frame gap={{{}}} />", "[".repeat(100_000));
768 let problem = parse(&deep).unwrap_err();
769 assert_eq!(
770 problem.message,
771 format!("nested more than {MAX_DEPTH} deep")
772 );
773 let problem = parse(&format!("<Frame width={{{}}} />", "9".repeat(400))).unwrap_err();
774 assert!(
775 problem
776 .message
777 .ends_with("is too large: numbers go up to 1000000"),
778 "{}",
779 problem.message
780 );
781 assert!(parse("<Frame width={1000000} />").is_ok());
782 let fine = "<Frame>".repeat(MAX_DEPTH) + &"</Frame>".repeat(MAX_DEPTH);
783 assert!(parse(&fine).is_ok());
784 }
785
786 #[test]
787 fn arrays_and_objects_count_toward_the_limit_as_elements_do() {
788 let at = |n: usize| format!("<Frame gap={{{}1{}}} />", "[".repeat(n), "]".repeat(n));
790 assert!(parse(&at(MAX_DEPTH - 1)).is_ok());
791 assert_eq!(
792 parse(&at(MAX_DEPTH)).unwrap_err().message,
793 format!("nested more than {MAX_DEPTH} deep")
794 );
795 let objects = |n: usize| {
796 format!(
797 "<Frame shadow={{{}1{}}} />",
798 "{ a: ".repeat(n),
799 "}".repeat(n)
800 )
801 };
802 assert!(parse(&objects(MAX_DEPTH - 1)).is_ok());
803 assert!(parse(&objects(MAX_DEPTH)).is_err());
804 }
805
806 #[test]
807 fn a_number_below_the_limit_is_too_small() {
808 assert_eq!(
809 parse("<Frame x={-1000001} />").unwrap_err().message,
810 "`-1000001` is too small: numbers go down to -1000000"
811 );
812 assert!(parse("<Frame x={-1000000} />").is_ok());
813 }
814
815 #[test]
816 fn a_theme_color_is_a_value_with_its_place() {
817 let file = parse(
818 "<Frame fill={theme.surface} shadow={{ color: theme.shadow-dark }}>\n <Text>{theme.text}</Text>\n</Frame>",
819 )
820 .unwrap();
821 let root = &file.root;
822 assert_eq!(
823 root.attrs[0].value,
824 Value::Theme("surface".into(), Pos { line: 1, col: 14 })
825 );
826 assert_eq!(
827 root.attrs[1].value,
828 Value::Object(vec![(
829 "color".into(),
830 Value::Theme("shadow-dark".into(), Pos { line: 1, col: 46 })
831 )])
832 );
833 let Child::Element(text) = &root.children[0] else {
834 panic!()
835 };
836 assert_eq!(
837 text.children,
838 vec![Child::Text(
839 vec![TextPart::Theme("text".into(), Pos { line: 2, col: 10 })],
840 Pos { line: 2, col: 9 }
841 )]
842 );
843 assert_eq!(
845 parse("<Frame fill={theme} />").unwrap().root.attrs[0].value,
846 Value::Prop("theme".into())
847 );
848 assert_eq!(
849 parse("<Frame fill={theme.} />").unwrap_err().message,
850 "expected a name"
851 );
852 }
853
854 #[test]
855 fn text_follows_jsx_whitespace() {
856 let file = parse("<Text>\n Free shipping\n on orders\n </Text>").unwrap();
857 assert_eq!(
858 file.root.children,
859 vec![Child::Text(
860 vec![TextPart::Literal("Free shipping on orders".into())],
861 Pos { line: 2, col: 5 }
862 )]
863 );
864 }
865}