vhdl_syntax 0.1.0

Library to work with VHDL files
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c)  2025, Lukas Scheller lukasscheller@icloud.com

use crate::parser::Parser;
use crate::syntax::node_kind::NodeKind::*;
use crate::tokens::Keyword as Kw;
use crate::tokens::TokenKind::*;

impl Parser {
    pub(crate) fn opt_generic_clause(&mut self) {
        if self.next_is(Keyword(Kw::Generic)) {
            self.generic_clause();
        }
    }

    pub fn generic_clause(&mut self) {
        self.start_node(GenericClause);
        self.start_node(GenericClausePreamble);
        self.expect_kw(Kw::Generic);
        self.expect_token(LeftPar);
        self.end_node();
        if !(self.next_is(RightPar)) {
            self.interface_list();
        }
        self.start_node(GenericClauseEpilogue);
        self.expect_tokens([RightPar, SemiColon]);
        self.end_node();
        self.end_node();
    }

    pub fn opt_port_clause(&mut self) {
        if self.next_is(Keyword(Kw::Port)) {
            self.port_clause();
        }
    }

    pub fn port_clause(&mut self) {
        self.start_node(PortClause);
        self.start_node(PortClausePreamble);
        self.expect_kw(Kw::Port);
        self.expect_token(LeftPar);
        self.end_node();
        if !(self.next_is(RightPar)) {
            self.interface_list();
        }
        self.start_node(PortClauseEpilogue);
        self.expect_tokens([RightPar, SemiColon]);
        self.end_node();
        self.end_node();
    }

    pub fn interface_list(&mut self) {
        self.start_node(InterfaceList);
        self.separated_list(Parser::interface_declaration, SemiColon);
        self.end_node();
    }

    pub fn interface_declaration(&mut self) {
        match self.peek_token() {
            Keyword(Kw::Signal | Kw::Constant | Kw::Variable) | Identifier => {
                self.interface_object_declaration();
            }
            Keyword(Kw::File) => self.interface_file_declaration(),
            Keyword(Kw::Type) => self.interface_type_declaration(),
            Keyword(Kw::Function | Kw::Procedure | Kw::Impure | Kw::Pure) => {
                self.interface_subprogram_declaration()
            }
            Keyword(Kw::Package) => self.interface_package_declaration(),
            _ => self.expect_tokens_err([
                Keyword(Kw::Signal),
                Keyword(Kw::Constant),
                Keyword(Kw::Variable),
                Identifier,
                Keyword(Kw::File),
                Keyword(Kw::Type),
                Keyword(Kw::Function),
                Keyword(Kw::Procedure),
                Keyword(Kw::Impure),
                Keyword(Kw::Pure),
            ]),
        }
    }

    pub fn interface_file_declaration(&mut self) {
        self.start_node(InterfaceFileDeclaration);
        self.expect_kw(Kw::File);
        self.identifier_list();
        self.expect_token(Colon);
        self.subtype_indication();
        self.end_node();
    }

    pub fn interface_type_declaration(&mut self) {
        self.start_node(InterfaceIncompleteTypeDeclaration);
        self.expect_kw(Kw::Type);
        self.identifier();
        self.end_node();
    }

    pub fn interface_subprogram_declaration(&mut self) {
        self.start_node(InterfaceSubprogramDeclaration);
        self.interface_subprogram_specification();
        if self.opt_token(Keyword(Kw::Is)) {
            self.interface_subprogram_default();
        }
        self.end_node();
    }

    pub fn interface_subprogram_default(&mut self) {
        if self.next_is(BOX) {
            self.skip_into_node(InterfaceSubprogramDefaultBox);
        } else {
            self.start_node(InterfaceSubprogramDefaultName);
            self.name();
            self.end_node();
        }
    }

    pub fn interface_subprogram_specification(&mut self) {
        if self.next_is(Keyword(Kw::Procedure)) {
            self.interface_procedure_specification();
        } else {
            self.interface_function_specification();
        }
    }

    pub fn interface_procedure_specification(&mut self) {
        self.start_node(InterfaceProcedureSpecification);
        self.expect_kw(Kw::Procedure);
        self.designator();
        self.opt_parameter_list();
        self.end_node();
    }

    pub fn interface_function_specification(&mut self) {
        self.start_node(InterfaceFunctionSpecification);
        self.opt_function_purity();
        self.expect_kw(Kw::Function);
        self.designator();
        self.opt_parameter_list();
        self.expect_kw(Kw::Return);
        self.type_mark();
        self.end_node();
    }

    pub fn opt_function_purity(&mut self) {
        self.opt_tokens([Keyword(Kw::Pure), Keyword(Kw::Impure)]);
    }

    pub fn interface_package_declaration(&mut self) {
        self.start_node(InterfacePackageDeclaration);
        self.interface_package_declaration_preamble();
        self.expect_kw(Kw::New);
        self.name();
        self.interface_package_generic_map_aspect();
        self.end_node();
    }

    pub fn interface_package_declaration_preamble(&mut self) {
        self.start_node(InterfacePackageDeclarationPreamble);
        self.expect_kw(Kw::Package);
        self.identifier();
        self.expect_kw(Kw::Is);
        self.end_node();
    }

    pub fn interface_package_generic_map_aspect(&mut self) {
        self.start_node(InterfacePackageGenericMapAspect);
        self.expect_kw(Kw::Generic);
        self.expect_kw(Kw::Map);
        self.expect_token(LeftPar);
        if self.next_is(BOX) {
            self.skip_into_node(InterfacePackageGenericMapAspectBox);
        } else if self.next_is(Keyword(Kw::Default)) {
            self.skip_into_node(InterfacePackageGenericMapAspectDefault);
        } else {
            self.start_node(InterfacePackageGenericMapAspectAssociations);
            self.association_list();
            self.end_node();
        }
        self.expect_token(RightPar);
        self.end_node();
    }

    pub fn interface_object_declaration(&mut self) {
        let checkpoint = self.checkpoint();
        let tok = self.opt_tokens([
            Keyword(Kw::Signal),
            Keyword(Kw::Constant),
            Keyword(Kw::Variable),
        ]);
        match tok {
            Some(Keyword(Kw::Signal)) => self.start_node_at(checkpoint, InterfaceSignalDeclaration),
            Some(Keyword(Kw::Variable)) => {
                self.start_node_at(checkpoint, InterfaceVariableDeclaration)
            }
            _ => self.start_node_at(checkpoint, InterfaceConstantDeclaration),
        }
        self.identifier_list();
        self.expect_token(Colon);
        self.opt_mode();
        self.subtype_indication();
        self.opt_token(Keyword(Kw::Bus));
        if self.opt_token(ColonEq) {
            self.expression();
        }
        self.end_node();
    }

    pub fn opt_mode(&mut self) {
        self.opt_tokens([
            Keyword(Kw::In),
            Keyword(Kw::Out),
            Keyword(Kw::Inout),
            Keyword(Kw::Buffer),
            Keyword(Kw::Linkage),
        ]);
    }

    pub fn association_list(&mut self) {
        self.start_node(AssociationList);
        self.separated_list(
            |parser| {
                let end_of_element_idx =
                    match parser.lookahead_max_token_index(usize::MAX, [Comma, RightPar]) {
                        Ok((_, idx)) => idx,
                        Err((_, idx)) => idx,
                    };
                parser.association_element_bounded(end_of_element_idx);
            },
            Comma,
        );
        self.end_node();
    }

    fn association_element_bounded(&mut self, max_index: usize) {
        self.start_node(AssociationElement);

        // TODO: Error handling is done at a bare minimum.
        if self
            .lookahead_max_token_index(max_index, [RightArrow])
            .is_ok()
        {
            self.formal_part();
            self.expect_token(RightArrow);
        }
        self.actual_part();

        self.end_node();
    }

    pub fn formal_part(&mut self) {
        self.start_node(FormalPart);
        self.name();
        // Note: `self.name()` will already consume any trailing parenthesized names!
        self.end_node();
    }

    pub fn actual_part(&mut self) {
        // actual_part       ::= actual_designator | name "(" actual_designator ")"
        //                     | type_mark "(" actual_designator ")"
        // actual_designator ::= [inertial] expression | subtype_indication | open
        //
        // Dispatch between `Expression` and `SubtypeIndication` is decided by
        // a single lookahead: the only syntactic signal that a subtype is
        // intended is a second name following the first (either the bare
        // `resolution_function_name type_mark` form or the
        // `(element_resolution) type_mark` form). The LRM-wrapped forms
        // `name "(" actual_designator ")"` collapse into `Expression`
        // because `Name` accepts a `ParenthesizedName` tail; analysis sorts
        // them out later.
        self.start_node(ActualPart);
        self.opt_token(Keyword(Kw::Inertial));

        if self.next_is(Keyword(Kw::Open)) {
            self.start_node(ActualPartOpen);
            self.skip();
            self.end_node();
        } else if self.next_is(LeftPar) {
            // Look past the matching `)`. If a name-starter follows, the
            // parenthesized group is an `(element_resolution)` and we are in
            // a subtype_indication; otherwise it is a parenthesized
            // expression / aggregate.
            let is_subtype = match self.lookahead_skip_n(1, [RightPar]) {
                Ok((_, end_index)) => matches!(
                    self.peek_nth_token(end_index - self.token_index() + 1),
                    Identifier | StringLiteral | CharacterLiteral | LtLt
                ),
                Err(_) => false,
            };
            if is_subtype {
                self.start_node(ActualPartSubtypeIndication);
                self.subtype_indication();
                self.end_node();
            } else {
                self.start_node(ActualPartExpression);
                self.expression();
                self.end_node();
            }
        } else if matches!(
            self.peek_token(),
            Identifier | StringLiteral | CharacterLiteral | LtLt
        ) {
            // The actual_part starts with a name. Parse it greedily; if a
            // second name follows, the first was a `resolution_function_name`
            // and we promote to subtype_indication retroactively. Otherwise
            // the name is the leading primary of an expression.
            let cp = self.checkpoint();
            self.name();
            if matches!(
                self.peek_token(),
                Identifier | StringLiteral | CharacterLiteral | LtLt
            ) {
                self.start_node_at(cp, ActualPartSubtypeIndication);
                self.start_node_at(cp, SubtypeIndication);
                self.start_node_at(cp, NameResolutionIndication);
                self.end_node(); // NameResolutionIndication
                self.name(); // type_mark
                self.end_node(); // SubtypeIndication
                self.end_node(); // ActualPartSubtypeIndication
            } else {
                self.start_node_at(cp, ActualPartExpression);
                self.continue_primary_after_name(cp);
                self.expression_from_primary(cp);
                self.end_node(); // ActualPartExpression
            }
        } else {
            self.start_node(ActualPartExpression);
            self.expression();
            self.end_node();
        }

        self.end_node();
    }
}

#[cfg(test)]
mod tests {
    use crate::parser::test_utils::to_test_text;
    use crate::parser::Parser;

    #[test]
    fn association_list() {
        insta::assert_snapshot!(to_test_text(Parser::association_list, "arg1, arg2",));

        insta::assert_snapshot!(to_test_text(
            Parser::association_list,
            "p1 => 1, std_ulogic(p2)=>     sl_sig"
        ));
    }

    #[test]
    fn actual_part_open() {
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "open"));
    }

    #[test]
    fn actual_part_inertial_open() {
        // `inertial` only meaningfully binds to an expression per the LRM;
        // we accept it before any body and let analysis reject misuse.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "inertial open"));
    }

    #[test]
    fn actual_part_expression() {
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "42"));
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "lib.pkg.sig"));
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "a + b * 2"));
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "-foo"));
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "(foo) + 1"));
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "(a, b, c)"));
    }

    #[test]
    fn actual_part_expression_type_conversion_shape() {
        // `std_ulogic(p)` — the LRM `type_mark "(" actual_designator ")"`
        // wrapped form. Broadened into an Expression whose Name has a
        // ParenthesizedName tail; analysis recovers the conversion.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "std_ulogic(p)"));
    }

    #[test]
    fn actual_part_expression_inertial() {
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "inertial a + 1"));
    }

    #[test]
    fn actual_part_expression_qualified() {
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "T'(1, 2, 3)"));
    }

    #[test]
    fn actual_part_subtype_resolution_function_name() {
        // `resolve std_logic` — two adjacent names ⇒ subtype_indication
        // with a `NameResolutionIndication`.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "resolve std_logic"));
    }

    #[test]
    fn actual_part_subtype_resolution_function_selected_name() {
        insta::assert_snapshot!(to_test_text(
            Parser::actual_part,
            "lib.pkg.resolve std_logic"
        ));
    }

    #[test]
    fn actual_part_subtype_paren_array_resolution() {
        // `(resolve) bit_vector` — `(element_resolution)` followed by a
        // type_mark name ⇒ subtype_indication.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "(resolve) bit_vector"));
    }

    #[test]
    fn actual_part_subtype_paren_record_resolution() {
        // Record element resolution — `(field fn)` followed by a type_mark.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "(elem resolve) rec_t"));
    }

    #[test]
    fn actual_part_subtype_with_range_constraint() {
        // `integer range 0 to 7` — bare type_mark with a range constraint.
        // `name()` greedily consumes the trailing range, so this is
        // broadened into an `ActualPartExpression` whose `Name` carries a
        // `RangeConstraint` tail; analysis recognizes the subtype shape.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "integer range 0 to 7"));
    }

    #[test]
    fn actual_part_subtype_with_array_constraint_shape() {
        // `bit_vector(7 downto 0)` — bare type_mark with an array
        // constraint, indistinguishable from an indexed-name expression at
        // parse time and emitted as `ActualPartExpression`.
        insta::assert_snapshot!(to_test_text(Parser::actual_part, "bit_vector(7 downto 0)"));
    }

    #[test]
    fn interface_lists() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_list,
            "\
constant foo : std_logic;
bar : natural"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_list,
            "\
signal foo : in std_logic;
bar : natural"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_list,
            "\
signal foo : in std_logic;
constant bar : natural;
variable xyz : var"
        ));
    }

    #[test]
    fn empty_generic_clause() {
        insta::assert_snapshot!(to_test_text(Parser::generic_clause, "generic();",));
    }

    #[test]
    fn empty_port_clause() {
        insta::assert_snapshot!(to_test_text(Parser::port_clause, "port();",));
    }

    #[test]
    fn object_declaration() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : in std_logic",
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : out std_logic"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "signal a : out std_logic"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "constant a : out std_logic"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : inout std_logic"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : linkage std_logic",
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : buffer std_logic"
        ));
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a, b, c : in std_logic"
        ));
    }

    #[test]
    fn subtype_indication_in_interface_declaration() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "a : std_ulogic_vector(31 downto 0)",
        ));
    }

    #[test]
    fn parses_interface_type() {
        insta::assert_snapshot!(to_test_text(Parser::interface_declaration, "type name"));
    }

    #[test]
    fn parses_interface_identifier_list() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "constant foo, bar : natural",
        ));
    }

    #[test]
    fn parses_interface_file_declaration() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "file foo : text open read_mode",
        ));
    }

    #[test]
    fn parses_interface_file_declaration_no_file_name() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "file foo : text is \"file_name\"",
        ));
    }

    #[test]
    fn parses_interface_subprogram() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "function foo return bar"
        ));
    }

    #[test]
    fn parses_interface_subprogram_with_parameters() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "function Match(Actual : ActualType) return boolean"
        ));
    }

    #[test]
    fn parses_interface_subprogram_default() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "function foo return bar is lib.name"
        ));

        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "function foo return bar is <>"
        ));
    }

    #[test]
    fn interface_package_generic_map_aspect() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "\
package foo is new lib.pkg
    generic map (foo => bar)"
        ));
    }

    #[test]
    fn interface_package_generic_map_box() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "\
package foo is new lib.pkg
     generic map (<>)"
        ));
    }

    #[test]
    fn interface_package_generic_map_default() {
        insta::assert_snapshot!(to_test_text(
            Parser::interface_declaration,
            "\
package foo is new lib.pkg
     generic map (default)"
        ));
    }
}