veryl-analyzer 0.20.0

A modern hardware description language
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
use crate::AnalyzerError;
use crate::namespace::Namespace;
use crate::namespace_table;
use crate::symbol::{ParameterKind, Symbol, SymbolId, SymbolKind};
use crate::symbol_path::{GenericSymbolPath, GenericSymbolPathNamespace, SymbolPath};
use crate::symbol_table;
use crate::{HashMap, HashSet};
use bimap::BiMap;
use daggy::petgraph::visit::Dfs;
use daggy::{Dag, NodeIndex, Walker, petgraph::algo};
use std::cell::RefCell;
use veryl_parser::resource_table::PathId;
use veryl_parser::veryl_token::Token;

#[derive(Clone, Debug)]
pub enum TypeDagCandidate {
    Path {
        path: Box<GenericSymbolPath>,
        namespace: Namespace,
        project_namespace: Namespace,
        parent: Option<(SymbolId, Context)>,
    },
    Symbol {
        id: SymbolId,
        context: Context,
        project_namespace: Namespace,
        parent: Option<(SymbolId, Context)>,
        import: Vec<GenericSymbolPathNamespace>,
    },
}

impl TypeDagCandidate {
    pub fn set_parent(&mut self, x: (SymbolId, Context)) {
        match self {
            TypeDagCandidate::Path { parent, .. } => {
                *parent = Some(x);
            }
            TypeDagCandidate::Symbol { parent, .. } => {
                *parent = Some(x);
            }
        }
    }
}

#[derive(Clone, Default)]
pub struct TypeDag {
    dag: Dag<(), Context, u32>,
    /// One-to-one relation between SymbolId and DAG NodeIdx
    nodes: BiMap<SymbolId, u32>,
    /// Map between NodeIdx and Symbol Resolve Information
    paths: HashMap<u32, TypeResolveInfo>,
    symbols: HashMap<u32, Symbol>,
    source: u32,
    candidates: Vec<TypeDagCandidate>,
    errors: Vec<DagError>,
    dag_owned: HashMap<u32, HashSet<u32>>,
    file_dag: Dag<(), (), u32>,
    file_nodes: BiMap<PathId, u32>,
}

#[derive(Clone, Debug)]
pub struct TypeResolveInfo {
    pub symbol_id: SymbolId,
    pub name: String,
    pub token: Token,
}

#[derive(Default, Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub enum Context {
    #[default]
    Irrelevant,
    Struct,
    Union,
    Enum,
    Function,
    TypeDef,
    Const,
    Alias,
    Module,
    Interface,
    Package,
    Modport,
    GenericInstance,
    Embed,
}

#[derive(Debug, Clone)]
pub enum DagError {
    Cyclic(Box<Symbol>, Box<Symbol>),
}

impl From<DagError> for AnalyzerError {
    fn from(value: DagError) -> Self {
        let DagError::Cyclic(s, e) = value;
        AnalyzerError::cyclic_type_dependency(
            &s.token.to_string(),
            &e.token.to_string(),
            &e.token.into(),
        )
    }
}

impl TypeDag {
    #[allow(dead_code)]
    fn new() -> Self {
        let mut dag = Dag::<(), Context, u32>::new();
        let source = dag.add_node(()).index() as u32;
        Self {
            dag,
            nodes: BiMap::new(),
            paths: HashMap::default(),
            symbols: HashMap::default(),
            source,
            candidates: Vec::new(),
            errors: Vec::new(),
            dag_owned: HashMap::default(),
            file_dag: Dag::new(),
            file_nodes: BiMap::new(),
        }
    }

    fn add(&mut self, cand: TypeDagCandidate) {
        self.candidates.push(cand);
    }

    fn apply(&mut self) -> Vec<AnalyzerError> {
        symbol_table::suppress_cache_clear();
        let candidates: Vec<_> = self.candidates.drain(..).collect();

        // Process symbol declarations at first to construct dag_owned
        for cand in &candidates {
            if let TypeDagCandidate::Symbol {
                id,
                context,
                project_namespace,
                parent,
                import,
            } = cand
                && let Some(symbol) = symbol_table::get(*id)
                && let Some(child) = self.insert_declaration_symbol(&symbol, parent)
            {
                for x in import {
                    if let Ok(import) = symbol_table::resolve(x)
                        && let Some(import) = self.insert_symbol(&import.found)
                    {
                        self.insert_dag_edge(child, import, *context, false);
                    }
                }

                for map in symbol.generic_maps() {
                    for arg_path in map.map.values() {
                        // insert edge between given generic arg and base symbol
                        self.insert_path(
                            arg_path,
                            &symbol.namespace,
                            project_namespace,
                            &Some((*id, *context)),
                        );
                    }
                }
            }
        }

        // Process symbol references using dag_owned
        for cand in &candidates {
            if let TypeDagCandidate::Path {
                path,
                namespace,
                project_namespace,
                parent,
            } = cand
            {
                self.insert_path(path, namespace, project_namespace, parent);
            }
        }

        symbol_table::resume_cache_clear();
        self.errors.drain(..).map(|x| x.into()).collect()
    }

    fn insert_path(
        &mut self,
        path: &GenericSymbolPath,
        namespace: &Namespace,
        project_namespace: &Namespace,
        parent: &Option<(SymbolId, Context)>,
    ) {
        namespace_table::set_default(&project_namespace.paths);

        let mut path = path.clone();
        path.resolve_imported(namespace, None);

        for i in 0..path.len() {
            let Some(base_symbol) =
                Self::resolve_symbol_path(&path.slice(i).generic_path(), namespace)
            else {
                continue;
            };

            if let Some((parent_symbol, parent_context)) =
                parent.map(|(id, context)| (symbol_table::get(id).unwrap(), context))
            {
                if !base_symbol.namespace.included(&parent_symbol.namespace) {
                    let (parent_symbol, parent_context) =
                        if let Some(symbol) = parent_symbol.get_parent_component() {
                            let context = if symbol.is_module(true) {
                                Context::Module
                            } else if symbol.is_interface(true) {
                                Context::Interface
                            } else {
                                Context::Package
                            };
                            (symbol, context)
                        } else {
                            (parent_symbol, parent_context)
                        };
                    let base_symbol = if let Some(symbol) = base_symbol.get_parent_component() {
                        symbol
                    } else {
                        base_symbol
                    };
                    let recursive_ref = namespace.included(&base_symbol.inner_namespace());
                    self.insert_path_symbols(
                        &parent_symbol,
                        parent_context,
                        &base_symbol,
                        recursive_ref,
                    );
                } else {
                    let recursive_ref = namespace.included(&base_symbol.inner_namespace());
                    self.insert_path_symbols(
                        &parent_symbol,
                        parent_context,
                        &base_symbol,
                        recursive_ref,
                    );
                }
            } else {
                self.insert_symbol(&base_symbol);
            }
        }
    }

    fn resolve_symbol_path(path: &SymbolPath, namespace: &Namespace) -> Option<Symbol> {
        let symbol = symbol_table::resolve((path, namespace)).ok()?;
        if let Some(alias_path) = symbol.found.alias_target(false) {
            // alias referenced as generic arg for generic instance put on the same namespace
            // causes cyclic dependency error.
            // https://github.com/veryl-lang/veryl/blob/52b46337148340b43f8ab1c8f2ab67f58cd3c943/crates/analyzer/src/tests.rs#L3740-L3743
            // Need to use the target symbol of the alias instead of it to prevent this situation.
            Self::resolve_symbol_path(&alias_path.generic_path(), &symbol.found.namespace)
        } else {
            Some((*symbol.found).clone())
        }
    }

    fn insert_path_symbols(
        &mut self,
        parent_symbol: &Symbol,
        parent_context: Context,
        base_symbol: &Symbol,
        recursive_ref: bool,
    ) {
        let Some(base) = self.insert_symbol(base_symbol) else {
            return;
        };
        if let Some(parent) = self.insert_symbol(parent_symbol)
            && !self.is_dag_owned(parent, base)
        {
            self.insert_dag_edge(parent, base, parent_context, recursive_ref);
        }
    }

    fn insert_symbol(&mut self, symbol: &Symbol) -> Option<u32> {
        let is_dag_symbol = match symbol.kind {
            SymbolKind::Module(_)
            | SymbolKind::AliasModule(_)
            | SymbolKind::Interface(_)
            | SymbolKind::AliasInterface(_)
            | SymbolKind::Modport(_)
            | SymbolKind::Package(_)
            | SymbolKind::AliasPackage(_)
            | SymbolKind::Enum(_)
            | SymbolKind::TypeDef(_)
            | SymbolKind::Struct(_)
            | SymbolKind::Union(_)
            | SymbolKind::Function(_)
            | SymbolKind::Test(_)
            | SymbolKind::Embed => true,
            SymbolKind::Parameter(ref x) => matches!(x.kind, ParameterKind::Const),
            _ => false,
        };
        if !is_dag_symbol {
            return None;
        }

        let name = symbol.token.to_string();
        match self.insert_node(symbol.id, &name) {
            Ok(n) => Some(n),
            Err(x) => {
                self.errors.push(x);
                None
            }
        }
    }

    fn insert_declaration_symbol(
        &mut self,
        symbol: &Symbol,
        parent: &Option<(SymbolId, Context)>,
    ) -> Option<u32> {
        if let Some(child) = self.insert_symbol(symbol) {
            if let Some(parent) = parent {
                let parent_symbol = symbol_table::get(parent.0).unwrap();
                let parent_context = parent.1;
                if let Some(parent) = self.insert_symbol(&parent_symbol) {
                    self.insert_dag_owned(parent, child);
                    self.insert_dag_edge(child, parent, parent_context, false);
                }
            }
            Some(child)
        } else {
            None
        }
    }

    fn insert_dag_edge(&mut self, parent: u32, child: u32, context: Context, recursive_ref: bool) {
        // Reversing this order to make traversal work
        if let Err(x) = self.insert_edge(child, parent, context, recursive_ref) {
            self.errors.push(x);
        }
    }

    fn insert_dag_owned(&mut self, parent: u32, child: u32) {
        // If there is already edge to owned type, remove it.
        // Argument order should be the same as insert_edge.
        if self.exist_edge(child, parent) {
            self.remove_edge(child, parent);
        }
        self.dag_owned.entry(parent).or_default().insert(child);
    }

    fn is_dag_owned(&self, parent: u32, child: u32) -> bool {
        if let Some(owned) = self.dag_owned.get(&parent) {
            owned.contains(&child)
        } else {
            false
        }
    }

    fn insert_node(&mut self, symbol_id: SymbolId, name: &str) -> Result<u32, DagError> {
        let symbol = symbol_table::get(symbol_id).unwrap();
        let trinfo = TypeResolveInfo {
            symbol_id,
            name: name.into(),
            token: symbol.token,
        };
        if let Some(node_index) = self.nodes.get_by_left(&symbol_id) {
            Ok(*node_index)
        } else {
            if let Some(path) = symbol.token.source.get_path() {
                let file_node = self.file_dag.add_node(()).index() as u32;
                self.file_nodes.insert(path, file_node);
            }

            let node_index = self.dag.add_node(()).index() as u32;
            self.insert_edge(self.source, node_index, Context::Irrelevant, false)?;
            self.nodes.insert(symbol_id, node_index);
            self.paths.insert(node_index, trinfo);
            self.symbols.insert(node_index, symbol);
            Ok(node_index)
        }
    }

    fn get_symbol(&self, node: u32) -> Symbol {
        match self.symbols.get(&node) {
            Some(x) => x.clone(),
            None => {
                panic!("Must insert node before accessing");
            }
        }
    }

    fn insert_edge(
        &mut self,
        start: u32,
        end: u32,
        edge: Context,
        recursive_ref: bool,
    ) -> Result<(), DagError> {
        match self.dag.add_edge(start.into(), end.into(), edge) {
            Ok(_) => {
                self.insert_file_edge(start, end);
                Ok(())
            }
            Err(_) => {
                let is_allowed_direct_reference = match edge {
                    Context::Module | Context::Interface | Context::Function => {
                        // Direct recursion of module/interface/function is allowed
                        start == end
                    }
                    Context::Package => {
                        // Self reference given as generic arg
                        start == end && !recursive_ref
                    }
                    _ => false,
                };
                if is_allowed_direct_reference {
                    Ok(())
                } else {
                    let ssym = self.get_symbol(start);
                    let esym = self.get_symbol(end);
                    Err(DagError::Cyclic(Box::new(ssym), Box::new(esym)))
                }
            }
        }
    }

    fn insert_file_edge(&mut self, start: u32, end: u32) {
        if start != self.source {
            let start = self.get_symbol(start);
            let end = self.get_symbol(end);
            if let (Some(start), Some(end)) =
                (start.token.source.get_path(), end.token.source.get_path())
            {
                let start = self.file_nodes.get_by_left(&start).unwrap();
                let end = self.file_nodes.get_by_left(&end).unwrap();
                let start: NodeIndex = (*start).into();
                let end: NodeIndex = (*end).into();
                if start != end && self.file_dag.find_edge(start, end).is_none() {
                    let err = self.file_dag.add_edge(start, end, ());
                    // cyclic error should be caught by dag
                    err.unwrap();
                }
            }
        }
    }

    fn exist_edge(&self, start: u32, end: u32) -> bool {
        self.dag.find_edge(start.into(), end.into()).is_some()
    }

    fn remove_edge(&mut self, start: u32, end: u32) {
        while let Some(x) = self.dag.find_edge(start.into(), end.into()) {
            self.dag.remove_edge(x);
        }
    }

    fn toposort(&self) -> Vec<Symbol> {
        let nodes = algo::toposort(self.dag.graph(), None).unwrap();
        let mut ret = vec![];
        for node in nodes {
            let index = node.index() as u32;
            if self.paths.contains_key(&index) {
                let sym = self.get_symbol(index);
                ret.push(sym);
            }
        }
        ret
    }

    fn connected_components(&self) -> Vec<Vec<Symbol>> {
        let mut ret = Vec::new();
        let mut graph = self.dag.graph().clone();

        // Reverse edge to traverse nodes which are called from parent node
        graph.reverse();

        for node in self.symbols.keys() {
            let mut connected = Vec::new();
            let mut dfs = Dfs::new(&graph, (*node).into());
            while let Some(x) = dfs.next(&graph) {
                let index = x.index() as u32;
                if self.paths.contains_key(&index) {
                    let symbol = self.get_symbol(index);
                    connected.push(symbol);
                }
            }
            if !connected.is_empty() {
                ret.push(connected);
            }
        }

        ret
    }

    fn dependent_files(&self) -> HashMap<PathId, Vec<PathId>> {
        let mut ret = HashMap::default();
        let graph = self.file_dag.graph().clone();

        for node in self.file_nodes.right_values() {
            let mut dependents = Vec::new();
            let mut dfs = Dfs::new(&graph, (*node).into());
            while let Some(x) = dfs.next(&graph) {
                let index = x.index() as u32;
                if index != *node
                    && let Some(x) = self.file_nodes.get_by_right(&index)
                {
                    dependents.push(*x);
                }
            }
            if !dependents.is_empty()
                && let Some(x) = self.file_nodes.get_by_right(node)
            {
                ret.insert(*x, dependents);
            }
        }

        ret
    }

    fn dump(&self) -> String {
        let mut nodes = algo::toposort(self.dag.graph(), None).unwrap();
        let mut ret = "".to_string();

        nodes.sort_by_key(|x| {
            let idx = x.index() as u32;
            if let Some(path) = self.paths.get(&idx) {
                path.name.clone()
            } else {
                "".to_string()
            }
        });

        let mut max_width = 0;
        for node in &nodes {
            let idx = node.index() as u32;
            if let Some(path) = self.paths.get(&idx) {
                max_width = max_width.max(path.name.len());
                for parent in self.dag.parents(*node).iter(&self.dag) {
                    let node = parent.1.index() as u32;
                    if let Some(path) = self.paths.get(&node) {
                        max_width = max_width.max(path.name.len() + 4);
                    }
                }
            }
        }

        for node in &nodes {
            let idx = node.index() as u32;
            if let Some(path) = self.paths.get(&idx) {
                let symbol = self.symbols.get(&idx).unwrap();
                ret.push_str(&format!(
                    "{}{} : {}\n",
                    path.name,
                    " ".repeat(max_width - path.name.len()),
                    symbol.kind
                ));
                let mut set = HashSet::default();
                for parent in self.dag.parents(*node).iter(&self.dag) {
                    let node = parent.1.index() as u32;
                    if !set.contains(&node) {
                        set.insert(node);
                        if let Some(path) = self.paths.get(&node) {
                            let symbol = self.symbols.get(&node).unwrap();
                            ret.push_str(&format!(
                                " |- {}{} : {}\n",
                                path.name,
                                " ".repeat(max_width - path.name.len() - 4),
                                symbol.kind
                            ));
                        }
                    }
                }
            }
        }
        ret
    }

    fn dump_file(&self) -> String {
        let nodes = algo::toposort(self.file_dag.graph(), None).unwrap();
        let mut ret = "".to_string();

        for node in &nodes {
            let idx = node.index() as u32;
            if let Some(path) = self.file_nodes.get_by_right(&idx) {
                ret.push_str(&format!("{path}\n"));
                for parent in self.file_dag.parents(*node).iter(&self.file_dag) {
                    let idx = parent.1.index() as u32;
                    if let Some(path) = self.file_nodes.get_by_right(&idx) {
                        ret.push_str(&format!(" |- {path}\n"));
                    }
                }
            }
        }
        ret
    }

    fn clear(&mut self) {
        self.clone_from(&Self::new());
    }
}

thread_local!(static TYPE_DAG: RefCell<TypeDag> = RefCell::new(TypeDag::new()));

pub fn add(cand: TypeDagCandidate) {
    TYPE_DAG.with(|f| f.borrow_mut().add(cand))
}

pub fn apply() -> Vec<AnalyzerError> {
    TYPE_DAG.with(|f| f.borrow_mut().apply())
}

pub fn toposort() -> Vec<Symbol> {
    TYPE_DAG.with(|f| f.borrow().toposort())
}

pub fn connected_components() -> Vec<Vec<Symbol>> {
    TYPE_DAG.with(|f| f.borrow().connected_components())
}

pub fn dependent_files() -> HashMap<PathId, Vec<PathId>> {
    TYPE_DAG.with(|f| f.borrow().dependent_files())
}

pub fn dump() -> String {
    TYPE_DAG.with(|f| f.borrow().dump())
}

pub fn dump_file() -> String {
    TYPE_DAG.with(|f| f.borrow().dump_file())
}

pub fn clear() {
    TYPE_DAG.with(|f| f.borrow_mut().clear())
}