python-clinic / clinic.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
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
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
#!/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.
#

## TODO
##
## extension api should support arbitrary lines of initialization code
##
## make extension api convenient for caller, not callee.
##

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


# we play with builtins.print a lot
real_print = builtins.print


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()


type_map = {}

def type_map_register(cls):
    type_map[cls.type] = cls
    return cls

def type_map_alias(type):
    def decorator(cls):
        type_map[type] = cls
        return cls
    return decorator


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

    When subclassing, the most relevant things to override are:
        type
        format_unit_map
        format_unit_flags
        default
        cleanup
    """

    type = None

    def __init__(self, name, default=unspecified):
        self.name = name
        self.str_default = default
        self.flags = {}

    def impl_argument(self):
        """
        The C code to pass this argument in to the impl function.
        Returns an iterable.
        """
        assert self.name and self.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.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.type
        return ("&" + self.name,)

    def simple_declaration(self):
        """
        Computes the basic declaration of the variable.
        Used in computing the prototype declaration and the
        variable declaration.
        """
        assert self.name and self.type
        prototype = [self.type]
        if not self.type.endswith('*'):
            prototype.append(" ")
        prototype.append(self.name)
        return ("".join(prototype),)

    def prototype(self):
        """
        The C code to define this variable as an argument to a function.
        Returns an iterable.
        """
        return self.simple_declaration()

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

    def default(self, s):
        """
        Returns a string to be used as the initializer for this variable, or None if no initializer is needed.
        s is a Python value.
        If s is the special value 'unspecified', no default was specified.
        """
        if s is unspecified:
            return None
        return self.value_to_cvalue_map.get(s, s)

    def declaration(self):
        """
        The C statement to declare this variable.
        Returns an iterable.
        """
        declaration = list(self.simple_declaration())
        default = self.default(self.str_default)
        if default:
            declaration.append(" = ")
            declaration.append(default)
        declaration.append(";")
        return ("".join(declaration),)

    def cleanup(self):
        """
        The C statements required to clean up after this variable.
        Returns an iterable.
        (If no cleanup is necessary, returns an empty iterable.)
        """
        return ()

    # should be a map of frozenset(flags) -> string
    # the string represent "true" flags
    # if there are also associated "types", then the key becomes a tuple
    #   first element is frozenset(flags)
    #   second element is frozenset(types)
    format_unit_map = {}

    # the set of flags get_format_unit() will pay attention
    # to when computing the format unit.
    format_unit_flags = frozenset("bitwise encoding immutable length nullable zeroes".split())

    @property
    def format_unit(self):
        if 'converter' in self.flags:
            return "O&"

        flags = dict(self.flags)
        if 'types' in flags:
            types = frozenset(flags['types'].split())
            del flags['types']
        else:
            types = None

        key = set()
        for flag in self.format_unit_flags:
            if flags.get(flag):
                key.add(flag)
        key = frozenset(key)
        if types:
            key = (key, types)
        format_unit = self.format_unit_map.get(key)
        if not format_unit:
            sys.exit("No valid format unit for " + self.__class__.__name__ + " " + self.name + " (no match for flags " + repr(key) + ")")
        return format_unit


@type_map_register
class CVariable_PyObject_star(CVariable):
    """
    PyObject * = O
    """

    type = "PyObject *"

    format_unit_map = {
        frozenset() : "O",
        }


@type_map_register
class CVariable_Py_UNICODE_star(CVariable):
    """
    Py_UNICODE * = u
    Py_UNICODE * length = u#
    Py_UNICODE * nullable = Z
    Py_UNICODE * length nullable = Z#
    """

    type = "Py_UNICODE *"

    format_unit_map = {
        frozenset() : "u",
        frozenset(('length',)) : "u#",
        frozenset(('nullable',)) : "Z",
        frozenset(('length', 'nullable')) : "Z#",
        }

@type_map_register
class CVariable_char_star(CVariable):
    """
    char * encoding = es
    char * encoding (str bytes bytearray) = et
    char * encoding length = es#
    char * encoding length (str bytes bytearray) = et#
    """

    type = "char *"

    str_types = frozenset(('str', 'bytes', 'bytearray'))

    format_unit_map = {
        frozenset(('encoding',)) : "es",
        frozenset(('encoding', 'length')) : "es#",
        (frozenset(('encoding',)), str_types) : "et",
        (frozenset(('encoding', 'length')), str_types) : "et#",
        }
    
@type_map_register
class CVariable_const_char_star(CVariable):
    """
    const char * = s
    const char * nullable = z
    const char * (bytes) = y
    const char * length (bytes buffer) = y#
    const char * length zeroes (str bytes buffer) = s#
    const char * length nullable zeroes (str bytes buffer) = z#
    """

    type = "const char *"

    types_bytes = frozenset(('bytes,'))
    types_bytes_buffer = frozenset(('buffer,')) | types_bytes
    types_str_bytes_buffer = frozenset(('str,')) | types_bytes_buffer

    format_unit_map = {
        frozenset() : "s",
        frozenset(('nullable',)) : "z",
        (frozenset(), types_bytes) : "y",
        (frozenset(('length',)), types_bytes_buffer) : "y#",

        (frozenset(('length', 'zeroes')), types_str_bytes_buffer) : "s#",
        (frozenset(('length', 'nullable', 'zeroes')), types_str_bytes_buffer) : "z#",
        }

@type_map_register
class CVariable_Py_buffer(CVariable):
    """
    Py_buffer (bytes bytearray buffer) = y*
    Py_buffer zeroes (str bytes bytearray buffer) = s*
    Py_buffer nullable zeroes (str bytes bytearray buffer) = z*
    """

    type = 'Py_buffer'

    bytes_types = frozenset(('bytes', 'bytearray', 'buffer'))
    bytes_types_and_str = frozenset(('str',)) | bytes_types

    format_unit_map = {
        (frozenset(), bytes_types) : "y*",
        (frozenset(('zeroes',)), bytes_types_and_str) : "s*",
        (frozenset(('nullable', 'zeroes',)), bytes_types_and_str) : "z*",
        }


@type_map_register
class CVariable_PyUnicodeObject_star(CVariable):
    """
    PyUnicodeObject * = U
    """

    type = 'PyUnicodeObject *'

    format_unit_map = {
        frozenset() : "U",
        }


@type_map_register
class CVariable_PyBytesObject_star(CVariable):
    """
    PyBytesObject * = S
    """

    type = 'PyBytesObject *'

    format_unit_map = {
        frozenset() : "S",
        }


@type_map_register
class CVariable_PyBytesArrayObject_star(CVariable):
    """
    PyBytesArrayObject * = Y
    """

    type = 'PyBytesArrayObject *'

    format_unit_map = {
        frozenset() : "Y",
        }

@type_map_register
class CVariable_unsigned_char(CVariable):
    """
    unsigned char = b
    unsigned char bitwise = B
    """

    type = 'unsigned char'

    format_unit_map = {
        frozenset() : "b",
        frozenset(('bitwise',)) : "B",
        }

@type_map_register
@type_map_alias('short int')
@type_map_alias('signed short')
@type_map_alias('signed short int')
class CVariable_short(CVariable):
    """
    short = h
    """

    type = 'short'

    format_unit_map = {
        frozenset() : "h",
        }



@type_map_register
@type_map_alias('unsigned short int')
class CVariable_unsigned_short(CVariable):
    """
    unsigned short bitwise = H
    """

    type = 'unsigned short'

    format_unit_map = {
        frozenset(('bitwise',)) : "H",
        }


@type_map_register
@type_map_alias('signed int')
class CVariable_int(CVariable):
    """
    int = i
    int (bool) = p
    """

    type = 'int'

    format_unit_map = {
        frozenset() : "i",
        (frozenset(), frozenset(('bool',))) : "p",
        }

@type_map_register
@type_map_alias('unsigned')
class CVariable_unsigned_int(CVariable):
    """
    unsigned int bitwise = I
    """

    type = 'unsigned int'

    format_unit_map = {
        frozenset(('bitwise',)) : "I",
        }

@type_map_register
@type_map_alias('signed long')
@type_map_alias('long int')
@type_map_alias('signed long int')
class CVariable_long(CVariable):
    """
    long = l
    """

    type = 'long'

    format_unit_map = {
        frozenset() : "l",
        }

@type_map_register
@type_map_alias('unsigned long int')
class CVariable_unsigned_long(CVariable):
    """
    unsigned long bitwise = k
    """

    type = 'unsigned long'

    format_unit_map = {
        frozenset(('bitwise',)) : "k",
        }


@type_map_register
class CVariable_PY_LONG_LONG(CVariable):
    """
    PY_LONG_LONG = L
    """

    type = 'PY_LONG_LONG'

    format_unit_map = {
        frozenset() : "L",
        }

@type_map_register
class CVariable_unsigned_PY_LONG_LONG(CVariable):
    """
    unsigned PY_LONG_LONG bitwise = K
    """

    type = 'unsigned PY_LONG_LONG'

    format_unit_map = {
        frozenset(('bitwise',)) : "K",
        }




@type_map_register
class CVariable_Py_ssize_t(CVariable):
    """
    Py_ssize_t = n
    """

    type = 'Py_ssize_t'

    format_unit_map = {
        frozenset() : "n",
        }

@type_map_register
class CVariable_char(CVariable):
    """
    char = C
    char (bytes bytearray) = c
    """

    type = 'char'

    format_unit_map = {
        frozenset() : "C",
        (frozenset(), frozenset(('bytes', 'bytearray'))) : "c",
        }

@type_map_register
class CVariable_float(CVariable):
    """
    float = f
    """

    type = 'float'

    format_unit_map = {
        frozenset() : "f",
        }



@type_map_register
class CVariable_double(CVariable):
    """
    double = d
    """

    type = 'double'

    format_unit_map = {
        frozenset() : "d",
        }

@type_map_register
class CVariable_Py_complex_star(CVariable):
    """
    Py_complex * = D
    """

    type = 'Py_complex *'

    format_unit_map = {
        frozenset() : "D",
        }


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 cleanup(self):
        return self._from_variables("cleanup")

    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, flags, line, default=unspecified):
        self.variables = []

        type = type_map.get(c_type)
        if not type:
            sys.exit("Could not create variable of type " + repr(c_type))
        self.variable = type(name, default)
        self.variable.flags.update(flags)

        if 'converter' in flags:
            self.variable.type = c_type

        self.name = name
        self.line = line
        self.default = default
        self.docstrings = []

    @property
    def flags(self):
        return self.variable.flags

    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)

        self.variables.append(self.variable)

        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, NameError):
                    value = self.default
            l.append(value)
        return l

    def format_unit(self):
        """
        Render argument "format unit" in PyArg_ParseTupleAndKeywords format string.
        Returns string.
        """
        return self.variable.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.PythonOutputBlock.begin_string,
            Clinic.ClinicOutputBlock.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()

    @property
    def output(self):
        text = "".join(self._output)
        assert (not text) or (text.endswith('\n'))
        return text


class CountedDeque:
    def __init__(self, iterable=()):
        self.line = -1
        self.deque = collections.deque(iterable)
        self.left = []

    def __bool__(self):
        return bool(self.deque) or bool(self.left)

    def popleft(self):
        self.line += 1
        if self.left:
            return self.left.pop()
        return self.deque.popleft()

    def extendleft(self, i):
        for line in i:
            self.line -= 1
            self.left.append(line)

def directive(f):
    f.directive = True
    return f

def is_directive(f):
    return callable(f) and getattr(f, 'directive', False)

class Clinic:
    def __init__(self, *, verify=True):
        self.state = self.state_reset
        self.verify = verify
        self.impl_file = None
        self.modules = {}
        self.current_module = None
        self.block = None

    @directive
    def module(self, name):
        if name not in self.modules:
            self.modules[name] = {'methoddefs':[]}
        self.current_module = name

    @directive
    def methoddefs(self, module=None):
        assert self.current_module, "no module was ever declared!"
        for s in self.modules[module or self.current_module]['methoddefs']:
            ifdef = None
            if isinstance(s, tuple):
                ifdef, s = s
            if ifdef:
                print("    #ifdef", ifdef)
            print("    " + s + ",")
            if ifdef:
                print("    #endif")

    @directive
    def write_clinic_file(self, filename=None):
        filename = filename or (self.filename.partition('.c')[0] + "_clinic.c")
        self.clinic_filename = filename
        if os.path.isfile(filename):
            os.unlink(filename)
        self.impl_file = open(filename, "wt")

    @directive
    def include_clinic_file(self, filename=None):
        print('#include "' + os.path.basename(self.clinic_filename) + '"')

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

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

        self.output = []
        with open(self.filename, "rt") as f:
            self.input = CountedDeque(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)

        if self.impl_file:
            i = self.impl_file
            self.impl_file = None
            i.close()

        tempfiles.remove(name)

    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)
            # real_print("LINE", line, self.state.__qualname__)
            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, *, next=None):
        if line == self.ClinicOutputBlock.end_string:
            next = next or self.state_dsl_end
            self.next(next, 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):
        # real_print(self.state.__name__, "->", state.__name__, ", line=", line)
        self.state = state
        if line is not None:
            self.state(line)

    class OutputBlock:

        def __init__(self, clinic):
            self.clinic = clinic

            self.faux = FauxPrint()
            self.print = self.faux.print

            # and force everyone to use it            
            self.old_print = builtins.print
            builtins.print = self.faux.print

        def close(self):
            clinic.find_terminator(self.end_output_prefix, self.begin_string)

            builtins.print = self.old_print
            append = self.clinic.output.append

            text = self.faux.output

            data = text.encode('utf-8')

            checksum = hashlib.sha1(data).hexdigest()
            if 0:
                if len(data) > 23:
                    data = data[:10] + b"..." + data[-10:]
                print("checksum for", repr(data), "is", checksum)
            output = "".join([
                text,
                self.end_output_prefix,
                checksum,
                self.end_output_suffix,
                ])
            self.clinic.output.append(output)


    class PythonOutputBlock(OutputBlock):
        begin_string = "/*[python]"
        end_string =   "[python]*/"
        end_output_prefix = "/*[python end:"
        end_output_suffix = "]*/"

    class ClinicOutputBlock(OutputBlock):
        begin_string = "/*[clinic]"
        end_string = "[clinic]*/"
        end_output_prefix = "/*[clinic end:"
        end_output_suffix = "]*/"


    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()
            saved.append(line)
            if line == begin_string:
                break
            if line.startswith(terminator_prefix):
                if self.verify:
                    saved.pop() # remove terminator_prefix line from the end
                    # 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')
                    if saved:
                        data += b'\n'
                    checksum = hashlib.sha1(data).hexdigest()
                    if 0:
                        if len(data) > 23:
                            data = data[:10] + b"..." + data[-10:]
                        real_print("checking checksum for", repr(data), "is", checksum)
                    if checksum != stored_checksum:
                        sys.exit('Checksum doesn\'t match for marker line:\n    ' + line + '\nGiving up.')
                return

        # 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):
        if self.block:
            self.block.close()
            self.block = 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.ClinicOutputBlock.begin_string:
            self.next(self.state_dsl_start)
        if line == self.PythonOutputBlock.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.PythonOutputBlock.end_string:
            self.next(self.state_python_end, line)
            return
        self.code.append(line)

    def state_python_end(self, line):
        block = self.PythonOutputBlock(self)
        exec("\n".join(self.code))
        block.close()

        self.next(self.state_reset)

    def state_dsl_start(self, line):
        self.block = self.ClinicOutputBlock(self)
        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.found_dsl_end(line, next=self.state_reset):
            return

        if self.ignore_line(line):
            return

        assert not line[0].isspace(), "first line of clinic dsl should not start with whitespace:" + repr(line)

        # is it a directive?
        fields = shlex.split(line)
        f = getattr(self, fields[0], None)
        if is_directive(f):
            # it's a directive!
            f(*fields[1:])
            return

        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 + ")")

        self.variable_ctype = ctype
        self.variable_name = aname
        self.variable_line = line
        self.variable_original_line = original_line
        self.variable_default = default
        self.variable_flags = {}

        # 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)

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

        # transition to next state,
        # this is a good time for a whole bunch o' processing
        a = Argument(self.variable_ctype, self.variable_name, self.variable_flags, self.variable_line, self.variable_default)
        a.original_line = self.variable_original_line
        self.arguments.append(a)

        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):
        debug = builtins.print

        # 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()

        if self.impl_file:
            impl_printer = FauxPrint()
            print = impl_printer.print
        else:
            print = self.block.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 {parameters} string for the docstring
        arguments_docstring = "\n".join(docstring_arguments)

        docstring_end = '\n'.join(self.docstring)
        if docstring_end:
            if '{parameters}' not in docstring_end:
                docstring_end = '{parameters}\n\n' + docstring_end
            arguments_docstring = arguments_docstring.rstrip()
            final = []
            for line in docstring_end.split('\n'):
                indent, is_arguments_line, _ = line.partition('{parameters}')
                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!
        methoddef_name = "{}_METHODDEF".format(prototype_name_upper)
        meth_keywords = " | METH_KEYWORDS" if not self.flag('positional-only') else ''
        print('#define {methoddef_name}    \\'.format(**locals()))
        print('    {{"{last_name}", (PyCFunction){prototype_name}, METH_VARARGS{meth_keywords}, {prototype_name}__doc__}}'.format(**locals()))
        print()

        if self.current_module:
            ifdef = self.flag('ifdef')
            if ifdef:
                value = (ifdef, methoddef_name)
            else:
                value = methoddef_name
            self.modules[self.current_module]['methoddefs'].append(value)

        # 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("{")
        print("    PyObject *_return_value;")

        # 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_value = ' + impl + '(self, ' + ', '.join(impl_arguments) + ');')

        for a in self.arguments:
            for line in a.cleanup():
                print("   ", line)

        print("    return _return_value;")
        print("}")
        print()

        # the header for the impl!
        self.block.print(impl_prototype)

        if self.impl_file:
            impl_printer.print()
            self.impl_file.write("".join(impl_printer.output))

        self.next(self.state_reset)

    
clinic = None

def main(argv):
    global clinic
    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:]))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.