stack-graphs 0.10.1

Name binding for arbitrary programming languages
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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2022, stack-graphs authors.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------

use itertools::Itertools;
use lsp_positions::Offset;
use lsp_positions::Position;
use lsp_positions::Span;
use serde::ser::Serialize;
use serde::ser::SerializeSeq;
use serde::ser::SerializeStruct;
use serde::ser::Serializer;
use serde_json::Value;
use std::ops::Index;
use thiserror::Error;

use crate::arena::Handle;
use crate::graph::DebugEntry;
use crate::graph::DebugInfo;
use crate::graph::Edge;
use crate::graph::File;
use crate::graph::Node;
use crate::graph::NodeID;
use crate::graph::SourceInfo;
use crate::graph::StackGraph;
use crate::paths::Path;
use crate::paths::PathEdge;
use crate::paths::PathEdgeList;
use crate::paths::Paths;
use crate::paths::ScopeStack;
use crate::paths::ScopedSymbol;
use crate::paths::SymbolStack;
use crate::NoCancellation;

#[derive(Debug, Error)]
#[error(transparent)]
pub struct JsonError(#[from] serde_json::error::Error);

//-----------------------------------------------------------------------------
// Filter

pub trait Filter {
    /// Return whether elements for the given file must be included.
    fn include_file(&self, graph: &StackGraph, file: &Handle<File>) -> bool;

    /// Return whether the given node must be included.
    /// Nodes of excluded files are always excluded.
    fn include_node(&self, graph: &StackGraph, node: &Handle<Node>) -> bool;

    /// Return whether the given edge must be included.
    /// Edges via excluded nodes are always excluded.
    fn include_edge(&self, graph: &StackGraph, source: &Handle<Node>, sink: &Handle<Node>) -> bool;

    /// Return whether the given path must be included.
    /// Paths via excluded nodes or edges are always excluded.
    fn include_path(&self, graph: &StackGraph, paths: &Paths, path: &Path) -> bool;
}

impl<F> Filter for F
where
    F: Fn(&StackGraph, &Handle<File>) -> bool,
{
    fn include_file(&self, graph: &StackGraph, file: &Handle<File>) -> bool {
        self(graph, file)
    }

    fn include_node(&self, _graph: &StackGraph, _node: &Handle<Node>) -> bool {
        true
    }

    fn include_edge(
        &self,
        _graph: &StackGraph,
        _source: &Handle<Node>,
        _sink: &Handle<Node>,
    ) -> bool {
        true
    }

    fn include_path(&self, _graph: &StackGraph, _paths: &Paths, _path: &Path) -> bool {
        true
    }
}

/// Struct that ensures the implications of exclusions.
/// For example, that nodes frome excluded files are not included, etc.
struct ImplicationFilter<'a>(&'a dyn Filter);

impl Filter for ImplicationFilter<'_> {
    fn include_file(&self, graph: &StackGraph, file: &Handle<File>) -> bool {
        self.0.include_file(graph, file)
    }

    fn include_node(&self, graph: &StackGraph, node: &Handle<Node>) -> bool {
        graph[*node]
            .id()
            .file()
            .map_or(true, |f| self.include_file(graph, &f))
            && self.0.include_node(graph, node)
    }

    fn include_edge(&self, graph: &StackGraph, source: &Handle<Node>, sink: &Handle<Node>) -> bool {
        self.include_node(graph, source)
            && self.include_node(graph, sink)
            && self.0.include_edge(graph, source, sink)
    }

    fn include_path(&self, graph: &StackGraph, paths: &Paths, path: &Path) -> bool {
        path.edges
            .iter_unordered(paths)
            .map(|e| graph.node_for_id(e.source_node_id).unwrap())
            .chain(std::iter::once(path.end_node))
            .tuple_windows()
            .all(|(source, sink)| self.include_edge(graph, &source, &sink))
            && self.0.include_path(graph, paths, path)
    }
}

//-----------------------------------------------------------------------------
// InStackGraph

struct InStackGraph<'a, T>(T, &'a StackGraph, &'a dyn Filter);

impl<'a, T> InStackGraph<'a, T> {
    fn with<U>(&'a self, u: U) -> InStackGraph<'a, U> {
        InStackGraph(u, self.1, self.2)
    }

    fn with_idx<Idx: Copy, U: ?Sized>(&'a self, idx: Idx) -> InStackGraph<'a, (Idx, &U)>
    where
        StackGraph: Index<Idx, Output = U>,
    {
        InStackGraph((idx, &self.1[idx]), self.1, self.2)
    }
}

//-----------------------------------------------------------------------------
// StackGraph

impl<'a> StackGraph {
    pub fn to_json(&'a self, f: &'a dyn Filter) -> JsonStackGraph {
        JsonStackGraph(self, f)
    }
}

pub struct JsonStackGraph<'a>(&'a StackGraph, &'a dyn Filter);

impl<'a> JsonStackGraph<'a> {
    pub fn to_value(&self) -> Result<Value, JsonError> {
        Ok(serde_json::to_value(self)?)
    }

    pub fn to_string(&self) -> Result<String, JsonError> {
        Ok(serde_json::to_string(self)?)
    }

    pub fn to_string_pretty(&self) -> Result<String, JsonError> {
        Ok(serde_json::to_string_pretty(self)?)
    }
}

impl Serialize for JsonStackGraph<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut ser = serializer.serialize_struct("stack_graph", 2)?;
        ser.serialize_field(
            "files",
            &InStackGraph(&Files, self.0, &ImplicationFilter(self.1)),
        )?;
        ser.serialize_field(
            "nodes",
            &InStackGraph(&Nodes, self.0, &ImplicationFilter(self.1)),
        )?;
        ser.serialize_field(
            "edges",
            &InStackGraph(&Edges, self.0, &ImplicationFilter(self.1)),
        )?;
        ser.end()
    }
}

//-----------------------------------------------------------------------------
// Files

struct Files;

impl<'a> Serialize for InStackGraph<'a, &Files> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let filter = self.2;

        let mut ser = serializer.serialize_seq(None)?;
        for file in graph.iter_files().filter(|f| filter.include_file(graph, f)) {
            ser.serialize_element(&self.with_idx(file))?;
        }
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, (Handle<File>, &File)> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let file = self.0 .1;
        serializer.serialize_str(file.name())
    }
}

//-----------------------------------------------------------------------------
// Nodes

struct Nodes;

impl Serialize for InStackGraph<'_, &Nodes> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let filter = self.2;

        let mut nodes = serializer.serialize_seq(None)?;
        for node in self
            .1
            .iter_nodes()
            .filter(|n| filter.include_node(graph, &n))
        {
            nodes.serialize_element(&self.with_idx(node))?;
        }
        nodes.end()
    }
}

impl Serialize for InStackGraph<'_, (Handle<Node>, &Node)> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let handle = self.0 .0;
        let node = self.0 .1;
        let source_info = graph.source_info(handle);
        let debug_info = graph.debug_info(handle);

        let mut len = 2;
        if source_info.is_some() {
            len += 1;
        }
        if debug_info.is_some() {
            len += 1;
        }

        let mut ser = match node {
            Node::DropScopes(_node) => {
                let mut ser = serializer.serialize_struct("node", len + 1)?;
                ser.serialize_field("type", "drop_scopes")?;
                ser
            }
            Node::JumpTo(_node) => {
                let mut ser = serializer.serialize_struct("node", len + 1)?;
                ser.serialize_field("type", "jump_to_scope")?;
                ser
            }
            Node::PopScopedSymbol(node) => {
                let mut ser = serializer.serialize_struct("node", len + 3)?;
                ser.serialize_field("type", "pop_scoped_symbol")?;
                ser.serialize_field("symbol", &graph[node.symbol])?;
                ser.serialize_field("is_definition", &node.is_definition)?;
                ser
            }
            Node::PopSymbol(node) => {
                let mut ser = serializer.serialize_struct("node", len + 3)?;
                ser.serialize_field("type", "pop_symbol")?;
                ser.serialize_field("symbol", &graph[node.symbol])?;
                ser.serialize_field("is_definition", &node.is_definition)?;
                ser
            }
            Node::PushScopedSymbol(node) => {
                let mut ser = serializer.serialize_struct("node", len + 4)?;
                ser.serialize_field("type", "push_scoped_symbol")?;
                ser.serialize_field("symbol", &graph[node.symbol])?;
                ser.serialize_field("scope", &self.with(&node.scope))?;
                ser.serialize_field("is_reference", &node.is_reference)?;
                ser
            }
            Node::PushSymbol(node) => {
                let mut ser = serializer.serialize_struct("node", len + 3)?;
                ser.serialize_field("type", "push_symbol")?;
                ser.serialize_field("symbol", &graph[node.symbol])?;
                ser.serialize_field("is_reference", &node.is_reference)?;
                ser
            }
            Node::Root(_node) => {
                let mut ser = serializer.serialize_struct("node", len + 1)?;
                ser.serialize_field("type", "root")?;
                ser
            }
            Node::Scope(node) => {
                let mut ser = serializer.serialize_struct("node", len + 2)?;
                ser.serialize_field("type", "scope")?;
                ser.serialize_field("is_exported", &node.is_exported)?;
                ser
            }
        };

        ser.serialize_field("id", &self.with(&node.id()))?;
        if let Some(source_info) = source_info {
            ser.serialize_field("source_info", &self.with(source_info))?;
        }
        if let Some(debug_info) = debug_info {
            ser.serialize_field("debug_info", &self.with(debug_info))?;
        }

        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &NodeID> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let node_id = self.0;

        let len = 1 + node_id.file().map(|_| 1).unwrap_or(0);
        let mut ser = serializer.serialize_struct("node_id", len)?;
        if let Some(file) = node_id.file() {
            ser.serialize_field("file", &self.with_idx(file))?;
        }
        ser.serialize_field("local_id", &node_id.local_id())?;
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &SourceInfo> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let source_info = self.0;

        let mut len = 1;
        if source_info.syntax_type.is_some() {
            len += 1;
        }

        let mut ser = serializer.serialize_struct("source_info", len)?;
        ser.serialize_field("span", &self.with(&source_info.span))?;
        if let Some(syntax_type) = source_info.syntax_type {
            ser.serialize_field("syntax_type", &graph[syntax_type])?;
        }
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &DebugInfo> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let debug_info = self.0;

        let mut ser = serializer.serialize_seq(None)?;
        for entry in debug_info.iter() {
            ser.serialize_element(&self.with(entry))?;
        }
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &DebugEntry> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let debug_entry = self.0;

        let mut ser = serializer.serialize_struct("debug_entry", 2)?;
        ser.serialize_field("key", &graph[debug_entry.key])?;
        ser.serialize_field("value", &graph[debug_entry.value])?;
        ser.end()
    }
}

//-----------------------------------------------------------------------------
// Edges

struct Edges;

impl Serialize for InStackGraph<'_, &Edges> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let filter = self.2;

        let mut ser = serializer.serialize_seq(None)?;
        for source in self.1.iter_nodes() {
            for edge in self
                .1
                .outgoing_edges(source)
                .filter(|e| filter.include_edge(graph, &e.source, &e.sink))
            {
                ser.serialize_element(&self.with(&edge))?;
            }
        }
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &Edge> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let graph = self.1;
        let edge = self.0;

        let mut ser = serializer.serialize_struct("edge", 3)?;
        ser.serialize_field("source", &self.with(&graph[edge.source].id()))?;
        ser.serialize_field("sink", &self.with(&graph[edge.sink].id()))?;
        ser.serialize_field("precedence", &edge.precedence)?;
        ser.end()
    }
}

//-----------------------------------------------------------------------------
// Span, Position, Offset

impl Serialize for InStackGraph<'_, &Span> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut ser = serializer.serialize_struct("span", 2)?;
        ser.serialize_field("start", &self.with(&self.0.start))?;
        ser.serialize_field("end", &self.with(&self.0.end))?;
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &Position> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let position = self.0;

        let mut ser = serializer.serialize_struct("position", 2)?;
        ser.serialize_field("line", &position.line)?;
        ser.serialize_field("column", &self.with(&position.column))?;
        ser.end()
    }
}

impl Serialize for InStackGraph<'_, &Offset> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let offset = self.0;

        let mut ser = serializer.serialize_struct("offset", 3)?;
        ser.serialize_field("utf8_offset", &offset.utf8_offset)?;
        ser.serialize_field("utf16_offset", &offset.utf16_offset)?;
        ser.serialize_field("grapheme_offset", &offset.grapheme_offset)?;
        ser.end()
    }
}

//-----------------------------------------------------------------------------
// InPaths

struct InPaths<'a, T>(T, &'a Paths, &'a StackGraph, &'a dyn Filter);

impl<'a, T> InPaths<'a, T> {
    fn with<U>(&'a self, u: U) -> InPaths<'a, U> {
        InPaths(u, self.1, self.2, self.3)
    }

    fn in_stack_graph(&'a self) -> InStackGraph<'a, T>
    where
        T: Copy,
    {
        InStackGraph(self.0, self.2, self.3)
    }
}

//-----------------------------------------------------------------------------
// Paths

impl<'a> Paths {
    pub fn to_json(&'a mut self, graph: &'a StackGraph, f: &'a dyn Filter) -> JsonPaths<'_> {
        JsonPaths(self, graph, f)
    }
}

pub struct JsonPaths<'a>(&'a mut Paths, &'a StackGraph, &'a dyn Filter);

impl<'a> JsonPaths<'a> {
    pub fn to_value(&mut self) -> Result<Value, JsonError> {
        let filter = ImplicationFilter(self.2);
        let paths = Self::to_path_vec(self.1, self.0, &filter);
        Ok(serde_json::to_value(&InPaths(
            &paths, self.0, self.1, &filter,
        ))?)
    }

    pub fn to_string(&mut self) -> Result<String, JsonError> {
        let filter = ImplicationFilter(self.2);
        let paths = Self::to_path_vec(self.1, self.0, &filter);
        Ok(serde_json::to_string(&InPaths(
            &paths, self.0, self.1, &filter,
        ))?)
    }

    pub fn to_string_pretty(&mut self) -> Result<String, JsonError> {
        let filter = ImplicationFilter(self.2);
        let paths = Self::to_path_vec(self.1, self.0, &filter);
        Ok(serde_json::to_string_pretty(&InPaths(
            &paths, self.0, self.1, &filter,
        ))?)
    }

    fn to_path_vec(graph: &StackGraph, paths: &mut Paths, filter: &dyn Filter) -> Vec<Path> {
        let mut path_vec = Vec::new();
        paths
            .find_all_paths(graph, graph.iter_nodes(), &NoCancellation, |g, ps, p| {
                if filter.include_path(g, ps, &p) {
                    let mut p = p;
                    p.edges.ensure_forwards(ps);
                    path_vec.push(p);
                }
            })
            .expect("should never be cancelled");
        path_vec
    }
}

impl Serialize for InPaths<'_, &Vec<Path>> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let paths = self.0;

        let mut ser = serializer.serialize_seq(paths.len().into())?;
        for path in paths {
            ser.serialize_element(&self.with(path))?;
        }
        ser.end()
    }
}

impl Serialize for InPaths<'_, &Path> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let path = self.0;
        let graph = self.2;

        let mut ser = serializer.serialize_struct("path", 5)?;
        ser.serialize_field(
            "start_node",
            &self.in_stack_graph().with(&graph[path.start_node].id()),
        )?;
        ser.serialize_field(
            "end_node",
            &self.in_stack_graph().with(&graph[path.end_node].id()),
        )?;
        ser.serialize_field("symbol_stack", &self.with(&path.symbol_stack))?;
        ser.serialize_field("scope_stack", &self.with(&path.scope_stack))?;
        ser.serialize_field("edges", &self.with(&path.edges))?;
        ser.end()
    }
}

impl Serialize for InPaths<'_, &SymbolStack> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let symbol_stack = self.0;
        let paths = self.1;

        let mut ser = serializer.serialize_seq(symbol_stack.len().into())?;
        for scoped_symbol in symbol_stack.iter(paths) {
            ser.serialize_element(&self.with(&scoped_symbol))?;
        }
        ser.end()
    }
}

impl Serialize for InPaths<'_, &ScopedSymbol> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let scoped_symbol = self.0;
        let graph = self.2;

        let mut len = 1;
        if scoped_symbol.scopes.is_some() {
            len += 1;
        }

        let mut ser = serializer.serialize_struct("scoped_symbol", len)?;
        ser.serialize_field("symbol", &graph[scoped_symbol.symbol])?;
        if let Some(scopes) = scoped_symbol.scopes.into_option() {
            ser.serialize_field("scopes", &self.with(&scopes))?;
        }
        ser.end()
    }
}

impl Serialize for InPaths<'_, &ScopeStack> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let scope_stack = self.0;
        let paths = self.1;
        let graph = self.2;

        let mut ser = serializer.serialize_seq(scope_stack.len().into())?;
        for node in scope_stack.iter(paths) {
            ser.serialize_element(&self.in_stack_graph().with(&graph[node].id()))?;
        }
        ser.end()
    }
}

impl Serialize for InPaths<'_, &PathEdgeList> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let edge_list = self.0;
        let paths = self.1;

        let mut ser = serializer.serialize_seq(edge_list.len().into())?;
        for edge in edge_list.iter_unordered(paths) {
            ser.serialize_element(&self.with(&edge))?;
        }
        ser.end()
    }
}

impl Serialize for InPaths<'_, &PathEdge> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let edge = self.0;

        let mut ser = serializer.serialize_struct("path_edge", 2)?;
        ser.serialize_field("source", &self.in_stack_graph().with(&edge.source_node_id))?;
        ser.serialize_field("precedence", &edge.precedence)?;
        ser.end()
    }
}