-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunc_trait.rs
More file actions
74 lines (62 loc) · 2.07 KB
/
Copy pathfunc_trait.rs
File metadata and controls
74 lines (62 loc) · 2.07 KB
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
use std::fmt;
use crate::types::{Namespace, ObjectRef};
use super::result::Params;
// Function Trait ------------------------------------------------------
pub trait FuncTrait {
fn ns(&self) -> &Namespace;
fn module_name(&self) -> &String;
fn module(&self) -> ObjectRef;
fn name(&self) -> &String;
fn params(&self) -> &Params;
fn get_doc(&self) -> ObjectRef {
self.ns().get("$doc").unwrap().clone()
}
/// Returns the required number of args.
fn arity(&self) -> usize {
let params = self.params();
if let Some(name) = params.last() {
if name.is_empty() {
// Has var args; return number of required args
params.len() - 1
} else {
// Does not have var args; all args required
params.len()
}
} else {
0
}
}
/// If the function has var args, this returns the index of the var
/// args in the args list (which is also equal to the required
/// number of args).
fn var_args_index(&self) -> Option<usize> {
let params = self.params();
if let Some(name) = params.last() {
if name.is_empty() {
return Some(params.len() - 1);
}
}
None
}
fn has_var_args(&self) -> bool {
self.var_args_index().is_some()
}
fn format_string(&self, id: Option<usize>) -> String {
let name = &self.name();
let arity = self.arity();
let suffix = if self.var_args_index().is_some() { "+" } else { "" };
let id = id.map_or_else(|| "".to_string(), |id| format!(" @ {id}"));
format!("function {name}/{arity}{suffix}{id}")
}
}
// Display -------------------------------------------------------------
impl fmt::Display for dyn FuncTrait {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.format_string(None))
}
}
impl fmt::Debug for dyn FuncTrait {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}