-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.rs
177 lines (156 loc) · 6 KB
/
build.rs
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
// Adapted from https://github.com/rhaiscript/rhai-sci
use std::fs::File;
#[allow(unused)]
fn main() {
// Update if needed
println!("cargo:rerun-if-changed=src");
println!("cargo:rerun-if-changed=build.rs");
// Make empty file for documentation
let doc_file_path = std::env::var("OUT_DIR").unwrap() + "/rhai-fs-docs.md";
let mut doc_file = File::create(doc_file_path).expect("create doc file");
#[cfg(feature = "metadata")]
doc_gen::generate_doc(&mut doc_file);
}
#[cfg(feature = "metadata")]
mod doc_gen {
use rhai::{plugin::*, Engine};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write;
// Rhai modules in the `rhai-fs` package.
mod pkg {
include!("src/path.rs");
include!("src/file.rs");
include!("src/dir.rs");
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Metadata {
#[serde(default)]
pub functions: Vec<DocFunc>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[allow(non_snake_case)]
struct DocFunc {
pub access: String,
pub baseHash: u128,
pub fullHash: u128,
pub name: String,
pub namespace: String,
pub numParams: usize,
pub params: Option<Vec<HashMap<String, String>>>,
pub signature: String,
pub returnType: Option<String>,
pub docComments: Option<Vec<String>>,
}
impl DocFunc {
pub fn fmt_signature(&self) -> String {
self.signature
.replace(" -> Result<", " -> ")
.replace(", Box<EvalAltResult>>", "")
.replace("&mut ", "")
.replace(" -> ()", "")
.replace("ImmutableString", "String")
}
pub fn fmt_doc_comments(&self) -> Option<String> {
self.docComments.clone().map(|dc| {
dc.join("\n")
.replace("/// ", "")
.replace("///", "")
.replace("/**", "")
.replace("**/", "")
.replace("**/", "")
})
}
// pub fn fmt_operator_fn(&self) -> Option<String> {
// Some(
// self.name
// .chars()
// .map_while(|c| match c {
// '+' => Some("add"),
// '*' => Some("multiply"),
// '-' => Some("subtract"),
// '/' => Some("divide"),
// '%' => Some("remainder"),
// '=' => Some("equal"),
// '!' => Some("not"),
// '>' => Some("greater"),
// '<' => Some("less"),
// '|' => Some("bitor"),
// '^' => Some("bitxor"),
// _ => None,
// })
// .collect::<String>(),
// )
// .filter(|s| !s.is_empty())
// }
}
fn fmt_fn_name(mut name: &str, mut signature: String) -> (&str, &str, String) {
let mut prefix = "";
if name.starts_with("get$") {
signature.drain(0..4);
name = &name[4..];
prefix = "property get ";
}
if name.starts_with("set$") {
signature.drain(0..4);
name = &name[4..];
prefix = "property set ";
}
if name == "index$get" {
signature.drain(0..6);
name = "get";
prefix = "indexer ";
}
if name == "index$set" {
signature.drain(0..6);
name = "set";
prefix = "indexer ";
}
(prefix, name, signature)
}
pub fn generate_doc(writer: &mut impl Write) {
let mut engine = Engine::new();
let mut fs_module = Module::new();
combine_with_exported_module!(&mut fs_module, "rhai_fs_path", pkg::path_functions);
combine_with_exported_module!(&mut fs_module, "rhai_file_path", pkg::file_functions);
combine_with_exported_module!(&mut fs_module, "rhai_dir_path", pkg::dir_functions);
engine.register_global_module(fs_module.into());
// Extract metadata
let json_fns = engine.gen_fn_metadata_to_json(false).unwrap();
let v: Metadata = serde_json::from_str(&json_fns).unwrap();
let function_list = v.functions;
// Write functions
let mut indented = false;
for (idx, function) in function_list.iter().enumerate() {
// Pull out basic info
let name: &str = &function.name;
if !name.starts_with("anon$") {
let signature = function.fmt_signature();
let comments = function.fmt_doc_comments().unwrap_or_default();
let (prefix, name, signature) = fmt_fn_name(name, signature);
// Check if there are multiple arities, and if so add a header and indent
if idx < function_list.len() - 1 {
if name == function_list[idx + 1].name && !indented {
writeln!(writer, "## {prefix}`{}`", name.to_owned())
.expect("Cannot write to {doc_file}");
indented = true;
}
}
// Print definition with right level of indentation
if indented {
writeln!(writer, "### {prefix}`{signature}`\n\n{comments}")
.expect("Cannot write to {doc_file}");
} else {
writeln!(writer, "## {prefix}`{signature}`\n{comments}")
.expect("Cannot write to {doc_file}");
}
// End indentation when its time
if idx != 0 && idx < function_list.len() - 1 {
if name == function_list[idx - 1].name && name != function_list[idx + 1].name {
indented = false;
}
}
}
}
}
}