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
//! Variable scope for InSymbol (variables, parameters, fields)
use serde::{Deserialize, Serialize};
/// Variable scope type for InSymbol
///
/// Used to distinguish different kinds of "inner" symbols within
/// a containing symbol (function, struct, etc.).
///
/// # Path Format
/// - Parameter: `my_crate::my_fn::$param::x`
/// - Local variable: `my_crate::my_fn::$var::result`
/// - Struct field: `my_crate::MyStruct::$field::name`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VarScope {
/// Function parameter: `$param`
Param,
/// Local variable: `$var`
Local,
/// Struct/enum field: `$field`
Field,
}
impl VarScope {
/// Get the scope segment string
///
/// # Examples
/// ```
/// # use ryo_symbol::VarScope;
/// assert_eq!(VarScope::Param.segment(), "$param");
/// assert_eq!(VarScope::Local.segment(), "$var");
/// assert_eq!(VarScope::Field.segment(), "$field");
/// ```
pub fn segment(&self) -> &'static str {
match self {
VarScope::Param => "$param",
VarScope::Local => "$var",
VarScope::Field => "$field",
}
}
/// Parse from a segment string
///
/// # Examples
/// ```
/// # use ryo_symbol::VarScope;
/// assert_eq!(VarScope::from_segment("$param"), Some(VarScope::Param));
/// assert_eq!(VarScope::from_segment("$var"), Some(VarScope::Local));
/// assert_eq!(VarScope::from_segment("$field"), Some(VarScope::Field));
/// assert_eq!(VarScope::from_segment("foo"), None);
/// ```
pub fn from_segment(s: &str) -> Option<Self> {
match s {
"$param" => Some(VarScope::Param),
"$var" => Some(VarScope::Local),
"$field" => Some(VarScope::Field),
_ => None,
}
}
/// Check if a string is a valid scope marker
pub fn is_scope_marker(s: &str) -> bool {
Self::from_segment(s).is_some()
}
}
impl std::fmt::Display for VarScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.segment())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_var_scope_segment() {
assert_eq!(VarScope::Param.segment(), "$param");
assert_eq!(VarScope::Local.segment(), "$var");
assert_eq!(VarScope::Field.segment(), "$field");
}
#[test]
fn test_var_scope_from_segment() {
assert_eq!(VarScope::from_segment("$param"), Some(VarScope::Param));
assert_eq!(VarScope::from_segment("$var"), Some(VarScope::Local));
assert_eq!(VarScope::from_segment("$field"), Some(VarScope::Field));
assert_eq!(VarScope::from_segment("invalid"), None);
assert_eq!(VarScope::from_segment("$invalid"), None);
}
#[test]
fn test_var_scope_display() {
assert_eq!(format!("{}", VarScope::Param), "$param");
assert_eq!(format!("{}", VarScope::Local), "$var");
assert_eq!(format!("{}", VarScope::Field), "$field");
}
}