/
build.rs
362 lines (334 loc) · 11.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
Copyright 2020 <盏一 w@hidva.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use lalrpop;
use proc_macro2::{Literal, TokenStream};
use quote::{format_ident, quote, ToTokens};
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use yaml_rust::Yaml;
mod common;
#[derive(Default)]
struct Guc {
name: String,
context: String,
short_desc: String,
vartype: String,
boot_val: String,
flags: String, // zero or flags.
long_desc: Option<String>,
preassign: Option<String>,
show: Option<String>,
}
#[derive(Default)]
struct Gucs {
bool_gucs: Vec<Guc>,
int_gucs: Vec<Guc>,
str_gucs: Vec<Guc>,
real_gucs: Vec<Guc>,
}
fn yaml_tostr(input: &Yaml) -> String {
common::yaml_try_tostr(input).unwrap()
}
impl Guc {
fn new(val: &Yaml) -> Guc {
Guc {
name: val["name"].as_str().unwrap().to_string(),
context: val["context"].as_str().unwrap().to_string(),
short_desc: val["short_desc"].as_str().unwrap().to_string(),
vartype: val["vartype"].as_str().unwrap().to_string(),
boot_val: yaml_tostr(&val["boot_val"]),
flags: val["flags"].as_str().or(Some("0")).unwrap().to_string(),
long_desc: val["long_desc"].as_str().map(|v| v.to_string()),
preassign: val["preassign"].as_str().map(|v| v.to_string()),
show: val["show"].as_str().map(|v| v.to_string()),
}
}
}
fn load_gucs() -> Gucs {
let mut gucs = Gucs::default();
const INPUTFILE: &str = "./src/guc/gucdef.yaml";
let yamldocs = common::load_yaml(INPUTFILE).unwrap();
let yamldoc = &yamldocs[0];
for gucdat in yamldoc.as_vec().unwrap() {
let vartype = gucdat["vartype"].as_str().unwrap();
let guc = Guc::new(gucdat);
match vartype {
"INT" => gucs.int_gucs.push(guc),
"BOOL" => gucs.bool_gucs.push(guc),
"STR" => gucs.str_gucs.push(guc),
"REAL" => gucs.real_gucs.push(guc),
_ => panic!("Unknown vartype. vartype={}", vartype),
}
}
gucs
}
fn option_tokenstream(input: &Option<String>, asstr: bool) -> TokenStream {
match input {
None => "None".parse().unwrap(),
Some(v) => {
let val = if asstr {
Literal::string(v).into_token_stream()
} else {
v.parse().unwrap()
};
quote! { Some(#val) }
}
}
}
struct FormatRet {
name: Vec<TokenStream>,
enumitem: Vec<TokenStream>,
boot_val: Vec<TokenStream>,
}
fn char_has_case(c: char) -> bool {
c.is_lowercase() || c.is_uppercase()
}
fn to_camel_case(s: &str) -> String {
s.trim_matches('_')
.split('_')
.filter(|component| !component.is_empty())
.map(|component| {
let mut camel_cased_component = String::new();
let mut new_word = true;
let mut prev_is_lower_case = true;
for c in component.chars() {
// Preserve the case if an uppercase letter follows a lowercase letter, so that
// `camelCase` is converted to `CamelCase`.
if prev_is_lower_case && c.is_uppercase() {
new_word = true;
}
if new_word {
camel_cased_component.extend(c.to_uppercase());
} else {
camel_cased_component.extend(c.to_lowercase());
}
prev_is_lower_case = c.is_lowercase();
new_word = false;
}
camel_cased_component
})
.fold(
(String::new(), None),
|(acc, prev): (String, Option<String>), next| {
// separate two components with an underscore if their boundary cannot
// be distinguished using a uppercase/lowercase case distinction
let join = if let Some(prev) = prev {
let l = prev.chars().last().unwrap();
let f = next.chars().next().unwrap();
!char_has_case(l) && !char_has_case(f)
} else {
false
};
(acc + if join { "_" } else { "" } + &next, Some(next))
},
)
.0
}
// var_logical_type is the logical type of guc, such as Str, Int,
fn format_gucs(f: &mut File, var_logical_type: &'static str, gucs: &Vec<Guc>) -> FormatRet {
let mut name = Vec::<TokenStream>::new();
let mut context = Vec::<TokenStream>::new();
let mut short_desc = Vec::<TokenStream>::new();
let mut vartype = Vec::<TokenStream>::new(); // var enum type, See guc::Type.
let mut boot_val = Vec::<TokenStream>::new();
let mut long_desc = Vec::<TokenStream>::new();
let mut flags = Vec::<TokenStream>::new();
let mut preassign = Vec::<TokenStream>::new();
let mut show = Vec::<TokenStream>::new();
let mut enumitem = Vec::<TokenStream>::new();
for guc in gucs {
name.push(Literal::string(&guc.name).into_token_stream());
context.push(guc.context.parse().unwrap());
short_desc.push(Literal::string(&guc.short_desc).into_token_stream());
vartype.push(guc.vartype.parse().unwrap());
boot_val.push(if var_logical_type != "Str" {
guc.boot_val.parse().unwrap()
} else {
Literal::string(&guc.boot_val).into_token_stream()
});
flags.push(guc.flags.parse().unwrap());
long_desc.push(option_tokenstream(&guc.long_desc, true));
preassign.push(option_tokenstream(&guc.preassign, false));
show.push(option_tokenstream(&guc.show, false));
enumitem.push(to_camel_case(&guc.name).parse().unwrap());
}
let const_type = format_ident!("{}", var_logical_type);
let const_size = gucs.len();
let const_ident = format_ident!("{}_GUCS", var_logical_type.to_ascii_uppercase());
let enum_ident = format_ident!("{}", var_logical_type.chars().nth(0).unwrap());
let guctts = quote! {
#(
#const_type {
gen: Generic {
context: #context,
flags: #flags,
show: #show,
},
preassign: #preassign,
}
),*
};
write!(
f,
"{}",
quote! {
pub const #const_ident: [#const_type; #const_size] = [
#guctts
];
}
)
.unwrap();
write!(f, "\n").unwrap();
write!(
f,
"{}",
quote! {
#[derive(Copy, Clone)]
pub enum #enum_ident {
#(#enumitem,)*
}
}
)
.unwrap();
FormatRet {
name,
enumitem,
boot_val,
}
}
fn gen_gucdef() {
let gucs = load_gucs();
let out_dir = env::var_os("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("gucdef.rs");
let mut outputf = File::create(dest_path).unwrap();
write!(
&mut outputf,
"
/*
Copyright 2020 <盏一 w@hidva.com>
Licensed under the Apache License, Version 2.0 (the \"License\");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an \"AS IS\" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"
)
.unwrap();
let bool_formatret = format_gucs(&mut outputf, "Bool", &gucs.bool_gucs);
let bool_boot_vals = &bool_formatret.boot_val;
write!(&mut outputf, "\n").unwrap();
let int_formatret = format_gucs(&mut outputf, "Int", &gucs.int_gucs);
let int_boot_vals = &int_formatret.boot_val;
write!(&mut outputf, "\n").unwrap();
let str_formatret = format_gucs(&mut outputf, "Str", &gucs.str_gucs);
let str_boot_vals = &str_formatret.boot_val;
write!(&mut outputf, "\n").unwrap();
let real_formatret = format_gucs(&mut outputf, "Real", &gucs.real_gucs);
let real_boot_vals = &real_formatret.boot_val;
write!(&mut outputf, "\n").unwrap();
let bool_guc_num = gucs.bool_gucs.len();
let str_guc_num = gucs.str_gucs.len();
let int_guc_num = gucs.int_gucs.len();
let real_guc_num = gucs.real_gucs.len();
// the type of str_boot_vals is &'static str.
// and the type of string_boot_vals is String
let mut string_boot_vals = Vec::<TokenStream>::new();
for strval in str_boot_vals {
string_boot_vals.push(quote! {
#strval.to_string()
})
}
write!(
&mut outputf,
"{}",
quote! {
#[derive(Clone)]
pub struct GucVals {
pub bool_vals: [bool; #bool_guc_num],
pub str_vals: [String; #str_guc_num],
pub int_vals: [i32; #int_guc_num],
pub real_vals: [f64; #real_guc_num],
}
impl std::default::Default for GucVals {
fn default() -> Self {
GucVals {
bool_vals: [
#( #bool_boot_vals ),*
],
str_vals: [
#( #string_boot_vals ),*
],
int_vals: [
#( #int_boot_vals ),*
],
real_vals: [
#( #real_boot_vals ),*
]
}
}
}
}
)
.unwrap();
write!(&mut outputf, "\n").unwrap();
let bool_enumitem = &bool_formatret.enumitem;
let bool_name = &bool_formatret.name;
let int_enumitem = &int_formatret.enumitem;
let int_name = &int_formatret.name;
let real_enumitem = &real_formatret.enumitem;
let real_name = &real_formatret.name;
let str_enumitem = &str_formatret.enumitem;
let str_name = &str_formatret.name;
write!(
&mut outputf,
"{}",
quote! {
#[derive(Copy , Clone)]
pub enum GucIdx {
I(I),
B(B),
S(S),
R(R)
}
lazy_static::lazy_static! {
pub static ref GUC_NAMEINFO_MAP: HashMap<&'static str, GucIdx> = {
let mut m = HashMap::new();
#(m.insert(#bool_name, GucIdx::B(B::#bool_enumitem));)*
#(m.insert(#int_name, GucIdx::I(I::#int_enumitem));)*
#(m.insert(#str_name, GucIdx::S(S::#str_enumitem));)*
#(m.insert(#real_name, GucIdx::R(R::#real_enumitem));)*
m
};
}
}
)
.unwrap();
}
fn copy_common() {
const INPUT: &str = "./common.rs";
let out_dir = env::var_os("OUT_DIR").unwrap();
let output = Path::new(&out_dir).join("common.rs");
std::fs::copy(INPUT, output).unwrap();
}
fn main() {
gen_gucdef();
copy_common();
lalrpop::process_root().unwrap();
}