Source

python-clinic / clinic.py

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
#!/usr/bin/env python3
#
# Argument Clinic (clinic.py)
#
# DSL for argument preprocessing
#
# Copyright 2012 by Larry Hastings.
# Licensed to the PSF under a Contributor Agreement.
#


import atexit
import builtins
import collections
import hashlib
import os
import re
import shlex
import sys
import tempfile
import textwrap


tempfiles = []
def remove_tempfiles():
	for filename in tempfiles:
		try:
			os.unlink(filename)
		except BaseException:
			pass

atexit.register(remove_tempfiles)



NULL = object()

class Unspecified:
	def __repr__(self):
		return '<Unspecified>'

unspecified = Unspecified()



# This "type_map" thing is just for the Clinic prototype.
# It maps Clinic type declarations to PyArg_Parse format units.
# I expect to replace it before this ever ships in a Python release,
# hopefully something based on a new more granular
# argument parsing library.
#
# Syntax of type_map:
#   <C type> <options> = <format unit>
# Declarations are one per line.
#
# <C type> is first and can contain spaces.  (In truth, anything the
#	parser doesn't recognize is appended to the C type.)
#
# options are in the middle, and can be any / all / none of the following:
#
#		bitwise
#       converter
#		encoding
#		immutable
#		length
#		nullable
#		zeroes
#		( one or more python types, between parentheses, separated by whitespace )
#
# with the exception of stuff inside parentheses, all these options
# are boolean flags and default to false.
# ("converter" and "encoding" just indicate whether or not the user
#  specified a converter / encoding.  for the purposes of the type map
#  we don't care what the converter or encoding actually is.)
#
# The line ends with
#		= <format unit>
#   which is the format unit used with PyArg_ParseTuple
#
# Note: for convenience's sakes, "const char *" by default
#   maps to strings, not bytes.
#
#
# Unimplemented so far:
#   w*

type_map = """
PyObject * = O
void * converter = O&

Py_UNICODE * = u
Py_UNICODE * length = u#
Py_UNICODE * nullable = Z
Py_UNICODE * length nullable = Z#

const char * = s
const char * nullable = z

char * encoding = es
char * encoding (str bytes bytearray) = et
char * encoding length = es#
char * encoding length (str bytes bytearray) = et#

const char * (bytes) = y
Py_buffer (bytes bytearray buffer) = y*
const char * length (bytes buffer) = y#

Py_buffer zeroes (str bytes bytearray buffer) = s*
Py_buffer nullable zeroes (str bytes bytearray buffer) = z*
const char * length zeroes (str bytes buffer) = s#
const char * length nullable zeroes (str bytes buffer) = z#

PyUnicodeObject * = U

PyBytesObject * = S

PyBytesArrayObject * = Y

unsigned char = b
unsigned char bitwise = B
short = h
short int = h
unsigned short bitwise = H
unsigned short int bitwise = H
int = i
unsigned int bitwise = I
long = l
long int = l
unsigned long bitwise = k
unsigned long int bitwise = k
PY_LONG_LONG = L
unsigned PY_LONG_LONG bitwise = K
Py_ssize_t = n
char (bytes bytearray) = c
char = C
int (bool) = p

float = f
double = d
Py_complex * = D

"""

format_unit_map = {}

options = collections.OrderedDict()
for key in "bitwise converter encoding immutable length nullable zeroes".split():
	options[key] = False

def get_format_unit(c_type,
	bitwise=False, converter=False, encoding=False, immutable=False,
	length=False, nullable=False, zeroes=False, py_types=()):
	if converter:
		c_type = "void *"
	keys = (c_type, bitwise, converter, encoding, immutable, length, nullable, zeroes, py_types)
	keystr = "c_type, bitwise, converter, encoding, immutable, length, nullable, zeroes, py_types".split()
	d = format_unit_map
	for key, name in zip(keys, keystr):
		before_d = d
		d = d.get(key, None)
		if not d:
			break
	return d

def set_format_unit(format_unit, c_type,
	bitwise=False, converter=False, encoding=False, immutable=False,
	length=False, nullable=False, zeroes=False, py_types=()):
	if converter:
		c_type = "void *"
	keys, last_key = (c_type, bitwise, converter, encoding, immutable, length, nullable, zeroes), py_types
	d = format_unit_map
	for key in keys:
		d = d.setdefault(key, {})
	d[last_key] = format_unit

# conversion:

for line in type_map.split("\n"):
	line = line.strip()
	if not line:
		continue
	fields, _, format_unit = line.rpartition('=')
	format_unit = format_unit.strip()
	bitwise = converter = encoding = immutable = False
	length = nullable = zeroes = False
	c_type = []
	types = []
	in_types = False
	line_options = options.copy()
	for field in fields.split():
		if not field:
			continue

		if in_types:
			if ')' in field:
				field, _, should_be_empty = field.partition(')')
				assert not should_be_empty, "don't abuse the lame type_map parser"
				in_types = False
			if field:
				types.append(field)
			continue
		if field in line_options:
			if line_options[field]:
				sys.exit("Error: Can't specify " + field + " twice.\n\t" + line)
			line_options[field] = True
			continue
		if field.startswith('('):
			assert not in_types
			field = field[1:].strip()
			if ')' in field:
				field, _, should_be_empty = field.partition(')')
				assert not should_be_empty, "don't abuse the lame type_map parser"
			else:
				in_types = True
			if field:
				types.append(field)
			continue
		c_type.append(field)
	assert c_type, "no c_type specified for type_map initializer line"
	c_type = " ".join(c_type)
	types = tuple(sorted(types))
	splat = tuple(line_options.values()) + (types,)
	set_format_unit(format_unit, c_type, *splat)


value_to_cvalue_map = {
	NULL: "NULL",
	None: "Py_None",
}

def value_to_cvalue(v):
	return value_to_cvalue_map.get(v, v)



class CVariable:
	"""
	An individual C variable required by an Argument.
	(Some Arguments require more than one.)
	"""
	name = ""
	c_type = ""
	default = unspecified

	def __init__(self, c_type, name, default=unspecified):
		self.c_type = c_type
		self.name = name
		self.default = default

	def impl_argument(self):
		"""
		The C code to pass this argument in to the impl function.
		Returns an iterable.
		"""
		assert self.name and self.c_type
		return (self.name,)

	def keyword(self):
		"""
		The value to add to the 'keywords' array for PyArg_ParseTupleAndKeywords.
		Returns an iterable.
		"""
		assert self.name and self.c_type
		return ('"' + self.name + '"',)

	def parse_argument(self):
		"""
		The C code to pass this argument in to PyArg_ParseTuple &c.
		Returns an iterable.
		"""
		assert self.name and self.c_type
		return ("&" + self.name,)

	def prototype(self):
		"""
		The C code to define this variable as an argument to a function.
		Returns an iterable.
		"""
		assert self.name and self.c_type
		prototype = [self.c_type]
		if not self.c_type.endswith('*'):
			prototype.append(" ")
		prototype.append(self.name)
		return ("".join(prototype),)

	def declaration(self):
		"""
		The C statement to declare this variable.
		Returns an iterable.
		"""
		declaration = list(self.prototype())
		if self.default != unspecified:
			declaration.append(" = {}".format(self.default))
		declaration.append(";")
		return ("".join(declaration),)


class CHardCodedParserArgument(CVariable):
	def __init__(self, argument):
		self._parse_argument = (argument,)

	def parse_argument(self):
		return self._parse_argument

	def impl_argument(self):
		return ()

	prototype = declaration = keyword = impl_argument


class CGroupBoolean(CVariable):
	def __init__(self, name):
		super().__init__("int", name, 0)

	def parse_argument(self):
		return ()

	keyword = parse_argument


class ArgumentBase:

	def __init__(self):
		self.variables = []
		self.flags = {}

	def flag(self, key, default=False):
		return self.flags.get(key, default)

	def required():
		return (self.default == unspecified) or self.flag('required')

	def _finalize(self):
		pass

	def _from_variables(self, name):
		self._finalize()
		l = []
		for v in self.variables:
			l.extend(getattr(v, name)())
		return l

	def is_optional(self):
		return False

	def impl_argument(self):
		return self._from_variables("impl_argument")

	def keyword(self):
		return self._from_variables("keyword")

	def parse_argument(self):
		return self._from_variables("parse_argument")
		
	def prototype(self):
		return self._from_variables("prototype")
		
	def declaration(self):
		return self._from_variables("declaration")

	def format_unit(self):
		return ''
		


class Optional(ArgumentBase):
	def __init__(self):
		super().__init__()
		self.name = '* optional *'

	def format_unit(self):
		return "|"

	def docstring(self):
		return ()


class KeywordOnly(ArgumentBase):
	def __init__(self):
		super().__init__()
		self.name = '* keyword-only *'

	def format_unit(self):
		return "$"

	def docstring(self):
		return ('*',)


class Argument(ArgumentBase):
	def __init__(self, c_type, name, line, default=unspecified):
		super().__init__()
		self.c_type = c_type
		self.name = name
		self.line = line
		self.default = default
		self.docstrings = []

	def is_optional(self):
		return (self.default != unspecified) and not self.flag('required')

	def _finalize(self):
		if self.variables:
			return

		if self.flag('group-first'):
			group = self.flag('group', None)
			if group is not None:
				group_boolean = CGroupBoolean(group + "_group")
				self.variables.append(group_boolean)

		converter = self.flag('converter', '')
		encoding  = self.flag('encoding', '')
		assert not (converter and encoding)
		if encoding:
			v = CHardCodedParserArgument('"' + encoding + '"')
			self.variables.append(v)
		elif converter:
			v = CHardCodedParserArgument(converter)
			self.variables.append(v)

		v = CVariable(self.c_type, self.name, self.default)
		self.variables.append(v)

		if self.flag('length'):
			length_name = self.name + "_length"
			length = CVariable('Py_ssize_t', length_name, -1)
			self.variables.append(length)

	def docstring(self):
		l = [self.name]
		if self.is_optional():
			l.append('=')
			value = self.flag('default', unspecified)
			if value is unspecified:
				try:
					value = repr(eval(self.default))
				except ValueError:
					value = self.default
			l.append(value)
		return l

	def format_unit(self):
		"""
		Render argument "format unit" in PyArg_ParseTupleAndKeywords format string.
		Returns iterable.
		"""
		types = tuple(sorted(self.flag('types', '').strip().split()))
		flag_tuple = tuple((bool(self.flag(flag)) for flag in options)) + (types,)
		format_unit = get_format_unit(self.c_type, *flag_tuple)
		if not format_unit:
			sys.exit("Sorry, I don't have a format unit for " + repr(self.line))
		return format_unit


re_argument = re.compile(r"^(?P<ctype>[A-Za-z0-9_\s]+)((?P<splat>\s*\*\s*)|(\s+))(?P<name>\w+)(\s*=\s*(?P<default>\S.*))?$")

class FauxPrint:
	def __init__(self):
		self.output = []

	def print(self, *args, sep=' ', end='\n', file=sys.stdout, flush=False):
		line = sep.join(str(a) for a in args) + end
		invalid_lines = (
			Clinic.python_begin_string,
			Clinic.dsl_begin_string,
			)
		if line.startswith(invalid_lines):
			error = ["Invalid line in output!  You can't use any of the following"]
			error.append("in the output of a Python section:")
			error.extend(["  " + invalid for invalid in invalid_lines])
			sys.exit("\n".join(error))
		if file == sys.stdout:
			self.output.append(line)
		else:
			file.write(line)
			if flush:
				file.flush()


class Clinic:
	def __init__(self, *, verify=True):
		self.state = self.state_reset
		self.verify = verify

	def rewrite(self, filename):
		self.read(filename)
		self.write(filename)

	def read(self, filename):
		self.filename = filename

		self.input = collections.deque()
		self.output = []
		with open(self.filename, "rt") as f:
			self.input = collections.deque(f.readlines())

	def write(self, filename):
		if not self.output:
			self._rewrite()

		self.filename = filename


		body = "\n".join(self.output)
		# always end .c files with a blank line
		if not body.endswith("\n"):
			body += "\n"
		body = body.encode("utf-8")
		directory = os.path.dirname(filename)
		f, name = tempfile.mkstemp(text=True, dir=directory)
		tempfiles.append(name)
		os.write(f, body)
		os.close(f)
		os.rename(name, self.filename)
		tempfiles.remove(name)

	python_begin_string = "/*[python]"
	python_end_string =   "[python]*/"
	python_end_output_prefix = "/*[python end:"
	python_end_output_suffix = "]*/"

	dsl_begin_string = "/*[clinic]"
	dsl_end_string = "[clinic]*/"
	dsl_end_output_prefix = "/*[clinic end:"
	dsl_end_output_suffix = "]*/"

	def _rewrite(self):
		while self.input:
			line = self.input.popleft().rstrip()
			# Always append the line to the output here.
			# When we throw away lines from the input,
			# we do so from a separate input-reading spot.
			self.output.append(line)
			self.state(line)
		assert self.state == self.state_idle
		self.next(self.state_reset)

	@staticmethod
	def ignore_line(line):
		# ignore comment-only lines
		if line.lstrip().startswith('#'):
			return True

		# Ignore empty lines too
		# (but not in docstring sections!)
		if not line.strip():
			return True

		return False

	@staticmethod
	def tab_nanny(line):
		if '\t' in line:
			sys.exit('Error: you used a tab in the DSL.\n\t' + repr(line))

	@staticmethod
	def calculate_indent(line):
		return len(line) - len(line.strip())

	def flag(self, name, default=False):
		return self.flags.get(name, default)

	def found_dsl_end(self, line):
		if line == self.dsl_end_string:
			self.next(self.state_dsl_end, line)
			return True
		return False

	@staticmethod
	def parse_flags_line(d, line):
		line = line.strip()
		if not line:
			return

		if '#' in line:
			# we want to support # line comments on flag lines.
			# but there could be a # inside a quoted string!  what to do?
			#
			# shlex.split is smart about complaining about unterminated quotes.
			# so: try clipping the line at every instance of a '#'
			# and use the first one where shlex.split doesn't complain.
			subline = ""
			for segment in line.split('#'):
				subline += segment
				try:
					attempt = shlex.split(subline)
					line = subline
					break
				except ValueError:
					subline += '#'
					continue
		for field in shlex.split(line):
			if '=' in field:
				name, _, value = field.partition('=')
				name = name.strip()
				value = value.strip()
			else:
				name = field
				value = True
			if name in d:
				sys.exit("Error: Can't specify " + repr(name) + " twice.\n\t" + line)
			d[name] = value

	def next(self, state, line=None):
		# print(self.state.__name__, "->", state.__name__, ", line=", line)
		self.state = state
		if line is not None:
			self.state(line)

	def find_terminator(self, terminator_prefix, begin_string):
		# read ahead until we find the end marker
		saved = []

		while self.input:
			line = self.input.popleft().rstrip()
			if line == begin_string:
				break
			if line.startswith(terminator_prefix):
				if self.verify:
					# verify checksum
					checksum_and_comment_end = line[len(terminator_prefix):]
					stored_checksum, comment, eol = checksum_and_comment_end.partition(']*/')
					if eol or not comment:
						sys.exit('Invalid marker line found:\n    ' + line + '\nGiving up.')
					data = "\n".join(saved).encode('utf-8') + b'\n'
					checksum = hashlib.sha1(data).hexdigest()
					if checksum != stored_checksum:
						sys.exit('Checksum doesn\'t match for marker line:\n    ' + line + '\nGiving up.')
				return
			saved.append(line)

		# if we got here, we didn't find a valid end marker for this block.
		# restore the entire remainder of the file.
		# (we'll automatically insert the marker with the template)
		self.input.extendleft(reversed(saved))

	def state_reset(self, line=None):
		# dsl
		self.module_name = self.name = None
		self.return_annotation = None
		self.flags = {}
		self.indent =  self.argument_indent = None
		self.arguments = []
		self.is_optional = self.is_keyword_only = False
		self.docstring = []
		self.groups = set()

		# python
		self.code = []

		self.next(self.state_idle, line)

	def state_idle(self, line):
		if line == self.dsl_begin_string:
			self.next(self.state_dsl_start)
		if line == self.python_begin_string:
			self.next(self.state_python_start)

	def state_python_start(self, line):
		self.next(self.state_python_body, line)

	def state_python_body(self, line):
		if line == self.python_end_string:
			self.next(self.state_python_end, line)
			return
		self.code.append(line)

	def state_python_end(self, line):
		self.find_terminator(self.python_end_output_prefix, self.python_begin_string)
		code = "\n".join(self.code)

		faux = FauxPrint()

		old_print = builtins.print
		builtins.print = faux.print
		exec(code)
		builtins.print = old_print

		output = "".join(faux.output)
		if output and output[-1] == '\n':
			output = output[:-1]
		self.output.append(output)
		data = output.encode('utf-8') + b'\n'
		line = "".join([
			self.python_end_output_prefix,
			hashlib.sha1(data).hexdigest(),
			self.python_end_output_suffix,
			])
		self.output.append(line)

		self.next(self.state_reset)

	def state_dsl_start(self, line):
		self.next(self.state_modulename_name, line)

	def state_modulename_name(self, line):
		# looking for declaration at left column
		# line should be
		#     modulename.fnname -> return annotation
		# everything after here ^
		# is optional.

		if self.ignore_line(line) or self.found_dsl_end(line):
			return
		assert not line[0].isspace(), "first line of clinic dsl should not start with whitespace:" + repr(line)
		self.tab_nanny(line)
		line, arrow, return_annotation = line.partition('->')
		self.return_annotation = return_annotation.strip()
		self.module_name, period, self.name = line.strip().partition('.')
		self.next(self.state_function_flags)

	def state_function_flags(self, line):
		if self.ignore_line(line) or self.found_dsl_end(line):
			return

		if line[0].isspace():
			return self.next(self.state_argument, line)

		self.tab_nanny(line)
		self.parse_flags_line(self.flags, line)


	# in the arguments section.
	# the rule is:
	#   * the first line must be an argument declaration.
	#   * this first line establishes the indent for arguments.
	#   * thenceforth:
	#      * one or more lines immediately after an argument declaration
	#        at the same indent level are flags lines.
	#      * lines indented further are docstrings for the previous arg.
	#      * the section ends if we hit the function docstring.
	#      * the first line of the function docstring must be at column 0.
	#      * it's illegal to have something outdented but not at column 0
	#        (until you get to the function docstring).

	def state_argument(self, line):
		if self.ignore_line(line) or self.found_dsl_end(line):
			return

		self.tab_nanny(line)

		if self.argument_indent == None:
			self.argument_indent = self.calculate_indent(line)

		# be nice: allow ";" but clip it here
		original_line = line
		if line.endswith(';'):
			line = line[:-1].strip()

		match = re_argument.match(line)
		d = match.groupdict()
		ctype = d['ctype'].strip()
		if d.get('splat'):
			ctype += ' *'
		aname = d['name']
		# can't use d.get for the default argument,
		# it's always set to None if it wasn't found.
		# (thanks, re module!)
		default = d["default"]
		if default == None:
			default = unspecified
		elif self.flag('positional-only'):
			sys.exit("Error: Can't use default values for arguments with positional-only functions (see " + self.module_name + "." + self.name + ")")

		a = Argument(ctype, aname, line, default)
		a.original_line = original_line
		self.arguments.append(a)

		self.next(self.state_argument_flags)

	def state_argument_flags(self, line):
		if self.ignore_line(line) or self.found_dsl_end(line):
			return

		self.tab_nanny(line)

		assert self.arguments
		a = self.arguments[-1]

		indent = self.calculate_indent(line)
		if indent == self.argument_indent:
			self.parse_flags_line(a.flags, line)
			return

		# transition to next state,
		# this is a good time for a whole bunch o' processing
		keyword_only = a.flag('keyword-only')
		optional = (a.default != unspecified) and (not a.flag('required'))

		if keyword_only and not optional:
			sys.exit("Error: You can't have a parameter which is keyword-only and required:\n\t" + a.original_line)

		if optional:
			if not self.is_optional:
				self.is_optional = True
				self.arguments[-1] = Optional()
				self.arguments.append(a)
		elif self.is_optional:
			sys.exit("Error: required parameter:\n\t" + a.original_line + "\nspecified after optional parameter.")

		if keyword_only and not self.is_keyword_only:
			self.is_keyword_only = True
			self.arguments[-1] = KeywordOnly()
			self.arguments.append(a)

		group = a.flag('group')
		if group and group not in self.groups:
			self.groups.add(group)
			a.flags['group-first'] = True

		return self.next(self.state_arguments_docstring, line)


	def state_arguments_docstring(self, line):
		if line.lstrip().startswith('#'):
			return

		self.tab_nanny(line)
		
		assert self.arguments
		a = self.arguments[-1]

		if not line.strip():
			a.docstrings.append('')
			return

		indent = self.calculate_indent(line)

		if indent == self.argument_indent:
			return self.next(self.state_argument, line)
		elif indent < self.argument_indent:
			assert not indent, "The first line of the function docstring must be at column 0."
			return self.next(self.state_docstring, line)

		a.docstrings.append(line[self.argument_indent:])

	def state_docstring(self, line):
		if line.lstrip().startswith('#'):
			return

		if self.found_dsl_end(line):
			return

		self.tab_nanny(line)
		
		self.docstring.append(line)


	def argument_list(self, name):
		l = []
		for a in self.arguments:
			l.extend(getattr(a, name)())
		return l

	def state_dsl_end(self, line):
		self.find_terminator(self.dsl_end_output_prefix, self.dsl_begin_string)

		# used by .format(**locals())
		module_name = self.module_name
		name = self.name
		# for names which are themselves dotted
		last_name = name.rpartition('.')[2]

		is_optional = False
		is_keyword_only = False
		using_groups = False

		# ensure that optional and keyword-only stuff is sane
		for a in self.arguments:

			if isinstance(a, Optional):
				assert not is_optional
				is_optional = True
				continue

			if isinstance(a, KeywordOnly):
				assert is_optional
				assert not is_keyword_only
				is_keyword_only = True
				continue

			using_groups = using_groups or a.flag('group')

		if using_groups and not self.flag('positional-only'):
			sys.exit("Error: can't use groups without positional-only (see " + repr(module_name + '.' + name) + ")")

		module_name_upper = module_name.upper()
		name_upper = name.upper()
		prototype_name = "{module_name}_{name}".format(**locals()).replace('.', '_')
		prototype_name = self.flag('basename') or prototype_name
		prototype_name_upper = prototype_name.upper()

		debug = builtins.print

		faux = FauxPrint()
		print = faux.print

		##
		## compute stuff that's the same whether or not we're doing positional-only
		##

		# compute square brackets for docstring first line
		if self.flag('positional-only'):
			# count how many arguments there are in each group
			groups = []
			counter = collections.Counter()
			group_to_arguments = {}
			left_groups = []
			right_groups = []
			append_to = left_groups
			last = unspecified
			for a in self.arguments:
				group = a.flag('group', None)
				if group != last:
					last = group
					if group in groups:
						sys.exit("Non-contiguous use of group " + repr(group))
					groups.append(group)
					group_to_arguments[group] = []
					if group is None:
						append_to = right_groups
					append_to.append(group)
				counter[group] += 1
				group_to_arguments[group].append(a)
			left_groups = list(reversed(left_groups))

			right_bracket_counts = {None:0}
			# skip None group (which is first in right_groups)
			for group_list in (left_groups, right_groups[1:]):
				right_bracket_counts.update({group: i+1 for (i, group) in enumerate(group_list)})
			last = unspecified
			for a in self.arguments:
				group = a.flag('group', None)
				a.right_bracket_count = right_bracket_counts[group]
		else:
			# not positional-only
			# all optional arguments are ungrouped and separately right-bracketed
			# but: all keyword-only arguments don't get brackets!
			i = 0
			is_keyword_only = False
			for a in self.arguments:
				if 0 and isinstance(a, KeywordOnly):
					is_keyword_only = True
					i = 0
				elif not is_keyword_only and a.is_optional():
					i += 1
				a.right_bracket_count = i

		# the docstring!
		docstring_first_line = 'PyDoc_STRVAR({prototype_name}__doc__,\n"{module_name}.{name}('.format(**locals())

		first_line = []
		docstring_arguments = []
		right_bracket_count = 0
		def fix_right_bracket_count(desired):
			nonlocal right_bracket_count
			s = ''
			while right_bracket_count < desired:
				s += '['
				right_bracket_count += 1
			while right_bracket_count > desired:
				s += ']'
				right_bracket_count -= 1
			return s

		for a in self.arguments:
			s = "".join(a.docstring())
			if s:
				s = fix_right_bracket_count(a.right_bracket_count) + s
				for old, new in (
					('"', '\\"'),
					("'", "\\'"),
					):
					s = s.replace(old, new)
				first_line.append(s)
			if isinstance(a, Argument):
				docstring_arguments.append(a.name)
				for line in a.docstrings:
					docstring_arguments.append(('  ' + line).rstrip())

		docstring_first_line += ', '.join(first_line) + fix_right_bracket_count(0) + ')'

		# now fix up the places where the brackets look wrong
		# and quote the strings
		for old, new in (
			(', ]', ',] '),
			(', [', '[, '),
			):
			docstring_first_line = docstring_first_line.replace(old, new)

		if self.return_annotation:
			annotation = self.return_annotation
			docstring_first_line += ' -> ' + annotation
		docstring_first_line += '\\n"\n"\\n"\n'

		# the contents of the {arguments} string for the docstring
		arguments_docstring = "\n".join(docstring_arguments)

		docstring_end = '\n'.join(self.docstring)
		if docstring_end:
			if '{arguments}' not in docstring_end:
				docstring_end = '  {arguments}\n\n' + docstring_end
			arguments_docstring = arguments_docstring.rstrip()
			final = []
			for line in docstring_end.split('\n'):
				indent, is_arguments_line, _ = line.partition('{arguments}')
				if is_arguments_line:
					final.append(textwrap.indent(arguments_docstring, indent))
				else:
					final.append(line)
			docstring_end = "\n".join(final)
			docstring_end = '"' + docstring_end.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n"\n"') + '\\n"'

		docstring = docstring_first_line + docstring_end + ');'

		print()
		print(docstring)
		print()

		# the methoddef define!
		meth_keywords = " | METH_KEYWORDS" if not self.flag('positional-only') else ''
		print('#define {prototype_name_upper}_METHODDEF    \\'.format(**locals()))
		print('    {{"{last_name}", (PyCFunction){prototype_name}, METH_VARARGS{meth_keywords}, {prototype_name}__doc__}}'.format(**locals()))
		print()

		# the prototype!
		prototype_arguments = ", ".join(self.argument_list('prototype'))
		impl = prototype_name + "_impl"
		impl_prototype = "static PyObject *\n{impl}(PyObject *self, {prototype_arguments})".format(**locals())
		print(impl_prototype + ';')
		print()

		print("static PyObject *")
		kwargs = ", PyObject *kwargs" if not self.flag('positional-only') else ''
		print("{prototype_name}(PyObject *self, PyObject *args{kwargs})".format(**locals()))
		print("{")

		# declarations, with defaults
		for a in self.arguments:
			for line in a.declaration():
				print("   ", line)

		if not self.flag('positional-only'):
			# not positional only, aka uses PyArg_ParseTupleAndKeywords

			format_units = ''
			parse_arguments = []
			for a in self.arguments:
				format_units += a.format_unit()
				parse_arguments.extend(a.parse_argument())
			format_units += ':' + last_name

			# "keywords" array for PyArg_ParseTupleAndKeywords
			quoted_names = self.argument_list('keyword')
			quoted_names.append("NULL")
			keywords = "    static char *_keywords[] = {" + ", ".join(quoted_names) + "};"
			print(keywords)

			print()

			print("    if (!PyArg_ParseTupleAndKeywords(args, kwargs,")
			print('        "' + format_units + '", _keywords,')
			print('        ' + ', '.join(parse_arguments) + '))')
			print('        return NULL;')

		else:
			# positional only, grouped, optional arguments!
			# can be optional on the left or right.
			# here's an example:
			#
			# [ [ [ A1 A2 ] B1 B2 B3 ] C1 C2 ] D1 D2 D3 [ E1 E2 E3 [ F1 F2 F3 ] ]
			#
			# Here group D are required, and all other groups are optional.
			# (Group D's "group" is actually None.)
			# We can figure out which sets of arguments we have based on
			# how many arguments are in the tuple.
			#
			# Note that you need to count up on both sides.  For example,
			# you could have groups C and D, or C & D & E, or C & D & E & F.
			#
			# What if the number of arguments leads us to an ambiguous result?
			# Why, then, you're a *loser* my dear!  Clinic will exit with
			# an error message.

			left_bundles = [()]
			l = []
			for group in left_groups:
				l.append(group)
				left_bundles.append(tuple(l))

			count_min = 10000
			count_max = -1
			print()
			print("    switch (PyTuple_Size(args)) {")
			bundle_counts = {}
			for b in left_bundles:
				l = list(b)
				for group in right_groups:
					l.append(group)
					bundle = tuple(l)
					count = sum(counter[g] for g in bundle)
					count_min = min(count_min, count)
					count_max = max(count_max, count)
					if count in bundle_counts:
						sys.exit("Can't process arguments for " + self.module_name + "." + self.name + ": two bundles with same argument counts, " + repr(bundle) + " and " + repr(bundle_counts[count]))
					bundle_counts[bundle] = count

					print("        case " + str(count) + ":")
					print('            if (!PyArg_ParseTuple(args, "', end='')
					parse_arguments = []
					group_booleans = []
					for group in bundle:
						if group is not None:
							group_booleans.append(group + "_group")
						for a in group_to_arguments[group]:
							print(a.format_unit(), end='')
							parse_arguments.extend(a.parse_argument())
					print(':' + last_name + '", ', end='')
					print(", ".join(parse_arguments) + "))")
					print("                return NULL;")
					for group in bundle:
						if group is not None:
							print("            " + group + "_group = 1;")
					print("            break;")
			print("        default:")
			print('            PyErr_SetString(PyExc_TypeError, "' + self.name + ' requires', count_min, 'to', count_max, 'arguments");')
			print('            return NULL;')
			print("    }")

		impl_arguments = []
		for a in self.arguments:
			impl_arguments.extend(a.impl_argument())
		print()
		print('    return ' + impl + '(self, ' + ', '.join(impl_arguments) + ');')

		print("}")
		print()

		# the header for the impl!
		print(impl_prototype)

		# write output!
		text = "".join(faux.output)
		data = text.encode('ascii')
		checksum = hashlib.sha1(data).hexdigest()
		self.output.append("".join([
			text,
			self.dsl_end_output_prefix,
			checksum,
			self.dsl_end_output_suffix,
			]))

		self.next(self.state_reset)

	def dead_code(self):
		argument_declarations = argument_declarations


		pyarg_format_string += ":" + name


		if 0: # else:
			# the first line of the docstring


			parse_code = keywords + """
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "{pyarg_format_string}",
                                     _keywords{pyarg_arguments}))
        return NULL;"""

		template = """
{docstring}
{impl_prototype};

#define {module_name_upper}_{name_upper}_METHODDEF    \\
    {{"{name}", (PyCFunction){module_name}_{name}, METH_VARARGS | METH_KEYWORDS, {module_name}_{name}__doc__}}

static PyObject *
{module_name}_{name}(PyObject *self, PyObject *args, PyObject *kwargs)
{{
    {argument_declarations}
""" + parse_code + """
    return {module_name}_{name}_impl(self{invocation_arguments});
}}

{impl_prototype}
"""

		text = template.format(**locals())
		data = text.encode('utf-8')


def main(argv):
	import argparse
	cmdline = argparse.ArgumentParser()
	cmdline.add_argument("-f", "--force", action='store_true')
	cmdline.add_argument("-o", "--output", type=str)
	cmdline.add_argument("filename", type=str, nargs="+")
	ns = cmdline.parse_args(argv)
	if ns.output and (len(ns.filename) > 1):
		sys.exit("Error: can't use -o with multiple filenames")
	for filename in ns.filename:
		clinic = Clinic(verify=not (ns.force or ns.output))
		clinic.read(filename)
		clinic.write(ns.output or filename)


if __name__ == "__main__":
	sys.exit(main(sys.argv[1:]))