-
Notifications
You must be signed in to change notification settings - Fork 0
/
yoda
executable file
·1226 lines (996 loc) · 29.6 KB
/
yoda
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
#!/usr/bin/env python
#
# Yoda -- Yet Options Descriptor Another.
#
# An utility to generate command-line related things like options C parser,
# help text, man page bash completion, etc.
#
# * This program is licensed under the GNU General Public License v2 (you can
# find its text in the COPYING file). This program is distributed in the hope
# that it will be useful, but without any warranty; without even the implied
# warranty of merchantability OR fitness for a particular purpose. See the GNU
# General Public License for more details.
#
# * Any file generated by this program (parser, help text, man page, anything
# else) is licenses under any license, the person who runs this program, wants.
#
# (C) Copyright Pavel Emelyanov <[email protected]>, 2013
#
import sys
import os
import argparse
yoda_version = "0.1"
yoda_url = "https://github.com/xemul/yoda/"
opt_option = 1
opt_argument = 2
typ_boolean = 1
typ_integer = 2
typ_string = 3
typ_path = 4
generators = [ "cparser", "bashcomp", "manopts" ]
class yoption:
def __init__(self, otype):
self.choice = []
self.schoice = []
self.otype = otype
self.pile = def_pile
self.imply = []
pass
class ychoice:
pass
class ygroup:
def __init__(self, name):
self.yopts = []
self.parent = None
self.name = name
pass
yopt_groups = {}
yopt_groups["generic"] = ygroup("generic")
#
# Our own command line
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-f", "--file", required=True, help="yoda file to parse", type=str)
arg_parser.add_argument("-n", "--name", required=False, help="project name", type=str)
arg_parser.add_argument("-g", "--generate", required=False, help="what to generate (%s)" % ", ".join(generators), type=str)
arg_parser.add_argument("-o", "--output", required=False, help="output file(s), separated with :", type=str)
arg_opts = arg_parser.parse_args()
if arg_opts.file == None:
arg_parser.print_help()
sys.exit(1)
ytmpl_dir = os.path.dirname(sys.argv[0])
if arg_opts.name == None:
yname = ""
else:
yname = arg_opts.name;
# Read yoda file in
yfile = open(arg_opts.file)
yopts = []
yopt_name_len_max = 0
std_shorts = set(["v", "V", "h"])
short_help = None
short_version = None
def_for = None
def_req_for = None
def_pile = False
def_hgroup = None
auto_alias_dashed = False
def yopt_find_l(s, yopts):
if not s:
return None
res = filter(lambda x: x.lname == s, yopts)
if len(res):
return res[0]
else:
return None
def yopt_find_s(s, yopts):
res = filter(lambda x: getattr(x, "sname", None) == s, yopts)
if len(res):
return res[0]
else:
return None
def next_rover(rover):
rover += 1
while chr(rover).isalnum() or (chr(rover) == '?'):
rover += 1
return rover
def make_dash_alias(name):
if "-" in name:
return name.replace("-", "_")
elif "_" in name:
return name.replace("_", "-")
else:
return None
sopt_rover = next_rover(1)
lcollect = ""
for l in yfile:
l = l.strip()
if (l.startswith("#")):
continue
if (l.endswith("\\")):
lcollect += " " + l.rstrip("\\")
continue
if lcollect:
l = lcollect + " " + l
lcollect = ""
ls = l.split(None, 1)
if (not ls):
continue
if (ls[0] == "option"):
yopt = yoption(opt_option)
ln = ls[1].split("/")
yopt.lname = ln.pop(0)
if len(ln):
yopt.sname = ln.pop(0)
if yopt.sname and (yopt.sname in std_shorts):
std_shorts.remove(yopt.sname)
if len(ln):
yopt.laliases = ln
if auto_alias_dashed:
als = []
al = make_dash_alias(yopt.lname)
if al:
als.append(al)
if getattr(yopt, "laliases", None):
for al in yopt.laliases:
als.append(al)
al = make_dash_alias(al)
if al:
als.append(al)
if len(als):
yopt.laliases = als
if not getattr(yopt, "sname", None):
yopt.sname_nr = sopt_rover
sopt_rover = next_rover(sopt_rover)
if def_for:
yopt.optional_for = def_for
if def_req_for:
yopt.required_for = def_req_for
if def_hgroup:
yopt.hgroup = def_hgroup
yopts.append(yopt)
if (yopt_name_len_max < len(yopt.lname)):
yopt_name_len_max = len(yopt.lname)
elif (ls[0] == "arg"):
yopt = yoption(opt_argument)
yopt.lname = ls[1]
yopts.append(yopt)
if (yopt_name_len_max < len(yopt.lname)):
yopt_name_len_max = len(yopt.lname)
elif (ls[0] == "int"):
yopt.atype = typ_integer
if len(ls) == 2:
yopt.summary = ls[1]
elif (ls[0] == "bool"):
yopt.atype = typ_boolean
if len(ls) == 2:
yopt.summary = ls[1]
elif (ls[0] == "string"):
yopt.atype = typ_string
if len(ls) == 2:
yopt.summary = ls[1]
elif (ls[0] == "path"):
yopt.atype = typ_path
if len(ls) == 2:
yopt.summary = ls[1]
elif (ls[0] == "choice"):
cs = ls[1].split(None, 1)
yc = ychoice()
css = cs[0].split("/")
yc.val = css.pop(0)
if yc.val.startswith("!"):
yc.val = yc.val.lstrip("!")
yc.schoice = True
if len(css):
yc.aliases = css
if len(cs) > 1:
yc.summary = cs[1]
else:
yc.summary = ""
yopt.choice.append(yc)
elif (ls[0] == "default"):
yopt.defval = ls[1]
elif (ls[0] == "req_for"):
yopt.required_for = ls[1]
elif (ls[0] == "for"):
yopt.optional_for = ls[1]
elif (ls[0] == "hgroup"):
yopt.hgroup = ls[1]
elif (ls[0] == "clash"):
yopt.conflicts = ls[1]
elif (ls[0] == "imply"):
if yopt.otype != opt_option:
print "Implications for argument %s not allowed" % yopt.lname
sys.exit(1)
yopt.imply.append(ls[1])
elif (ls[0] == "optarg"):
yopt.optarg = ls[1]
elif (ls[0] == "pile"):
yopt.pile = True
elif (ls[0] == "help"):
yopt.helptext = ls[1]
elif (ls[0] == "set"):
ls = ls[1].split(None, 1)
if ls[0] == "for":
def_for = ls[1]
elif ls[0] == "req_for":
def_req_for = ls[1]
elif ls[0] == "hgroup":
def_hgroup = ls[1]
elif ls[0] == "pile":
def_pile = True
elif ls[0] == "auto_dash_alias":
assert(len(yopts) == 0)
auto_alias_dashed = True
elif ls[0] == "short_help":
assert(len(yopts) == 0)
short_help = ls[1]
elif ls[0] == "short_version":
assert(len(yopts) == 0)
short_version = ls[1]
else:
print "Unknown set", ls[0]
elif (ls[0] == "unset"):
if ls[1] == "for":
def_for = None
elif ls[1] == "req_for":
def_req_for = None
elif ls[1] == "hgroup":
def_hgroup = None
elif ls[1] == "pile":
def_pile = False
else:
print "Unknown unset", ls[0]
else:
print "Unknown keyword", ls[0]
sys.exit(1)
yfile.close()
# Add standart help option
yopt = yoption(opt_option)
yopt.lname = "help"
yopt.atype = typ_boolean
yopt.summary = "show help text"
if short_help:
yopt.sname = short_help
elif "h" in std_shorts:
yopt.sname = "h"
else:
yopt.sname_nr = sopt_rover
sopt_rover = next_rover(sopt_rover)
yopts.append(yopt)
# Add version option
yopt = yoption(opt_option)
yopt.lname = "version"
yopt.atype = typ_boolean
yopt.summary = "show version"
yopt.genonly = True
if short_version:
yopt.sname = short_version
elif "v" in std_shorts:
yopt.sname = "v"
elif "V" in std_shorts:
yopt.sname = "V"
else:
yopt.sname_nr = sopt_rover
sopt_rover = next_rover(sopt_rover)
yopts.append(yopt)
def opt_deprecated(yopt):
return not getattr(yopt, "summary", None)
# Classify options
# each option may get into one or more "group", each
# group will have its own options-table that will be
# switched by the parser
active_classifier = None
for yopt in yopts:
if yopt.otype != opt_option:
continue
if opt_deprecated(yopt):
continue
exps = []
ygrps = []
if getattr(yopt, "required_for", None):
exps.extend(yopt.required_for.split("|"))
if getattr(yopt, "optional_for", None):
exps.extend(yopt.optional_for.split("|"))
if not exps:
ygrps = [ yopt_groups["generic"] ]
else:
for exp in exps:
exp_str = "%s" % exp.strip()
eps = exp_str.partition("=")
ep = eps[0].strip()
y = yopt_find_l(ep, yopts)
if not y:
print "No option for expression with %s" % ep
sys.exit(1)
if y.otype == opt_option:
# option depening on other option
# should be added to that other's
# groups
if not getattr(y, "in_groups", None):
print "Target option unclassified, reshuffle options"
sys.exit(1)
ygrps.extend(y.in_groups)
else:
if not active_classifier:
active_classifier = y
elif y != active_classifier:
print "More than one active classifier."
sys.exit(1)
if not yopt_groups.has_key(exp_str):
yopt_groups[exp_str] = ygroup(eps[2].strip().replace("-", "_"))
ygrps.append(yopt_groups[exp_str])
if not ygrps:
ygrps = [ yopt_groups["generic"] ]
yopt.in_groups = []
ygrps = list(set(ygrps)) # remove duplicates
for ygrp in ygrps:
if getattr(yopt, "lname", None):
y = yopt_find_l(yopt.lname, ygrp.yopts)
if y:
print "Duplicate option long name %s" % yopt.lname
sys.exit(1)
if getattr(yopt, "sname", None):
y = yopt_find_s(yopt.sname, ygrp.yopts)
if y:
print "Duplicate option short name %s" % yopt.sname
ygrp.yopts.append(yopt)
yopt.in_groups.append(ygrp)
# Name of yopts struct member
def opt_cname(yopt):
if yopt.lname:
return yopt.lname.replace("-", "_")
else:
return "opt_" + yopt.sname
# Name of option when printed on a screen
def opt_pname(yopt):
if yopt.otype == opt_option:
if yopt.lname:
return "--%s" % yopt.lname
else:
return "-%s" % yopt.sname
else:
if yopt.lname:
return yopt.lname
else:
return yopt.sname
# Name of variable (with struct name)
def opt_sname(yopt):
return "%syopts.%s" % (yname, opt_cname(yopt))
# Basic validity checks
for yopt in yopts:
if not getattr(yopt, "atype", None):
print "Option %s without type" % opt_pname(yopt)
sys.exit(1)
if len(yopt.choice):
if yopt.atype in (typ_boolean, typ_path):
print "Can't have choices for bool/path option %s" % opt_pname(yopt)
sys.exit(1)
if yopt.atype == typ_boolean:
if getattr(yopt, "defval", None):
print "Boolean option %s can't have default" % opt_pname(yopt)
sys.exit(1)
if getattr(yopt, "optarg", None):
print "Boolean option %s can't have optarg" % opt_pname(yopt)
sys.exit(1)
if not arg_opts.generate:
print "Nothing to generate"
sys.exit(0)
if not arg_opts.generate in generators:
print "Can't generate %s, but can one of: %s" % \
(arg_opts.generate, ", ".join(generators))
sys.exit(0)
def c_indent(istr, code):
return istr + istr.join(code.splitlines(True))
def yopt_argname(yopt):
if yopt.atype == typ_boolean:
return ""
opt_astrs = {
typ_integer: "NUM",
typ_string: "STR",
typ_path: "PATH",
}
# Remove all but UPPERCASE letters
s = filter(lambda x: x.isupper(), yopt.summary)
if getattr(yopt, "optarg", None):
s = "[%s]" % s
return len(s) and s or opt_astrs[yopt.atype]
def yoda_put_header(ystr):
ystr = ystr.replace("${VERSION}", yoda_version)
ystr = ystr.replace("${INPUTFILE}", os.path.basename(arg_opts.file))
ystr = ystr.replace("${PROJECT_URL}", yoda_url)
return ystr
def generate_cparser():
##
#
# Generate sources
#
##
if arg_opts.output:
c_files = arg_opts.output.split(":")
else:
c_files = [ "%syopts.h" % yname, "%syopts.c" % yname ]
ctypes = {
typ_boolean: "bool",
typ_integer: "int",
typ_string: "char *",
typ_path: "char *",
}
#
# Generate the .h file
#
yinfile = open(os.path.join(ytmpl_dir, "yopts.h.in"))
yincode = yinfile.read()
yincode = yincode.replace("${PROJ}", yname)
yincode = yoda_put_header(yincode)
# Generate the yopts structure
yopt_str = ""
def opt_vdecl(vtyp, vname, ptr = False):
return "%s%s %s;\n\t" % (ctypes[vtyp], ptr and "*" or "", vname)
for yopt in yopts:
if yopt.pile:
yopt_str += opt_vdecl(typ_integer, opt_cname(yopt) + "_nr")
# For non ints with choice generate numerical constants
# for faster comparisons in the code
if len(yopt.choice) and (yopt.atype != typ_integer):
yopt_str += opt_vdecl(typ_integer, opt_cname(yopt) + "_code")
yopt_str += opt_vdecl(yopt.atype, opt_cname(yopt), yopt.pile)
yincode = yincode.replace("${STRUCTURE}", yopt_str)
# Generate constants for choice-d options and arguments
yopt_str = ""
for yopt in yopts:
if yopt.atype != typ_string:
continue
if not len(yopt.choice):
continue
for ch in yopt.choice:
ch.ccode = "YOPT_%s_%s" % (opt_cname(yopt).upper(), ch.val.upper().replace("-", "_"))
vals = map(lambda x: "\t%s,\n" % x.ccode, yopt.choice)
vals.insert(0, "\tYOPT_%s_DFLT = 0,\n" % opt_cname(yopt).upper())
yopt_str += "enum {\n"
yopt_str += "".join(vals)
yopt_str += "};\n\n"
yincode = yincode.replace("${CHOICES}", yopt_str)
# Commit the code into .h file
youtfile = open(c_files[0], "w")
youtfile.write(yincode)
yinfile.close()
youtfile.close()
#
# Generate the .c file
#
# Get the template in
yinfile = open(os.path.join(ytmpl_dir, "yopts.c.in"))
yincode = yinfile.read()
yincode = yincode.replace("${PROJ}", yname)
yincode = yoda_put_header(yincode)
yincode = yincode.replace("${HEADERFILE}", os.path.basename(c_files[0]))
yinsfile = open(os.path.join(ytmpl_dir, "yopt_set.c.in"))
yinscode = yinsfile.read()
yinscode = yinscode.replace("${PROJ}", yname)
def cstrval(s):
return "\"%s\"" % s.strip("\"")
# Generate default values
yopt_str = ""
for yopt in yopts:
if not getattr(yopt, "defval", None):
continue
if yopt_str:
yopt_str += "\t"
if yopt.atype in (typ_string, typ_path):
yassig = cstrval(yopt.defval)
elif yopt.atype == typ_integer:
yassig = "%s" % yopt.defval
yopt_str += ".%s = %s,\n" % (opt_cname(yopt), yassig)
yincode = yincode.replace("${DEFAULTS}", yopt_str)
#
# Generate option sets
#
def gen_opt_set(name, yopts, ng_yopts):
yscode = yinscode.replace("${YSET}", name)
# Generate and put short options array
yopt_str = ""
for yopt in yopts:
if not getattr(yopt, "sname", None):
continue
if ng_yopts and getattr(yopt, "genonly", None):
continue
yopt_str += yopt.sname
if yopt.atype != typ_boolean:
if getattr(yopt, "optarg", None):
yopt_str += "::"
else:
yopt_str += ":"
yscode = yscode.replace("${SOPTS}", yopt_str)
# Generate and put long options array
def opt_cassign(yopt):
if getattr(yopt, "sname", None):
return "'%s'" % yopt.sname
else:
return "%d" % yopt.sname_nr
yopt_str = ""
for yopt in yopts:
if yopt.otype != opt_option:
continue
if not getattr(yopt, "lname", None):
continue
if ng_yopts and getattr(yopt, "genonly", None):
continue
if yopt.atype == typ_boolean:
yopt_rarg = "no_argument"
elif getattr(yopt, "optarg", None):
yopt_rarg = "optional_argument"
else:
yopt_rarg = "required_argument"
yopt_sopt = opt_cassign(yopt)
lnames = getattr(yopt, "laliases", [])
lnames.insert(0, yopt.lname)
for lname in lnames:
if yopt_str:
yopt_str += "\n\t"
yopt_str += "{\"%s\", %s, 0, %s}," % (lname, yopt_rarg, yopt_sopt)
yscode = yscode.replace("${LOPTS}", yopt_str)
# Generate options assignment
def optarg_assign(yopt):
if yopt.atype in (typ_string, typ_path):
return cstrval(yopt.optarg)
elif yopt.optarg.startswith("+"):
return "%s %s" % (opt_sname(yopt), yopt.optarg)
else:
return yopt.optarg
def opt_assign_code(yopt, value):
yopt_str = ""
yopt_vassign = opt_sname(yopt)
if yopt.pile:
yopt_vassign = "%s[%s_nr++]" % (opt_sname(yopt), opt_sname(yopt))
if yopt.atype == typ_boolean:
yopt_assign = "true"
elif yopt.atype in (typ_string, typ_path):
yopt_assign = value
elif yopt.atype == typ_integer:
yopt_assign = "yopt_parse_int(%s)" % value
if (value != "optarg") and getattr(yopt, "optarg", None):
yopt_assign = "(optarg ? %s : %s)" % (yopt_assign, optarg_assign(yopt))
yopt_str += "\t\tdprint(\"%s assigned to %%s\\n\", %s);\n" % (opt_sname(yopt), value)
if yopt.pile:
yopt_str += "\t\t%s = yopt_realloc_mem(%s, (%s_nr + 1) * sizeof(%s));\n" % \
(opt_sname(yopt), opt_sname(yopt), opt_sname(yopt), ctypes[yopt.atype])
yopt_str += "\t\tif (%s)\n\t" % opt_sname(yopt)
yopt_str += "\t\t%s = %s;\n" % (yopt_vassign, yopt_assign)
return yopt_str
if not ng_yopts:
yscode = yscode.replace("${GENERIC}", "true")
ng_yopts = yopts
else:
yscode = yscode.replace("${GENERIC}", "false")
yopt_str = ""
for yopt in ng_yopts:
if yopt.otype != opt_option:
continue
if yopt_str:
yopt_str += "\n\t"
yopt_str += "case %s:\n" % opt_cassign(yopt)
yopt_str += opt_assign_code(yopt, "optarg")
for impl in yopt.imply:
imps = impl.partition("=")
iyopt = yopt_find_l(imps[0].strip(), yopts)
if not iyopt:
print "No target option for %s implication" % impl
sys.exit(1)
if iyopt.atype == typ_boolean:
if imps[2]:
print "No value for boolean imply"
sys.exit(1)
iassign = "NULL"
else:
iassign = cstrval(imps[2].strip())
yopt_str += opt_assign_code(iyopt, iassign)
yopt_str += "\t\tbreak;"
return yscode.replace("${OPTS_ASSIGN}", yopt_str);
#yinscode = gen_opt_set("generic", yopts)
def gen_opt_set_grp(ygrp):
if ygrp.name == "generic":
return gen_opt_set("generic", ygrp.yopts, None)
yopts = []
yopts.extend(ygrp.yopts)
yopts.extend(yopt_groups["generic"].yopts)
return gen_opt_set(ygrp.name, yopts, ygrp.yopts)
yinsscode = ""
for gname in yopt_groups:
ygrp = yopt_groups[gname]
yinsscode += "/*\n * Set for %s\n */\n" % ygrp.name
yinsscode += gen_opt_set_grp(ygrp)
yinsscode += "/* End of %s set */\n" % ygrp.name
#
# End generating sets -- put them into main .c file
#
yincode = yincode.replace("${YSETS}", yinsscode)
# Generate validation routine (choices)
yopt_str = ""
def gen_choice_fixup(yopt):
def opt_is_dflt(yopt):
if getattr(yopt, "defval", None):
if yopt.atype == typ_string:
return "!strcmp(%s, %s)" % (opt_sname(yopt), cstrval(yopt.defval))
else:
return "%s == %s" % (opt_sname(yopt), yopt.defval)
else:
return "!%s" % opt_sname(yopt)
yopt_str = ""
if yopt.atype == typ_string:
if yopt.otype == opt_option:
yopt_str += "if (%s) {\n" % opt_is_dflt(yopt)
yopt_str += "\t;\n"
yopt_str += "} else "
for ch in yopt.choice:
vals = getattr(ch, "aliases", None) or []
vals.insert(0, ch.val)
cmps = map(lambda x: "!strcmp(%s, \"%s\")" % (opt_sname(yopt), x), vals)
cmps = " || ".join(cmps)
yopt_str += "if (%s) {\n" % cmps
yopt_str += "\t%s_code = %s;\n" % (opt_sname(yopt), ch.ccode)
if getattr(ch, "schoice", None):
yopt_str += "\treturn -1;\n"
elif yopt == active_classifier:
ykey = "%s = %s" % (yopt.lname, ch.val)
if yopt_groups.has_key(ykey):
yopt_str += "\tycur = &%s_set;\n" % yopt_groups[ykey].name
yopt_str += "\tnew_set = true;\n"
yopt_str += "} else "
yopt_str += " {\n"
yopt_str += "\tyopt_print(\"Unknown value for %s\\n\");\n" % opt_pname(yopt)
yopt_str += "\tyopt_err = YOPTS_PARSE_ERR;\n"
yopt_str += "}\n\n"
elif yopt.atype == typ_integer:
yopt_str += "switch (%s) {\n" % opt_sname(yopt)
cases = map(lambda x: "case %s:\n" % x.val, yopt.choice)
yopt_str += "".join(cases)
yopt_str += "\tbreak;\n"
yopt_str += "default:\n"
if (yopt.otype == opt_option):
yopt_str += "\tif (%s)\n" % opt_is_dflt(yopt)
yopt_str += "\t\tbreak;\n"
yopt_str += "\tyopt_print(\"Unknown value for %s\\n\");\n" % opt_pname(yopt)
yopt_str += "\tyopt_err = YOPTS_PARSE_ERR;\n"
yopt_str += "}\n\n"
return yopt_str
for yopt in yopts:
if yopt.otype == opt_argument:
continue
if not len(yopt.choice):
continue
yopt_str += gen_choice_fixup(yopt)
yopt_str = c_indent("\t", yopt_str)
yincode = yincode.replace("${FIX_CHOICES}", yopt_str)
# Generate arguments (arg-s) parsing. The getopt_long puts leaves them at the end of argv array
yopt_str = ""
args_nr = 0
for yopt in yopts:
if yopt.otype != opt_argument:
continue
if yopt.atype in (typ_string, typ_path):
arg_assign = "arg"
elif yopt.atype == typ_integer:
arg_assign = "yopt_parse_int(arg)"
else:
print "Wrong type for an argument\n"
sys.exit(1)
yopt_str += "case %d:\n" % args_nr
yopt_str += "\tdprint(\"%s assigned to %%s\\n\", arg);\n" % opt_sname(yopt)
yopt_str += "\t%s = %s;\n" % (opt_sname(yopt), arg_assign)
if len(yopt.choice):
yopt_str += c_indent("\t", gen_choice_fixup(yopt))
yopt_str += "\tbreak;\n"
args_nr += 1
yopt_str = c_indent("\t", yopt_str)
yincode = yincode.replace("${ASSIGN_ARGS}", yopt_str)
yincode = yincode.replace("${NR_ARGS}", "%d" % args_nr)
yopt_str = ""
arg_nr = 0
for yopt in yopts:
if yopt.otype != opt_argument:
continue
yopt_str += "if (yopt_next_arg <= %d) {\n" % arg_nr
yopt_str += "\tyopt_print(\"Argument %s missing\\n\");\n" % opt_pname(yopt)
yopt_str += "\tyopt_err = YOPTS_PARSE_ERR;\n"
yopt_str += "}\n\n"
arg_nr += 1
yopt_str = c_indent("\t", yopt_str)
yincode = yincode.replace("${CHECK_ARGS}", yopt_str)
# Expressions generator
def yoda_gen_one_cexp(exp):
parts = exp.partition("=")
for yopt in yopts:
if yopt.lname == parts[0].strip():
break;
if yopt.atype == typ_boolean:
fixup = ""
comp = ""
cval = ""
elif (yopt.atype in (typ_string, typ_path)) and len(yopt.choice):
fixup = "_code"
comp = " == "
for ch in yopt.choice:
if ch.val == parts[2].strip():
cval = ch.ccode
break
else:
sys.exit(1)
elif yopt.atype == typ_integer:
fixup = ""
if parts[1]:
comp = " == "
cval = parts[2]
else:
comp = " != "
cval = "0"
else:
print "No req check for %s\n" % opt_sname(yopt)
sys.exit(1)
return "%s%s%s%s" % (opt_sname(yopt), fixup, comp, cval)
def yoda_gen_cexpression(exp_str):
exps = exp_str.partition("|")
ret_str = yoda_gen_one_cexp(exps[0])
if exps[1]:
return ("(%s) || " % ret_str) + yoda_gen_cexpression(exps[2])
else:
return "(%s)" % ret_str
def yoda_get_group_desc(exp_str):
gacts = {}
exps = exp_str.split("|")
for exp in exps:
parts = map(lambda a: a.strip(), exp.split("="))
if len(parts) == 1:
if yopt_find_l(parts[0], yopts):
parts = ['option', parts[0]]
else:
parts = ['', parts[0]]
if not gacts.has_key(parts[0]):
gacts[parts[0]] = []
gacts[parts[0]].append(parts[1])
gstr = ""
for t in gacts:
if gstr:
gstr += " or "
else:
gstr += "for "
gstr += ", ".join(gacts[t])
gstr += " %s" % t
if len(gacts[t]) > 1:
gstr += "s"
return gstr.capitalize().strip()
# Generate requirements checks (req_for-s and clash-es)
yopt_str = ""
for yopt in yopts:
if getattr(yopt, "required_for", None):
yopt_str += "if (%s) {\n" % yoda_gen_cexpression(yopt.required_for)
yopt_str += "\tif (!%s) {\n" % opt_sname(yopt)
yopt_str += "\t\tyopt_err = YOPTS_PARSE_ERR;\n"
yopt_str += "\t\tyopt_print(\"Option %s required\\n\");\n" % opt_pname(yopt)
yopt_str += "\t}\n"
yopt_str += "}\n\n"
if getattr(yopt, "conflicts", None):
yopt_str += "if (%s && (%s)) {\n" % (opt_sname(yopt), yoda_gen_cexpression(yopt.conflicts))
yopt_str += "\tyopt_err = YOPTS_PARSE_ERR;\n"
yopt_str += "\tyopt_print(\"Option %s conflict\\n\");\n" % opt_pname(yopt)
yopt_str += "}\n\n"
yopt_str = c_indent("\t", yopt_str)
yincode = yincode.replace("${CHECK_REQS}", yopt_str)
# Generate usage text
yopt_str = ""
yopt_align = "\t "
yopt_indent = " "
yopt_el = yopt_align + "\"\\n\"\n"
yopt_str += yopt_align + "\"" + yopt_indent + "%s"
for yopt in yopts:
if yopt.otype != opt_argument:
continue
if opt_deprecated(yopt):
continue
yopt_str += " <%s>" % yopt.lname
yopt_str += " [<options>]\\n\"\n"
yopt_str += yopt_el
# "Arguments" block
for yopt in yopts:
if (yopt.otype != opt_argument):
continue
if opt_deprecated(yopt):
continue
yopt_str += yopt_align + "\"%s: %s\\n\"\n" % (yopt.lname.capitalize(), yopt.summary)
if len(yopt.choice) > 0:
for ch in yopt.choice:
yopt_str += yopt_align + "\"" + yopt_indent + \
ch.val.ljust(10 + yopt_name_len_max) + \
ch.summary + "\\n\"\n"
yopt_str += yopt_el
yopt_str += yopt_align + "\"Options:\\n\"\n"
yopts_groups = {}
yopts_default = []
yopts_generic = []
# Classify options
for yopt in yopts:
if yopt.otype != opt_option:
continue
if opt_deprecated(yopt):
continue
for_expr = []