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
use crate::error::RuleError;
use crate::validation::context::ValidatorContext;
use crate::validation::visitor::Visitor;
use graphql_parser::query::{Document, FragmentDefinition, FragmentSpread};
use graphql_parser::Pos;
use std::collections::{HashMap, HashSet};

struct CycleDetector<'a> {
    visited: HashSet<&'a str>,
    spreads: &'a HashMap<&'a str, Vec<(&'a str, Pos)>>,
    path_indices: HashMap<&'a str, usize>,
    errors: Vec<RuleError>,
}

impl<'a> CycleDetector<'a> {
    fn detect_from(&mut self, from: &'a str, path: &mut Vec<(&'a str, Pos)>) {
        self.visited.insert(from);

        if !self.spreads.contains_key(from) {
            return;
        }

        self.path_indices.insert(from, path.len());

        for (name, pos) in &self.spreads[from] {
            let index = self.path_indices.get(name).cloned();

            if let Some(index) = index {
                let err_pos = if index < path.len() {
                    path[index].1
                } else {
                    *pos
                };

                self.errors.push(RuleError {
                    locations: vec![err_pos],
                    message: format!("Cannot spread fragment \"{}\"", name),
                });
            } else if !self.visited.contains(name) {
                path.push((name, *pos));
                self.detect_from(name, path);
                path.pop();
            }
        }

        self.path_indices.remove(from);
    }
}

#[derive(Default)]
pub struct NoFragmentCycles<'a> {
    current_fragment: Option<&'a str>,
    spreads: HashMap<&'a str, Vec<(&'a str, Pos)>>,
    fragment_order: Vec<&'a str>,
}

impl<'a> Visitor<'a> for NoFragmentCycles<'a> {
    fn exit_document(&mut self, ctx: &mut ValidatorContext<'a>, _doc: &'a Document) {
        let mut detector = CycleDetector {
            visited: HashSet::new(),
            spreads: &self.spreads,
            path_indices: HashMap::new(),
            errors: Vec::new(),
        };

        for frag in &self.fragment_order {
            if !detector.visited.contains(frag) {
                let mut path = Vec::new();
                detector.detect_from(frag, &mut path);
            }
        }

        ctx.append_errors(detector.errors);
    }

    fn enter_fragment_definition(
        &mut self,
        _ctx: &mut ValidatorContext<'a>,
        fragment_definition: &'a FragmentDefinition,
    ) {
        self.current_fragment = Some(&fragment_definition.name);
        self.fragment_order.push(&fragment_definition.name);
    }

    fn exit_fragment_definition(
        &mut self,
        _ctx: &mut ValidatorContext<'a>,
        _fragment_definition: &'a FragmentDefinition,
    ) {
        self.current_fragment = None;
    }

    fn enter_fragment_spread(
        &mut self,
        _ctx: &mut ValidatorContext<'a>,
        fragment_spread: &'a FragmentSpread,
    ) {
        if let Some(current_fragment) = self.current_fragment {
            self.spreads
                .entry(current_fragment)
                .or_insert_with(Vec::new)
                .push((&fragment_spread.fragment_name, fragment_spread.position));
        }
    }
}