dsntk_feel_parser/
scope.rs

1//! Implementation of the scope used while parsing FEEL expressions.
2
3use crate::context::ParsingContext;
4use dsntk_feel::Name;
5use std::cell::RefCell;
6use std::collections::HashSet;
7use std::fmt;
8use std::fmt::Display;
9
10/// Parsing scope.
11pub struct ParsingScope {
12  /// The stack of parsing contexts.
13  stack: RefCell<Vec<ParsingContext>>,
14  /// Set of parsed names.
15  names: RefCell<HashSet<Name>>,
16}
17
18impl From<&dsntk_feel::FeelScope> for ParsingScope {
19  /// Temporary - remove
20  fn from(scope: &dsntk_feel::FeelScope) -> Self {
21    let stack = RefCell::new(vec![]);
22    for feel_context in scope.contexts() {
23      stack.borrow_mut().push(feel_context.into());
24    }
25    let names = RefCell::new(HashSet::default());
26    Self { stack, names }
27  }
28}
29
30impl Default for ParsingScope {
31  /// Creates a default parsing scope containing single parsing context.
32  fn default() -> Self {
33    Self {
34      stack: RefCell::new(vec![ParsingContext::default()]),
35      names: RefCell::new(HashSet::default()),
36    }
37  }
38}
39
40impl Display for ParsingScope {
41  /// Converts parsing scope to text representation.
42  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43    write!(f, "[{}]", self.stack.borrow_mut().iter().map(|ctx| ctx.to_string()).collect::<Vec<String>>().join(", "))
44  }
45}
46
47impl ParsingScope {
48  /// Returns a context removed from the top of the stack.
49  pub fn pop(&self) -> Option<ParsingContext> {
50    self.stack.borrow_mut().pop()
51  }
52
53  /// Puts a context on the top of the stack.
54  pub fn push(&self, ctx: ParsingContext) {
55    self.stack.borrow_mut().push(ctx);
56  }
57
58  /// Puts a default context on the top of the stack.
59  pub fn push_default(&self) {
60    self.stack.borrow_mut().push(ParsingContext::default());
61  }
62
63  /// Sets a specified entry name in context placed on the top of the stack.
64  pub fn set_entry_name(&self, name: Name) {
65    if let Some(last_ctx) = self.stack.borrow_mut().last_mut() {
66      last_ctx.set_name(name);
67    }
68  }
69
70  /// Sets a context under a specified name in the context placed on the top of the stack.
71  pub fn set_context(&self, name: Name, ctx: ParsingContext) {
72    if let Some(last_ctx) = self.stack.borrow_mut().last_mut() {
73      last_ctx.set_context(name, ctx);
74    }
75  }
76
77  /// Adds a name to a set of already parsed names.
78  pub fn add_name(&self, name: Name) {
79    self.names.borrow_mut().insert(name);
80  }
81
82  /// Returns already parsed flattened keys and names.
83  pub fn flattened(&self) -> HashSet<String> {
84    let keys = self.stack.borrow().iter().flat_map(|ctx| ctx.flattened_keys()).collect::<HashSet<String>>();
85    let names = self.names.borrow().iter().map(|name| name.to_string()).collect::<HashSet<String>>();
86    keys.union(&names).cloned().collect()
87  }
88}