/
skdoc.py
4261 lines (3507 loc) · 133 KB
/
skdoc.py
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
import io
import os
import abc
import inspect
import pkgutil
import pathlib
import logging
import textwrap
import distutils
import importlib
import functools
import collections
import regex as re
log = logging.getLogger('skdoc')
def ucfirst(s):
if not s:
return s
return s[0].upper() + s[1:]
def lcfirst(s):
if not s:
return s
return s[0].lower() + s[1:]
# http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#sss:keywords
ml_keywords = set(
re.split(
r'\s+', """
and as assert asr begin class
constraint do done downto else end
exception external false for fun function
functor if in include inherit initializer
land lazy let lor lsl lsr
lxor match method mod module mutable
new nonrec object of open or
private rec sig struct then to
true try type val virtual when
while with
""".strip()))
def tag(s):
if not s:
s = 'T'
ops = {
'-': 'Minus',
'+': 'Plus',
' ': 'Space',
'*': 'Mult',
'/': 'Div',
'<': 'Lt',
'>': 'Gt',
'==': 'Eq',
'<=': 'Lte',
'>=': 'Gte',
'!=': 'Neq',
# Note that these could probably more explicit.
'r': 'R',
'w': 'W',
'r+': 'R_plus',
'w+': 'W_plus',
'rw': 'RW',
'a': 'A',
'A+': 'A_plus'
}
if s in ops:
return ops[s]
s = re.sub(r'[^a-zA-Z0-9_]+', '_', s)
s = re.sub(r'^([^a-zA-Z])', r'T\1', s)
return ucfirst(s)
def mlid(s):
if s is None:
return None
if s == '_':
return '_dummy'
# DESCR -> descr
if s == s.upper():
return s.lower()
s = lcfirst(s)
if s in ml_keywords:
return s + '_'
return s
def make_module_name(x):
if not re.match(r'^[a-zA-Z]', x):
return 'M' + x
else:
return ucfirst(x)
class Section_title:
def __init__(self, text):
self.text = text
def __str__(self):
return repr(self)
def __repr__(self):
return f"{self.__class__.__name__}('{self.text}')"
class Paragraph:
def __init__(self, text):
self.text = text
def __str__(self):
return repr(self)
def __repr__(self):
return f"{self.__class__.__name__}('{self.text}')"
class TypeContext:
def __init__(self, **kwargs):
self.bindings = kwargs
def add(self, **kwargs):
ret = type(self)(**self.bindings)
ret.bindings.update(kwargs)
return ret
def __getattr__(self, name):
return self.bindings[name]
def __str__(self):
return repr(self)
def __repr__(self):
ret = "--------- context:\n"
for k, v in self.bindings.items():
ret += f"{k}:\n"
ret += indent(maybe_to_string(v)) + "\n"
return ret
class Registry:
def __init__(self):
self.types = collections.defaultdict(list)
self.module_path = {}
self.bases = collections.defaultdict(set)
self.generated_files = []
self.generated_doc_files = []
self.elements = collections.defaultdict(list)
def add(self, name, element):
self.elements[element].append(name)
def add_generated_file(self, f):
f = pathlib.Path(f)
assert f not in self.generated_files, f"source file already generated: {f}"
self.generated_files.append(f)
def add_generated_doc_file(self, f):
f = pathlib.Path(f)
assert f not in self.generated_doc_files, f"doc file already generated: {f}"
self.generated_doc_files.append(f)
def add_class(self, klass, module_path):
if self.module_path.get(klass, module_path) != module_path:
# existing = self.module_path[klass]
# if 'Base' not in existing:
# print(
# f"WW {klass.__name__} is already registered with path {existing}, ignoring path {module_path}"
# )
pass
else:
self.module_path[klass] = module_path
for ancestor in interesting_ancestors(klass):
self.types[ancestor].append(klass)
self.bases[klass].add(ancestor)
def write(self, build_dir):
pass
def report_generated(self):
multiple = []
for element, names in self.elements.items():
if len(names) > 1:
multiple.append((len(names), element, names))
multiple.sort(key=lambda x: x[0])
for num, element, names in multiple:
ename = getattr(element, '__name__', maybe_to_string(element))
log.warning(f"skdoc.py:0:{type(element).__name__} {ename}: was emitted under {num} names:")
for name in names:
log.warning(f"- {name.full_python_name()} / {name.full_ml_name()}")
if self.generated_files:
log.info("generated source files:")
for f in sorted(self.generated_files):
print(f)
if self.generated_doc_files:
log.info("generated doc files:")
for f in sorted(self.generated_doc_files):
print(f)
def deindent(line):
m = re.match('^( *)(.*)$', line)
assert m is not None
return len(m.group(1)), m.group(2)
def parse(doc):
lines = doc.split("\n")
elements = []
element = []
previous_indent = None
first_line, *lines = lines
for line in lines:
indent, line = deindent(line)
if previous_indent is None:
previous_indent = indent
# print(f"line: '{line}' indent: {indent} previous: {previous_indent}")
if not line or indent < previous_indent:
# log.debug("-> end paragraph")
elements.append(Paragraph("\n".join(element)))
element = []
previous_indent = None
if line:
element.append(line)
elif re.match(r'^-+$', line):
# print(f'found underline, element: {element}')
if not element:
log.warning(f"found underline with nothing above:\n{doc}")
continue
block, title = element[:-1], element[-1]
if block:
elements.append(Paragraph("\n".join(block)))
elements.append(Section_title(title))
element = []
previous_indent = None
else:
# log.debug("append line to existing element")
element.append(line)
previous_indent = indent
if element:
elements.append(Paragraph("\n".join(element)))
return elements
def parse_params(doc, section='Parameters'):
elements = parse(doc)
# if section not in doc:
# print(f"no section {section} in doc")
# if section == 'Returns':
# print(elements)
in_section = False
params = []
for elt in elements:
if isinstance(elt, Section_title):
if elt.text == section:
in_section = True
continue
else:
if in_section:
break
if in_section:
params.append(elt)
# if section == 'Returns':
# print(f"params for section {section}: {params}")
return params
def remove_default(text):
text = re.sub(r'(,\s*)?\(\S+\s+by\s+default\)', '', text)
text = re.sub(r'\s*\(default\)', '', text)
text = re.sub(r'\s*\(if [^()]+\)', '', text)
text = re.sub(r'[Dd]efaults\s+to\s+\S+\.?', '', text)
text = re.sub(r'[Dd]efault\s+is\s+\S+\.?', '', text)
text = re.sub(r'\(?\s*[Dd]efault\s*[:=]?\s*.+\)?$', '', text)
text = re.sub(r'\s*optional', '', text)
text = re.sub(r'(,\s*)?\S+\s+by\s+default', '', text)
return text
class ReParser:
"""Parsing things with regexps, like shapes and enums. This is
probably the cleanest I can do without turning to a proper
parser generator.
"""
def __init__(self):
nob = r'(?:[^()[\]]*)'
onep = rf'(?:\({nob}\))'
oneb = rf'(?:\[{nob}\])'
onec = rf'(?:\{{{nob}\}})'
one = rf'(?:{oneb}|{onep}|{onec})'
onepn = r'(?:\( (?:[nm]\w*,\s*)+ (?:[nm]\w*)? \))'
onebn = r'(?:\[ (?:[nm]\w*,\s*)+ (?:[nm]\w*)? \])'
onecn = r'(?:\{ (?:[nm]\w*,\s*)+ (?:[nm]\w*)? \})'
onen = rf'(?:{onepn}|{onebn}|{onecn})'
twop = rf'(?:\((?:{nob}{one})*{nob}?\))'
twob = rf'(?:\[(?:{nob}{one})*{nob}?\])'
twoc = rf'(?:\{{(?:{nob}{one})*{nob}?\}})'
two = rf'(?:{twob}|{twop}|{twoc})'
threep = rf'(?:\((?:{nob}{two})*{nob}?\))'
threeb = rf'(?:\[(?:{nob}{two})*{nob}?\])'
threec = rf'(?:\{{(?:{nob}{two})*{nob}?\}})'
three = rf'(?:{threeb}|{threep}|{threec})'
self.three = three
ifelse = rf'(if \s+ \S+ \s* =+ \s* \S+ \s+ else \s* {three})'
ort = rf'(,? \s* or \s* ({three}|smaller) (\s* if \s+ \S+ \s* =+ \s* \S+)?)'
# Things inside parentheses, with several spaces but no comma (=>
# not a tuple). There can be paren groups with commas inside them, though.
p_no_tuple = rf'(\( ([^(),]* {three})* [^(),]* \s [^\s(),]+ \s ([^(),]* {three})* [^(),]* \))'
res = [
rf'(((of|with) \s+)? shape) (\s* ([=:]\s* | of \s*)?)? {three} (\s* ({ifelse}|{ort}))?',
rf'(of \s*)? {onen} (?:\s* if \s+ \S+ \s* =+ \s* \S+)?',
r'(of|with) \s+ length (\s+ | \s*[=:]\s*) \S+',
r'\S+-dimension(al)?',
p_no_tuple,
]
shape = '|'.join([rf'({x})' for x in res])
shape = rf'(,\s*)?(?:{shape})'
self.shape = self._comp(shape)
enum_elt = rf'(?P<elt>(?:(?:(?! (?:, \s* | \s) or \s+) [^()[\],])* {three})* (?:(?! (?:, \s* | \s) or \s+)[^()[\],])*)' # noqa
enum_comma = rf'(?:(?:{enum_elt},)+ {enum_elt})'
enum_semi = rf'(?:(?:{enum_elt};)+ {enum_elt})'
enum_pipe = rf'(?:(?:{enum_elt}\|)+ {enum_elt})'
enum_or = rf'(?:(?:{enum_elt} (?:,\s* | \s) or \s)+ {enum_elt})'
enum_comma_or = rf'(?:{enum_comma} (?:,\s* | \s) or \s {enum_elt})'
string = r'''(?P<elt>"[^"]+" | '[^']+' | None) (?: \s* \( \s* default \s* \) \s*)?'''
strings_comma = rf'(?:(?:{string} \s* , \s*)* {string})'
strings_semi = rf'(?:(?:{string} \s* ; \s*)* {string})'
strings_pipe = rf'(?:(?:{string} \s* \| \s*)* {string})'
strings = rf'(?:\s* (?:{strings_comma} | {strings_semi} | {strings_pipe}) \s*)'
strings_p = rf'(?:\( \s* {strings} \s* \))'
strings_b = rf'(?:\[ \s* {strings} \s* \])'
strings_c = rf'(?:\{{ \s* {strings} \s* \}})'
string_enum = rf'(?:(?:str(ing)? (?:\s+ in | \s* [,:])? \s*)? (?:{strings_p} | {strings_b} | {strings_c} | {strings_pipe}))' # noqa
enum_c = rf'(?: \{{ (?:{enum_comma} | {enum_semi} | {enum_pipe}) \}})'
enum = rf'^\s* (?:(?:string, \s*)? either \s+)? (?:{string_enum} | {enum_c} | {enum_comma} | {enum_pipe} | {enum_or} | {enum_comma_or}) \s*$' # noqa e501
self.string = self._comp(string)
self.strings = self._comp(strings)
self.strings_c = self._comp(strings_c)
self.string_enum = self._comp(string_enum)
self.enum_elt = self._comp(enum_elt)
self.enum_comma = self._comp(enum_comma)
self.enum_or = self._comp(enum_or)
self.enum_comma_or = self._comp(enum_comma_or)
self.enum = self._comp(enum)
doc_sig = rf'^\s*(?:\w \s* (?:, \s* \w \s*)* = \s*)? ([\w\.]+)({three})'
self.doc_sig = self._comp(doc_sig)
def _comp(self, patt):
return re.compile(patt, flags=re.VERBOSE | re.IGNORECASE)
re_parser = ReParser()
def remove_shape(text):
text = re.sub(re_parser.shape, '', text)
return text
def test_remove_shape():
tests = [
'shape [n,m]', 'of shape (n_samples,) or (n_samples, n_outputs)',
'shape (n_samples, n_features)',
'(len() equal to cv or 1 if cv == "prefit")', 'of shape [n_samples]',
'of shape (n_class,)', 'shape (n_bins,) or smaller',
'shape = [1, n_features] if n_classes == 2 else [n_classes, n_features]',
'shape (n_samples, n_features), or (n_samples, n_samples)',
'shape of (n_samples, n_features)', 'of shape of (n_targets,)',
'shape of (n_class * (n_class-1) / 2,)', 'of (N,)', 'of (n_features,)',
"""shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed'""",
'(n_samples, n_features)',
"[n_samples_a, n_samples_a] if metric == 'precomputed'"
]
success = True
for test in tests:
result = remove_shape(test)
if result:
log.error(f"test fails: '{test}' -> '{result}' (expected '')")
success = False
tests_no = [
"string in ['raw_values', 'uniform_average', 'variance_weighted']",
'list of (int,) or list of (int, int)'
]
for test in tests_no:
result = remove_shape(test)
if result != test:
log.error(
f"test fails: '{test}' -> '{result}' (expected '{test}')")
success = False
return success
def is_string(x):
if not x:
return False
return (x[0] == x[-1] and x[0] in ("'", '"')) or x in [
"eigen'"
] # hack for doc bug of RidgeCV
def is_int(x):
return re.match(r'^\d+$', x)
def parse_enum(t):
m = re.match(re_parser.enum, t)
if m is None:
return None
ret = m.captures("elt")
ret = [x.strip() for x in ret]
ret = [x for x in ret if x]
return ret
def test_parse_enum():
tests = [
('list of (int,) or list of (int, int)',
['list of (int,)', 'list of (int, int)']),
('list of (int,) or list of (int, int) or list of str',
['list of (int,)', 'list of (int, int)', 'list of str']),
('list of (int,), list of (int, int)',
['list of (int,)', 'list of (int, int)']),
('list of (int,), list of (int, int) or list of ndarray',
['list of (int,)', 'list of (int, int)', 'list of ndarray']),
("string in {'a', 'b'}", ["'a'", "'b'"]),
("str in {'a', 'b'}", ["'a'", "'b'"]),
("str, {'a', 'b'}", ["'a'", "'b'"]),
("string, {'a', 'b'}", ["'a'", "'b'"]),
("string in ['a', 'b']", ["'a'", "'b'"]),
("str in ['a', 'b']", ["'a'", "'b'"]),
("str, ['a', 'b']", ["'a'", "'b'"]),
("string, ['a', 'b']", ["'a'", "'b'"]),
("string in ('a', 'b')", ["'a'", "'b'"]),
("str in ('a', 'b')", ["'a'", "'b'"]),
("str, ('a', 'b')", ["'a'", "'b'"]),
("string, ('a', 'b')", ["'a'", "'b'"]),
("string : {'a', 'b'}", ["'a'", "'b'"]),
("str : {'a', 'b'}", ["'a'", "'b'"]),
("str: {'a', 'b'}", ["'a'", "'b'"]),
("{array-like, sparse matrix}", ['array-like', 'sparse matrix']),
("""string, [None, 'binary', 'micro', 'macro', 'samples', 'weighted']""",
['None', "'binary'", "'micro'", "'macro'", "'samples'",
"'weighted'"]),
("""string, [None, 'binary' (default), 'micro', 'macro', 'samples', 'weighted']""",
['None', "'binary'", "'micro'", "'macro'", "'samples'",
"'weighted'"]),
("{'raw_values', 'uniform_average'} or array-like of shape",
["{'raw_values', 'uniform_average'}", "array-like of shape"]),
('array-like or BallTree', ['array-like', 'BallTree']),
('array-like, BallTree', ['array-like', 'BallTree']),
('array-like, BallTree or Tata', ['array-like', 'BallTree', 'Tata']),
('array-like, BallTree, or Tata', ['array-like', 'BallTree',
'Tata']),
('array-like or BallTree, or Tata',
['array-like', 'BallTree', 'Tata']),
("'linear' | 'poly' | 'rbf' | 'sigmoid' | 'cosine' | 'precomputed'", [
"'linear'", "'poly'", "'rbf'", "'sigmoid'", "'cosine'",
"'precomputed'"
]), ("string, either '-', '+', or ' '", ["'-'", "'+'", "' '"])
]
success = True
for test, expected in tests:
elts = parse_enum(test)
if elts != expected:
log.error(
f"error in enum test: '{test}' -> {elts} (expected {expected})"
)
success = False
return success
def partition(li, pred):
sat = []
unsat = []
for x in li:
if pred(x):
sat.append(x)
else:
unsat.append(x)
return sat, unsat
# this does not cover all cases it seems, where different instances of
# the same class with the same params are considered different?
# using elt.__class__ is appealing but would break StringValue for instance.
def remove_duplicates(elts):
return list(set(elts))
# got = set()
# ret = []
# for elt in elts:
# if elt not in got:
# ret.append(elt)
# got.add(elt)
# return ret
def simplify_arr(enum):
arr, not_arr = partition(enum.elements,
lambda x: isinstance(x, (Arr, Ndarray)))
sparse, not_arr_not_sparse = partition(
not_arr, lambda x: isinstance(x, (SparseMatrix, CsrMatrix, CscMatrix)))
if arr and sparse:
return type(enum)([Arr()] + not_arr_not_sparse)
else:
return enum
def simplify_arr_or_float(enum):
if len(enum.elements) != 2:
return enum
e0, e1 = enum.elements
if ((isinstance(e0, Float) and isinstance(e1, Arr))
or (isinstance(e1, Float) and isinstance(e0, Arr))):
return type(enum)([Arr()])
return enum
def simplify_enum(enum):
# log.debug(f"simplifying enum %s", enum)
# flatten (once should be enough?)
elts = []
for elt in enum.elements:
if isinstance(elt, Enum):
elts += elt.elements
else:
elts.append(elt)
enum = type(enum)(elts)
false_true, not_false_true = partition(
enum.elements, lambda x: isinstance(x, (FalseValue, TrueValue)))
# assert len(false_true) in [0, 2], enum
# There are (probably legitimate) cases where False is accepted
# but not True!
if len(false_true) == 2:
bool, not_bool = partition(not_false_true,
lambda x: isinstance(x, Bool))
enum = Enum([Bool()] + not_bool)
none, not_none = partition(enum.elements,
lambda x: isinstance(x, NoneValue))
assert len(none) <= 1, enum
if none:
if not_none:
inside = simplify_enum(type(enum)(not_none))
return Optional(inside)
else:
return none
# enum = EnumOption(not_none)
# enum = type(enum)(not_none + [NoneValue()])
# log.debug("enum 2: %s", enum)
# Enum(String, StringValue, StringValue) should just be
# Enum(StringValue, StringValue) since that is (probably) a
# misparsing of "str, 'l1' or 'l2'"
is_string_value, is_not_string_value = partition(
enum.elements, lambda x: isinstance(x, StringValue))
if is_string_value and len(is_not_string_value) == 1 and isinstance(
is_not_string_value[0], String):
enum = type(enum)(is_string_value)
# Int|TupleOfInts -> TupleOfInts
if len(enum.elements) == 2:
a, b = enum.elements
if isinstance(a, Int) and isinstance(b, TupleOfInts):
return b
if isinstance(b, Int) and isinstance(a, TupleOfInts):
return a
# log.debug("enum 3: %s", enum)
enum = type(enum)(remove_duplicates(enum.elements))
# Arr | SparseMatrix == Arr
enum = simplify_arr(enum)
# An Arr.t is able to represent a single Numpy scalar also.
enum = simplify_arr_or_float(enum)
# log.debug("enum 4: %s", enum)
# There is no point having more than one Py.Object tag in an enum.
is_obj, is_not_obj = partition(
enum.elements, lambda x: isinstance(x, (PyObject, UnknownType)))
if len(is_obj) > 1:
enum = type(enum)(is_not_obj + [PyObject()]) # XXX
# A one-element enum is just the element itself.
if len(enum.elements) == 1:
# log.debug("simplified enum: just one element: %s", enum.elements[0])
return enum.elements[0]
# log.debug("simplified enum: %s", enum)
return enum
def remove_ranges(t):
# print(f"remove_ranges: {t}")
t = re.sub(r'(float|int)\s*(in\s*(range\s*)?)\s*[()[\]][^\]]+[()[\]]',
r'\1', t)
t = re.sub(r'(float|int)\s*,?\s*(greater|smaller)\s+than\s+\d+(\.\d+)?',
r'\1', t)
t = re.sub(r'(float|int)\s*,?\s*(<=|<|>=|>)\s*\d+(\.\d+)?', r'\1', t)
t = re.sub(r'(float|int)\s*,?\s*\(\s*(<=|<|>=|>)\s*\d+(\.\d+)?\s*\)',
r'\1', t)
t = t.strip(" \n\t,.;")
return t
def indent(s, w=4):
has_nl = False
if s and s[-1] == "\n":
has_nl = True
s = s[:-1]
ret = re.sub(r'^', ' ' * w, s, flags=re.MULTILINE)
if has_nl:
ret += "\n"
return ret
def maybe_to_string(x):
try:
return str(x)
except: # noqa: E722
return '<str failed>'
def append(container, ctor, *args, **kwargs):
try:
elt = ctor(*args, **kwargs)
except NoSignature as e:
f = e.args[0]
doc = f.__doc__
if doc is None or not doc.startswith('Not implemented'):
qn = qualname(f)
if qn != '<no name>':
log.warning(f"no signature for {qn} ({f})")
return
except AlreadySeen:
return
except (OutsideScope, NoDoc, Deprecated) as e:
if ctor in [Module, Class]:
log.warning(
f"append: caught error building {ctor.__name__} {maybe_to_string(args[0])}: {type(e).__name__}"
)
return
if hasattr(elt, 'ml_name'):
while elt.ml_name in [getattr(x, 'ml_name', None) for x in container]:
new_name = elt.ml_name + "'"
log.warning(
f"renaming {elt.ml_name} to {new_name} to prevent name clash")
elt.ml_name = new_name
container.append(elt)
# XXX TODO make this immutable if possible
class Name(abc.ABC):
def __init__(self, python_name, parent, ml_name=None):
assert parent is None or isinstance(
parent, Name), f"parent is not a Name: {type(parent)}"
self._parent = parent
self._python_name = python_name
if ml_name is None:
self._ml_name = self.fix_ml(self.python_name())
else:
self._ml_name = ml_name
self._path = list(reversed(self._compute_rev_path()))
# assert not self.full_ml_name().startswith('Numpy'), self
@property
def parent(self):
return self._parent
@abc.abstractmethod
def fix_ml(self, n):
pass
def python_name(self):
return self._python_name
def ml_name(self):
return self.fix_ml(self._ml_name)
def set_ml_name(self, n):
self._ml_name = n
def ml_name_opt(self):
ret = self.ml_name()
if ret.endswith('_'):
return ret + 'opt'
else:
return ret + '_opt'
def _compute_rev_path(self):
ret = []
x = self
while x is not None:
ret.append(x)
x = x._parent
return ret
def full_python_name(self):
return '.'.join(x.python_name() for x in self._path)
def full_ml_name(self):
return '.'.join(x.ml_name() for x in self._path)
def adjust(self):
self._ml_name += "'"
def apply_overrides(self, overrides):
ml = overrides.ml_name(self.full_python_name())
if ml is not None:
self._ml_name = ml
def __str__(self):
return repr(self)
def __repr__(self):
return f'{self.__class__.__name__}({self.full_ml_name()}, {self.full_python_name()})'
class UpperName(Name):
def fix_ml(self, n):
return make_module_name(n)
class LowerName(Name):
def fix_ml(self, n):
return mlid(n)
# def in_ml_namespace(ns, name):
# super_ml_name = name.ml_name
# def ml_name():
# return ns + '.' + super_ml_name()
# name.ml_name = ml_name
# return name
class Package:
def __init__(self, pkg, overrides, registry, builtin):
self.pkg = pkg
self.name = UpperName(self.pkg.__name__, parent=None)
self.modules = self._list_modules(pkg, overrides, registry, builtin)
self.registry = registry
self.overrides = overrides
def _list_module_raw(self, pkg):
ret = []
for mod in pkgutil.iter_modules(pkg.__path__):
name = mod.name
if name.startswith('_') or name.endswith('_'):
continue
name = UpperName(name, self.name)
module = importlib.import_module(name.full_python_name())
ret.append((name, module))
return ret
def _list_modules(self, pkg, overrides, registry, builtin):
ret = []
modules = self._list_module_raw(pkg)
# scipy has the toplevel modules (scipy.stats,
# scipy.linalg...) appearing as submodules in various places,
# this causes terrible duplication.
for module in modules:
overrides.add_blacklisted_submodule(module)
for name, module in modules:
append(ret,
Module,
name,
module,
overrides=overrides,
registry=registry,
builtin=builtin)
return ret
def __str__(self):
return repr(self)
def __repr__(self):
ret = f"Package({self.name.full_python_name()})[\n"
for mod in self.modules:
ret += indent(repr(mod) + ",") + "\n"
ret += "]"
return ret
def output_dir(self, path):
# path / self.pkg.__name__
return path
def write(self, path):
dire = self.output_dir(path)
log.info(f"writing package {self.name.full_python_name()} to {dire}")
dire.mkdir(parents=True, exist_ok=True)
for mod in self.modules:
mod.write(dire)
def write_doc(self, path):
dire = self.output_dir(path)
dire.mkdir(parents=True, exist_ok=True)
for mod in self.modules:
mod.write_doc(dire)
def write_examples(self, path):
dire = self.output_dir(path)
dire.mkdir(parents=True, exist_ok=True)
for mod in self.modules:
mod.write_examples(dire)
class OutsideScope(Exception):
pass
class AlreadySeen(Exception):
pass
class NoDoc(Exception):
pass
class Deprecated(Exception):
pass
def write_generated_header(f):
f.write(
"(* This file was generated by lib/skdoc.py, do not edit by hand. *)\n"
)
def fix_naming(elements):
names = set()
for elt in elements:
if hasattr(elt, 'name'):
while elt.name.ml_name() in names:
elt.name.adjust()
names.add(elt.name.ml_name())
class Module:
def __init__(self, name, module, overrides, registry, builtin, inside=[]):
assert isinstance(name, UpperName)
self.name = name
# Scipy has the modules exported everywhere. Trying to keep only one copy is hard.
# Reverting to preventing cycles.
if module in inside:
raise AlreadySeen(module)
inside = [module] + inside
# We pass both the exposed Python name and the builtin module
# full name through the scope check.
if not overrides.check_scope(name.full_python_name(), module):
raise OutsideScope(name)
if not overrides.check_scope(module.__name__, module):
raise OutsideScope(name)
if '.externals.' in name.full_python_name():
raise OutsideScope(name)
registry.add(name, module)
self.module = module
self.elements = self._list_elements(module, overrides, registry,
builtin, inside)
self.registry = registry
self.overrides = overrides
def _list_modules_raw(self, module, overrides):
modules = []
for name in dir(module):
if name.startswith('_') or name.endswith('_'):
continue
if name in ['test', 'scipy']: # for scipy
continue
if (name in [
'core',
'lib',
'compat',
'ctypeslib',
'matrixlib',
'scimath',
'testing',
'records',
] and self.name.full_python_name().startswith('numpy')):
continue
item = getattr(module, name)
if overrides.is_blacklisted_submodule(item):
# print(f"DD blacklisting submodule {qualname}: {item}")
continue
if inspect.ismodule(item):
modules.append((UpperName(name, self.name), item))
return modules
def _list_elements(self, module, overrides, registry, builtin, inside):
# List modules without creating their wrappers, and blacklist
# them so that if we find them deeper we don't rewrap them.
modules_raw = self._list_modules_raw(module, overrides)
for mod in modules_raw:
overrides.add_blacklisted_submodule(mod)
modules = []
# Create classes and functions first so that we find those at
# the root before the copies in the modules below.
classes = []
functions = []
for name in dir(module):
# qualname = f"{self.full_python_name}.{name}"
if name.startswith('_') or name.endswith('_'):
continue
if name in ['test', 'scipy']: # for scipy
continue
# emit this one separately, not inside sklearn.metrics
# if name == "csr_matrix":
# continue
item = getattr(module, name)
# parent_name = self.full_ml_name
# print(f"DD wrapping {parent_name}.{name}: {module}")
if inspect.isclass(item):
append(classes, Class, UpperName(name, self.name), item,
overrides, registry, builtin)
elif callable(item):
append(functions, Function, LowerName(name, self.name), item,
overrides, registry, builtin)
# We list modules, and blacklist them so that we don't wrap
# them again deeper in the hierarchy; then we wrap them.
for mod_name, mod in modules_raw:
append(modules, Module, mod_name, mod, overrides, registry,
builtin, inside)
elements = classes + modules + functions
fix_naming(elements)
return elements
def __str__(self):
return repr(self)
def __repr__(self):
ret = f"Module({self.name.full_python_name()})[\n"
for elt in self.elements:
ret += indent(repr(elt) + ",") + "\n"
ret += "]"
return ret
def has_callables(self):
for elt in self.elements:
if isinstance(elt, (Function, Class)):
return True
return False
def write_header(self, f):
# if self.has_callables():
f.write("let () = Wrap_utils.init ();;\n")
# Importing the exposed name does not always work, we must
# import the name of the actual underlying module. See for
# example numpy.char.
import_name = self.module.__name__
f.write(f'let __wrap_namespace = Py.import "{import_name}"\n\n')
# else:
# f.write(
# "(* this module has no callables, skipping init and ns *)\n")
def write(self, path):
# print(f"DD writing module {self.python_name}")
# module_path = f"{module_path}.{self.name.ml_name}"