fluidattacks-blends-domain 0.2.0

Blends functional core: pure AST graph to syntax graph (no_std)
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
//! Counterpart of `blends/syntax/metadata/java.py`: the node-0 metadata
//! registries (class/method structure and Java instance tracking).

use alloc::borrow::ToOwned;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use crate::syntax::node::{FileInstanceData, FileStructData, FileStructValue, SyntaxNode};
use crate::syntax::SyntaxGraphArgs;
use crate::syntax::SyntaxGraphError;
use crate::{Language, NodeId};

#[allow(dead_code, reason = "wired when the java class reader lands")]
pub fn add_class_to_metadata(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
    name: &str,
) -> Result<(), SyntaxGraphError> {
    let Some(SyntaxNode::Metadata { structure, .. }) = args.syntax_graph.nodes.get_mut(&NodeId(0))
    else {
        return Err(SyntaxGraphError::UnexpectedAstShape);
    };

    let mut parent_class = structure;
    for elem in &args.metadata.class_path {
        let data = &mut parent_class
            .get_mut(elem)
            .ok_or(SyntaxGraphError::UnexpectedAstShape)?
            .data;

        parent_class = match data {
            FileStructValue::MethodName(_) => return Ok(()),
            FileStructValue::Children(children) => children,
        };
    }

    parent_class.insert(
        name.to_owned(),
        FileStructData {
            node: n_id,
            kind: "class".to_owned(),
            data: FileStructValue::Children(BTreeMap::new()),
            node_range: None,
        },
    );
    args.metadata.class_path.push(name.to_owned());

    Ok(())
}

#[allow(dead_code, reason = "wired when the java method reader lands")]
pub fn add_method_to_metadata(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
    name: &str,
) -> Result<(), SyntaxGraphError> {
    let Some(SyntaxNode::Metadata { structure, .. }) = args.syntax_graph.nodes.get_mut(&NodeId(0))
    else {
        return Err(SyntaxGraphError::UnexpectedAstShape);
    };

    let mut parent_class = structure;
    for elem in &args.metadata.class_path {
        let data = &mut parent_class
            .get_mut(elem)
            .ok_or(SyntaxGraphError::UnexpectedAstShape)?
            .data;

        parent_class = match data {
            FileStructValue::MethodName(_) => return Ok(()),
            FileStructValue::Children(children) => children,
        };
    }

    parent_class.insert(
        name.to_owned(),
        FileStructData {
            node: n_id,
            kind: "method".to_owned(),
            data: FileStructValue::MethodName(name.to_owned()),
            node_range: None,
        },
    );

    Ok(())
}

pub fn add_node_range_to_method(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
    name: &str,
) -> Result<(), SyntaxGraphError> {
    let node_range: Vec<NodeId> = args
        .syntax_graph
        .nodes
        .keys()
        .copied()
        .skip_while(|node_id| *node_id != n_id)
        .collect();

    let Some(SyntaxNode::Metadata { structure, .. }) = args.syntax_graph.nodes.get_mut(&NodeId(0))
    else {
        return Err(SyntaxGraphError::UnexpectedAstShape);
    };

    let mut parent_class = structure;
    for elem in &args.metadata.class_path {
        let data = &mut parent_class
            .get_mut(elem)
            .ok_or(SyntaxGraphError::UnexpectedAstShape)?
            .data;

        parent_class = match data {
            FileStructValue::MethodName(_) => return Ok(()),
            FileStructValue::Children(children) => children,
        };
    }

    if let Some(method_data) = parent_class.get_mut(name) {
        method_data.node_range = Some(node_range);
    }

    Ok(())
}

#[allow(
    dead_code,
    reason = "wired when the java variable-declaration reader lands"
)]
pub fn add_instance_to_metadata(
    args: &mut SyntaxGraphArgs<'_>,
    var_type: &str,
    var_name: &str,
    multi_paths: &[&str],
) -> Result<(), SyntaxGraphError> {
    let Some(current_class) = args.metadata.class_path.last().cloned() else {
        return Ok(());
    };
    let extension = primary_extension(args.language);

    let imports: Vec<String> = match args.syntax_graph.nodes.get(&NodeId(0)) {
        Some(SyntaxNode::Metadata { imports, .. }) => imports.clone(),
        _ => return Err(SyntaxGraphError::UnexpectedAstShape),
    };

    let Some(SyntaxNode::Metadata { instances, .. }) = args.syntax_graph.nodes.get_mut(&NodeId(0))
    else {
        return Err(SyntaxGraphError::UnexpectedAstShape);
    };
    let class_instances = instances.entry(current_class).or_default();

    let mut possible_path = var_type.replace('.', "/");
    possible_path.push_str(extension);
    if let Some(path) = get_file_from_path(&possible_path, multi_paths) {
        class_instances.insert(
            var_name.to_owned(),
            FileInstanceData {
                object: split_on_last_dot(var_type).1.to_owned(),
                source: path.to_owned(),
                source_type: "file_path".to_owned(),
            },
        );
    }

    for imported_package in &imports {
        let (import_prefix, import_leaf) = split_on_last_dot(imported_package);
        let (var_prefix, _) = split_on_last_dot(var_type);
        let is_match = if import_leaf == "*" {
            imported_package == var_type || import_prefix == var_prefix
        } else {
            imported_package == var_type || import_leaf == var_type
        };
        if is_match {
            class_instances.insert(
                var_name.to_owned(),
                FileInstanceData {
                    object: var_type.to_owned(),
                    source: import_prefix.to_owned(),
                    source_type: "package".to_owned(),
                },
            );
        }
    }

    Ok(())
}

#[allow(dead_code, reason = "wired when build_assignment_node lands")]
pub fn del_metadata_instance(
    args: &mut SyntaxGraphArgs<'_>,
    variable_id: NodeId,
    value_id: NodeId,
) -> Result<(), SyntaxGraphError> {
    let Some(SyntaxNode::SymbolLookup { symbol, .. }) = args.syntax_graph.nodes.get(&variable_id)
    else {
        return Ok(());
    };
    if symbol.is_empty() {
        return Ok(());
    }
    let var = symbol.clone();

    let Some(current_class) = args.metadata.class_path.last().cloned() else {
        return Ok(());
    };

    let new_object = match args.syntax_graph.nodes.get(&value_id) {
        Some(SyntaxNode::ObjectCreation { name, .. }) => Some(name.clone()),
        _ => None,
    };

    let Some(SyntaxNode::Metadata { instances, .. }) = args.syntax_graph.nodes.get_mut(&NodeId(0))
    else {
        return Err(SyntaxGraphError::UnexpectedAstShape);
    };
    let Some(class_instances) = instances.get_mut(&current_class) else {
        return Ok(());
    };
    let Some(tracked_object) = class_instances.get(&var).map(|data| data.object.clone()) else {
        return Ok(());
    };

    if new_object.as_deref() != Some(tracked_object.as_str()) {
        class_instances.remove(&var);
    }

    Ok(())
}

const fn primary_extension(language: Language) -> &'static str {
    match language {
        Language::CSharp => ".cs",
        Language::Elixir => ".ex",
        Language::Go => ".go",
        Language::Hcl => ".hcl",
        Language::Java => ".java",
        Language::JavaScript => ".js",
        Language::Json => ".json",
        Language::Kotlin => ".kt",
        Language::Php => ".php",
        Language::Python => ".py",
        Language::Ruby => ".rb",
        Language::Rust => ".rs",
        Language::Scala => ".scala",
        Language::Swift => ".swift",
        Language::TypeScript => ".ts",
        Language::Yaml => ".yaml",
    }
}

fn split_on_last_dot(value: &str) -> (&str, &str) {
    value.rsplit_once('.').map_or((value, ""), |split| split)
}

fn get_file_from_path<'a>(file_name: &str, multi_paths: &'a [&str]) -> Option<&'a str> {
    const MIN_PATH_DEPTH: usize = 4;
    if file_name.matches('/').count() >= MIN_PATH_DEPTH {
        return multi_paths
            .iter()
            .copied()
            .find(|path| path.contains(file_name));
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{
        add_class_to_metadata, add_instance_to_metadata, add_method_to_metadata,
        del_metadata_instance, split_on_last_dot,
    };
    use crate::ast::AstGraph;
    use crate::syntax::node::{FileInstanceData, FileStructValue, SyntaxNode};
    use crate::syntax::{SyntaxGraph, SyntaxGraphArgs, SyntaxMetadata, SyntaxReader};
    use crate::{Language, NodeId};
    use alloc::borrow::ToOwned;
    use alloc::collections::BTreeMap;
    use alloc::string::String;
    use alloc::vec;
    use alloc::vec::Vec;

    fn no_dispatch(_: &str) -> Option<SyntaxReader> {
        None
    }

    fn metadata_graph() -> SyntaxGraph {
        let mut graph = SyntaxGraph::new();
        graph.add_node(
            NodeId(0),
            SyntaxNode::Metadata {
                path: "F.java".to_owned(),
                structure: BTreeMap::new(),
                instances: BTreeMap::new(),
                imports: Vec::new(),
                package: None,
            },
        );
        graph
    }

    fn instances(graph: &SyntaxGraph) -> &BTreeMap<String, BTreeMap<String, FileInstanceData>> {
        match graph.nodes.get(&NodeId(0)) {
            Some(SyntaxNode::Metadata { instances, .. }) => instances,
            _ => panic!("node 0 must be Metadata"),
        }
    }

    #[test]
    fn split_on_last_dot_splits_at_the_final_dot() {
        assert_eq!(split_on_last_dot("a.b.c"), ("a.b", "c"));
        assert_eq!(split_on_last_dot("nodot"), ("nodot", ""));
        assert_eq!(split_on_last_dot(""), ("", ""));
    }

    #[test]
    fn class_and_method_nest_under_the_class_path() {
        let ast = AstGraph::new();
        let mut graph = metadata_graph();
        let mut meta = SyntaxMetadata::seeded(NodeId(1));

        {
            let mut args =
                SyntaxGraphArgs::new(Language::Java, &ast, &mut graph, &mut meta, no_dispatch);
            add_class_to_metadata(&mut args, NodeId(5), "Foo").unwrap();
            add_method_to_metadata(&mut args, NodeId(6), "bar").unwrap();
        }

        assert_eq!(meta.class_path, vec!["Foo".to_owned()]);
        let Some(SyntaxNode::Metadata { structure, .. }) = graph.nodes.get(&NodeId(0)) else {
            panic!("node 0 must be Metadata");
        };
        let FileStructValue::Children(children) = &structure.get("Foo").unwrap().data else {
            panic!("Foo must be a class with children");
        };
        assert!(matches!(
            &children.get("bar").unwrap().data,
            FileStructValue::MethodName(name) if name == "bar"
        ));
    }

    #[test]
    fn add_instance_matches_an_imported_package() {
        let ast = AstGraph::new();
        let mut graph = metadata_graph();
        if let Some(SyntaxNode::Metadata { imports, .. }) = graph.nodes.get_mut(&NodeId(0)) {
            imports.push("com.example.Widget".to_owned());
        }
        let mut meta = SyntaxMetadata::seeded(NodeId(1));
        meta.class_path.push("Foo".to_owned());

        {
            let mut args =
                SyntaxGraphArgs::new(Language::Java, &ast, &mut graph, &mut meta, no_dispatch);
            add_instance_to_metadata(&mut args, "com.example.Widget", "w", &[]).unwrap();
        }

        let data = instances(&graph).get("Foo").unwrap().get("w").unwrap();
        assert_eq!(data.object, "com.example.Widget");
        assert_eq!(data.source, "com.example");
        assert_eq!(data.source_type, "package");
    }

    #[test]
    fn add_instance_matches_a_resolved_file_path() {
        let ast = AstGraph::new();
        let mut graph = metadata_graph();
        let mut meta = SyntaxMetadata::seeded(NodeId(1));
        meta.class_path.push("Foo".to_owned());

        {
            let mut args =
                SyntaxGraphArgs::new(Language::Java, &ast, &mut graph, &mut meta, no_dispatch);
            add_instance_to_metadata(
                &mut args,
                "a.b.c.d.Widget",
                "w",
                &["/root/a/b/c/d/Widget.java"],
            )
            .unwrap();
        }

        let data = instances(&graph).get("Foo").unwrap().get("w").unwrap();
        assert_eq!(data.object, "Widget");
        assert_eq!(data.source, "/root/a/b/c/d/Widget.java");
        assert_eq!(data.source_type, "file_path");
    }

    #[test]
    fn del_metadata_instance_removes_on_a_non_matching_reassignment() {
        let ast = AstGraph::new();
        let mut graph = metadata_graph();
        if let Some(SyntaxNode::Metadata { instances, .. }) = graph.nodes.get_mut(&NodeId(0)) {
            let mut class_map = BTreeMap::new();
            class_map.insert(
                "obj".to_owned(),
                FileInstanceData {
                    object: "Widget".to_owned(),
                    source: "s".to_owned(),
                    source_type: "package".to_owned(),
                },
            );
            instances.insert("Foo".to_owned(), class_map);
        }
        graph.add_node(
            NodeId(10),
            SyntaxNode::SymbolLookup {
                symbol: "obj".to_owned(),
                symbol_scope: None,
                value: None,
            },
        );
        graph.add_node(
            NodeId(11),
            SyntaxNode::ObjectCreation {
                name: "Other".to_owned(),
                arguments_id: None,
                initializer_id: None,
            },
        );
        let mut meta = SyntaxMetadata::seeded(NodeId(1));
        meta.class_path.push("Foo".to_owned());

        {
            let mut args =
                SyntaxGraphArgs::new(Language::Java, &ast, &mut graph, &mut meta, no_dispatch);
            del_metadata_instance(&mut args, NodeId(10), NodeId(11)).unwrap();
        }

        assert!(instances(&graph).get("Foo").unwrap().get("obj").is_none());
    }

    #[test]
    fn del_metadata_instance_keeps_a_matching_object_creation() {
        let ast = AstGraph::new();
        let mut graph = metadata_graph();
        if let Some(SyntaxNode::Metadata { instances, .. }) = graph.nodes.get_mut(&NodeId(0)) {
            let mut class_map = BTreeMap::new();
            class_map.insert(
                "obj".to_owned(),
                FileInstanceData {
                    object: "Widget".to_owned(),
                    source: "s".to_owned(),
                    source_type: "package".to_owned(),
                },
            );
            instances.insert("Foo".to_owned(), class_map);
        }
        graph.add_node(
            NodeId(10),
            SyntaxNode::SymbolLookup {
                symbol: "obj".to_owned(),
                symbol_scope: None,
                value: None,
            },
        );
        graph.add_node(
            NodeId(11),
            SyntaxNode::ObjectCreation {
                name: "Widget".to_owned(),
                arguments_id: None,
                initializer_id: None,
            },
        );
        let mut meta = SyntaxMetadata::seeded(NodeId(1));
        meta.class_path.push("Foo".to_owned());

        {
            let mut args =
                SyntaxGraphArgs::new(Language::Java, &ast, &mut graph, &mut meta, no_dispatch);
            del_metadata_instance(&mut args, NodeId(10), NodeId(11)).unwrap();
        }

        assert!(instances(&graph).get("Foo").unwrap().get("obj").is_some());
    }
}