FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpython/Tools/clinic/clinic.py at pythoncapi · pythoncapi/cpython · GitHub
cpython/Tools/clinic/clinic.py at pythoncapi · pythoncapi/cpython · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
pythoncapi
/
cpython
Public
forked from
python/cpython
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Tools
/
clinic
/
clinic.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
executable file
·
4472 lines (3731 loc) · 152 KB
Breadcrumbs
cpython
/
Tools
/
clinic
/
clinic.py
Copy path
File metadata and controls
executable file
·
4472 lines (3731 loc) · 152 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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 python3
#
# Argument Clinic
# Copyright 2012-2013 by Larry Hastings.
# Licensed to the PSF under a contributor agreement.
#
import
abc
import
ast
import
collections
import
contextlib
import
copy
import
cpp
import
functools
import
hashlib
import
inspect
import
io
import
itertools
import
os
import
pprint
import
re
import
shlex
import
string
import
sys
import
tempfile
import
textwrap
import
traceback
import
types
from
types
import
*
NoneType
=
type
(
None
)
# TODO:
#
# soon:
#
# * allow mixing any two of {positional-only, positional-or-keyword,
# keyword-only}
# * dict constructor uses positional-only and keyword-only
# * max and min use positional only with an optional group
# and keyword-only
#
version
=
'1'
_empty
=
inspect
.
_empty
_void
=
inspect
.
_void
NoneType
=
type
(
None
)
class
Unspecified
:
def
__repr__
(
self
):
return
'<Unspecified>'
unspecified
=
Unspecified
()
class
Null
:
def
__repr__
(
self
):
return
'<Null>'
NULL
=
Null
()
class
Unknown
:
def
__repr__
(
self
):
return
'<Unknown>'
unknown
=
Unknown
()
sig_end_marker
=
'--'
_text_accumulator_nt
=
collections
.
namedtuple
(
"_text_accumulator"
,
"text append output"
)
def
_text_accumulator
():
text
=
[]
def
output
():
s
=
''
.
join
(
text
)
text
.
clear
()
return
s
return
_text_accumulator_nt
(
text
,
text
.
append
,
output
)
text_accumulator_nt
=
collections
.
namedtuple
(
"text_accumulator"
,
"text append"
)
def
text_accumulator
():
"""
Creates a simple text accumulator / joiner.
Returns a pair of callables:
append, output
"append" appends a string to the accumulator.
"output" returns the contents of the accumulator
joined together (''.join(accumulator)) and
empties the accumulator.
"""
text
,
append
,
output
=
_text_accumulator
()
return
text_accumulator_nt
(
append
,
output
)
def
warn_or_fail
(
fail
=
False
,
*
args
,
filename
=
None
,
line_number
=
None
):
joined
=
" "
.
join
([
str
(
a
)
for
a
in
args
])
add
,
output
=
text_accumulator
()
if
fail
:
add
(
"Error"
)
else
:
add
(
"Warning"
)
if
clinic
:
if
filename
is
None
:
filename
=
clinic
.
filename
if
getattr
(
clinic
,
'block_parser'
,
None
)
and
(
line_number
is
None
):
line_number
=
clinic
.
block_parser
.
line_number
if
filename
is
not
None
:
add
(
' in file "'
+
filename
+
'"'
)
if
line_number
is
not
None
:
add
(
" on line "
+
str
(
line_number
))
add
(
':
\n
'
)
add
(
joined
)
print
(
output
())
if
fail
:
sys
.
exit
(
-
1
)
def
warn
(
*
args
,
filename
=
None
,
line_number
=
None
):
return
warn_or_fail
(
False
,
*
args
,
filename
=
filename
,
line_number
=
line_number
)
def
fail
(
*
args
,
filename
=
None
,
line_number
=
None
):
return
warn_or_fail
(
True
,
*
args
,
filename
=
filename
,
line_number
=
line_number
)
def
quoted_for_c_string
(
s
):
for
old
,
new
in
(
(
'
\\
'
,
'
\\
\\
'
),
# must be first!
(
'"'
,
'
\\
"'
),
(
"'"
,
"
\\
'"
),
):
s
=
s
.
replace
(
old
,
new
)
return
s
def
c_repr
(
s
):
return
'"'
+
s
+
'"'
is_legal_c_identifier
=
re
.
compile
(
'^[A-Za-z_][A-Za-z0-9_]*$'
).
match
def
is_legal_py_identifier
(
s
):
return
all
(
is_legal_c_identifier
(
field
)
for
field
in
s
.
split
(
'.'
))
# identifiers that are okay in Python but aren't a good idea in C.
# so if they're used Argument Clinic will add "_value" to the end
# of the name in C.
c_keywords
=
set
(
"""
asm auto break case char const continue default do double
else enum extern float for goto if inline int long
register return short signed sizeof static struct switch
typedef typeof union unsigned void volatile while
"""
.
strip
().
split
())
def
ensure_legal_c_identifier
(
s
):
# for now, just complain if what we're given isn't legal
if
not
is_legal_c_identifier
(
s
):
fail
(
"Illegal C identifier: {}"
.
format
(
s
))
# but if we picked a C keyword, pick something else
if
s
in
c_keywords
:
return
s
+
"_value"
return
s
def
rstrip_lines
(
s
):
text
,
add
,
output
=
_text_accumulator
()
for
line
in
s
.
split
(
'
\n
'
):
add
(
line
.
rstrip
())
add
(
'
\n
'
)
text
.
pop
()
return
output
()
def
format_escape
(
s
):
# double up curly-braces, this string will be used
# as part of a format_map() template later
s
=
s
.
replace
(
'{'
,
'{{'
)
s
=
s
.
replace
(
'}'
,
'}}'
)
return
s
def
linear_format
(
s
,
**
kwargs
):
"""
Perform str.format-like substitution, except:
* The strings substituted must be on lines by
themselves. (This line is the "source line".)
* If the substitution text is empty, the source line
is removed in the output.
* If the field is not recognized, the original line
is passed unmodified through to the output.
* If the substitution text is not empty:
* Each line of the substituted text is indented
by the indent of the source line.
* A newline will be added to the end.
"""
add
,
output
=
text_accumulator
()
for
line
in
s
.
split
(
'
\n
'
):
indent
,
curly
,
trailing
=
line
.
partition
(
'{'
)
if
not
curly
:
add
(
line
)
add
(
'
\n
'
)
continue
name
,
curly
,
trailing
=
trailing
.
partition
(
'}'
)
if
not
curly
or
name
not
in
kwargs
:
add
(
line
)
add
(
'
\n
'
)
continue
if
trailing
:
fail
(
"Text found after {"
+
name
+
"} block marker! It must be on a line by itself."
)
if
indent
.
strip
():
fail
(
"Non-whitespace characters found before {"
+
name
+
"} block marker! It must be on a line by itself."
)
value
=
kwargs
[
name
]
if
not
value
:
continue
value
=
textwrap
.
indent
(
rstrip_lines
(
value
),
indent
)
add
(
value
)
add
(
'
\n
'
)
return
output
()[:
-
1
]
def
indent_all_lines
(
s
,
prefix
):
"""
Returns 's', with 'prefix' prepended to all lines.
If the last line is empty, prefix is not prepended
to it. (If s is blank, returns s unchanged.)
(textwrap.indent only adds to non-blank lines.)
"""
split
=
s
.
split
(
'
\n
'
)
last
=
split
.
pop
()
final
=
[]
for
line
in
split
:
final
.
append
(
prefix
)
final
.
append
(
line
)
final
.
append
(
'
\n
'
)
if
last
:
final
.
append
(
prefix
)
final
.
append
(
last
)
return
''
.
join
(
final
)
def
suffix_all_lines
(
s
,
suffix
):
"""
Returns 's', with 'suffix' appended to all lines.
If the last line is empty, suffix is not appended
to it. (If s is blank, returns s unchanged.)
"""
split
=
s
.
split
(
'
\n
'
)
last
=
split
.
pop
()
final
=
[]
for
line
in
split
:
final
.
append
(
line
)
final
.
append
(
suffix
)
final
.
append
(
'
\n
'
)
if
last
:
final
.
append
(
last
)
final
.
append
(
suffix
)
return
''
.
join
(
final
)
def
version_splitter
(
s
):
"""Splits a version string into a tuple of integers.
The following ASCII characters are allowed, and employ
the following conversions:
a -> -3
b -> -2
c -> -1
(This permits Python-style version strings such as "1.4b3".)
"""
version
=
[]
accumulator
=
[]
def
flush
():
if
not
accumulator
:
raise
ValueError
(
'Unsupported version string: '
+
repr
(
s
))
version
.
append
(
int
(
''
.
join
(
accumulator
)))
accumulator
.
clear
()
for
c
in
s
:
if
c
.
isdigit
():
accumulator
.
append
(
c
)
elif
c
==
'.'
:
flush
()
elif
c
in
'abc'
:
flush
()
version
.
append
(
'abc'
.
index
(
c
)
-
3
)
else
:
raise
ValueError
(
'Illegal character '
+
repr
(
c
)
+
' in version string '
+
repr
(
s
))
flush
()
return
tuple
(
version
)
def
version_comparitor
(
version1
,
version2
):
iterator
=
itertools
.
zip_longest
(
version_splitter
(
version1
),
version_splitter
(
version2
),
fillvalue
=
0
)
for
i
, (
a
,
b
)
in
enumerate
(
iterator
):
if
a
<
b
:
return
-
1
if
a
>
b
:
return
1
return
0
class
CRenderData
:
def
__init__
(
self
):
# The C statements to declare variables.
# Should be full lines with \n eol characters.
self
.
declarations
=
[]
# The C statements required to initialize the variables before the parse call.
# Should be full lines with \n eol characters.
self
.
initializers
=
[]
# The C statements needed to dynamically modify the values
# parsed by the parse call, before calling the impl.
self
.
modifications
=
[]
# The entries for the "keywords" array for PyArg_ParseTuple.
# Should be individual strings representing the names.
self
.
keywords
=
[]
# The "format units" for PyArg_ParseTuple.
# Should be individual strings that will get
self
.
format_units
=
[]
# The varargs arguments for PyArg_ParseTuple.
self
.
parse_arguments
=
[]
# The parameter declarations for the impl function.
self
.
impl_parameters
=
[]
# The arguments to the impl function at the time it's called.
self
.
impl_arguments
=
[]
# For return converters: the name of the variable that
# should receive the value returned by the impl.
self
.
return_value
=
"return_value"
# For return converters: the code to convert the return
# value from the parse function. This is also where
# you should check the _return_value for errors, and
# "goto exit" if there are any.
self
.
return_conversion
=
[]
# The C statements required to clean up after the impl call.
self
.
cleanup
=
[]
class
FormatCounterFormatter
(
string
.
Formatter
):
"""
This counts how many instances of each formatter
"replacement string" appear in the format string.
e.g. after evaluating "string {a}, {b}, {c}, {a}"
the counts dict would now look like
{'a': 2, 'b': 1, 'c': 1}
"""
def
__init__
(
self
):
self
.
counts
=
collections
.
Counter
()
def
get_value
(
self
,
key
,
args
,
kwargs
):
self
.
counts
[
key
]
+=
1
return
''
class
Language
(
metaclass
=
abc
.
ABCMeta
):
start_line
=
""
body_prefix
=
""
stop_line
=
""
checksum_line
=
""
def
__init__
(
self
,
filename
):
pass
@
abc
.
abstractmethod
def
render
(
self
,
clinic
,
signatures
):
pass
def
parse_line
(
self
,
line
):
pass
def
validate
(
self
):
def
assert_only_one
(
attr
,
*
additional_fields
):
"""
Ensures that the string found at getattr(self, attr)
contains exactly one formatter replacement string for
each valid field. The list of valid fields is
['dsl_name'] extended by additional_fields.
e.g.
self.fmt = "{dsl_name} {a} {b}"
# this passes
self.assert_only_one('fmt', 'a', 'b')
# this fails, the format string has a {b} in it
self.assert_only_one('fmt', 'a')
# this fails, the format string doesn't have a {c} in it
self.assert_only_one('fmt', 'a', 'b', 'c')
# this fails, the format string has two {a}s in it,
# it must contain exactly one
self.fmt2 = '{dsl_name} {a} {a}'
self.assert_only_one('fmt2', 'a')
"""
fields
=
[
'dsl_name'
]
fields
.
extend
(
additional_fields
)
line
=
getattr
(
self
,
attr
)
fcf
=
FormatCounterFormatter
()
fcf
.
format
(
line
)
def
local_fail
(
should_be_there_but_isnt
):
if
should_be_there_but_isnt
:
fail
(
"{} {} must contain {{{}}} exactly once!"
.
format
(
self
.
__class__
.
__name__
,
attr
,
name
))
else
:
fail
(
"{} {} must not contain {{{}}}!"
.
format
(
self
.
__class__
.
__name__
,
attr
,
name
))
for
name
,
count
in
fcf
.
counts
.
items
():
if
name
in
fields
:
if
count
>
1
:
local_fail
(
True
)
else
:
local_fail
(
False
)
for
name
in
fields
:
if
fcf
.
counts
.
get
(
name
)
!=
1
:
local_fail
(
True
)
assert_only_one
(
'start_line'
)
assert_only_one
(
'stop_line'
)
field
=
"arguments"
if
"{arguments}"
in
self
.
checksum_line
else
"checksum"
assert_only_one
(
'checksum_line'
,
field
)
class
PythonLanguage
(
Language
):
language
=
'Python'
start_line
=
"#/*[{dsl_name} input]"
body_prefix
=
"#"
stop_line
=
"#[{dsl_name} start generated code]*/"
checksum_line
=
"#/*[{dsl_name} end generated code: {arguments}]*/"
def
permute_left_option_groups
(
l
):
"""
Given [1, 2, 3], should yield:
()
(3,)
(2, 3)
(1, 2, 3)
"""
yield
tuple
()
accumulator
=
[]
for
group
in
reversed
(
l
):
accumulator
=
list
(
group
)
+
accumulator
yield
tuple
(
accumulator
)
def
permute_right_option_groups
(
l
):
"""
Given [1, 2, 3], should yield:
()
(1,)
(1, 2)
(1, 2, 3)
"""
yield
tuple
()
accumulator
=
[]
for
group
in
l
:
accumulator
.
extend
(
group
)
yield
tuple
(
accumulator
)
def
permute_optional_groups
(
left
,
required
,
right
):
"""
Generator function that computes the set of acceptable
argument lists for the provided iterables of
argument groups. (Actually it generates a tuple of tuples.)
Algorithm: prefer left options over right options.
If required is empty, left must also be empty.
"""
required
=
tuple
(
required
)
result
=
[]
if
not
required
:
assert
not
left
accumulator
=
[]
counts
=
set
()
for
r
in
permute_right_option_groups
(
right
):
for
l
in
permute_left_option_groups
(
left
):
t
=
l
+
required
+
r
if
len
(
t
)
in
counts
:
continue
counts
.
add
(
len
(
t
))
accumulator
.
append
(
t
)
accumulator
.
sort
(
key
=
len
)
return
tuple
(
accumulator
)
def
strip_leading_and_trailing_blank_lines
(
s
):
lines
=
s
.
rstrip
().
split
(
'
\n
'
)
while
lines
:
line
=
lines
[
0
]
if
line
.
strip
():
break
del
lines
[
0
]
return
'
\n
'
.
join
(
lines
)
@
functools
.
lru_cache
()
def
normalize_snippet
(
s
,
*
,
indent
=
0
):
"""
Reformats s:
* removes leading and trailing blank lines
* ensures that it does not end with a newline
* dedents so the first nonwhite character on any line is at column "indent"
"""
s
=
strip_leading_and_trailing_blank_lines
(
s
)
s
=
textwrap
.
dedent
(
s
)
if
indent
:
s
=
textwrap
.
indent
(
s
,
' '
*
indent
)
return
s
def
wrap_declarations
(
text
,
length
=
78
):
"""
A simple-minded text wrapper for C function declarations.
It views a declaration line as looking like this:
xxxxxxxx(xxxxxxxxx,xxxxxxxxx)
If called with length=30, it would wrap that line into
xxxxxxxx(xxxxxxxxx,
xxxxxxxxx)
(If the declaration has zero or one parameters, this
function won't wrap it.)
If this doesn't work properly, it's probably better to
start from scratch with a more sophisticated algorithm,
rather than try and improve/debug this dumb little function.
"""
lines
=
[]
for
line
in
text
.
split
(
'
\n
'
):
prefix
,
_
,
after_l_paren
=
line
.
partition
(
'('
)
if
not
after_l_paren
:
lines
.
append
(
line
)
continue
parameters
,
_
,
after_r_paren
=
after_l_paren
.
partition
(
')'
)
if
not
_
:
lines
.
append
(
line
)
continue
if
','
not
in
parameters
:
lines
.
append
(
line
)
continue
parameters
=
[
x
.
strip
()
+
", "
for
x
in
parameters
.
split
(
','
)]
prefix
+=
"("
if
len
(
prefix
)
<
length
:
spaces
=
" "
*
len
(
prefix
)
else
:
spaces
=
" "
*
4
while
parameters
:
line
=
prefix
first
=
True
while
parameters
:
if
(
not
first
and
(
len
(
line
)
+
len
(
parameters
[
0
])
>
length
)):
break
line
+=
parameters
.
pop
(
0
)
first
=
False
if
not
parameters
:
line
=
line
.
rstrip
(
", "
)
+
")"
+
after_r_paren
lines
.
append
(
line
.
rstrip
())
prefix
=
spaces
return
"
\n
"
.
join
(
lines
)
class
CLanguage
(
Language
):
body_prefix
=
"#"
language
=
'C'
start_line
=
"/*[{dsl_name} input]"
body_prefix
=
""
stop_line
=
"[{dsl_name} start generated code]*/"
checksum_line
=
"/*[{dsl_name} end generated code: {arguments}]*/"
def
__init__
(
self
,
filename
):
super
().
__init__
(
filename
)
self
.
cpp
=
cpp
.
Monitor
(
filename
)
self
.
cpp
.
fail
=
fail
def
parse_line
(
self
,
line
):
self
.
cpp
.
writeline
(
line
)
def
render
(
self
,
clinic
,
signatures
):
function
=
None
for
o
in
signatures
:
if
isinstance
(
o
,
Function
):
if
function
:
fail
(
"You may specify at most one function per block.
\n
Found a block containing at least two:
\n
\t
"
+
repr
(
function
)
+
" and "
+
repr
(
o
))
function
=
o
return
self
.
render_function
(
clinic
,
function
)
def
docstring_for_c_string
(
self
,
f
):
text
,
add
,
output
=
_text_accumulator
()
# turn docstring into a properly quoted C string
for
line
in
f
.
docstring
.
split
(
'
\n
'
):
add
(
'"'
)
add
(
quoted_for_c_string
(
line
))
add
(
'
\\
n"
\n
'
)
if
text
[
-
2
]
==
sig_end_marker
:
# If we only have a signature, add the blank line that the
# __text_signature__ getter expects to be there.
add
(
'"
\\
n"'
)
else
:
text
.
pop
()
add
(
'"'
)
return
''
.
join
(
text
)
def
output_templates
(
self
,
f
):
parameters
=
list
(
f
.
parameters
.
values
())
assert
parameters
assert
isinstance
(
parameters
[
0
].
converter
,
self_converter
)
del
parameters
[
0
]
converters
=
[
p
.
converter
for
p
in
parameters
]
has_option_groups
=
parameters
and
(
parameters
[
0
].
group
or
parameters
[
-
1
].
group
)
default_return_converter
=
(
not
f
.
return_converter
or
f
.
return_converter
.
type
==
'PyObject *'
)
positional
=
parameters
and
parameters
[
-
1
].
is_positional_only
()
all_boring_objects
=
False
# yes, this will be false if there are 0 parameters, it's fine
first_optional
=
len
(
parameters
)
for
i
,
p
in
enumerate
(
parameters
):
c
=
p
.
converter
if
type
(
c
)
!=
object_converter
:
break
if
c
.
format_unit
!=
'O'
:
break
if
p
.
default
is
not
unspecified
:
first_optional
=
min
(
first_optional
,
i
)
else
:
all_boring_objects
=
True
new_or_init
=
f
.
kind
in
(
METHOD_NEW
,
METHOD_INIT
)
meth_o
=
(
len
(
parameters
)
==
1
and
parameters
[
0
].
is_positional_only
()
and
not
converters
[
0
].
is_optional
()
and
not
new_or_init
)
# we have to set these things before we're done:
#
# docstring_prototype
# docstring_definition
# impl_prototype
# methoddef_define
# parser_prototype
# parser_definition
# impl_definition
# cpp_if
# cpp_endif
# methoddef_ifndef
return_value_declaration
=
"PyObject *return_value = NULL;"
methoddef_define
=
normalize_snippet
(
"""
#define {methoddef_name}
\\
{{"{name}", (PyCFunction){c_basename}, {methoddef_flags}, {c_basename}__doc__}},
"""
)
if
new_or_init
and
not
f
.
docstring
:
docstring_prototype
=
docstring_definition
=
''
else
:
docstring_prototype
=
normalize_snippet
(
"""
PyDoc_VAR({c_basename}__doc__);
"""
)
docstring_definition
=
normalize_snippet
(
"""
PyDoc_STRVAR({c_basename}__doc__,
{docstring});
"""
)
impl_definition
=
normalize_snippet
(
"""
static {impl_return_type}
{c_basename}_impl({impl_parameters})
"""
)
impl_prototype
=
parser_prototype
=
parser_definition
=
None
parser_prototype_keyword
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *args, PyObject *kwargs)
"""
)
parser_prototype_varargs
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *args)
"""
)
parser_prototype_fastcall
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *const *args, Py_ssize_t nargs)
"""
)
parser_prototype_fastcall_keywords
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
"""
)
# parser_body_fields remembers the fields passed in to the
# previous call to parser_body. this is used for an awful hack.
parser_body_fields
=
()
def
parser_body
(
prototype
,
*
fields
):
nonlocal
parser_body_fields
add
,
output
=
text_accumulator
()
add
(
prototype
)
parser_body_fields
=
fields
fields
=
list
(
fields
)
fields
.
insert
(
0
,
normalize_snippet
(
"""
{{
{return_value_declaration}
{declarations}
{initializers}
"""
)
+
"
\n
"
)
# just imagine--your code is here in the middle
fields
.
append
(
normalize_snippet
(
"""
{modifications}
{return_value} = {c_basename}_impl({impl_arguments});
{return_conversion}
{exit_label}
{cleanup}
return return_value;
}}
"""
))
for
field
in
fields
:
add
(
'
\n
'
)
add
(
field
)
return
output
()
def
insert_keywords
(
s
):
return
linear_format
(
s
,
declarations
=
'static const char * const _keywords[] = {{{keywords}, NULL}};
\n
'
'static _PyArg_Parser _parser = {{"{format_units}:{name}", _keywords, 0}};
\n
'
'{declarations}'
)
if
not
parameters
:
# no parameters, METH_NOARGS
flags
=
"METH_NOARGS"
parser_prototype
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *Py_UNUSED(ignored))
"""
)
parser_definition
=
parser_prototype
if
default_return_converter
:
parser_definition
=
parser_prototype
+
'
\n
'
+
normalize_snippet
(
"""
{{
return {c_basename}_impl({impl_arguments});
}}
"""
)
else
:
parser_definition
=
parser_body
(
parser_prototype
)
elif
meth_o
:
flags
=
"METH_O"
if
(
isinstance
(
converters
[
0
],
object_converter
)
and
converters
[
0
].
format_unit
==
'O'
):
meth_o_prototype
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({impl_parameters})
"""
)
if
default_return_converter
:
# maps perfectly to METH_O, doesn't need a return converter.
# so we skip making a parse function
# and call directly into the impl function.
impl_prototype
=
parser_prototype
=
parser_definition
=
''
impl_definition
=
meth_o_prototype
else
:
# SLIGHT HACK
# use impl_parameters for the parser here!
parser_prototype
=
meth_o_prototype
parser_definition
=
parser_body
(
parser_prototype
)
else
:
argname
=
'arg'
if
parameters
[
0
].
name
==
argname
:
argname
+=
'_'
parser_prototype
=
normalize_snippet
(
"""
static PyObject *
{c_basename}({self_type}{self_name}, PyObject *%s)
"""
%
argname
)
parser_definition
=
parser_body
(
parser_prototype
,
normalize_snippet
(
"""
if (!PyArg_Parse(%s, "{format_units}:{name}", {parse_arguments})) {{
goto exit;
}}
"""
%
argname
,
indent
=
4
))
elif
has_option_groups
:
# positional parameters with option groups
# (we have to generate lots of PyArg_ParseTuple calls
# in a big switch statement)
flags
=
"METH_VARARGS"
parser_prototype
=
parser_prototype_varargs
parser_definition
=
parser_body
(
parser_prototype
,
' {option_group_parsing}'
)
elif
positional
and
all_boring_objects
:
# positional-only, but no option groups,
# and nothing but normal objects:
# PyArg_UnpackTuple!
if
not
new_or_init
:
flags
=
"METH_FASTCALL"
parser_prototype
=
parser_prototype_fastcall
parser_definition
=
parser_body
(
parser_prototype
,
normalize_snippet
(
"""
if (!_PyArg_UnpackStack(args, nargs, "{name}",
{unpack_min}, {unpack_max},
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
))
else
:
flags
=
"METH_VARARGS"
parser_prototype
=
parser_prototype_varargs
parser_definition
=
parser_body
(
parser_prototype
,
normalize_snippet
(
"""
if (!PyArg_UnpackTuple(args, "{name}",
{unpack_min}, {unpack_max},
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
))
elif
positional
:
if
not
new_or_init
:
# positional-only, but no option groups
# we only need one call to _PyArg_ParseStack
flags
=
"METH_FASTCALL"
parser_prototype
=
parser_prototype_fastcall
parser_definition
=
parser_body
(
parser_prototype
,
normalize_snippet
(
"""
if (!_PyArg_ParseStack(args, nargs, "{format_units}:{name}",
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
))
else
:
# positional-only, but no option groups
# we only need one call to PyArg_ParseTuple
flags
=
"METH_VARARGS"
parser_prototype
=
parser_prototype_varargs
parser_definition
=
parser_body
(
parser_prototype
,
normalize_snippet
(
"""
if (!PyArg_ParseTuple(args, "{format_units}:{name}",
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
))
elif
not
new_or_init
:
flags
=
"METH_FASTCALL|METH_KEYWORDS"
parser_prototype
=
parser_prototype_fastcall_keywords
body
=
normalize_snippet
(
"""
if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser,
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
)
parser_definition
=
parser_body
(
parser_prototype
,
body
)
parser_definition
=
insert_keywords
(
parser_definition
)
else
:
# positional-or-keyword arguments
flags
=
"METH_VARARGS|METH_KEYWORDS"
parser_prototype
=
parser_prototype_keyword
body
=
normalize_snippet
(
"""
if (!_PyArg_ParseTupleAndKeywordsFast(args, kwargs, &_parser,
{parse_arguments})) {{
goto exit;
}}
"""
,
indent
=
4
)
parser_definition
=
parser_body
(
parser_prototype
,
body
)
parser_definition
=
insert_keywords
(
parser_definition
)
if
new_or_init
:
methoddef_define
=
''
if
f
.
kind
==
METHOD_NEW
:
parser_prototype
=
parser_prototype_keyword
else
:
return_value_declaration
=
"int return_value = -1;"
parser_prototype
=
normalize_snippet
(
"""
static int
{c_basename}({self_type}{self_name}, PyObject *args, PyObject *kwargs)
"""
)
fields
=
list
(
parser_body_fields
)
parses_positional
=
'METH_NOARGS'
not
in
flags
parses_keywords
=
'METH_KEYWORDS'
in
flags
if
parses_keywords
:
assert
parses_positional
if
not
parses_keywords
:
fields
.
insert
(
0
,
normalize_snippet
(
"""
if ({self_type_check}!_PyArg_NoKeywords("{name}", kwargs)) {{
goto exit;
}}
"""
,
indent
=
4
))
if
not
parses_positional
:
fields
.
insert
(
0
,
normalize_snippet
(
"""
if ({self_type_check}!_PyArg_NoPositional("{name}", args)) {{
goto exit;
}}
"""
,
indent
=
4
))
parser_definition
=
parser_body
(
parser_prototype
,
*
fields
)
if
parses_keywords
:
parser_definition
=
insert_keywords
(
parser_definition
)
if
f
.
methoddef_flags
:
flags
+=
'|'
+
f
.
methoddef_flags
methoddef_define
=
methoddef_define
.
replace
(
'{methoddef_flags}'
,
flags
)
methoddef_ifndef
=
''
conditional
=
self
.
cpp
.
condition
()
if
not
conditional
:
cpp_if
=
cpp_endif
=
''
else
:
cpp_if
=
"#if "
+
conditional
cpp_endif
=
"#endif /* "
+
conditional
+
" */"
if
methoddef_define
and
f
.
full_name
not
in
clinic
.
ifndef_symbols
:
clinic
.
ifndef_symbols
.
add
(
f
.
full_name
)
methoddef_ifndef
=
normalize_snippet
(
"""
#ifndef {methoddef_name}
#define {methoddef_name}
#endif /* !defined({methoddef_name}) */
"""
)
# add ';' to the end of parser_prototype and impl_prototype
# (they mustn't be None, but they could be an empty string.)
assert
parser_prototype
is
not
None
if
parser_prototype
:
assert
not
parser_prototype
.
endswith
(
';'
)
parser_prototype
+=
';'
if
impl_prototype
is
None
:
impl_prototype
=
impl_definition
if
impl_prototype
:
impl_prototype
+=
";"
parser_definition
=
parser_definition
.
replace
(
"{return_value_declaration}"
,
return_value_declaration
)
d
=
{
"docstring_prototype"
:
docstring_prototype
,
"docstring_definition"
:
docstring_definition
,
"impl_prototype"
:
impl_prototype
,
"methoddef_define"
:
methoddef_define
,
"parser_prototype"
:
parser_prototype
,
"parser_definition"
:
parser_definition
,
"impl_definition"
:
impl_definition
,
"cpp_if"
:
cpp_if
,
"cpp_endif"
:
cpp_endif
,
"methoddef_ifndef"
:
methoddef_ifndef
,
}
# make sure we didn't forget to assign something,
# and wrap each non-empty value in \n's
d2
=
{}
for
name
,
value
in
d
.
items
():
assert
value
is
not
None
,
"got a None value for template "
+
repr
(
name
)
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL