asterust-junos 0.5.0

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
//! `term`
//! `policy-options { policy-statement <name> { term <name> { from { ... } to { ... } then { ... } } } }`.
//!
//! A policy written without `term` statements is a single unnamed term. Each term carries `from`,
//! `to` and `then` statements.
//!
//! # See also
//!
//! - [policy-statement](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/policy-statement-edit-policy-options.html)
//! - [load-balance (ecmp)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/load-balance-edit-policy-options-policy-statement-then.html)
//! - [route-filter](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/route-filter-edit-policy-options.html)

use crate::{
    active_children, arg_of, child_block, has_leaf, list_values, split_keyword, split_name, statements, unquote,
};
use asterust::config::ConfigLine;

/// A `route-filter <prefix> <match-type>` condition.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RouteFilter {
    pub prefix: String,
    /// Everything after the prefix, e.g. `"exact"`, `"orlonger"`, `"upto /24"`.
    pub match_type: Option<String>,
}

/// A `database <name>` entry of a `validation-database-instance`, with the validation state it matches.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ValidationDatabaseMatch {
    pub name: String,
    /// `"valid"`, `"invalid"` or `"unknown"`.
    pub state: Option<String>,
}

/// The `validation-database-instance` condition of Junos OS Evolved.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ValidationDatabaseInstance {
    /// The `state` that applies whichever database matched: `"valid"`, `"invalid"` or `"unknown"`.
    pub state: Option<String>,
    pub databases: Vec<ValidationDatabaseMatch>,
}

/// The match conditions of a term's `from` or `to` statement. Conditions not listed here are
/// ignored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyConditions {
    pub protocols: Vec<String>,
    pub families: Vec<String>,
    pub communities: Vec<String>,
    pub as_paths: Vec<String>,
    pub prefix_lists: Vec<String>,
    /// The raw `prefix-list-filter` argument, e.g. `"CUSTOMERS orlonger"`.
    pub prefix_list_filters: Vec<String>,
    pub route_filters: Vec<RouteFilter>,
    pub neighbors: Vec<String>,
    /// Subroutine policies from `policy`.
    pub policies: Vec<String>,
    /// `aggregate-contributor`: routes that contribute to a configured aggregate.
    pub aggregate_contributor: bool,
    /// The OSPF `area` identifiers.
    pub areas: Vec<String>,
    /// The `as-path-group` names.
    pub as_path_groups: Vec<String>,
    /// The raw `as-path-neighbors`, `as-path-origins` and `as-path-transits` arguments, which name an AS list or an AS
    /// list group, e.g. `"as-list PEERS"` or `"as-list-group GROUP"`.
    pub as_path_neighbors: Vec<String>,
    pub as_path_origins: Vec<String>,
    pub as_path_transits: Vec<String>,
    /// Everything after `as-path-unique-count`, e.g. `"2 orhigher"`.
    pub as_path_unique_count: Option<String>,
    /// Everything after `as-path-calc-length`, e.g. `"4 equal"`.
    pub as_path_calc_length: Option<String>,
    /// Everything after `color`, e.g. `"10"` or `"10 color2 5"`.
    pub color: Option<String>,
    /// Everything after `community-count`, e.g. `"5 orlower"`.
    pub community_count: Option<String>,
    /// The `condition` names defined under `policy-options`.
    pub conditions: Vec<String>,
    /// `external`: IGP external routes. The `type` argument is in `external_type`.
    pub external: bool,
    /// The OSPF metric type after `external type`, `"1"` or `"2"`.
    pub external_type: Option<String>,
    /// `internal`: IGP internal routes.
    pub internal: bool,
    pub interfaces: Vec<String>,
    /// The IS-IS `level`.
    pub level: Option<String>,
    pub local_preference: Option<String>,
    /// Everything after `metric`, e.g. `"10"` or `"10 metric2 20"`.
    pub metric: Option<String>,
    pub mac_filter_lists: Vec<String>,
    /// Everything after `multicast-scoping`, e.g. `"link-local"` or `"4 orhigher"`.
    pub multicast_scoping: Option<String>,
    pub next_hops: Vec<String>,
    /// The `next-hop-type`, e.g. `"merged"`.
    pub next_hop_type: Option<String>,
    /// The NLRI route types, `"1"` through `"10"`.
    pub nlri_route_types: Vec<String>,
    pub origin: Option<String>,
    /// Everything after `preference`, e.g. `"10"` or `"10 preference2 20"`.
    pub preference: Option<String>,
    /// `programmed`.
    pub programmed: bool,
    /// The routing tables named by `rib`, e.g. `"vrf-a.inet.0"`.
    pub ribs: Vec<String>,
    pub route_filter_lists: Vec<String>,
    /// The `route-type`, `"external"` or `"internal"`.
    pub route_type: Option<String>,
    /// The raw `rtf-prefix-list` argument, e.g. `"LIST route-targets"`.
    pub rtf_prefix_lists: Vec<String>,
    pub source_address_filter_lists: Vec<String>,
    /// The `source-address-filter` entries, which have the same form as `route-filter`.
    pub source_address_filters: Vec<RouteFilter>,
    /// The route state, `"active"` or `"inactive"`.
    pub state: Option<String>,
    /// Everything after `tag`, e.g. `"100"` or `"100 tag2 200"`.
    pub tag: Option<String>,
    /// `traffic-engineering`.
    pub traffic_engineering: bool,
    /// The `validation-database` match: `"valid"`, `"invalid"` or `"unknown"`, the origin validation state of the route.
    pub validation_database: Option<String>,
    /// The `validation-database-instance` block of Junos OS Evolved.
    pub validation_database_instance: Option<ValidationDatabaseInstance>,
}

/// The flow-control action ending a term.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PolicyAction {
    Accept,
    Reject,
    NextTerm,
    NextPolicy,
}

/// How a `then community` action changes the route's communities.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommunityOperation {
    Add,
    Set,
    Delete,
}

/// A `then community (add | set | delete) <name>` action.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommunityAction {
    pub operation: CommunityOperation,
    pub community: String,
}

/// A `then srv6 locator <name> <sid>` action, which selects the SRv6 service SID that BGP advertises for the route.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicySrv6Action {
    pub locator: String,
    /// `end-dt4-sid`, `micro-dt46-sid` and the like.
    pub sid_type: Option<String>,
    /// The static SID value, if given.
    pub sid_value: Option<String>,
}

/// The `prefix-segment` action: the SID index of a prefix and whether it is a node segment.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyPrefixSegment {
    pub index: Option<String>,
    pub node_segment: bool,
}

/// The actions of a term's `then` statement. Actions not listed here are ignored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyActions {
    pub action: Option<PolicyAction>,
    /// Everything after `metric`, e.g. `"63"` or `"add 10"`.
    pub metric: Option<String>,
    pub local_preference: Option<String>,
    pub next_hop: Option<String>,
    pub as_path_prepend: Option<String>,
    pub communities: Vec<CommunityAction>,
    /// Everything after `load-balance`, e.g. `"per-packet"`. A `load-balance { ...; }` block is not read.
    pub load_balance: Option<String>,
    /// The `resolution-map` to apply, which is defined under `policy-options`.
    pub resolution_map: Option<String>,
    pub multipath_resolve: bool,
    pub srv6: Option<PolicySrv6Action>,
    /// The action the policy takes when no term matches, from `default-action`.
    pub default_action: Option<PolicyAction>,
    /// Everything after `add-path`, e.g. `"send-count 16"`.
    pub add_path: Option<String>,
    pub advertise_locator: bool,
    pub aggregate_bandwidth: bool,
    /// The `multiplier` of the `aggregate-weight` block.
    pub aggregate_weight: Option<String>,
    /// `aigp-originate`; the value after `distance` is in `aigp_distance`.
    pub aigp_originate: bool,
    pub aigp_distance: Option<String>,
    /// Everything after `as-path-expand`, e.g. `"2"` or `"last-as count 2"`.
    pub as_path_expand: Option<String>,
    /// Everything after `assisted-replication`.
    pub assisted_replication: Option<String>,
    pub bgp_output_queue_priority: Option<String>,
    /// The `class` that the route is placed in.
    pub class: Option<String>,
    /// Everything after `color`, e.g. `"10"` or `"add 5"`.
    pub color: Option<String>,
    pub cos_next_hop_map: Option<String>,
    /// The `damping` parameters to apply, named under `policy-options damping`.
    pub damping: Option<String>,
    pub destination_class: Option<String>,
    pub dynamic_tunnel_attributes: Option<String>,
    /// Everything after `external`, e.g. `"type 2 metric 10"`.
    pub external: Option<String>,
    pub forwarding_class: Option<String>,
    /// Everything after `install-nexthop`, e.g. `"strict lsp LSP1"`.
    pub install_nexthop: Option<String>,
    /// `Some(true)` for `install-to-fib`, `Some(false)` for `no-install-to-fib`.
    pub install_to_fib: Option<bool>,
    pub limit_bandwidth: Option<String>,
    pub map_to_interface: Option<String>,
    pub no_entropy_label_capability: bool,
    pub origin: Option<String>,
    /// Everything after `preference`, e.g. `"10"` or `"add 5"`.
    pub preference: Option<String>,
    pub prefix_attribute_flags: bool,
    pub prefix_segment: Option<PolicyPrefixSegment>,
    /// `"high"`, `"medium"` or `"low"`.
    pub priority: Option<String>,
    pub set_down_bit: bool,
    pub source_class: Option<String>,
    pub sr_te_template: Option<String>,
    pub ssm_sources: Vec<String>,
    /// Everything after `tag`, e.g. `"100"` or `"add 5"`.
    pub tag: Option<String>,
    /// `"valid"`, `"invalid"` or `"unknown"`.
    pub validation_state: Option<String>,
}

/// One term of a policy statement.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyTerm {
    /// `None` for the unnamed term, which is the only one in a policy written without `term`
    /// statements.
    pub name: Option<String>,
    pub from: PolicyConditions,
    pub to: PolicyConditions,
    pub then: PolicyActions,
}

pub(super) fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
    PolicyTerm {
        name: name.map(str::to_string),
        from: parse_conditions(line, "from"),
        to: parse_conditions(line, "to"),
        then: parse_actions(line),
    }
}

fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
    let mut conditions = PolicyConditions {
        validation_database_instance: active_children(line)
            .filter(|c| c.text == keyword)
            .find_map(|block| child_block(block, "validation-database-instance"))
            .map(parse_validation_database_instance),
        ..PolicyConditions::default()
    };
    for statement in statements(line, keyword) {
        let (condition, arg) = split_keyword(statement);
        match condition {
            "protocol" => conditions.protocols.extend(list_values(arg)),
            "family" => conditions.families.push(unquote(arg).to_string()),
            "community" => conditions.communities.extend(list_values(arg)),
            "as-path" => conditions.as_paths.extend(list_values(arg)),
            "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
            "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
            "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
            "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
            "policy" => conditions.policies.push(unquote(arg).to_string()),
            "aggregate-contributor" => conditions.aggregate_contributor = true,
            "area" => conditions.areas.push(arg.to_string()),
            "as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
            "as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
            "as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
            "as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
            "as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
            "as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
            "color" => conditions.color = rest(arg),
            "community-count" => conditions.community_count = rest(arg),
            "condition" => conditions.conditions.extend(list_values(arg)),
            "external" => {
                conditions.external = true;
                conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
            }
            "internal" => conditions.internal = true,
            "interface" => conditions.interfaces.extend(list_values(arg)),
            "level" => conditions.level = rest(arg),
            "local-preference" => conditions.local_preference = rest(arg),
            "metric" => conditions.metric = rest(arg),
            "mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
            "multicast-scoping" => conditions.multicast_scoping = rest(arg),
            "next-hop" => conditions.next_hops.extend(list_values(arg)),
            "next-hop-type" => conditions.next_hop_type = rest(arg),
            "nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
            "origin" => conditions.origin = rest(arg),
            "preference" => conditions.preference = rest(arg),
            "programmed" => conditions.programmed = true,
            "rib" => conditions.ribs.extend(list_values(arg)),
            "route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
            "route-type" => conditions.route_type = rest(arg),
            "rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
            "source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
            "source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
            "state" => conditions.state = rest(arg),
            "tag" => conditions.tag = rest(arg),
            "traffic-engineering" => conditions.traffic_engineering = true,
            "validation-database" => conditions.validation_database = rest(arg),
            _ => {}
        }
    }
    conditions
}

fn parse_validation_database_instance(line: &ConfigLine) -> ValidationDatabaseInstance {
    ValidationDatabaseInstance {
        state: arg_of(line, "state").map(str::to_string),
        databases: active_children(line)
            .filter_map(|c| c.arg("database"))
            .map(|arg| {
                let (name, after) = split_name(arg);
                ValidationDatabaseMatch {
                    name: unquote(name).to_string(),
                    state: after.strip_prefix("state").and_then(|s| rest(s.trim())),
                }
            })
            .collect(),
    }
}

fn rest(arg: &str) -> Option<String> {
    Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
}

fn parse_route_filter(arg: &str) -> RouteFilter {
    let (prefix, match_type) = split_keyword(arg);
    RouteFilter {
        prefix: prefix.to_string(),
        match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
    }
}

fn parse_actions(line: &ConfigLine) -> PolicyActions {
    let mut actions = PolicyActions::default();
    for statement in statements(line, "then") {
        let (action, arg) = split_keyword(statement);
        let value = || Some(unquote(arg).to_string());
        match (action, arg) {
            ("accept", "") => actions.action = Some(PolicyAction::Accept),
            ("reject", "") => actions.action = Some(PolicyAction::Reject),
            ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
            ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
            ("metric", _) => actions.metric = value(),
            ("local-preference", _) => actions.local_preference = value(),
            ("next-hop", _) => actions.next_hop = value(),
            ("as-path-prepend", _) => actions.as_path_prepend = value(),
            ("community", _) => actions.communities.extend(parse_community_actions(arg)),
            ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
            ("resolution-map", _) => actions.resolution_map = value(),
            ("multipath-resolve", "") => actions.multipath_resolve = true,
            ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
            ("default-action", "accept") => actions.default_action = Some(PolicyAction::Accept),
            ("default-action", "reject") => actions.default_action = Some(PolicyAction::Reject),
            ("add-path", _) => actions.add_path = value(),
            ("advertise-locator", "") => actions.advertise_locator = true,
            ("aggregate-bandwidth", "") => actions.aggregate_bandwidth = true,
            ("aigp-originate", _) => {
                actions.aigp_originate = true;
                actions.aigp_distance = arg.strip_prefix("distance").map(|d| d.trim().to_string());
            }
            ("as-path-expand", _) => actions.as_path_expand = value(),
            ("assisted-replication", _) => actions.assisted_replication = value(),
            ("bgp-output-queue-priority", _) => actions.bgp_output_queue_priority = value(),
            ("class", _) => actions.class = value(),
            ("color", _) => actions.color = value(),
            ("cos-next-hop-map", _) => actions.cos_next_hop_map = value(),
            ("damping", _) => actions.damping = value(),
            ("destination-class", _) => actions.destination_class = value(),
            ("dynamic-tunnel-attributes", _) => actions.dynamic_tunnel_attributes = value(),
            ("external", _) => actions.external = value(),
            ("forwarding-class", _) => actions.forwarding_class = value(),
            ("install-nexthop", _) => actions.install_nexthop = value(),
            ("install-to-fib", "") => actions.install_to_fib = Some(true),
            ("no-install-to-fib", "") => actions.install_to_fib = Some(false),
            ("limit-bandwidth", _) => actions.limit_bandwidth = value(),
            ("map-to-interface", _) => actions.map_to_interface = value(),
            ("no-entropy-label-capability", "") => actions.no_entropy_label_capability = true,
            ("origin", _) => actions.origin = value(),
            ("preference", _) => actions.preference = value(),
            ("prefix-attribute-flags", "") => actions.prefix_attribute_flags = true,
            ("priority", _) => actions.priority = value(),
            ("set-down-bit", "") => actions.set_down_bit = true,
            ("source-class", _) => actions.source_class = value(),
            ("sr-te-template", _) => actions.sr_te_template = value(),
            ("ssm-source", _) => actions.ssm_sources.extend(list_values(arg)),
            ("tag", _) => actions.tag = value(),
            ("validation-state", _) => actions.validation_state = value(),
            _ => {}
        }
    }
    for block in active_children(line).filter(|c| c.text == "then") {
        if let Some(weight) = child_block(block, "aggregate-weight") {
            actions.aggregate_weight = arg_of(weight, "multiplier").map(str::to_string);
        }
        if let Some(segment) = child_block(block, "prefix-segment") {
            actions.prefix_segment = Some(PolicyPrefixSegment {
                index: arg_of(segment, "index").map(str::to_string),
                node_segment: has_leaf(segment, "node-segment"),
            });
        }
    }
    actions
}

fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
    let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
    let (sid_type, sid_value) = split_keyword(sid);
    Some(PolicySrv6Action {
        locator: unquote(locator).to_string(),
        sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
        sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
    })
}

fn parse_community_actions(arg: &str) -> Vec<CommunityAction> {
    let (operation, communities) = split_name(arg);
    let operation = match operation {
        "add" | "+" => CommunityOperation::Add,
        "set" | "=" => CommunityOperation::Set,
        "delete" | "-" => CommunityOperation::Delete,
        _ => return Vec::new(),
    };
    list_values(communities)
        .into_iter()
        .map(|community| CommunityAction { operation, community })
        .collect()
}

#[cfg(test)]
mod tests {
    use crate::policy_options::{
        policy_options, CommunityOperation, PolicyAction, PolicyActions, PolicyConditions, PolicyOptions,
    };
    use asterust::config::juniper;

    fn parse(text: &str) -> PolicyOptions {
        policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
    }

    fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
        &options.policy_statements[policy].terms[term].from
    }

    // Adapted from the Routing Policies, Firewall Filters, and Traffic Policers User Guide: the `show policy-options`
    // output of Example: Configuring BGP Import Policy Based on Community Count, the source address filter examples
    // of Configuring Route Lists for Use in Routing Policy Match Conditions, the route filter list example, the
    // conditional prefix example, the `next-table` example of the actions page and the MVPN damping example. The
    // `set` examples are written in brace form. See the README "Sources".
    const DOC_CONDITIONS: &str = r#"
policy-options {
    policy-statement import-communities {
        term 1 {
            from {
                protocol bgp;
                community-count 5 orlower;
            }
            then accept;
        }
        term 2 {
            then reject;
        }
    }
    policy-statement join-filter {
        from {
            neighbor 10.14.12.20;
            source-address-filter 10.83.0.0/16 orlonger;
        }
        then reject;
    }
    policy-statement join-filter-interface {
        from {
            interface so-1/0/0.0;
            source-address-filter 10.83.0.0/16 orlonger;
        }
        then reject;
    }
    policy-statement as-list-match {
        term neighbor-match {
            from as-path-neighbors as-list peer-match;
        }
        term group-match {
            from as-path-origins as-list-group origin_group;
        }
    }
    policy-statement rf-test-policy {
        term term2 {
            from route-filter-list rf-list-1;
        }
    }
    policy-statement conditional-export-bgp {
        term conditional-default {
            from {
                condition prefix_11;
                route-filter 0.0.0.0/0 exact;
            }
            then accept;
        }
    }
    policy-statement dampPolicy {
        term term1 {
            from nlri-route-type [ 3 4 5 ];
        }
    }
    policy-statement vrf-leak {
        term 1 {
            from {
                protocol bgp;
                rib vrf-customer2.inet.0;
                community customer;
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_community_count() {
        let options = parse(DOC_CONDITIONS);
        let from = from_of(&options, 0, 0);
        assert_eq!(from.protocols, ["bgp"]);
        assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
        assert_eq!(from_of(&options, 0, 1).community_count, None);
    }

    #[test]
    fn reads_the_guide_source_address_filters() {
        let options = parse(DOC_CONDITIONS);
        let from = from_of(&options, 1, 0);
        assert_eq!(from.neighbors, ["10.14.12.20"]);
        assert_eq!(from.source_address_filters.len(), 1);
        assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
        assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));

        let from = from_of(&options, 2, 0);
        assert_eq!(from.interfaces, ["so-1/0/0.0"]);
    }

    #[test]
    fn reads_the_guide_as_lists() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
        assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
    }

    #[test]
    fn reads_the_guide_lists_and_conditions() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);

        let from = from_of(&options, 5, 0);
        assert_eq!(from.conditions, ["prefix_11"]);
        assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
    }

    #[test]
    fn reads_the_guide_nlri_route_types_and_rib() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);

        let from = from_of(&options, 7, 0);
        assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
        assert_eq!(from.communities, ["customer"]);
    }

    // Not from documentation: written from the match condition tables of the Routing Policies, Firewall Filters, and
    // Traffic Policers User Guide. See the README "Sources".
    #[test]
    fn reads_the_other_match_conditions() {
        let options = parse(
            r#"
policy-options {
    policy-statement igp {
        term ospf {
            from {
                protocol ospf;
                area 0.0.0.0;
                external type 2;
                level 2;
                tag 100 tag2 200;
                state active;
                aggregate-contributor;
                programmed;
                traffic-engineering;
            }
        }
        term internal {
            from {
                internal;
                route-type external;
                color 10 color2 5;
                metric 20 metric2 30;
                preference 100 preference2 200;
                local-preference 150;
                origin igp;
                next-hop [ 192.0.2.1 192.0.2.2 ];
                next-hop-type merged;
                as-path-group TRANSIT;
                as-path-unique-count 2 orhigher;
                as-path-calc-length 4 equal;
                mac-filter-list MACS;
                multicast-scoping link-local;
                rtf-prefix-list RTF route-targets;
                source-address-filter-list SOURCES;
            }
        }
        term bare {
            from external;
        }
    }
}
"#,
        );
        let ospf = from_of(&options, 0, 0);
        assert_eq!(ospf.areas, ["0.0.0.0"]);
        assert!(ospf.external);
        assert_eq!(ospf.external_type.as_deref(), Some("2"));
        assert_eq!(ospf.level.as_deref(), Some("2"));
        assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
        assert_eq!(ospf.state.as_deref(), Some("active"));
        assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
        assert!(!ospf.internal);

        let other = from_of(&options, 0, 1);
        assert!(other.internal && !other.external);
        assert_eq!(other.route_type.as_deref(), Some("external"));
        assert_eq!(other.color.as_deref(), Some("10 color2 5"));
        assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
        assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
        assert_eq!(other.local_preference.as_deref(), Some("150"));
        assert_eq!(other.origin.as_deref(), Some("igp"));
        assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
        assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
        assert_eq!(other.as_path_groups, ["TRANSIT"]);
        assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
        assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
        assert_eq!(other.mac_filter_lists, ["MACS"]);
        assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
        assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
        assert_eq!(other.source_address_filter_lists, ["SOURCES"]);

        let bare = from_of(&options, 0, 2);
        assert!(bare.external);
        assert_eq!(bare.external_type, None);
    }

    #[test]
    fn reads_to_conditions_with_the_same_statements() {
        let options = parse(
            "policy-options {\n    policy-statement export {\n        to {\n            level 1;\n            interface ge-0/0/0.0;\n        }\n    }\n}\n",
        );
        let to = &options.policy_statements[0].terms[0].to;
        assert_eq!(to.level.as_deref(), Some("1"));
        assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
    }

    // Adapted from the BGP User Guide, Example: Configuring Origin Validation for BGP (Device R0 `show policy-options`
    // and the validation-database import policy of Understanding Origin Validation for BGP); see the README "Sources".
    const DOC_VALIDATION: &str = r#"
policy-options {
    policy-statement validation {
        term valid {
            from {
                protocol bgp;
                validation-database valid;
            }
            then {
                validation-state valid;
                community add origin-validation-state-valid;
                accept;
            }
        }
        term invalid {
            from {
                protocol bgp;
                validation-database invalid;
            }
            then reject;
        }
        term unknown {
            from protocol bgp;
            then accept;
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_validation_database() {
        let options = parse(DOC_VALIDATION);
        assert_eq!(from_of(&options, 0, 0).protocols, ["bgp"]);
        assert_eq!(from_of(&options, 0, 0).validation_database.as_deref(), Some("valid"));
        assert_eq!(from_of(&options, 0, 1).validation_database.as_deref(), Some("invalid"));
        assert_eq!(from_of(&options, 0, 2).validation_database, None);
        assert_eq!(from_of(&options, 0, 0).validation_database_instance, None);
    }

    // Not from documentation: written from the `validation-database-instance` syntax of the policy-statement CLI
    // Reference page (Junos OS Evolved). See the README "Sources".
    #[test]
    fn reads_the_validation_database_instance() {
        let options = parse(
            r#"
policy-options {
    policy-statement rpki {
        term t {
            from {
                validation-database-instance {
                    database RPKI1 state valid;
                    database "RPKI 2";
                    state invalid;
                }
            }
        }
        term inline {
            from validation-database valid;
        }
    }
}
"#,
        );
        let instance = from_of(&options, 0, 0).validation_database_instance.as_ref().unwrap();
        assert_eq!(instance.state.as_deref(), Some("invalid"));
        assert_eq!(instance.databases.len(), 2);
        assert_eq!(instance.databases[0].name, "RPKI1");
        assert_eq!(instance.databases[0].state.as_deref(), Some("valid"));
        assert_eq!(instance.databases[1].name, "RPKI 2");
        assert_eq!(instance.databases[1].state, None);
        assert_eq!(from_of(&options, 0, 1).validation_database_instance, None);
    }

    fn then_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyActions {
        &options.policy_statements[policy].terms[term].then
    }

    // Adapted from the BGP User Guide: the `show policy-options` output of Understanding Load Balancing Using BGP
    // Add-Path and Multipath (`aggregate-bandwidth`, `as-path-expand`), the AIGP example of Autonomous Systems, the
    // damping examples of BGP Session Flaps, and the PTX default policy of Basic Routing Policies; see the README
    // "Sources".
    const DOC_THEN_ACTIONS: &str = r#"
policy-options {
    policy-statement aggregate_bw_and_limit_capacity {
        then {
            aggregate-bandwidth;
            limit-bandwidth 80000000;
            accept;
        }
    }
    policy-statement s2b {
        from protocol [ static direct ];
        then {
            as-path-expand 2;
            accept;
        }
    }
    policy-statement aigp {
        term 10 {
            from {
                protocol static;
                route-filter 44.0.0.0/24 exact;
            }
            then {
                aigp-originate distance 200;
                next-hop 10.100.1.4;
                accept;
            }
        }
    }
    policy-statement dampPolicy {
        term term1 {
            from {
                family inet-mvpn;
                nlri-route-type [ 3 4 5 ];
            }
            then accept;
        }
        then {
            damping no-damp;
            accept;
        }
    }
    policy-statement override-ptx-series-default {
        term 1 {
            from {
                prefix-list install-bgp;
            }
            then {
                load-balance per-prefix;
                install-to-fib;
            }
        }
    }
    policy-statement junos-ptx-series-default {
        term t1 {
            from {
                protocol bgp;
                rib inet.0;
            }
            then no-install-to-fib;
        }
    }
    policy-statement damp {
        term 1 {
            from {
                route-filter 10.128.0.0/9 exact damping dry;
                route-filter 0.0.0.0/0 prefix-length-range /17-/32 damping aggressive;
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_bandwidth_and_expand_actions() {
        let options = parse(DOC_THEN_ACTIONS);
        let bandwidth = then_of(&options, 0, 0);
        assert!(bandwidth.aggregate_bandwidth);
        assert_eq!(bandwidth.limit_bandwidth.as_deref(), Some("80000000"));
        assert_eq!(bandwidth.action, Some(PolicyAction::Accept));

        let expand = then_of(&options, 1, 0);
        assert_eq!(expand.as_path_expand.as_deref(), Some("2"));
        assert!(!expand.aggregate_bandwidth);
    }

    #[test]
    fn reads_the_guide_aigp_originate() {
        let options = parse(DOC_THEN_ACTIONS);
        let then = then_of(&options, 2, 0);
        assert!(then.aigp_originate);
        assert_eq!(then.aigp_distance.as_deref(), Some("200"));
        assert_eq!(then.next_hop.as_deref(), Some("10.100.1.4"));
    }

    #[test]
    fn reads_the_guide_damping() {
        let options = parse(DOC_THEN_ACTIONS);
        let policy = &options.policy_statements[3];
        assert_eq!(policy.terms.len(), 2);
        assert_eq!(policy.terms[0].name.as_deref(), Some("term1"));
        assert_eq!(policy.terms[1].name, None);
        assert_eq!(policy.terms[1].then.damping.as_deref(), Some("no-damp"));
        assert_eq!(policy.terms[1].then.action, Some(PolicyAction::Accept));

        let filters = &from_of(&options, 6, 0).route_filters;
        assert_eq!(filters[0].match_type.as_deref(), Some("exact damping dry"));
        assert_eq!(
            filters[1].match_type.as_deref(),
            Some("prefix-length-range /17-/32 damping aggressive")
        );
    }

    #[test]
    fn reads_the_guide_install_to_fib() {
        let options = parse(DOC_THEN_ACTIONS);
        let override_default = then_of(&options, 4, 0);
        assert_eq!(override_default.load_balance.as_deref(), Some("per-prefix"));
        assert_eq!(override_default.install_to_fib, Some(true));
        assert_eq!(then_of(&options, 5, 0).install_to_fib, Some(false));
        assert_eq!(then_of(&options, 0, 0).install_to_fib, None);
    }

    // Not from documentation: written from the action table of the Routing Policies, Firewall Filters, and Traffic
    // Policers User Guide and the policy-statement CLI Reference page. See the README "Sources".
    #[test]
    fn reads_the_other_actions() {
        let options = parse(
            r#"
policy-options {
    policy-statement actions {
        term a {
            then {
                default-action reject;
                add-path send-count 4;
                advertise-locator;
                aggregate-weight {
                    multiplier 2;
                }
                as-path-expand last-as count 3;
                assisted-replication replicator-ip 192.0.2.1 strict;
                bgp-output-queue-priority 5;
                class gold;
                color 10 color2 20;
                cos-next-hop-map MAP;
                destination-class DC;
                dynamic-tunnel-attributes TUNNEL;
                external type 2 metric 10;
                forwarding-class expedited-forwarding;
                install-nexthop strict lsp LSP1;
                map-to-interface self;
                no-entropy-label-capability;
                origin igp;
                preference add 5;
                prefix-attribute-flags;
                prefix-segment {
                    index 100;
                    node-segment;
                }
                priority high;
                set-down-bit;
                source-class SC;
                sr-te-template TEMPLATE;
                ssm-source [ 192.0.2.1 192.0.2.2 ];
                tag 100 tag2 200;
                validation-state valid;
            }
        }
    }
}
"#,
        );
        let then = then_of(&options, 0, 0);
        assert_eq!(then.default_action, Some(PolicyAction::Reject));
        assert_eq!(then.add_path.as_deref(), Some("send-count 4"));
        assert!(then.advertise_locator);
        assert_eq!(then.aggregate_weight.as_deref(), Some("2"));
        assert!(!then.aigp_originate);
        assert_eq!(then.as_path_expand.as_deref(), Some("last-as count 3"));
        assert_eq!(
            then.assisted_replication.as_deref(),
            Some("replicator-ip 192.0.2.1 strict")
        );
        assert_eq!(then.bgp_output_queue_priority.as_deref(), Some("5"));
        assert_eq!(then.class.as_deref(), Some("gold"));
        assert_eq!(then.color.as_deref(), Some("10 color2 20"));
        assert_eq!(then.cos_next_hop_map.as_deref(), Some("MAP"));
        assert_eq!(then.destination_class.as_deref(), Some("DC"));
        assert_eq!(then.dynamic_tunnel_attributes.as_deref(), Some("TUNNEL"));
        assert_eq!(then.external.as_deref(), Some("type 2 metric 10"));
        assert_eq!(then.forwarding_class.as_deref(), Some("expedited-forwarding"));
        assert_eq!(then.install_nexthop.as_deref(), Some("strict lsp LSP1"));
        assert_eq!(then.map_to_interface.as_deref(), Some("self"));
        assert!(then.no_entropy_label_capability);
        assert_eq!(then.origin.as_deref(), Some("igp"));
        assert_eq!(then.preference.as_deref(), Some("add 5"));
        assert!(then.prefix_attribute_flags);
        let segment = then.prefix_segment.as_ref().unwrap();
        assert_eq!(segment.index.as_deref(), Some("100"));
        assert!(segment.node_segment);
        assert_eq!(then.priority.as_deref(), Some("high"));
        assert!(then.set_down_bit);
        assert_eq!(then.source_class.as_deref(), Some("SC"));
        assert_eq!(then.sr_te_template.as_deref(), Some("TEMPLATE"));
        assert_eq!(then.ssm_sources, ["192.0.2.1", "192.0.2.2"]);
        assert_eq!(then.tag.as_deref(), Some("100 tag2 200"));
        assert_eq!(then.validation_state.as_deref(), Some("valid"));
    }

    // Not from documentation: the list and symbol forms of the `community` action on the actions page.
    #[test]
    fn reads_community_lists_and_symbols() {
        let options = parse(
            "policy-options {\n    policy-statement c {\n        then {\n            community add [ a b ];\n            community - old;\n            community = only;\n        }\n    }\n}\n",
        );
        let communities: Vec<_> = then_of(&options, 0, 0)
            .communities
            .iter()
            .map(|c| (c.operation, c.community.as_str()))
            .collect();
        assert_eq!(
            communities,
            [
                (CommunityOperation::Add, "a"),
                (CommunityOperation::Add, "b"),
                (CommunityOperation::Delete, "old"),
                (CommunityOperation::Set, "only"),
            ]
        );
    }
}