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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
#![allow(clippy::len_zero, clippy::redundant_closure, clippy::bool_comparison)]
use crate::arg::ArgAttrData;
use crate::macro_attribute::{MacroAttribute, NameValueAttribute};
use crate::option::OptionAttrData;
use crate::utils::NamePath;
use crate::var::{ArgLocalVar, ArgumentType};
use crate::TypeExt;
use proc_macro2::TokenStream;
use quote::*;
use std::path::PathBuf;
use syn::{AttrStyle, Attribute, AttributeArgs, Item, ItemFn, PatType, ReturnType, Stmt, Type};
/// Tokens for either `command` or `subcommand` attribute.
///
/// ```text
/// #[command(
/// description="Prints system time",
/// about="Gets the current system time in milliseconds",
/// version=0.1
/// )]
/// fn system_time(){
/// #[subcommand(description="Prints the current operative system", version="1.0.2")]
/// fn os(){
/// println!("{}", std::env::consts::OS);
/// }
///
/// println!("{}", std::time::SystemTime::now().elapsed().unwrap().as_millis());
/// }
/// ```
#[derive(Debug, Clone)]
pub struct CommandAttrData {
fn_name: NamePath,
name: Option<String>,
attribute: NameValueAttribute,
is_child: bool,
version: Option<String>,
description: Option<String>,
usage: Option<StringSource>,
help: Option<StringSource>,
item_fn: Option<ItemFn>,
children: Vec<CommandAttrData>,
is_hidden: Option<bool>,
options: Vec<OptionAttrData>,
args: Vec<ArgAttrData>,
vars: Vec<ArgLocalVar>,
command_help: Option<NamePath>,
command_usage: Option<NamePath>,
}
impl CommandAttrData {
pub fn from_fn(args: AttributeArgs, func: ItemFn) -> Self {
let name = func.sig.ident.to_string();
let attr_data =
NameValueAttribute::from_attribute_args(name.as_str(), args, AttrStyle::Outer)
.expect("failed to parse `command` attribute");
CommandAttrData::new_from_fn(attr_data, func, false, true, true)
}
pub fn from_path(args: AttributeArgs, func: ItemFn, path: PathBuf) -> Self {
imp::command_from_path(args, func, path)
}
fn new(fn_name: NamePath, attribute: NameValueAttribute, is_child: bool) -> Self {
CommandAttrData {
fn_name,
is_child,
attribute,
name: None,
version: None,
description: None,
usage: None,
help: None,
item_fn: None,
children: vec![],
options: vec![],
vars: vec![],
args: vec![],
is_hidden: None,
command_help: None,
command_usage: None,
}
}
fn new_from_fn(
name_value_attr: NameValueAttribute,
item_fn: ItemFn,
is_child: bool,
get_subcommands: bool,
get_help: bool,
) -> Self {
if is_child {
assert!(!get_help, "cannot `get_help` in a subcommand");
}
let name = item_fn.sig.ident.to_string();
imp::command_from_fn_with_name(
NamePath::new(name),
name_value_attr,
item_fn,
is_child,
get_subcommands,
get_help,
)
}
pub fn set_name(&mut self, name: String) {
assert!(self.name.is_none(), "command `name` is already defined");
assert!(!name.trim().is_empty(), "command `name` cannot be empty");
assert!(
name.trim().chars().all(|c| !c.is_whitespace()),
"command `name` cannot contain whitespaces"
);
self.name = Some(name);
}
pub fn set_version(&mut self, version: String) {
assert!(
self.version.is_none(),
"command `version` is already defined"
);
assert!(!version.trim().is_empty(), "`version` cannot be empty");
self.version = Some(version);
}
pub fn set_description(&mut self, description: String) {
assert!(
self.description.is_none(),
"command `description` is already defined"
);
self.description = Some(description);
}
pub fn set_usage(&mut self, usage: StringSource) {
assert!(self.usage.is_none(), "command `usage` is already defined");
self.usage = Some(usage);
}
pub fn set_help(&mut self, help: StringSource) {
assert!(self.help.is_none(), "command `help` is already defined");
self.help = Some(help);
}
pub fn set_child(&mut self, command: CommandAttrData) {
assert!(command.is_child);
if self.children.contains(&command) {
panic!(
"duplicated subcommand: `{}` in `{}`",
command.fn_name.name(),
self.fn_name.name()
)
}
// Infer the global options
self.children.push(command);
}
pub fn set_hidden(&mut self, is_hidden: bool) {
assert!(
self.is_hidden.is_none(),
"command `is_hidden` is already defined"
);
if is_hidden {
assert!(self.is_child, "only subcommands can be hidden");
}
self.is_hidden = Some(is_hidden);
}
pub fn set_option(&mut self, option: OptionAttrData) {
if self.options.contains(&option) {
panic!(
"duplicated option: `{}` in `{}`",
option.name(),
self.fn_name.name()
)
}
self.options.push(option);
}
pub fn set_args(&mut self, args: ArgAttrData) {
if self.args.contains(&args) {
panic!(
"duplicated arg: `{}` in `{}`",
args.name(),
self.fn_name.name()
)
}
self.args.push(args);
}
pub fn set_var(&mut self, var: ArgLocalVar) {
if self.vars.contains(&var) {
panic!(
"duplicated variable: `{}` in `{}`",
var.var_name(),
self.fn_name.name()
)
}
self.vars.push(var);
}
pub fn set_item_fn(&mut self, item_fn: ItemFn) {
self.item_fn = Some(item_fn);
}
pub fn set_command_help(&mut self, name_path: NamePath) {
self.command_help = Some(name_path);
}
pub fn set_command_usage(&mut self, name_path: NamePath) {
self.command_usage = Some(name_path);
}
pub fn get_mut_recursive(&mut self, name_path: &NamePath) -> Option<&mut CommandAttrData> {
if &self.fn_name == name_path {
return Some(self);
}
for child in &mut self.children {
if let Some(command) = child.get_mut_recursive(name_path) {
return Some(command);
}
}
None
}
pub fn expand(mut self) -> TokenStream {
assert!(
self.item_fn.is_some(),
"`ItemFn` is not set for command `{}`",
self.fn_name
);
self.assert_global_options();
// Apply only to root
if !self.is_child {
self.infer_global_options();
self.update_children_global_options();
}
// Command args
let args = self
.args
.iter()
.map(|tokens| quote! { .arg(#tokens) })
.collect::<Vec<TokenStream>>();
// Command options
let options = self
.options
.iter()
.filter(|x| !x.is_from_global())
.map(|x| quote! { .option(#x)})
.collect::<Vec<TokenStream>>();
// Command children
let children = self
.children
.iter()
.map(|x| quote! { .subcommand(#x)})
.collect::<Vec<TokenStream>>();
// Command function variables
let vars = self
.vars
.iter()
.map(|x| quote! { #x })
.collect::<Vec<TokenStream>>();
// Command description
let description = self
.description
.as_ref()
.map(|s| quote! { .description(#s) });
// Command hidden
let hidden = self.is_hidden.as_ref().map(|s| quote! { .hidden(#s) });
// Command usage
let usage = self.usage.as_ref().map(|s| quote! { .usage(#s) });
// Command help
let help = self.help.as_ref().map(|s| quote! { .help(#s) });
// Command version
let version = self.version.as_ref().map(|s| quote! { .version(#s) });
// Instantiate `Command` or `RootCommand`
let mut command = match &self.name {
Some(name) => {
quote! { clapi::Command::new(#name) }
}
None => {
if self.is_child {
let fn_name = quote_expr!(self.fn_name.name());
quote! { clapi::Command::new(#fn_name) }
} else {
quote! { clapi::Command::root() }
}
}
};
// Command handler
let handler = if contains_expressions(self.item_fn.as_ref().unwrap()) {
// Get the function body
let body = self.get_body(vars.as_slice());
quote! {
.handler(|opts, args|{
#body
})
}
} else {
/*
We omit the handler if is EMPTY (don't contains any expressions or locals), for example:
EMPTY:
fn test() {}
fn test(){ const VALUE : I64 = 0; }
NOT EMPTY:
fn test() { println!("HELLO WORLD"); }
fn test() { let value = 0; }
*/
quote! {}
};
// Build the command
command = quote! {
#command
#description
#usage
#hidden
#help
#version
#(#args)*
#(#options)*
#(#children)*
#handler
};
if self.is_child {
command
} else {
let name = self.fn_name.name().parse::<TokenStream>().unwrap();
let ret = &self.item_fn.as_ref().unwrap().sig.output;
let attrs = &self.item_fn.as_ref().unwrap().attrs;
let items = self.get_body_items();
let error_handling = match ret {
ReturnType::Type(_, ty) if is_clapi_result_type(ty) => quote! {
.map_err(|e| e.exit())
},
_ => quote! {
.map_err(|e| e.exit()).unwrap();
},
};
let use_help = {
if self.command_help.is_none() && self.command_usage.is_none() {
quote! { .use_default_help() }
} else {
let command_help = self
.command_help
.as_ref()
.map(|n| n.to_string().parse::<TokenStream>().unwrap())
.unwrap_or_else(|| quote! { clapi::help::command_help });
let command_usage = self
.command_usage
.as_ref()
.map(|n| n.to_string().parse::<TokenStream>().unwrap())
.unwrap_or_else(|| quote! { clapi::help::command_usage });
quote! {
.use_help({
clapi::help::HelpSource {
help: #command_help,
usage: #command_usage
}
})
}
}
};
// Emit the tokens to create the function with the `Command`
quote! {
#(#attrs)*
fn #name() #ret {
#(#items)*
let command = #command ;
clapi::CommandLine::new(command)
#use_help
.use_default_suggestions()
.run()
#error_handling
}
}
}
}
fn infer_global_options(&self) {
/*
FIXME: This is a hack to infer the options which requires to make a copy
of the options, and then iterate through the children,
The wanted solution is to make a parent <-> child relation with comment
which make easy to navigate through the tree to locale the parent which contains
the global options. This solution would require to make the Command a `Rc<RefCell<CommandAttrData>>`
to allow the children command use `Weak<RefCell<CommandAttrData>>` to access the parent.
*/
let global_options = self
.options
.iter()
.filter(|o| o.is_global())
.cloned()
.collect::<Vec<_>>();
global_options.iter().for_each(|o| {
self.set_global_options(o);
});
for child in self.children.iter() {
child.infer_global_options();
}
}
fn set_global_options(&self, option: &OptionAttrData) {
assert!(option.is_global());
for opt in self.options.iter() {
if opt.from_global.get().is_none() && opt.arg_name == option.arg_name {
if !opt.is_global() {
opt.set_from_global(true);
}
}
}
for child in self.children.iter() {
child.set_global_options(option);
}
}
fn assert_global_options(&self) {
if self.is_child {
return;
}
let mut global_options = Vec::from_iter(self.options.iter().filter(|o| o.is_global()));
for child in &self.children {
for option in &child.options {
if option.is_from_global() {
if !global_options.iter().any(|o| o.name() == option.name()) {
panic!(
"There is no global option named `{}` in a parent command",
option.name()
);
}
}
if option.is_global() {
global_options.push(option);
}
}
}
}
fn update_children_global_options(&mut self) {
/*
FIXME: This is a hack to update the children global options.
The wanted solution is to make a parent <-> child relation with comment
which make easy to navigate through the tree to locale the parent which contains
the global options. This solution would require to make the Command a `Rc<RefCell<CommandAttrData>>`
to allow the children command use `Weak<RefCell<CommandAttrData>>` to access the parent.
*/
fn update_children_options(opt: &OptionAttrData, parent: &mut CommandAttrData) {
for child in parent.children.iter_mut() {
if let Some(child_opt) = child
.options
.iter_mut()
.find(|o| o.arg_name == opt.arg_name)
{
if child_opt.is_from_global() {
// Updated the children and vars to match the global option names
child_opt.name = opt.name().to_string();
let var = child
.vars
.iter_mut()
.find(|v| v.var_name == opt.arg_name)
.unwrap();
var.name = Some(opt.name().to_string());
}
} else {
update_children_options(opt, child);
}
}
}
let global_options = self
.options
.iter()
.filter(|o| o.is_global())
.cloned()
.collect::<Vec<_>>();
for opt in global_options {
update_children_options(&opt, self);
}
for child in self.children.iter_mut() {
child.update_children_global_options();
}
}
fn get_body(&self, vars: &[TokenStream]) -> TokenStream {
let ret = &self.item_fn.as_ref().unwrap().sig.output;
let error_handling = match ret {
ReturnType::Type(_, ty) if is_clapi_result_type(ty) => quote! {},
// If return type is not `Result` we need return `fn_name(args) ; Ok(())`
_ => quote! { ; Ok(()) },
};
if self.is_child {
let fn_name = self.fn_name.to_string().parse::<TokenStream>().unwrap();
let inputs = self.vars.iter().map(|var| {
let var_name = var.var_name().parse::<TokenStream>().unwrap();
let is_ref = match var.arg_type() {
ArgumentType::Slice(ty) => {
if ty.mutability {
quote! { &mut }
} else {
quote! { & }
}
}
_ => quote! {},
};
quote! { #is_ref #var_name }
});
quote! {
#(#vars)*
#fn_name(#(#inputs,)*)
#error_handling
}
} else {
let statements = self.get_body_statements();
quote! {
#(#vars)*
#(#statements)*
#error_handling
}
}
}
fn get_body_statements(&self) -> Vec<TokenStream> {
// locals, expressions, ...
self.item_fn
.as_ref()
.unwrap()
.block
.stmts
.iter()
.filter(|s| !matches!(s, Stmt::Item(_)))
.map(|s| s.to_token_stream())
.collect()
}
fn get_body_items(&self) -> Vec<TokenStream> {
fn contains_subcommand_attribute(item_fn: &ItemFn) -> bool {
item_fn.attrs.iter().any(|attribute| {
let path = crate::utils::path_to_string(&attribute.path);
crate::consts::is_subcommand(&path)
})
}
fn statement_to_tokens(stmt: Stmt) -> TokenStream {
if let Stmt::Item(Item::Fn(ref item_fn)) = stmt {
if contains_subcommand_attribute(item_fn) && !contains_expressions(item_fn) {
let mut item_fn = item_fn.clone();
crate::utils::insert_allow_dead_code_attribute(&mut item_fn);
return drop_command_attributes(item_fn).to_token_stream();
}
}
stmt.to_token_stream()
}
// functions, struct, impl, const, statics, ...
self.item_fn
.as_ref()
.unwrap()
.block
.stmts
.clone()
.into_iter()
.filter(|s| matches!(s, Stmt::Item(_)))
.map(statement_to_tokens)
.collect()
}
}
impl ToTokens for CommandAttrData {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append_all(self.clone().expand().into_iter())
}
}
impl Eq for CommandAttrData {}
impl PartialEq for CommandAttrData {
fn eq(&self, other: &Self) -> bool {
self.fn_name == other.fn_name
}
}
// Information about an function argument of a function decorated with a `clapi_macros` attribute
#[derive(Debug, Clone)]
pub struct FnArgData {
// Name of the function argument
pub arg_name: String,
// Name specified with `name="value"`, if any
pub name: Option<String>,
// The function argument `PatType` like: `x : i64`
pub pat_type: PatType,
// The macro attribute if any, this is solely used for debugging,
// the actual information is from the `NameValueAttribute`
pub attribute: Option<MacroAttribute>,
// The name-values of the macro attribute
pub name_value: Option<NameValueAttribute>,
// If the function argument correspond to a command option.
pub is_option: bool,
}
// Represents the source of the string data used.
#[derive(Debug, Clone)]
pub enum StringSource {
// A string literal.
String(String),
// A function in the form: `fn() -> Into<String>`
Fn(syn::ExprPath),
}
impl StringSource {
// Creates a `StringSource::Fn` from a function path identifier
pub fn from_fn_path(s: &str) -> Result<Self, syn::Error> {
assert!(!s.trim().is_empty());
let path: syn::ExprPath = syn::parse_str(s)?;
Ok(StringSource::Fn(path))
}
}
impl ToTokens for StringSource {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
StringSource::String(s) => {
tokens.extend(s.into_token_stream());
}
StringSource::Fn(path) => tokens.extend(quote! { #path() }),
}
}
}
fn is_clapi_result_type(ty: &Type) -> bool {
if ty.is_result() {
return true;
}
matches!(
ty.path().unwrap().as_str(),
"clapi::Result" | "clapi::error::Result"
)
}
/// Check the statements of the `ItemFn` and returns `true`
/// if there is not expression declared.
///
/// The next is considered empty:
/// ```text
/// fn main(){
/// static VALUE: i64 = 0;
/// }
/// ```
///
/// Where the next don't
/// ```text
/// fn main(){
/// let value = 0;
/// }
/// ```
pub fn contains_expressions(item_fn: &ItemFn) -> bool {
use std::ops::Not;
item_fn
.block
.stmts
.iter()
.all(|stmt| matches!(stmt, Stmt::Item(_)))
.not()
}
/// Remove all the `clapi` macro attributes like `command`, `subcommand`, `option` and `arg`
/// from a `ItemFn`.
pub fn drop_command_attributes(mut item_fn: ItemFn) -> ItemFn {
item_fn.attrs = item_fn
.attrs
.iter()
.filter(|att| {
let path = att.path.to_token_stream().to_string();
!crate::consts::is_clapi_attribute(&path)
})
.cloned()
.collect::<Vec<Attribute>>();
item_fn
}
/// Checks if a function argument can be considered an option bool flag like: `--enable`
///
/// In the next example, `enable` is considered an option bool flag when passing: `--enable`
/// the parameter enable will have the value of `true` and `false` if absent.
///
/// ```text
/// #[command]
/// fn main(enable: bool){}
/// ```
pub fn is_option_bool_flag(fn_arg: &FnArgData) -> bool {
// Only `option`s can be bool flags
if !fn_arg.is_option {
return false;
}
// Of course, only bool can be an option bool flag
if !fn_arg.pat_type.ty.is_bool() {
return false;
}
if let Some(attribute) = &fn_arg.name_value {
// #[option(flag=false)]
if let Some(flag_value) = attribute.get(crate::consts::FLAG) {
if !flag_value
.to_bool_literal()
.expect("`flag` must be a bool literal")
{
return false;
}
}
let min = attribute
.get(crate::consts::MIN)
.map(|v| {
v.to_integer_literal::<usize>()
.expect("`min` must be an integer literal")
})
.unwrap_or(0);
let max = attribute
.get(crate::consts::MAX)
.map(|v| {
v.to_integer_literal::<usize>()
.expect("`max` must be a integer literal")
})
.unwrap_or(1);
let default = attribute
.get(crate::consts::DEFAULT)
.map(|v| {
v.to_bool_literal()
.expect("`default` must be a bool literal")
})
.unwrap_or(false);
// Is an option bool flag if: is boolean type and: min = 0, max = 1, default = false
min == 0 && max == 1 && default == false
} else {
true
}
}
mod imp {
use crate::arg::ArgAttrData;
use crate::command::{
drop_command_attributes, is_option_bool_flag, CommandAttrData, FnArgData, StringSource,
};
use crate::macro_attribute::{MacroAttribute, NameValueAttribute};
use crate::option::OptionAttrData;
use crate::query::QueryItem;
use crate::utils::{path_to_string, NamePath};
use crate::var::{ArgLocalVar, VarSource};
use crate::{consts, AttrQuery};
use quote::ToTokens;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use syn::{AttrStyle, Attribute, AttributeArgs, File, FnArg, Item, ItemFn, PatType, Stmt};
// Constructs a new `CommandAttrData` from a `ItemFn`
pub fn command_from_fn_with_name(
name: NamePath,
name_value_attr: NameValueAttribute,
item_fn: ItemFn,
is_child: bool,
get_subcommands: bool,
get_help: bool,
) -> CommandAttrData {
let mut command = CommandAttrData::new(name, name_value_attr.clone(), is_child);
for (key, value) in &name_value_attr {
match key.as_str() {
crate::consts::NAME => {
let name = value
.to_string_literal()
.expect("`name` must be a string literal");
command.set_name(name);
}
crate::consts::PARENT if is_child => { /*Parent is handle bellow*/ }
crate::consts::DESCRIPTION => {
let description = value
.to_string_literal()
.expect("`description` must be a string literal");
command.set_description(description);
}
crate::consts::HIDDEN => {
let hidden = value
.to_bool_literal()
.expect("`hidden` must be a bool literal");
command.set_hidden(hidden);
}
crate::consts::VERSION => {
assert!(
value.is_integer() || value.is_float() || value.is_string(),
"`version` must be an integer, float or string literal"
);
command.set_version(value.parse_literal::<String>().unwrap());
}
crate::consts::USAGE => {
let usage = value
.to_string_literal()
.expect("`usage` must be a string literal");
command.set_usage(StringSource::String(usage));
}
crate::consts::HELP => {
let help = value
.to_string_literal()
.expect("`help` must be a string literal");
command.set_help(StringSource::String(help));
}
crate::consts::WITH_USAGE => {
let expr = value
.to_string_literal()
.expect("`with_usage` must be a string literal");
let path = path_to_relative(&expr, &command.fn_name)
.unwrap_or_else(|| panic!("invalid expression: {}", expr))
.to_string();
let s = StringSource::from_fn_path(path.as_str())
.unwrap_or_else(|_|{
panic!("invalid expression for `with_usage` expected function path, but was {}", expr)
});
command.set_usage(s);
}
crate::consts::WITH_HELP => {
let expr = value
.to_string_literal()
.expect("`with_usage` must be a string literal");
let path = path_to_relative(&expr, &command.fn_name)
.unwrap_or_else(|| panic!("invalid expression: {}", expr))
.to_string();
let s = StringSource::from_fn_path(path.as_str()).unwrap_or_else(|_| {
panic!(
"invalid expression for `with_help` expected function path, but was {}",
expr
)
});
command.set_help(s);
}
_ => panic!("invalid `{}` key: `{}`", name_value_attr.path(), key),
}
}
let fn_args = get_fn_args(&item_fn);
let arg_count = fn_args.iter().filter(|f| !f.is_option).count();
// Pass function arguments in order
for fn_arg in &fn_args {
if fn_arg.is_option {
let source = if is_option_bool_flag(fn_arg) {
VarSource::OptBool
} else {
VarSource::Opts(fn_arg.arg_name.clone())
};
command.set_var(ArgLocalVar::new(
fn_arg.pat_type.clone(),
source,
fn_arg.name.clone(),
));
} else {
command.set_var(ArgLocalVar::new(
fn_arg.pat_type.clone(),
VarSource::Args(fn_arg.arg_name.clone()),
fn_arg.name.clone(),
));
}
}
// Add args
if arg_count > 0 {
for fn_arg in fn_args.iter().filter(|f| !f.is_option) {
command.set_args(ArgAttrData::from_arg_data(fn_arg.clone()));
}
}
// Add options
for fn_arg in fn_args.into_iter().filter(|n| n.is_option) {
let option = OptionAttrData::from_arg_data(fn_arg);
command.set_option(option);
}
// Add children
if get_subcommands {
let mut subcommands = Vec::new();
for (attribute, item_fn) in get_subcommands_from_fn(&item_fn) {
let subcommand =
CommandAttrData::new_from_fn(attribute.clone(), item_fn, true, true, false);
subcommands.push((subcommand, attribute.clone()));
}
while let Some((subcommand, attribute)) = subcommands.pop() {
if attribute.contains(crate::consts::PARENT) {
let literal = attribute
.get(crate::consts::PARENT)
.unwrap()
.to_string_literal()
.expect("`parent` must be a string literal");
// If attribute was: #[subcommand(parent="")]
assert!(
literal.trim().len() > 0,
"`parent` was empty in `fn {}`",
subcommand.fn_name.name()
);
// Converts the path in `literal` to a relative to `subcommand` module
let name_path =
path_to_relative(&literal, &subcommand.fn_name).unwrap_or_else(|| {
panic!(
"cannot find parent command `{}` for `{}`",
literal,
subcommand.fn_name.name()
)
});
if let Some(parent) = command.get_mut_recursive(&name_path) {
parent.set_child(subcommand);
} else {
let mut found = false;
for (c, _) in &mut subcommands {
if let Some(parent) = c.get_mut_recursive(&name_path) {
parent.set_child(subcommand.clone());
found = true;
break;
}
}
if !found {
panic!(
"cannot find parent subcommand: `{}` for `{}`",
name_path, subcommand.fn_name
);
}
}
} else {
command.set_child(subcommand);
}
}
}
// Gets the command help/usage
if get_help {
// Helper function
fn find_inner_decorate_item_fn(
item_fn: &ItemFn,
attribute_name: &str,
) -> Option<ItemFn> {
let mut result = item_fn
.block
.stmts
.iter()
.filter_map(|stmt| {
if let Stmt::Item(Item::Fn(item_fn)) = stmt {
if item_fn.contains_attribute(attribute_name) {
Some(item_fn)
} else {
None
}
} else {
None
}
})
.cloned()
.collect::<Vec<ItemFn>>();
if result.len() > 1 {
panic!("multiple `#[{}]` defined", attribute_name);
} else {
result.pop().map(|x| x)
}
}
// Finds the `command_help` if any in the body of the function
if let Some(command_help) = find_inner_decorate_item_fn(&item_fn, consts::COMMAND_HELP)
{
assert!(
command.command_help.is_none(),
"multiple #[{}] defined",
consts::COMMAND_HELP
);
command.set_command_help(NamePath::new(command_help.sig.ident.to_string()));
}
// Finds the `command_usage` if any in the body of the function
if let Some(command_usage) =
find_inner_decorate_item_fn(&item_fn, consts::COMMAND_USAGE)
{
assert!(
command.command_usage.is_none(),
"multiple #[{}] defined",
consts::COMMAND_USAGE
);
command.set_command_usage(NamePath::new(command_usage.sig.ident.to_string()));
}
}
command.set_item_fn(drop_command_attributes(item_fn));
command
}
// Get all the inner `fn` subcommands from the given `ItemFn`
fn get_subcommands_from_fn(item_fn: &ItemFn) -> Vec<(NameValueAttribute, ItemFn)> {
let mut ret = Vec::new();
for stmt in &item_fn.block.stmts {
if let Stmt::Item(Item::Fn(item_fn)) = stmt {
let subcommands = item_fn
.attrs
.iter()
.filter(|att| crate::consts::is_subcommand(path_to_string(&att.path).as_str()))
.cloned()
.collect::<Vec<Attribute>>();
if subcommands.len() > 0 {
assert_eq!(
subcommands.len(),
1,
"multiples `subcommand` attributes defined in `{}`",
item_fn.sig.ident.to_string()
);
let mut inner_fn = item_fn.clone();
let name_value_attr = if let Some(index) =
inner_fn.attrs.iter().position(|att| {
crate::consts::is_subcommand(path_to_string(&att.path).as_str())
}) {
MacroAttribute::new(inner_fn.attrs.swap_remove(index))
.into_name_values()
.unwrap()
} else {
unreachable!()
};
ret.push((name_value_attr, inner_fn))
}
}
}
ret
}
// Gets all the `FnArgData` from the given `ItemFn`
fn get_fn_args(item_fn: &ItemFn) -> Vec<FnArgData> {
fn get_fn_arg_ident_name(fn_arg: &FnArg) -> (String, PatType) {
if let FnArg::Typed(pat_type) = &fn_arg {
if let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() {
return (pat_ident.ident.to_string(), pat_type.clone());
}
}
panic!(
"`{}` is not a valid function arg",
fn_arg.to_token_stream().to_string()
);
}
let mut ret = Vec::new();
// We takes all the attributes that are `[arg(...)]` or `[option(...)]`
let attributes = item_fn
.attrs
.iter()
.cloned()
.map(MacroAttribute::new)
.filter(|attribute| {
crate::consts::is_option(attribute.path())
|| crate::consts::is_arg(attribute.path())
})
.map(split_attr_path_and_name_values)
.collect::<Vec<(String, MacroAttribute, NameValueAttribute)>>();
// Get all the function params and the name of the params
let fn_args = item_fn
.sig
.inputs
.iter()
.map(|f| get_fn_arg_ident_name(f))
.collect::<Vec<(String, PatType)>>();
// Look for duplicated fn arg attribute declaration for example:
// #[arg(x)]
// #[option(x)]
for index in 0..attributes.len() {
let (name, attribute, _) = &attributes[index];
if attributes[(index + 1)..]
.iter()
.any(|(arg_name, ..)| arg_name == name)
{
panic!(
"function argument `{}` is already used in `{}`",
name, attribute
);
}
}
// Check the argument declared in the `option` or `arg` exists in the function
for (path, _, _) in &attributes {
if !fn_args.iter().any(|(arg_name, _)| arg_name == path) {
panic!(
"argument `{}` is no defined in `fn {}`",
path, item_fn.sig.ident
);
}
}
for (arg_name, pat_type) in fn_args {
let (attribute, name_value) = if let Some((macro_attr, name_value_attr)) =
find_attribute_by_arg_name(&attributes, &arg_name)
{
(Some(macro_attr), Some(name_value_attr))
} else {
(None, None)
};
// Whether if this argument should be considered an option
let is_option = attribute
.as_ref()
.map(|attribute| crate::consts::is_option(attribute.path()))
.unwrap_or(true);
// Get the name defined by `name="value"`
let name = name_value
.as_ref()
.map(|name_value| name_value.get(consts::NAME))
.flatten()
.map(|x| x.to_string_literal())
.flatten();
ret.push(FnArgData {
arg_name,
name,
pat_type,
attribute,
name_value,
is_option,
});
}
ret
}
// Returns the attribute that match the argument name
fn find_attribute_by_arg_name(
attributes: &[(String, MacroAttribute, NameValueAttribute)],
arg_name: &str,
) -> Option<(MacroAttribute, NameValueAttribute)> {
attributes.iter().find_map(|(path, attribute, name_value)| {
if path == arg_name {
Some((attribute.clone(), name_value.clone()))
} else {
None
}
})
}
// Takes a `MacroAttribute` and returns its path, self and this name values
fn split_attr_path_and_name_values(
attribute: MacroAttribute,
) -> (String, MacroAttribute, NameValueAttribute) {
let name = attribute.get(0)
.cloned()
.unwrap_or_else(|| panic!("the first element in `{}` must be the argument name, but was empty", attribute))
.into_path()
.unwrap_or_else(|| {
panic!("first element in `{}` must be a path like: `#[{}(value, ...)]` where `value` is the name of the function argument", attribute, attribute.path())
});
let name_values = if attribute.len() == 1 {
NameValueAttribute::empty(attribute.path().to_owned(), AttrStyle::Outer)
} else {
let meta_items = attribute[1..].to_vec();
NameValueAttribute::new(attribute.path(), meta_items, AttrStyle::Outer).unwrap()
};
(name, attribute, name_values)
}
// Implementation of `CommandAttrData::from_path`
pub fn command_from_path(
args: AttributeArgs,
item_fn: ItemFn,
root_path: PathBuf,
) -> CommandAttrData {
// Ensure there is only 1 `#[command]` defined
static IS_DEFINED: AtomicBool = AtomicBool::new(false);
if let Ok(true) =
IS_DEFINED.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
{
panic!(
"multiple `command` entry points defined: `{}`",
item_fn.sig.ident
);
}
let src = std::fs::read_to_string(&root_path).unwrap();
let file = syn::parse_file(&src).unwrap();
assert_is_top_free_function(&file, &item_fn);
// The attribute of the root command
let attribute =
NameValueAttribute::from_attribute_args(crate::consts::COMMAND, args, AttrStyle::Outer)
.unwrap();
// The root command which is the command decorated with `#[command]`
let mut root = CommandAttrData::new_from_fn(attribute, item_fn, false, true, true);
// Gets all the subcommands searching in all the modules
let mut subcommands = get_subcommands_data(&root_path);
// Finds and set the `command_help` if any
if let Some(command_help) = find_decorated_item_fn(&root_path, consts::COMMAND_HELP) {
root.set_command_help(command_help);
}
// Finds and set the `command_usage` if any
if let Some(command_usage) = find_decorated_item_fn(&root_path, consts::COMMAND_USAGE) {
root.set_command_usage(command_usage);
}
while let Some((subcommand, _, attribute)) = subcommands.pop() {
if attribute.contains(crate::consts::PARENT) {
let literal = attribute
.get(crate::consts::PARENT)
.unwrap()
.to_string_literal()
.expect("`parent` must be a `string` literal");
// If attribute was: #[subcommand(parent="")]
assert!(
literal.trim().len() > 0,
"`parent` was empty in `fn {}`",
subcommand.fn_name.name()
);
// Converts the path in `literal` to a relative to `subcommand` module
let parent_name =
path_to_relative(&literal, &subcommand.fn_name).unwrap_or_else(|| {
panic!(
"cannot find parent command `{}` for `{}`",
literal,
subcommand.fn_name.name()
)
});
if parent_name == subcommand.fn_name {
panic!(
"self reference command parent in `{}`",
subcommand.attribute
);
}
if let Some(parent) = find_command_recursive(&mut root, &parent_name) {
parent.set_child(subcommand);
} else {
let mut found = false;
for (c, ..) in &mut subcommands {
if let Some(parent) = find_command_recursive(c, &parent_name) {
parent.set_child(subcommand.clone());
found = true;
break;
}
}
if !found {
let parent_name = attribute
.get(crate::consts::PARENT)
.unwrap()
.to_string_literal()
.unwrap();
panic!(
"cannot find parent command: `{}` for `{}`",
parent_name,
subcommand.fn_name.name()
);
}
}
} else {
root.set_child(subcommand);
}
}
root
}
// Find a `ItemFn` with the specified attribute and gets its `NamePath`
fn find_decorated_item_fn(root_path: &Path, attribute_name: &str) -> Option<NamePath> {
let mut result = crate::query::find_items(root_path, true, true, |item| {
if let Item::Fn(item_fn) = item {
item_fn.contains_attribute(attribute_name)
} else {
false
}
});
if result.len() > 1 {
panic!("multiple `#[{}]` defined", attribute_name)
}
result.pop().map(|x| x.name_path)
}
// Finds the command with the given `NamePath` starting from the command to its children.
fn find_command_recursive<'a>(
command: &'a mut CommandAttrData,
name: &'a NamePath,
) -> Option<&'a mut CommandAttrData> {
if &command.fn_name == name {
return Some(command);
}
for child in &mut command.children {
if let Some(c) = find_command_recursive(child, name) {
return Some(c);
}
}
None
}
// Converts the `path` to a relative of `root`.
// If root is `module::utils::math` and `path` is `super::get_id`
// the return is `module::utils::get_id`
fn path_to_relative(path: &str, root: &NamePath) -> Option<NamePath> {
// `self` is ignore because: `module::self::self` == `module`
let mut parent_path = path
.split("::")
.filter(|s| s != &"self")
.map(|s| s.to_owned())
.collect::<Vec<String>>();
// If the path starts like: `crate::` we remove `crate`.
if let Some(first) = parent_path.first() {
if first == "crate" {
parent_path.remove(0);
}
}
// The base path of the item, we ignore its name
let mut ret = Vec::from(root.item_path());
// Navigate from the `current` to the `parent`
for s in parent_path {
if s == "super" {
if ret.pop().is_none() {
break;
}
} else {
ret.push(s);
}
}
if ret.is_empty() {
return None;
}
Some(NamePath::from_path(ret))
}
// Starting from the given path and going through it's modules find all the `#[subcommand]`s.
fn get_subcommands_data(
root_path: &Path,
) -> Vec<(CommandAttrData, PathBuf, NameValueAttribute)> {
let query_data = get_subcommands_item_fn(root_path);
let mut subcommands = Vec::new();
for QueryItem {
path,
name_path,
item: (item_fn, attr),
..
} in query_data
{
let src = std::fs::read_to_string(&path).unwrap();
let file = syn::parse_file(&src).unwrap();
assert_is_top_free_function(&file, &item_fn);
let command =
command_from_fn_with_name(name_path, attr.clone(), item_fn, true, false, false);
subcommands.push((command, path, attr));
}
subcommands
}
// Helper function for `get_subcommands_data` this returns all the `#[subcommand]`s from the given path
// and it's modules but contained in a `QueryItem<(ItemFn, NameValueAttribute)`
fn get_subcommands_item_fn(root_path: &Path) -> Vec<QueryItem<(ItemFn, NameValueAttribute)>> {
fn if_subcommand_to_name_value(attribute: &Attribute) -> Option<NameValueAttribute> {
if consts::is_subcommand(&path_to_string(&attribute.path)) {
Some(
MacroAttribute::new(attribute.clone())
.into_name_values()
.unwrap(),
)
} else {
None
}
}
crate::query::find_map_items(root_path, true, true, |item| {
if let Item::Fn(item_fn) = item {
if let Some(attribute) = item_fn.attrs.iter().find_map(if_subcommand_to_name_value)
{
return Some((item_fn.clone(), attribute));
}
}
None
})
}
// Checks whether an items is a free function declared outside a ``mod { }``
fn assert_is_top_free_function(file: &File, item_fn: &ItemFn) {
fn eq_item_fn(left: &ItemFn, right: &ItemFn) -> bool {
left.block == right.block && left.sig == right.sig && left.vis == right.vis
}
for item in &file.items {
if let Item::Fn(cur_fn) = item {
if eq_item_fn(cur_fn, item_fn) {
return;
}
}
}
panic!("`{}` is not a top free function", item_fn.sig.ident);
}
}