This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
sageinspect.py
2200 lines (1791 loc) · 73.7 KB
/
sageinspect.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
r"""
Inspect Python, Sage, and Cython objects
This module extends parts of Python's inspect module to Cython objects.
AUTHORS:
- originally taken from Fernando Perez's IPython
- William Stein (extensive modifications)
- Nick Alexander (extensions)
- Nick Alexander (testing)
- Simon King (some extension for Cython, generalisation of SageArgSpecVisitor)
EXAMPLES::
sage: from sage.misc.sageinspect import *
Test introspection of modules defined in Python and Cython files:
Cython modules::
sage: sage_getfile(sage.rings.rational)
'.../rational.pyx'
sage: sage_getdoc(sage.rings.rational).lstrip()
'Rational Numbers...'
sage: sage_getsource(sage.rings.rational)[5:]
'Rational Numbers...'
Python modules::
sage: sage_getfile(sage.misc.sageinspect)
'.../sageinspect.py'
sage: print sage_getdoc(sage.misc.sageinspect).lstrip()[:40]
Inspect Python, Sage, and Cython objects
sage: sage_getsource(sage.misc.sageinspect).lstrip()[5:-1]
'Inspect Python, Sage, and Cython objects...'
Test introspection of classes defined in Python and Cython files:
Cython classes::
sage: sage_getfile(sage.rings.rational.Rational)
'.../rational.pyx'
sage: sage_getdoc(sage.rings.rational.Rational).lstrip()
'A rational number...'
sage: sage_getsource(sage.rings.rational.Rational)
'cdef class Rational...'
Python classes::
sage: sage_getfile(BlockFinder)
'.../sage/misc/sageinspect.py'
sage: sage_getdoc(BlockFinder).lstrip()
'Provide a tokeneater() method to detect the...'
sage: sage_getsource(BlockFinder)
'class BlockFinder:...'
Test introspection of functions defined in Python and Cython files:
Cython functions::
sage: sage_getdef(sage.rings.rational.make_rational, obj_name='mr')
'mr(s)'
sage: sage_getfile(sage.rings.rational.make_rational)
'.../rational.pyx'
sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
'Make a rational number ...'
sage: sage_getsource(sage.rings.rational.make_rational)[4:]
'make_rational(s):...'
Python functions::
sage: sage_getdef(sage.misc.sageinspect.sage_getfile, obj_name='sage_getfile')
'sage_getfile(obj)'
sage: sage_getfile(sage.misc.sageinspect.sage_getfile)
'.../sageinspect.py'
sage: sage_getdoc(sage.misc.sageinspect.sage_getfile).lstrip()
'Get the full file name associated to "obj" as a string...'
sage: sage_getsource(sage.misc.sageinspect.sage_getfile)[4:]
'sage_getfile(obj):...'
Unfortunately, there is no argspec extractable from builtins::
sage: sage_getdef(''.find, 'find')
'find( [noargspec] )'
sage: sage_getdef(str.find, 'find')
'find( [noargspec] )'
By :trac:`9976` and :trac:`14017`, introspection also works for interactively
defined Cython code, and with rather tricky argument lines::
sage: cython('def foo(unsigned int x=1, a=\')"\', b={not (2+1==3):\'bar\'}, *args, **kwds): return')
sage: print sage_getsource(foo)
def foo(unsigned int x=1, a=')"', b={not (2+1==3):'bar'}, *args, **kwds): return
sage: sage_getargspec(foo)
ArgSpec(args=['x', 'a', 'b'], varargs='args', keywords='kwds', defaults=(1, ')"', {False: 'bar'}))
"""
import ast
import inspect
import functools
import os
import tokenize
import types
EMBEDDED_MODE = False
from sage.env import SAGE_SRC
def isclassinstance(obj):
r"""
Checks if argument is instance of non built-in class
INPUT: ``obj`` - object
EXAMPLES::
sage: from sage.misc.sageinspect import isclassinstance
sage: isclassinstance(int)
False
sage: isclassinstance(FreeModule)
True
sage: class myclass: pass
sage: isclassinstance(myclass)
False
sage: class mymetaclass(type): pass
sage: class myclass2:
... __metaclass__ = mymetaclass
sage: isclassinstance(myclass2)
False
"""
return (not inspect.isclass(obj) and \
hasattr(obj, '__class__') and \
hasattr(obj.__class__, '__module__') and \
obj.__class__.__module__ not in ('__builtin__', 'exceptions'))
import re
# Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
# "\ " protects a space in re.VERBOSE mode.
__embedded_position_re = re.compile(r'''
^ # anchor to the beginning of the line
File:\ (?P<FILENAME>.*?) # match File: then filename
\ \(starting\ at\ line\ (?P<LINENO>\d+)\) # match line number
\n? # if there is a newline, eat it
(?P<ORIGINAL>.*) # the original docstring is the end
\Z # anchor to the end of the string
''', re.MULTILINE | re.DOTALL | re.VERBOSE)
# Parse Python identifiers
__identifier_re = re.compile(r"^[^\d\W]\w*")
def _extract_embedded_position(docstring):
r"""
If docstring has a Cython embedded position, return a tuple
(original_docstring, filename, line). If not, return None.
INPUT: ``docstring`` (string)
EXAMPLES::
sage: from sage.misc.sageinspect import _extract_embedded_position
sage: import inspect
sage: _extract_embedded_position(inspect.getdoc(var))[1][-21:]
'sage/calculus/var.pyx'
The following has been fixed in :trac:`13916`::
sage: cython('''cpdef test_funct(x,y): return''')
sage: print open(_extract_embedded_position(inspect.getdoc(test_funct))[1]).read()
<BLANKLINE>
include "interrupt.pxi" # ctrl-c interrupt block support
include "stdsage.pxi"
<BLANKLINE>
include "cdefs.pxi"
cpdef test_funct(x,y): return
AUTHORS:
- William Stein
- Extensions by Nick Alexander
- Extension for interactive Cython code by Simon King
"""
try:
res = __embedded_position_re.search(docstring)
except TypeError:
return None
if res is None:
return None
raw_filename = res.group('FILENAME')
filename = os.path.join(SAGE_SRC, raw_filename)
if not os.path.isfile(filename):
from sage.misc.misc import SPYX_TMP
filename = os.path.join(SPYX_TMP, '_'.join(raw_filename.split('_')[:-1]), raw_filename)
lineno = int(res.group('LINENO'))
original = res.group('ORIGINAL')
return (original, filename, lineno)
class BlockFinder:
"""
Provide a tokeneater() method to detect the end of a code block.
This is the Python library's :class:`inspect.BlockFinder` modified
to recognize Cython definitions.
"""
def __init__(self):
self.indent = 0
self.islambda = False
self.started = False
self.passline = False
self.last = 1
def tokeneater(self, type, token, srow_scol, erow_ecol, line):
srow, scol = srow_scol
erow, ecol = erow_ecol
if not self.started:
# look for the first "(cp)def", "class" or "lambda"
if token in ("def", "cpdef", "class", "lambda"):
if token == "lambda":
self.islambda = True
self.started = True
self.passline = True # skip to the end of the line
elif type == tokenize.NEWLINE:
self.passline = False # stop skipping when a NEWLINE is seen
self.last = srow
if self.islambda: # lambdas always end at the first NEWLINE
raise inspect.EndOfBlock
elif self.passline:
pass
elif type == tokenize.INDENT:
self.indent = self.indent + 1
self.passline = True
elif type == tokenize.DEDENT:
self.indent = self.indent - 1
# the end of matching indent/dedent pairs end a block
# (note that this only works for "def"/"class" blocks,
# not e.g. for "if: else:" or "try: finally:" blocks)
if self.indent <= 0:
raise inspect.EndOfBlock
elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
# any other token on the same indentation level end the previous
# block as well, except the pseudo-tokens COMMENT and NL.
raise inspect.EndOfBlock
def _getblock(lines):
"""
Extract the block of code at the top of the given list of lines.
This is the Python library's :func:`inspect.getblock`, except that
it uses an instance of our custom :class:`BlockFinder`.
"""
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (inspect.EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
def _extract_source(lines, lineno):
r"""
Given a list of lines or a multiline string and a starting lineno,
_extract_source returns [source_lines]. [source_lines] is the smallest
indentation block starting at lineno.
INPUT:
- ``lines`` - string or list of strings
- ``lineno`` - positive integer
EXAMPLES::
sage: from sage.misc.sageinspect import _extract_source
sage: s2 = "#hello\n\n class f():\n pass\n\n#goodbye"
sage: _extract_source(s2, 3)
[' class f():\n', ' pass\n']
"""
if lineno < 1:
raise ValueError("Line numbering starts at 1! (tried to extract line {})".format(lineno))
lineno -= 1
if isinstance(lines, str):
lines = lines.splitlines(True) # true keeps the '\n'
if len(lines) > 0:
# Fixes an issue with getblock
lines[-1] += '\n'
return _getblock(lines[lineno:])
class SageArgSpecVisitor(ast.NodeVisitor):
"""
A simple visitor class that walks an abstract-syntax tree (AST)
for a Python function's argspec. It returns the contents of nodes
representing the basic Python types: None, booleans, numbers,
strings, lists, tuples, and dictionaries. We use this class in
:func:`_sage_getargspec_from_ast` to extract an argspec from a
function's or method's source code.
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: visitor.visit(ast.parse('[1,2,3]').body[0].value)
[1, 2, 3]
sage: visitor.visit(ast.parse("{'a':('e',2,[None,({False:True},'pi')]), 37.0:'temp'}").body[0].value)
{37.0: 'temp', 'a': ('e', 2, [None, ({False: True}, 'pi')])}
sage: v = ast.parse("jc = ['veni', 'vidi', 'vici']").body[0]; v
<_ast.Assign object at ...>
sage: [x for x in dir(v) if not x.startswith('__')]
['_attributes', '_fields', 'col_offset', 'lineno', 'targets', 'value']
sage: visitor.visit(v.targets[0])
'jc'
sage: visitor.visit(v.value)
['veni', 'vidi', 'vici']
"""
def visit_Name(self, node):
"""
Visit a Python AST :class:`ast.Name` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- None, True, False, or the ``node``'s name as a string.
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Name(ast.parse(x).body[0].value)
sage: [vis(n) for n in ['True', 'False', 'None', 'foo', 'bar']]
[True, False, None, 'foo', 'bar']
sage: [type(vis(n)) for n in ['True', 'False', 'None', 'foo', 'bar']]
[<type 'bool'>, <type 'bool'>, <type 'NoneType'>, <type 'str'>, <type 'str'>]
"""
what = node.id
if what == 'None':
return None
elif what == 'True':
return True
elif what == 'False':
return False
return node.id
def visit_Num(self, node):
"""
Visit a Python AST :class:`ast.Num` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- the number the ``node`` represents
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Num(ast.parse(x).body[0].value)
sage: [vis(n) for n in ['123', '0.0', str(-pi.n())]]
[123, 0.0, -3.14159265358979]
"""
return node.n
def visit_Str(self, node):
r"""
Visit a Python AST :class:`ast.Str` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- the string the ``node`` represents
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Str(ast.parse(x).body[0].value)
sage: [vis(s) for s in ['"abstract"', "u'syntax'", '''r"tr\ee"''']]
['abstract', u'syntax', 'tr\\ee']
"""
return node.s
def visit_List(self, node):
"""
Visit a Python AST :class:`ast.List` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- the list the ``node`` represents
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_List(ast.parse(x).body[0].value)
sage: [vis(l) for l in ['[]', "['s', 't', 'u']", '[[e], [], [pi]]']]
[[], ['s', 't', 'u'], [['e'], [], ['pi']]]
"""
t = []
for n in node.elts:
t.append(self.visit(n))
return t
def visit_Tuple(self, node):
"""
Visit a Python AST :class:`ast.Tuple` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- the tuple the ``node`` represents
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Tuple(ast.parse(x).body[0].value)
sage: [vis(t) for t in ['()', '(x,y)', '("Au", "Al", "Cu")']]
[(), ('x', 'y'), ('Au', 'Al', 'Cu')]
"""
t = []
for n in node.elts:
t.append(self.visit(n))
return tuple(t)
def visit_Dict(self, node):
"""
Visit a Python AST :class:`ast.Dict` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- the dictionary the ``node`` represents
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Dict(ast.parse(x).body[0].value)
sage: [vis(d) for d in ['{}', "{1:one, 'two':2, other:bother}"]]
[{}, {1: 'one', 'other': 'bother', 'two': 2}]
"""
d = {}
for k, v in zip(node.keys, node.values):
d[self.visit(k)] = self.visit(v)
return d
def visit_BoolOp(self, node):
"""
Visit a Python AST :class:`ast.BoolOp` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- The result that ``node`` represents
AUTHOR:
- Simon King
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit(ast.parse(x).body[0].value)
sage: [vis(d) for d in ['True and 1', 'False or 3 or None', '3 and 4']] #indirect doctest
[1, 3, 4]
"""
op = node.op.__class__.__name__
L = list(node.values)
out = self.visit(L.pop(0))
if op == 'And':
while L:
next = self.visit(L.pop(0))
out = out and next
return out
if op == 'Or':
while L:
next = self.visit(L.pop(0))
out = out or next
return out
def visit_Compare(self, node):
"""
Visit a Python AST :class:`ast.Compare` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- The result that ``node`` represents
AUTHOR:
- Simon King
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_Compare(ast.parse(x).body[0].value)
sage: [vis(d) for d in ['1<2==2!=3', '1==1>2', '1<2>1', '1<3<2<4']]
[True, False, True, False]
"""
left = self.visit(node.left)
ops = list(node.ops)
comparators = list(node.comparators) # the things to be compared with.
while ops:
op = ops.pop(0).__class__.__name__
right = self.visit(comparators.pop(0))
if op=='Lt':
if not left<right:
return False
elif op=='LtE':
if not left<=right:
return False
elif op=='Gt':
if not left>right:
return False
elif op=='GtE':
if not left>=right:
return False
elif op=='Eq':
if not left==right:
return False
elif op=='NotEq':
if not left!=right:
return False
left = right
return True
def visit_BinOp(self, node):
"""
Visit a Python AST :class:`ast.BinOp` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- The result that ``node`` represents
AUTHOR:
- Simon King
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit(ast.parse(x).body[0].value)
sage: [vis(d) for d in ['(3+(2*4))', '7|8', '5^3', '7/3', '7//3', '3<<4']] #indirect doctest
[11, 15, 6, 2, 2, 48]
"""
op = node.op.__class__.__name__
if op == 'Add':
return self.visit(node.left)+self.visit(node.right)
if op == 'Mult':
return self.visit(node.left)*self.visit(node.right)
if op == 'BitAnd':
return self.visit(node.left)&self.visit(node.right)
if op == 'BitOr':
return self.visit(node.left) | self.visit(node.right)
if op == 'BitXor':
return self.visit(node.left) ^ self.visit(node.right)
if op == 'Div':
return self.visit(node.left) / self.visit(node.right)
if op == 'Eq':
return self.visit(node.left) == self.visit(node.right)
if op == 'FloorDiv':
return self.visit(node.left) // self.visit(node.right)
if op == 'NotEq':
return self.visit(node.left) != self.visit(node.right)
if op == 'NotIn':
return self.visit(node.left) not in self.visit(node.right)
if op == 'Pow':
return self.visit(node.left) ** self.visit(node.right)
if op == 'RShift':
return self.visit(node.left) >> self.visit(node.right)
if op == 'LShift':
return self.visit(node.left) << self.visit(node.right)
if op == 'Sub':
return self.visit(node.left) - self.visit(node.right)
if op == 'Gt':
return self.visit(node.left) > self.visit(node.right)
if op == 'GtE':
return self.visit(node.left) >= self.visit(node.right)
if op == 'In':
return self.visit(node.left) in self.visit(node.right)
if op == 'Is':
return self.visit(node.left) is self.visit(node.right)
if op == 'IsNot':
return self.visit(node.left) is not self.visit(node.right)
if op == 'Lt':
return self.visit(node.left) < self.visit(node.right)
if op == 'LtE':
return self.visit(node.left) <= self.visit(node.right)
if op == 'Mod':
return self.visit(node.left) % self.visit(node.right)
def visit_UnaryOp(self, node):
"""
Visit a Python AST :class:`ast.BinOp` node.
INPUT:
- ``node`` - the node instance to visit
OUTPUT:
- The result that ``node`` represents
AUTHOR:
- Simon King
EXAMPLES::
sage: import ast, sage.misc.sageinspect as sms
sage: visitor = sms.SageArgSpecVisitor()
sage: vis = lambda x: visitor.visit_UnaryOp(ast.parse(x).body[0].value)
sage: [vis(d) for d in ['+(3*2)', '-(3*2)']]
[6, -6]
"""
op = node.op.__class__.__name__
if op == 'Not':
return not self.visit(node.operand)
if op == 'UAdd':
return self.visit(node.operand)
if op == 'USub':
return -self.visit(node.operand)
def _grep_first_pair_of_parentheses(s):
"""
Return the first matching pair of parentheses in a code string.
INPUT:
A string
OUTPUT:
A substring of the input, namely the part between the first
(outmost) matching pair of parentheses (including the
parentheses).
Parentheses between single or double quotation marks do not
count. If no matching pair of parentheses can be found, a
``SyntaxError`` is raised.
EXAMPLE::
sage: from sage.misc.sageinspect import _grep_first_pair_of_parentheses
sage: code = 'def foo(a="\'):", b=4):\n return'
sage: _grep_first_pair_of_parentheses(code)
'(a="\'):", b=4)'
sage: code = 'def foo(a="%s):", \'b=4):\n return'%("'")
sage: _grep_first_pair_of_parentheses(code)
Traceback (most recent call last):
...
SyntaxError: The given string does not contain balanced parentheses
"""
out = []
single_quote = False
double_quote = False
escaped = False
level = 0
for c in s:
if level>0:
out.append(c)
if c=='(' and not single_quote and not double_quote and not escaped:
level += 1
elif c=='"' and not single_quote and not escaped:
double_quote = not double_quote
elif c=="'" and not double_quote and not escaped:
single_quote = not single_quote
elif c==')' and not single_quote and not double_quote and not escaped:
if level == 1:
return '('+''.join(out)
level -= 1
elif c=="\\" and (single_quote or double_quote):
escaped = not escaped
else:
escaped = False
raise SyntaxError("The given string does not contain balanced parentheses")
def _split_syntactical_unit(s):
"""
Split off a sub-expression from the start of a given string.
INPUT:
- ``s``, a string
OUTPUT:
A pair ``unit, s2``, such that ``unit`` is the string representation of a
string (single or double quoted) or of a sub-expression surrounded by
brackets (round, square or curly brackets), or of an identifier, or a
single character, if none of the above is available. The given string ``s``
is obtained by appending some whitespace followed by ``s2`` to ``unit``.
Blank space between the units is removed.
EXAMPLES::
sage: from sage.misc.sageinspect import _split_syntactical_unit
sage: s = "(Hel) lo_1=[)\"!\" ] '''? {world} '''?"
sage: while s:
... u, s = _split_syntactical_unit(s)
... print u
...
(Hel)
lo_1
=
[)"!"]
'''? {world} '''
?
If the string ends before the unit is completed (mispatching parentheses
or missing quotation mark), then a syntax error is raised::
sage: s = "'''({SAGE}]"
sage: _split_syntactical_unit(s)
Traceback (most recent call last):
...
SyntaxError: EOF while scanning string literal
sage: s = "({SAGE}]"
sage: _split_syntactical_unit(s)
Traceback (most recent call last):
...
SyntaxError: Syntactical group starting with '(' did not end with ')'
Numbers are not recognised:::
sage: _split_syntactical_unit('123')
('1', '23')
TEST:
The following was fixed in :trac:`16309`::
sage: _split_syntactical_unit('()): pass')
('()', '): pass')
"""
s = s.strip()
if not s:
return s
# Split a given string at the next unescaped quotation mark
def split_string(s, quot):
escaped = False
l = len(quot)
for i in range(len(s)):
if s[i] == '\\':
escaped = not escaped
continue
if not escaped and s[i:i+l] == quot:
return s[:i], s[i+l:]
escaped = False
raise SyntaxError("EOF while scanning string literal")
# 1. s is a triple-quoted string
if s.startswith('"""'):
a,b = split_string(s[3:], '"""')
return '"""'+a+'"""', b.strip()
if s.startswith('r"""'):
a,b = split_string(s[4:], '"""')
return 'r"""'+a+'"""', b.strip()
if s.startswith("'''"):
a,b = split_string(s[3:], "'''")
return "'''"+a+"'''", b.strip()
if s.startswith("r'''"):
a,b = split_string(s[4:], "'''")
return "r'''"+a+"'''", b.strip()
# 2. s is a single-quoted string
if s.startswith('"'):
a,b = split_string(s[1:], '"')
return '"'+a+'"', b.strip()
if s.startswith("'"):
a,b = split_string(s[1:], "'")
return "'"+a+"'", b.strip()
if s.startswith('r"'):
a,b = split_string(s[2:], '"')
return 'r"'+a+'"', b.strip()
if s.startswith("r'"):
a,b = split_string(s[2:], "'")
return "r'"+a+"'", b.strip()
# 3. s is not a string
start = s[0]
out = [start]
if start == '(':
stop = ')'
elif start == '[':
stop = ']'
elif start == '{':
stop = '}'
elif start == '\\':
# note that python would raise a syntax error
# if the line contains anything but whitespace
# after the backslash. But we assume here that
# the input is syntactically correct.
return _split_syntactical_unit(s[1:])
elif start == '#':
linebreak = s.index(os.linesep)
if linebreak == -1:
return '',''
return '', s[linebreak:].strip()
else:
M = __identifier_re.search(s)
if M is None:
return s[0], s[1:].strip()
return M.group(), s[M.end():].strip()
s = s[1:]
while s:
tmp_group, s = _split_syntactical_unit(s)
out.append(tmp_group)
s = s.strip()
if tmp_group==stop:
return ''.join(out), s
elif s.startswith(stop):
out.append(stop)
return ''.join(out), s[1:].strip()
raise SyntaxError("Syntactical group starting with %s did not end with %s"%(repr(start),repr(stop)))
def _sage_getargspec_from_ast(source):
r"""
Return an argspec for a Python function or method by compiling its
source to an abstract-syntax tree (AST) and walking its ``args``
subtrees with :class:`SageArgSpecVisitor`. We use this in
:func:`_sage_getargspec_cython`.
INPUT:
- ``source`` - a string; the function's (or method's) source code
definition. The function's body is ignored.
OUTPUT:
- an instance of :obj:`inspect.ArgSpec`, i.e., a named tuple
EXAMPLES::
sage: import inspect, sage.misc.sageinspect as sms
sage: from_ast = sms._sage_getargspec_from_ast
sage: s = "def f(a, b=2, c={'a': [4, 5.5, False]}, d=(None, True)):\n return"
sage: from_ast(s)
ArgSpec(args=['a', 'b', 'c', 'd'], varargs=None, keywords=None, defaults=(2, {'a': [4, 5.5, False]}, (None, True)))
sage: context = {}
sage: exec compile(s, '<string>', 'single') in context
sage: inspect.getargspec(context['f'])
ArgSpec(args=['a', 'b', 'c', 'd'], varargs=None, keywords=None, defaults=(2, {'a': [4, 5.5, False]}, (None, True)))
sage: from_ast(s) == inspect.getargspec(context['f'])
True
sage: set(from_ast(sms.sage_getsource(x)) == inspect.getargspec(x) for x in [factor, identity_matrix, Graph.__init__])
{True}
"""
ast_args = ast.parse(source.lstrip()).body[0].args
visitor = SageArgSpecVisitor()
args = [visitor.visit(a) for a in ast_args.args]
defaults = [visitor.visit(d) for d in ast_args.defaults]
return inspect.ArgSpec(args, ast_args.vararg, ast_args.kwarg,
tuple(defaults) if defaults else None)
def _sage_getargspec_cython(source):
r"""
inspect.getargspec from source code. That is, get the names and
default values of a function's arguments.
INPUT:
- ``source`` - a string; the function's (or method's) source code
definition. The function's body is ignored. The definition may
contain type definitions for the function arguments.
OUTPUT:
- an instance of :obj:`inspect.ArgSpec`, i.e., a named tuple
EXAMPLES::
sage: from sage.misc.sageinspect import _sage_getargspec_cython as sgc
sage: sgc("cpdef double abc(self, Element x=None, Parent base=0):")
ArgSpec(args=['self', 'x', 'base'], varargs=None, keywords=None, defaults=(None, 0))
sage: sgc("def __init__(self, x=None, unsigned int base=0):")
ArgSpec(args=['self', 'x', 'base'], varargs=None, keywords=None, defaults=(None, 0))
sage: sgc('def o(p, r={}, *q, **s) except? -1:')
ArgSpec(args=['p', 'r'], varargs='q', keywords='s', defaults=({},))
sage: sgc('cpdef how(r=(None, "u:doing?")):')
ArgSpec(args=['r'], varargs=None, keywords=None, defaults=((None, 'u:doing?'),))
sage: sgc('def _(x="):"):')
ArgSpec(args=['x'], varargs=None, keywords=None, defaults=('):',))
sage: sgc('def f(z = {(1, 2, 3): True}):\n return z')
ArgSpec(args=['z'], varargs=None, keywords=None, defaults=({(1, 2, 3): True},))
sage: sgc('def f(double x, z = {(1, 2, 3): True}):\n return z')
ArgSpec(args=['x', 'z'], varargs=None, keywords=None, defaults=({(1, 2, 3): True},))
sage: sgc('def f(*args): pass')
ArgSpec(args=[], varargs='args', keywords=None, defaults=None)
sage: sgc('def f(**args): pass')
ArgSpec(args=[], varargs=None, keywords='args', defaults=None)
Some malformed input is detected::
sage: sgc('def f(x,y')
Traceback (most recent call last):
...
SyntaxError: Unexpected EOF while parsing argument list
sage: sgc('def f(*x = 5, z = {(1,2,3): True}): pass')
Traceback (most recent call last):
...
SyntaxError: invalid syntax
sage: sgc('def f(int *x = 5, z = {(1,2,3): True}): pass')
Traceback (most recent call last):
...
SyntaxError: Pointer types not allowed in def or cpdef functions
sage: sgc('def f(x = , z = {(1,2,3): True}): pass')
Traceback (most recent call last):
...
SyntaxError: Definition of a default argument expected
sage: sgc('def f(int x = 5, , z = {(1,2,3): True}): pass')
Traceback (most recent call last):
...
SyntaxError: invalid syntax
TESTS:
Some input that is malformed in Python but wellformed in Cython
is correctly parsed::
sage: def dummy_python(self,*args,x=1): pass
Traceback (most recent call last):
...
SyntaxError: invalid syntax
sage: cython("def dummy_cython(self,*args,x=1): pass")
sage: sgc("def dummy_cython(self,*args,x=1): pass")
ArgSpec(args=['self', 'x'], varargs='args', keywords=None, defaults=(1,))
In some examples above, a syntax error was raised when a type
definition contains a pointer. An exception is made for ``char*``,
since C strings are acceptable input in public Cython functions::
sage: sgc('def f(char *x = "a string", z = {(1,2,3): True}): pass')
ArgSpec(args=['x', 'z'], varargs=None, keywords=None, defaults=('a string', {(1, 2, 3): True}))
AUTHORS:
- Nick Alexander: original version
- Simon King (02-2013): recognise varargs and default values in
cython code, and return an ``ArgSpec``.