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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use debversion::Version;
use std::iter::Peekable;
use std::str::Chars;

/// Let's start with defining all kinds of tokens and
/// composite nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(non_camel_case_types)]
#[repr(u16)]
pub enum SyntaxKind {
    IDENT = 0, // package name
    COLON,     // :
    PIPE,
    COMMA,      // ,
    L_PARENS,   // (
    R_PARENS,   // )
    L_BRACKET,  // [
    R_BRACKET,  // ]
    NOT,        // !
    L_ANGLE,    // <
    R_ANGLE,    // >
    EQUAL,      // =
    WHITESPACE, // whitespace
    COMMENT,    // comments
    DOLLAR,     // $
    L_CURLY,
    R_CURLY,
    ERROR, // as well as errors

    // composite nodes
    ROOT,       // The entire file
    ENTRY,      // A single entry
    RELATION,   // An alternative in a dependency
    VERSION,    // A version constraint
    CONSTRAINT, // (">=", "<=", "=", ">>", "<<")
    ARCHITECTURES,
    PROFILES,
    SUBSTVAR,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum VersionConstraint {
    GreaterThanEqual, // >=
    LessThanEqual,    // <=
    Equal,            // =
    GreaterThan,      // >>
    LessThan,         // <<
}

impl std::str::FromStr for VersionConstraint {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            ">=" => Ok(VersionConstraint::GreaterThanEqual),
            "<=" => Ok(VersionConstraint::LessThanEqual),
            "=" => Ok(VersionConstraint::Equal),
            ">>" => Ok(VersionConstraint::GreaterThan),
            "<<" => Ok(VersionConstraint::LessThan),
            _ => Err(ParseError(vec![format!(
                "Invalid version constraint: {}",
                s
            )])),
        }
    }
}

impl ToString for VersionConstraint {
    fn to_string(&self) -> String {
        match self {
            VersionConstraint::GreaterThanEqual => ">=".to_owned(),
            VersionConstraint::LessThanEqual => "<=".to_owned(),
            VersionConstraint::Equal => "=".to_owned(),
            VersionConstraint::GreaterThan => ">>".to_owned(),
            VersionConstraint::LessThan => "<<".to_owned(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BuildProfile {
    Enabled(String),
    Disabled(String),
}

impl ToString for BuildProfile {
    fn to_string(&self) -> String {
        match self {
            BuildProfile::Enabled(s) => s.clone(),
            BuildProfile::Disabled(s) => format!("!{}", s),
        }
    }
}

impl std::str::FromStr for BuildProfile {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(s) = s.strip_prefix('!') {
            Ok(BuildProfile::Disabled(s.to_string()))
        } else {
            Ok(BuildProfile::Enabled(s.to_string()))
        }
    }
}

use SyntaxKind::*;

/// Convert our `SyntaxKind` into the rowan `SyntaxKind`.
impl From<SyntaxKind> for rowan::SyntaxKind {
    fn from(kind: SyntaxKind) -> Self {
        Self(kind as u16)
    }
}

pub struct Lexer<'a> {
    input: Peekable<Chars<'a>>,
}

impl<'a> Lexer<'a> {
    pub fn new(input: &'a str) -> Self {
        Lexer {
            input: input.chars().peekable(),
        }
    }

    fn is_whitespace(c: char) -> bool {
        c == ' ' || c == '\t' || c == '\r' || c == '\n'
    }

    fn is_valid_key_char(c: char) -> bool {
        c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '+' || c == '*'
    }

    fn read_while<F>(&mut self, predicate: F) -> String
    where
        F: Fn(char) -> bool,
    {
        let mut result = String::new();
        while let Some(&c) = self.input.peek() {
            if predicate(c) {
                result.push(c);
                self.input.next();
            } else {
                break;
            }
        }
        result
    }

    fn next_token(&mut self) -> Option<(SyntaxKind, String)> {
        if let Some(&c) = self.input.peek() {
            match c {
                ':' => {
                    self.input.next();
                    Some((SyntaxKind::COLON, ":".to_owned()))
                }
                '|' => {
                    self.input.next();
                    Some((SyntaxKind::PIPE, "|".to_owned()))
                }
                ',' => {
                    self.input.next();
                    Some((SyntaxKind::COMMA, ",".to_owned()))
                }
                '(' => {
                    self.input.next();
                    Some((SyntaxKind::L_PARENS, "(".to_owned()))
                }
                ')' => {
                    self.input.next();
                    Some((SyntaxKind::R_PARENS, ")".to_owned()))
                }
                '[' => {
                    self.input.next();
                    Some((SyntaxKind::L_BRACKET, "[".to_owned()))
                }
                ']' => {
                    self.input.next();
                    Some((SyntaxKind::R_BRACKET, "]".to_owned()))
                }
                '!' => {
                    self.input.next();
                    Some((SyntaxKind::NOT, "!".to_owned()))
                }
                '$' => {
                    self.input.next();
                    Some((SyntaxKind::DOLLAR, "$".to_owned()))
                }
                '{' => {
                    self.input.next();
                    Some((SyntaxKind::L_CURLY, "{".to_owned()))
                }
                '}' => {
                    self.input.next();
                    Some((SyntaxKind::R_CURLY, "}".to_owned()))
                }
                '<' => {
                    self.input.next();
                    Some((SyntaxKind::L_ANGLE, "<".to_owned()))
                }
                '>' => {
                    self.input.next();
                    Some((SyntaxKind::R_ANGLE, ">".to_owned()))
                }
                '=' => {
                    self.input.next();
                    Some((SyntaxKind::EQUAL, "=".to_owned()))
                }
                _ if Self::is_whitespace(c) => {
                    let whitespace = self.read_while(Self::is_whitespace);
                    Some((SyntaxKind::WHITESPACE, whitespace))
                }
                '#' => {
                    self.input.next();
                    let comment = self.read_while(|c| c != '\n' && c != '\r');
                    Some((SyntaxKind::COMMENT, format!("#{}", comment)))
                }
                _ if Self::is_valid_key_char(c) => {
                    let key = self.read_while(Self::is_valid_key_char);
                    Some((SyntaxKind::IDENT, key))
                }
                _ => {
                    self.input.next();
                    Some((SyntaxKind::ERROR, c.to_string()))
                }
            }
        } else {
            None
        }
    }
}

impl Iterator for Lexer<'_> {
    type Item = (SyntaxKind, String);

    fn next(&mut self) -> Option<Self::Item> {
        self.next_token()
    }
}

pub(crate) fn lex(input: &str) -> Vec<(SyntaxKind, String)> {
    let mut lexer = Lexer::new(input);
    lexer.by_ref().collect::<Vec<_>>()
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParseError(Vec<String>);

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for err in &self.0 {
            writeln!(f, "{}", err)?;
        }
        Ok(())
    }
}

impl std::error::Error for ParseError {}

/// Second, implementing the `Language` trait teaches rowan to convert between
/// these two SyntaxKind types, allowing for a nicer SyntaxNode API where
/// "kinds" are values from our `enum SyntaxKind`, instead of plain u16 values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Lang {}
impl rowan::Language for Lang {
    type Kind = SyntaxKind;
    fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
        unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) }
    }
    fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
        kind.into()
    }
}

/// GreenNode is an immutable tree, which is cheap to change,
/// but doesn't contain offsets and parent pointers.
use rowan::GreenNode;

/// You can construct GreenNodes by hand, but a builder
/// is helpful for top-down parsers: it maintains a stack
/// of currently in-progress nodes
use rowan::GreenNodeBuilder;

/// The parse results are stored as a "green tree".
/// We'll discuss working with the results later
struct Parse {
    green_node: GreenNode,
    #[allow(unused)]
    errors: Vec<String>,
}

fn parse(text: &str) -> Parse {
    struct Parser {
        /// input tokens, including whitespace,
        /// in *reverse* order.
        tokens: Vec<(SyntaxKind, String)>,
        /// the in-progress tree.
        builder: GreenNodeBuilder<'static>,
        /// the list of syntax errors we've accumulated
        /// so far.
        errors: Vec<String>,
    }

    impl Parser {
        fn parse_substvar(&mut self) {
            self.builder.start_node(SyntaxKind::SUBSTVAR.into());
            self.bump();
            if self.current() != Some(L_CURLY) {
                self.error("expected {");
            } else {
                self.bump();
            }
            loop {
                match self.current() {
                    Some(IDENT) | Some(COLON) => {
                        self.bump();
                    }
                    Some(R_CURLY) => {
                        break;
                    }
                    e => {
                        self.error(format!("unexpected identifier: {:?}", e).as_str());
                    }
                }
            }
            if self.current() != Some(R_CURLY) {
                self.error("expected }");
            } else {
                self.bump();
            }
            self.builder.finish_node();
        }

        fn parse_entry(&mut self) {
            self.skip_ws();
            self.builder.start_node(SyntaxKind::ENTRY.into());
            loop {
                self.parse_relation();
                self.skip_ws();
                match self.current() {
                    Some(COMMA) => {
                        break;
                    }
                    Some(PIPE) => {
                        self.bump();
                        self.skip_ws();
                    }
                    None => {
                        break;
                    }
                    e => {
                        self.builder.start_node(SyntaxKind::ERROR.into());
                        if self.current().is_some() {
                            self.bump();
                        }
                        self.errors
                            .push(format!("Expected comma or pipe, not {:?}", e));
                        self.builder.finish_node();
                    }
                }
            }
            self.builder.finish_node();
        }

        fn error(&mut self, error: &str) {
            self.errors.push(error.to_owned());
            self.builder.start_node(SyntaxKind::ERROR.into());
            if self.current().is_some() {
                self.bump();
            }
            self.builder.finish_node();
        }

        fn parse_relation(&mut self) {
            self.builder.start_node(SyntaxKind::RELATION.into());
            if self.current() == Some(IDENT) {
                self.bump();
            } else {
                self.error("Expected package name");
            }
            self.skip_ws();
            match self.current() {
                Some(COLON) => {
                    self.bump();
                    self.skip_ws();
                    if self.current() == Some(IDENT) {
                        self.bump();
                    } else {
                        self.error("Expected architecture name");
                    }
                    self.skip_ws();
                }
                None | Some(L_PARENS) | Some(L_BRACKET) | Some(PIPE) | Some(COMMA) => {}
                e => {
                    self.error(
                        format!("Expected ':' or '|' or '[' or ',' but got {:?}", e).as_str(),
                    );
                }
            }

            self.skip_ws();

            if self.current() == Some(L_PARENS) {
                self.builder.start_node(VERSION.into());
                self.bump();
                self.skip_ws();

                self.builder.start_node(CONSTRAINT.into());

                while self.current() == Some(L_ANGLE)
                    || self.current() == Some(R_ANGLE)
                    || self.current() == Some(EQUAL)
                {
                    self.bump();
                }

                self.builder.finish_node();

                self.skip_ws();

                if self.current() == Some(IDENT) {
                    self.bump();
                } else {
                    self.error("Expected version");
                }

                if self.current() == Some(R_PARENS) {
                    self.bump();
                } else {
                    self.error("Expected ')'");
                }

                self.builder.finish_node();
            }

            self.skip_ws();

            if self.current() == Some(L_BRACKET) {
                self.builder.start_node(ARCHITECTURES.into());
                self.bump();
                loop {
                    self.skip_ws();
                    match self.current() {
                        Some(NOT) => {
                            self.bump();
                        }
                        Some(IDENT) => {
                            self.bump();
                        }
                        Some(R_BRACKET) => {
                            self.bump();
                            break;
                        }
                        _ => {
                            self.error("Expected architecture name or '!' or ']'");
                        }
                    }
                }
                self.builder.finish_node();
            }
            self.skip_ws();

            while self.current() == Some(L_ANGLE) {
                self.builder.start_node(PROFILES.into());
                self.bump();

                loop {
                    self.skip_ws();
                    match self.current() {
                        Some(IDENT) => {
                            self.bump();
                        }
                        Some(NOT) => {
                            self.bump();
                            self.skip_ws();
                            if self.current() == Some(IDENT) {
                                self.bump();
                            } else {
                                self.error("Expected profile");
                            }
                        }
                        Some(R_ANGLE) => {
                            self.bump();
                            break;
                        }
                        None => {
                            self.error("Expected profile or '>'");
                            break;
                        }
                        _ => {
                            self.error("Expected profile or '!' or '>'");
                        }
                    }
                }

                self.builder.finish_node();

                self.skip_ws();
            }

            self.builder.finish_node();
        }

        fn parse(mut self) -> Parse {
            self.builder.start_node(SyntaxKind::ROOT.into());

            self.skip_ws();

            while self.current().is_some() {
                match self.current() {
                    Some(IDENT) => self.parse_entry(),
                    Some(DOLLAR) => self.parse_substvar(),
                    _ => {
                        self.error("expected $ or identifier");
                    }
                }

                self.skip_ws();
                match self.current() {
                    Some(COMMA) => {
                        self.bump();
                    }
                    None => {
                        break;
                    }
                    _ => {
                        self.error("Expected comma");
                    }
                }
                self.skip_ws();
            }

            self.builder.finish_node();
            // Turn the builder into a GreenNode
            Parse {
                green_node: self.builder.finish(),
                errors: self.errors,
            }
        }
        /// Advance one token, adding it to the current branch of the tree builder.
        fn bump(&mut self) {
            let (kind, text) = self.tokens.pop().unwrap();
            self.builder.token(kind.into(), text.as_str());
        }
        /// Peek at the first unprocessed token
        fn current(&self) -> Option<SyntaxKind> {
            self.tokens.last().map(|(kind, _)| *kind)
        }
        fn skip_ws(&mut self) {
            while self.current() == Some(WHITESPACE) || self.current() == Some(COMMENT) {
                self.bump()
            }
        }
    }

    let mut tokens = lex(text);
    tokens.reverse();
    Parser {
        tokens,
        builder: GreenNodeBuilder::new(),
        errors: Vec::new(),
    }
    .parse()
}

/// To work with the parse results we need a view into the
/// green tree - the Syntax tree.
/// It is also immutable, like a GreenNode,
/// but it contains parent pointers, offsets, and
/// has identity semantics.

type SyntaxNode = rowan::SyntaxNode<Lang>;
#[allow(unused)]
type SyntaxToken = rowan::SyntaxToken<Lang>;
#[allow(unused)]
type SyntaxElement = rowan::NodeOrToken<SyntaxNode, SyntaxToken>;

impl Parse {
    fn syntax(&self) -> SyntaxNode {
        SyntaxNode::new_root(self.green_node.clone())
    }

    fn root(&self) -> Relations {
        Relations::cast(self.syntax()).unwrap()
    }
}

macro_rules! ast_node {
    ($ast:ident, $kind:ident) => {
        #[derive(PartialEq, Eq, Hash)]
        #[repr(transparent)]
        pub struct $ast(SyntaxNode);
        impl $ast {
            #[allow(unused)]
            fn cast(node: SyntaxNode) -> Option<Self> {
                if node.kind() == $kind {
                    Some(Self(node))
                } else {
                    None
                }
            }
        }

        impl ToString for $ast {
            fn to_string(&self) -> String {
                self.0.text().to_string()
            }
        }
    };
}

ast_node!(Relations, ROOT);
ast_node!(Entry, ENTRY);
ast_node!(Relation, RELATION);
ast_node!(Substvar, SUBSTVAR);

impl std::fmt::Debug for Relations {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Relations").finish()
    }
}

impl std::fmt::Debug for Entry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Entry").finish()
    }
}

impl std::fmt::Debug for Relation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Relation").finish()
    }
}

impl Relations {
    pub fn entries(&self) -> impl Iterator<Item = Entry> + '_ {
        self.0.children().filter_map(Entry::cast)
    }

    pub fn substvars(&self) -> impl Iterator<Item = String> + '_ {
        eprintln!("children: {:#?}", self.0.children().collect::<Vec<_>>());
        self.0
            .children()
            .filter_map(Substvar::cast)
            .map(|s| s.to_string())
    }
}

impl Entry {
    pub fn relations(&self) -> impl Iterator<Item = Relation> + '_ {
        self.0.children().filter_map(Relation::cast)
    }
}

impl Relation {
    pub fn name(&self) -> String {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) if token.kind() == IDENT => Some(token),
                _ => None,
            })
            .unwrap()
            .text()
            .to_string()
    }

    pub fn version(&self) -> Option<(VersionConstraint, Version)> {
        let vc = self.0.children().find(|n| n.kind() == VERSION);
        let vc = vc.as_ref()?;
        let constraint = vc.children().find(|n| n.kind() == CONSTRAINT);

        let version = vc.children_with_tokens().find_map(|it| match it {
            SyntaxElement::Token(token) if token.kind() == IDENT => Some(token),
            _ => None,
        });

        if let (Some(constraint), Some(version)) = (constraint, version) {
            let vc: VersionConstraint = constraint.to_string().parse().unwrap();
            return Some((vc, (version.text().to_string()).parse().unwrap()));
        } else {
            None
        }
    }

    pub fn arch_list(&self) -> impl Iterator<Item = String> + '_ {
        let architectures = self.0.children().find(|n| n.kind() == ARCHITECTURES);

        let architectures = architectures.as_ref().unwrap();

        architectures.children_with_tokens().filter_map(|node| {
            let token = node.as_token()?;
            if token.kind() == IDENT {
                Some(token.text().to_string())
            } else {
                None
            }
        })
    }

    pub fn profiles(&self) -> impl Iterator<Item = Vec<BuildProfile>> + '_ {
        let profiles = self.0.children().filter(|n| n.kind() == PROFILES);

        profiles.map(|profile| {
            // iterate over nodes separated by whitespace tokens
            let mut ret = vec![];
            let mut current = vec![];
            for token in profile.children_with_tokens() {
                match token.kind() {
                    WHITESPACE => {
                        if !current.is_empty() {
                            ret.push(current.join("").parse::<BuildProfile>().unwrap());
                            current = vec![];
                        }
                    }
                    L_ANGLE | R_ANGLE => {}
                    _ => {
                        current.push(token.to_string());
                    }
                }
            }
            if !current.is_empty() {
                ret.push(current.concat().parse().unwrap());
            }
            ret
        })
    }
}

impl std::str::FromStr for Relations {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parse = parse(s);
        if parse.errors.is_empty() {
            Ok(parse.root())
        } else {
            Err(parse.errors.join("\n"))
        }
    }
}

#[test]
fn test_parse() {
    let input = "python3-dulwich";
    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 1);
    let entry = parsed.entries().next().unwrap();
    assert_eq!(entry.to_string(), "python3-dulwich");
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(relation.to_string(), "python3-dulwich");
    assert_eq!(relation.version(), None);

    let input = "python3-dulwich (>= 0.20.21)";
    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 1);
    let entry = parsed.entries().next().unwrap();
    assert_eq!(entry.to_string(), "python3-dulwich (>= 0.20.21)");
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(relation.to_string(), "python3-dulwich (>= 0.20.21)");
    assert_eq!(
        relation.version(),
        Some((
            VersionConstraint::GreaterThanEqual,
            "0.20.21".parse().unwrap()
        ))
    );
}

#[test]
fn test_multiple() {
    let input = "python3-dulwich (>= 0.20.21), python3-dulwich (<< 0.21)";
    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 2);
    let entry = parsed.entries().next().unwrap();
    assert_eq!(entry.to_string(), "python3-dulwich (>= 0.20.21)");
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(relation.to_string(), "python3-dulwich (>= 0.20.21)");
    assert_eq!(
        relation.version(),
        Some((
            VersionConstraint::GreaterThanEqual,
            "0.20.21".parse().unwrap()
        ))
    );
    let entry = parsed.entries().nth(1).unwrap();
    assert_eq!(entry.to_string(), "python3-dulwich (<< 0.21)");
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(relation.to_string(), "python3-dulwich (<< 0.21)");
    assert_eq!(
        relation.version(),
        Some((VersionConstraint::LessThan, "0.21".parse().unwrap()))
    );
}

#[test]
fn test_arch_list() {
    let input = "python3-dulwich [amd64 arm64 armhf i386 mips mips64el mipsel ppc64el s390x]";
    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 1);
    let entry = parsed.entries().next().unwrap();
    assert_eq!(
        entry.to_string(),
        "python3-dulwich [amd64 arm64 armhf i386 mips mips64el mipsel ppc64el s390x]"
    );
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(
        relation.to_string(),
        "python3-dulwich [amd64 arm64 armhf i386 mips mips64el mipsel ppc64el s390x]"
    );
    assert_eq!(relation.version(), None);
    assert_eq!(
        relation.arch_list().collect::<Vec<_>>(),
        vec!["amd64", "arm64", "armhf", "i386", "mips", "mips64el", "mipsel", "ppc64el", "s390x"]
            .into_iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_profiles() {
    let input = "foo (>= 1.0) [i386 arm] <!nocheck> <!cross>, bar";
    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 2);
    let entry = parsed.entries().next().unwrap();
    assert_eq!(
        entry.to_string(),
        "foo (>= 1.0) [i386 arm] <!nocheck> <!cross>"
    );
    assert_eq!(entry.relations().count(), 1);
    let relation = entry.relations().next().unwrap();
    assert_eq!(
        relation.to_string(),
        "foo (>= 1.0) [i386 arm] <!nocheck> <!cross>"
    );
    assert_eq!(
        relation.version(),
        Some((VersionConstraint::GreaterThanEqual, "1.0".parse().unwrap()))
    );
    assert_eq!(
        relation.arch_list().collect::<Vec<_>>(),
        vec!["i386", "arm"]
            .into_iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
    );
    assert_eq!(
        relation.profiles().collect::<Vec<_>>(),
        vec![
            vec![BuildProfile::Disabled("nocheck".to_string())],
            vec![BuildProfile::Disabled("cross".to_string())]
        ]
    );
}

#[test]
fn test_substvar() {
    let input = "${shlibs:Depends}";

    let parsed: Relations = input.parse().unwrap();
    assert_eq!(parsed.to_string(), input);
    assert_eq!(parsed.entries().count(), 0);

    assert_eq!(
        parsed.substvars().collect::<Vec<_>>(),
        vec!["${shlibs:Depends}"]
    );
}