/
pyink.patch
1594 lines (1478 loc) · 58.1 KB
/
pyink.patch
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
# This is a partial patch that applies after we have renamed `black` to `pyink`.
# This file is provided so it's easier to see the actual differences between Black and Pyink.
--- a/__init__.py
+++ b/__init__.py
@@ -13,6 +13,7 @@ from json.decoder import JSONDecodeError
from pathlib import Path
from typing import (
Any,
+ Collection,
Dict,
Generator,
Iterator,
@@ -65,7 +66,7 @@ from pyink.linegen import LN, LineGenera
from pyink.lines import EmptyLineTracker, LinesBlock
from pyink.mode import FUTURE_FLAG_TO_FEATURE, VERSION_TO_FEATURES, Feature
from pyink.mode import Mode as Mode # re-exported
-from pyink.mode import TargetVersion, supports_feature
+from pyink.mode import QuoteStyle, TargetVersion, supports_feature
from pyink.nodes import (
STARS,
is_number_token,
@@ -76,6 +77,8 @@ from pyink.nodes import (
from pyink.output import color_diff, diff, dump_to_file, err, ipynb_diff, out
from pyink.parsing import InvalidInput # noqa F401
from pyink.parsing import lib2to3_parse, parse_ast, stringify_ast
+from pyink import ink
+from pyink import ink_adjusted_lines
from pyink.report import Changed, NothingChanged, Report
from pyink.trans import iter_fexpr_spans
from blib2to3.pgen2 import token
@@ -291,6 +294,41 @@ def validate_regex(
),
)
@click.option(
+ "--pyink/--no-pyink",
+ is_flag=True,
+ default=True,
+ help=(
+ "Enable the Pyink formatting mode. Disabling it should behave the same as"
+ " Black."
+ ),
+)
+@click.option(
+ "--pyink-indentation",
+ type=click.Choice(["2", "4"]),
+ default="4",
+ show_default=True,
+ help="The number of spaces used for indentation.",
+)
+@click.option(
+ "--pyink-lines",
+ multiple=True,
+ metavar="START-END",
+ help=(
+ 'Range of lines to format. Must be specified as "START-END", index is'
+ " 1-based and inclusive on both ends."
+ ),
+ default=None,
+)
+@click.option(
+ "--pyink-use-majority-quotes",
+ is_flag=True,
+ help=(
+ "When normalizing string quotes, infer preferred quote style by calculating the"
+ " majority in the file. Multi-line strings and docstrings are excluded from"
+ " this as they always use double quotes."
+ ),
+)
+@click.option(
"--check",
is_flag=True,
help=(
@@ -453,6 +491,10 @@ def main( # noqa: C901
skip_magic_trailing_comma: bool,
experimental_string_processing: bool,
preview: bool,
+ pyink: bool,
+ pyink_indentation: str,
+ pyink_lines: Optional[Sequence[str]],
+ pyink_use_majority_quotes: bool,
quiet: bool,
verbose: bool,
required_version: Optional[str],
@@ -531,6 +573,7 @@ def main( # noqa: C901
else:
# We'll autodetect later.
versions = set()
+ pyink_indentation = 2 if pyink_indentation == "2" else 4
mode = Mode(
target_versions=versions,
line_length=line_length,
@@ -542,8 +585,36 @@ def main( # noqa: C901
experimental_string_processing=experimental_string_processing,
preview=preview,
python_cell_magics=set(python_cell_magics),
+ is_pyink=pyink,
+ pyink_indentation=pyink_indentation,
+ quote_style=(
+ QuoteStyle.MAJORITY if pyink_use_majority_quotes else QuoteStyle.DOUBLE
+ ),
)
+ lines: Optional[List[Tuple[int, int]]] = None
+ if pyink_lines is not None:
+ lines = []
+ for lines_str in pyink_lines:
+ parts = lines_str.split("-")
+ if len(parts) != 2:
+ err(
+ "Incorrect --pyink-lines format, expect 'START-END', found"
+ f" {lines_str!r}"
+ )
+ ctx.exit(1)
+ try:
+ start = int(parts[0])
+ end = int(parts[1])
+ except ValueError:
+ err(
+ "Incorrect --pyink-lines value, expect integer ranges, found"
+ f" {lines_str!r}"
+ )
+ ctx.exit(1)
+ else:
+ lines.append((start, end))
+
if code is not None:
# Run in quiet mode by default with -c; the extra output isn't useful.
# You can still pass -v to get verbose output.
@@ -588,6 +659,7 @@ def main( # noqa: C901
write_back=write_back,
mode=mode,
report=report,
+ lines=lines,
)
else:
from pyink.concurrency import reformat_many
@@ -745,7 +817,13 @@ def reformat_code(
# not ideal, but this shouldn't cause any issues ... hopefully. ~ichard26
@mypyc_attr(patchable=True)
def reformat_one(
- src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
+ src: Path,
+ fast: bool,
+ write_back: WriteBack,
+ mode: Mode,
+ report: "Report",
+ *,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
) -> None:
"""Reformat a single file under `src` without spawning child processes.
@@ -770,7 +848,9 @@ def reformat_one(
mode = replace(mode, is_pyi=True)
elif src.suffix == ".ipynb":
mode = replace(mode, is_ipynb=True)
- if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
+ if format_stdin_to_stdout(
+ fast=fast, write_back=write_back, mode=mode, lines=lines
+ ):
changed = Changed.YES
else:
cache = Cache.read(mode)
@@ -778,7 +858,7 @@ def reformat_one(
if not cache.is_changed(src):
changed = Changed.CACHED
if changed is not Changed.CACHED and format_file_in_place(
- src, fast=fast, write_back=write_back, mode=mode
+ src, fast=fast, write_back=write_back, mode=mode, lines=lines
):
changed = Changed.YES
if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
@@ -798,6 +878,8 @@ def format_file_in_place(
mode: Mode,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
+ *,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
) -> bool:
"""Format file under `src` path. Return True if changed.
@@ -817,7 +899,9 @@ def format_file_in_place(
header = buf.readline()
src_contents, encoding, newline = decode_bytes(buf.read())
try:
- dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
+ dst_contents = format_file_contents(
+ src_contents, fast=fast, mode=mode, lines=lines
+ )
except NothingChanged:
return False
except JSONDecodeError:
@@ -862,6 +946,7 @@ def format_stdin_to_stdout(
content: Optional[str] = None,
write_back: WriteBack = WriteBack.NO,
mode: Mode,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
) -> bool:
"""Format file on stdin. Return True if changed.
@@ -880,7 +965,7 @@ def format_stdin_to_stdout(
dst = src
try:
- dst = format_file_contents(src, fast=fast, mode=mode)
+ dst = format_file_contents(src, fast=fast, mode=mode, lines=lines)
return True
except NothingChanged:
@@ -908,7 +993,11 @@ def format_stdin_to_stdout(
def check_stability_and_equivalence(
- src_contents: str, dst_contents: str, *, mode: Mode
+ src_contents: str,
+ dst_contents: str,
+ *,
+ mode: Mode,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
) -> None:
"""Perform stability and equivalence checks.
@@ -917,10 +1006,16 @@ def check_stability_and_equivalence(
content differently.
"""
assert_equivalent(src_contents, dst_contents)
- assert_stable(src_contents, dst_contents, mode=mode)
+ assert_stable(src_contents, dst_contents, mode=mode, lines=lines)
-def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileContent:
+def format_file_contents(
+ src_contents: str,
+ *,
+ fast: bool,
+ mode: Mode,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
+) -> FileContent:
"""Reformat contents of a file and return new contents.
If `fast` is False, additionally confirm that the reformatted code is
@@ -930,13 +1025,15 @@ def format_file_contents(src_contents: s
if mode.is_ipynb:
dst_contents = format_ipynb_string(src_contents, fast=fast, mode=mode)
else:
- dst_contents = format_str(src_contents, mode=mode)
+ dst_contents = format_str(src_contents, mode=mode, lines=lines)
if src_contents == dst_contents:
raise NothingChanged
if not fast and not mode.is_ipynb:
# Jupyter notebooks will already have been checked above.
- check_stability_and_equivalence(src_contents, dst_contents, mode=mode)
+ check_stability_and_equivalence(
+ src_contents, dst_contents, mode=mode, lines=lines
+ )
return dst_contents
@@ -1047,7 +1144,12 @@ def format_ipynb_string(src_contents: st
raise NothingChanged
-def format_str(src_contents: str, *, mode: Mode) -> str:
+def format_str(
+ src_contents: str,
+ *,
+ mode: Mode,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
+) -> str:
"""Reformat a string and return new contents.
`mode` determines formatting options, such as how many characters per line are
@@ -1076,17 +1178,28 @@ def format_str(src_contents: str, *, mod
) -> None:
hey
+ `lines` is either None or a list of tuples of integers. Each tuple
+ [start, end] in the list corresponds to a line range to format. They are
+ 1-based and inclusive on both ends. When not None, the formatting will be
+ restricted to those lines whenever possible.
"""
- dst_contents = _format_str_once(src_contents, mode=mode)
+ dst_contents = _format_str_once(src_contents, mode=mode, lines=lines)
# Forced second pass to work around optional trailing commas (becoming
# forced trailing commas on pass 2) interacting differently with optional
# parentheses. Admittedly ugly.
if src_contents != dst_contents:
- return _format_str_once(dst_contents, mode=mode)
+ if lines is not None:
+ lines = ink_adjusted_lines.adjusted_lines(lines, src_contents, dst_contents)
+ return _format_str_once(dst_contents, mode=mode, lines=lines)
return dst_contents
-def _format_str_once(src_contents: str, *, mode: Mode) -> str:
+def _format_str_once(
+ src_contents: str,
+ *,
+ mode: Mode,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
+) -> str:
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
dst_blocks: List[LinesBlock] = []
if mode.target_versions:
@@ -1095,6 +1208,8 @@ def _format_str_once(src_contents: str,
future_imports = get_future_imports(src_node)
versions = detect_target_versions(src_node, future_imports=future_imports)
+ if mode.string_normalization and mode.quote_style == QuoteStyle.MAJORITY:
+ mode = replace(mode, majority_quote=ink.majority_quote(src_node))
context_manager_features = {
feature
for feature in {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
@@ -1103,7 +1218,12 @@ def _format_str_once(src_contents: str,
if supports_feature(versions, feature)
}
normalize_fmt_off(src_node)
- lines = LineGenerator(mode=mode, features=context_manager_features)
+
+ if lines:
+ # This should be called after normalize_fmt_off.
+ ink.convert_unchanged_lines(src_node, lines)
+
+ line_generator = LineGenerator(mode=mode, features=context_manager_features)
elt = EmptyLineTracker(mode=mode)
split_line_features = {
feature
@@ -1111,7 +1231,7 @@ def _format_str_once(src_contents: str,
if supports_feature(versions, feature)
}
block: Optional[LinesBlock] = None
- for current_line in lines.visit(src_node):
+ for current_line in line_generator.visit(src_node):
block = elt.maybe_empty_lines(current_line)
dst_blocks.append(block)
for line in transform_line(
@@ -1379,12 +1499,20 @@ def assert_equivalent(src: str, dst: str
) from None
-def assert_stable(src: str, dst: str, mode: Mode) -> None:
+def assert_stable(
+ src: str,
+ dst: str,
+ mode: Mode,
+ *,
+ lines: Optional[Collection[Tuple[int, int]]] = None,
+) -> None:
"""Raise AssertionError if `dst` reformats differently the second time."""
# We shouldn't call format_str() here, because that formats the string
# twice and may hide a bug where we bounce back and forth between two
# versions.
- newdst = _format_str_once(dst, mode=mode)
+ if lines is not None:
+ lines = ink_adjusted_lines.adjusted_lines(lines, src, dst)
+ newdst = _format_str_once(dst, mode=mode, lines=lines)
if dst != newdst:
log = dump_to_file(
str(mode),
--- a/_width_table.py
+++ b/_width_table.py
@@ -3,7 +3,7 @@
# Unicode 15.0.0
from typing import Final, List, Tuple
-WIDTH_TABLE: Final[List[Tuple[int, int, int]]] = [
+WIDTH_TABLE: Final[Tuple[Tuple[int, int, int], ...]] = (
(0, 0, 0),
(1, 31, -1),
(127, 159, -1),
@@ -475,4 +475,4 @@ WIDTH_TABLE: Final[List[Tuple[int, int,
(131072, 196605, 2),
(196608, 262141, 2),
(917760, 917999, 0),
-]
+)
--- a/linegen.py
+++ b/linegen.py
@@ -8,6 +8,11 @@ from enum import Enum, auto
from functools import partial, wraps
from typing import Collection, Iterator, List, Optional, Set, Union, cast
+if sys.version_info < (3, 8):
+ from typing_extensions import Final, Literal
+else:
+ from typing import Final, Literal
+
from pyink.brackets import (
COMMA_PRIORITY,
DOT_PRIORITY,
@@ -16,6 +21,7 @@ from pyink.brackets import (
)
from pyink.comments import FMT_OFF, generate_comments, list_comments
from pyink.lines import (
+ Indentation,
Line,
RHSResult,
append_leaves,
@@ -84,6 +90,15 @@ LeafID = int
LN = Union[Leaf, Node]
+# Use a single-value enum as a sentinel object so that we could use it
+# inside a `Literal[]`.
+class _Dedent(Enum):
+ _DEDENT = auto()
+
+
+_DEDENT = _Dedent._DEDENT
+
+
class CannotSplit(CannotTransform):
"""A readable split that fits the allotted line length is impossible."""
@@ -103,7 +118,9 @@ class LineGenerator(Visitor[Line]):
self.current_line: Line
self.__post_init__()
- def line(self, indent: int = 0) -> Iterator[Line]:
+ def line(
+ self, indent: Union[Indentation, Literal[_Dedent._DEDENT], None] = None
+ ) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense.
@@ -112,7 +129,10 @@ class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
- self.current_line.depth += indent
+ if indent is _DEDENT:
+ self.current_line.depth = self.current_line.depth[:-1]
+ elif indent is not None:
+ self.current_line.depth = self.current_line.depth + (indent,)
return # Line is empty, don't emit. Creating a new one unnecessary.
if (
@@ -127,7 +147,13 @@ class LineGenerator(Visitor[Line]):
return
complete_line = self.current_line
- self.current_line = Line(mode=self.mode, depth=complete_line.depth + indent)
+ if indent is _DEDENT:
+ depth = complete_line.depth[:-1]
+ elif indent is not None:
+ depth = complete_line.depth + (indent,)
+ else:
+ depth = complete_line.depth
+ self.current_line = Line(mode=self.mode, depth=depth)
yield complete_line
def visit_default(self, node: LN) -> Iterator[Line]:
@@ -153,7 +179,9 @@ class LineGenerator(Visitor[Line]):
normalize_prefix(node, inside_brackets=any_open_brackets)
if self.mode.string_normalization and node.type == token.STRING:
node.value = normalize_string_prefix(node.value)
- node.value = normalize_string_quotes(node.value)
+ node.value = normalize_string_quotes(
+ node.value, preferred_quote=self.mode.preferred_quote
+ )
if node.type == token.NUMBER:
normalize_numeric_literal(node)
if node.type not in WHITESPACE:
@@ -163,7 +191,10 @@ class LineGenerator(Visitor[Line]):
def visit_test(self, node: Node) -> Iterator[Line]:
"""Visit an `x if y else z` test"""
- if Preview.parenthesize_conditional_expressions in self.mode:
+ if (
+ Preview.parenthesize_conditional_expressions in self.mode
+ and not self.mode.is_pyink
+ ):
already_parenthesized = (
node.prev_sibling and node.prev_sibling.type == token.LPAR
)
@@ -179,7 +210,7 @@ class LineGenerator(Visitor[Line]):
def visit_INDENT(self, node: Leaf) -> Iterator[Line]:
"""Increase indentation level, maybe yield a line."""
# In blib2to3 INDENT never holds comments.
- yield from self.line(+1)
+ yield from self.line(Indentation.SCOPE)
yield from self.visit_default(node)
def visit_DEDENT(self, node: Leaf) -> Iterator[Line]:
@@ -194,7 +225,7 @@ class LineGenerator(Visitor[Line]):
yield from self.visit_default(node)
# Finally, emit the dedent.
- yield from self.line(-1)
+ yield from self.line(_DEDENT)
def visit_stmt(
self, node: Node, keywords: Set[str], parens: Set[str]
@@ -306,9 +337,9 @@ class LineGenerator(Visitor[Line]):
) and is_stub_body(node):
yield from self.visit_default(node)
else:
- yield from self.line(+1)
+ yield from self.line(Indentation.SCOPE)
yield from self.visit_default(node)
- yield from self.line(-1)
+ yield from self.line(_DEDENT)
else:
if (
@@ -419,10 +450,13 @@ class LineGenerator(Visitor[Line]):
yield from self.visit_default(node)
def visit_STRING(self, leaf: Leaf) -> Iterator[Line]:
- if Preview.hex_codes_in_unicode_sequences in self.mode:
+ if (
+ Preview.hex_codes_in_unicode_sequences in self.mode
+ and not self.mode.is_pyink
+ ):
normalize_unicode_escape_sequences(leaf)
- if is_docstring(leaf) and "\\\n" not in leaf.value:
+ if is_docstring(leaf, self.mode.is_pyink) and "\\\n" not in leaf.value:
# We're ignoring docstrings with backslash newline escapes because changing
# indentation of those changes the AST representation of the code.
if self.mode.string_normalization:
@@ -433,7 +467,9 @@ class LineGenerator(Visitor[Line]):
# formatting as visit_default() is called *after*. To avoid a
# situation where this function formats a docstring differently on
# the second pass, normalize it early.
- docstring = normalize_string_quotes(docstring)
+ docstring = normalize_string_quotes(
+ docstring, preferred_quote=self.mode.preferred_quote
+ )
else:
docstring = leaf.value
prefix = get_string_prefix(docstring)
@@ -447,8 +483,9 @@ class LineGenerator(Visitor[Line]):
quote_len = 1 if docstring[1] != quote_char else 3
docstring = docstring[quote_len:-quote_len]
docstring_started_empty = not docstring
- indent = " " * 4 * self.current_line.depth
+ indent = " " * self.current_line.indentation_spaces()
+ original_has_trailing_newline = docstring.endswith("\n")
if is_multiline_string(leaf):
docstring = fix_docstring(docstring, indent)
else:
@@ -489,7 +526,13 @@ class LineGenerator(Visitor[Line]):
# If docstring is one line, we don't put the closing quotes on a
# separate line because it looks ugly (#3320).
lines = docstring.splitlines()
- last_line_length = len(lines[-1]) if docstring else 0
+ last_line_length = (
+ # When docstring ends with '\n' the last line is empty,
+ # not the last item from splitlines().
+ len(lines[-1])
+ if docstring and not docstring.endswith("\n")
+ else 0
+ )
# If adding closing quotes would cause the last line to exceed
# the maximum line length then put a line break before the
@@ -501,6 +544,15 @@ class LineGenerator(Visitor[Line]):
and not has_trailing_backslash
):
leaf.value = prefix + quote + docstring + "\n" + indent + quote
+ elif (
+ not indent
+ and len(lines) > 1
+ and not docstring.endswith("\n")
+ and original_has_trailing_newline
+ ):
+ # Special case for module docstrings that put trailing quotes on
+ # their own line.
+ leaf.value = prefix + quote + docstring + "\n" + indent + quote
else:
leaf.value = prefix + quote + docstring + quote
else:
@@ -535,7 +587,8 @@ class LineGenerator(Visitor[Line]):
self.visit_expr_stmt = partial(v, keywords=Ø, parens=assignments)
self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
- self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
+ if not self.mode.is_pyink:
+ self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
self.visit_async_funcdef = self.visit_async_stmt
self.visit_decorated = self.visit_decorators
@@ -581,10 +634,19 @@ def transform_line(
ll = mode.line_length
sn = mode.string_normalization
- string_merge = StringMerger(ll, sn)
- string_paren_strip = StringParenStripper(ll, sn)
- string_split = StringSplitter(ll, sn)
- string_paren_wrap = StringParenWrapper(ll, sn)
+ preferred_quote = mode.preferred_quote
+ string_merge = StringMerger(
+ ll, sn, preferred_quote=preferred_quote, line_str=line_str
+ )
+ string_paren_strip = StringParenStripper(
+ ll, sn, preferred_quote=preferred_quote, line_str=line_str
+ )
+ string_split = StringSplitter(
+ ll, sn, preferred_quote=preferred_quote, line_str=line_str
+ )
+ string_paren_wrap = StringParenWrapper(
+ ll, sn, preferred_quote=preferred_quote, line_str=line_str
+ )
transformers: List[Transformer]
if (
@@ -793,8 +855,7 @@ def _first_right_hand_split(
omit: Collection[LeafID] = (),
) -> RHSResult:
"""Split the line into head, body, tail starting with the last bracket pair.
-
- Note: this function should not have side effects. It's relied upon by
+ Note: this function should not have side effects. It's replied upon by
_maybe_split_omitting_optional_parens to get an opinion whether to prefer
splitting on the right side of an assignment statement.
"""
@@ -823,12 +884,53 @@ def _first_right_hand_split(
tail_leaves.reverse()
body_leaves.reverse()
head_leaves.reverse()
+
+ opening_brackets: List[Leaf] = [opening_bracket]
+ closing_brackets: List[Leaf] = [closing_bracket]
+ body: Optional[Line] = None
+ if line.mode.is_pyink and not (
+ # Only look inside when it doesn't start with invisible parens.
+ opening_bracket.type == token.LPAR
+ and not opening_bracket.value
+ and closing_bracket.type == token.RPAR
+ and not closing_bracket.value
+ ):
+ # Find an inner body...
+ inner_body_leaves = list(body_leaves)
+ inner_opening_brackets: List[Leaf] = []
+ inner_closing_brackets: List[Leaf] = []
+ while (
+ len(inner_body_leaves) >= 2
+ and inner_body_leaves[0].type in OPENING_BRACKETS
+ and inner_body_leaves[-1].type in CLOSING_BRACKETS
+ and inner_body_leaves[-1].opening_bracket is inner_body_leaves[0]
+ ):
+ inner_opening_brackets.append(inner_body_leaves.pop(0))
+ inner_closing_brackets.insert(0, inner_body_leaves.pop())
+ if len(inner_body_leaves) < len(body_leaves):
+ inner_body = bracket_split_build_line(
+ inner_body_leaves,
+ line,
+ opening_brackets[0],
+ component=_BracketSplitComponent.body,
+ )
+ if inner_body.should_split_rhs or (
+ inner_body_leaves and inner_body_leaves[-1].type == token.COMMA
+ ):
+ # Only when the inner body itself will be split or ends with a comma,
+ # should we prefer not break immediately nested brackets.
+ body_leaves = inner_body_leaves
+ head_leaves.extend(inner_opening_brackets)
+ tail_leaves = inner_closing_brackets + tail_leaves
+ body = inner_body # No need to re-calculate body.
+
head = bracket_split_build_line(
head_leaves, line, opening_bracket, component=_BracketSplitComponent.head
)
- body = bracket_split_build_line(
- body_leaves, line, opening_bracket, component=_BracketSplitComponent.body
- )
+ if body is None:
+ body = bracket_split_build_line(
+ body_leaves, line, opening_bracket, component=_BracketSplitComponent.body
+ )
tail = bracket_split_build_line(
tail_leaves, line, opening_bracket, component=_BracketSplitComponent.tail
)
@@ -987,7 +1089,7 @@ def bracket_split_build_line(
result = Line(mode=original.mode, depth=original.depth)
if component is _BracketSplitComponent.body:
result.inside_brackets = True
- result.depth += 1
+ result.depth = result.depth + (Indentation.CONTINUATION,)
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
@@ -1018,6 +1120,13 @@ def bracket_split_build_line(
and leaves[0].parent.next_sibling
and leaves[0].parent.next_sibling.type == token.VBAR
)
+ # Except the false negatives above for PEP 604 unions where we
+ # can't add the comma.
+ and not (
+ leaves[0].parent
+ and leaves[0].parent.next_sibling
+ and leaves[0].parent.next_sibling.type == token.VBAR
+ )
)
if original.is_import or no_commas:
@@ -1558,7 +1667,7 @@ def generate_trailers_to_omit(line: Line
if not line.magic_trailing_comma:
yield omit
- length = 4 * line.depth
+ length = line.indentation_spaces()
opening_bracket: Optional[Leaf] = None
closing_bracket: Optional[Leaf] = None
inner_brackets: Set[LeafID] = set()
--- a/lines.py
+++ b/lines.py
@@ -1,5 +1,7 @@
+from enum import Enum, auto
import itertools
import math
+import re
import sys
from dataclasses import dataclass, field
from typing import (
@@ -44,13 +46,28 @@ Index = int
LeafID = int
LN = Union[Leaf, Node]
+# This regex should contain a single capture group capturing the entire match.
+_PRAGMA_REGEX = re.compile("( *# (?:pylint|pytype):)")
+
+
+class Indentation(Enum):
+ SCOPE = auto() # Scope indentation.
+ CONTINUATION = auto() # Continuation/hanging indentation.
+
+ def num_spaces(self, mode: Mode) -> int:
+ if mode.is_pyink and self == Indentation.SCOPE:
+ return mode.pyink_indentation
+ else:
+ # Both pyink and black use 4 spaces for continuations.
+ return 4
+
@dataclass
class Line:
"""Holds leaves and comments. Can be printed with `str(line)`."""
mode: Mode = field(repr=False)
- depth: int = 0
+ depth: Tuple[Indentation, ...] = field(default_factory=tuple)
leaves: List[Leaf] = field(default_factory=list)
# keys ordered like `leaves`
comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
@@ -59,6 +76,9 @@ class Line:
should_split_rhs: bool = False
magic_trailing_comma: Optional[Leaf] = None
+ def indentation_spaces(self) -> int:
+ return sum(d.num_spaces(self.mode) for d in self.depth)
+
def append(
self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False
) -> None:
@@ -101,7 +121,7 @@ class Line:
Raises ValueError when any `leaf` is appended after a standalone comment
or when a standalone comment is not the first leaf on the line.
"""
- if self.bracket_tracker.depth == 0:
+ if not self.bracket_tracker.depth:
if self.is_comment:
raise ValueError("cannot append to standalone comments")
@@ -308,6 +328,20 @@ class Line:
return False
+ def trailing_pragma_comment_length(self) -> int:
+ if not self.leaves:
+ return 0
+
+ last_leaf = self.leaves[-1]
+ length = 0
+ for comment in self.comments.get(id(last_leaf), []):
+ # str(comment) contains the whitespace preceding the `#`
+ comment_str = str(comment)
+ parts = _PRAGMA_REGEX.split(comment_str, maxsplit=1)
+ if len(parts) == 3:
+ length += len(parts[1]) + len(parts[2])
+ return length
+
def contains_multiline_strings(self) -> bool:
return any(is_multiline_string(leaf) for leaf in self.leaves)
@@ -475,7 +509,7 @@ class Line:
if not self:
return "\n"
- indent = " " * self.depth
+ indent = " " * self.indentation_spaces()
leaves = iter(self.leaves)
first = next(leaves)
res = f"{first.prefix}{indent}{first.value}"
@@ -561,6 +595,7 @@ class EmptyLineTracker:
and self.previous_block.previous_block is None
and len(self.previous_block.original_line.leaves) == 1
and self.previous_block.original_line.is_triple_quoted_string
+ and not (current_line.is_class or current_line.is_def)
):
before = 1
@@ -591,7 +626,7 @@ class EmptyLineTracker:
def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
max_allowed = 1
- if current_line.depth == 0:
+ if not current_line.depth:
max_allowed = 1 if self.mode.is_pyi else 2
if current_line.leaves:
# Consume the first leaf's extra newlines.
@@ -606,7 +641,7 @@ class EmptyLineTracker:
depth = current_line.depth
previous_def = None
- while self.previous_defs and self.previous_defs[-1].depth >= depth:
+ while self.previous_defs and len(self.previous_defs[-1].depth) >= len(depth):
previous_def = self.previous_defs.pop()
if previous_def is not None:
@@ -655,10 +690,25 @@ class EmptyLineTracker:
if (
self.previous_line
- and self.previous_line.is_import
+ and (
+ self.previous_line.is_import
+ or self.previous_line.is_fmt_pass_converted(
+ first_leaf_matches=is_import
+ )
+ )
and not current_line.is_import
+ and not (
+ # Should not add empty lines before a STANDALONE_COMMENT.
+ current_line.is_comment
+ and not current_line.is_fmt_pass_converted()
+ )
+ and not (
+ # Should not add empty lines between fmt pass lines.
+ current_line.is_fmt_pass_converted()
+ and self.previous_line.is_fmt_pass_converted()
+ )
and not current_line.is_fmt_pass_converted(first_leaf_matches=is_import)
- and depth == self.previous_line.depth
+ and len(depth) == len(self.previous_line.depth)
):
return (before or 1), 0
@@ -671,6 +721,14 @@ class EmptyLineTracker:
return 0, 1
return before, 1
+ if (
+ self.mode.is_pyink
+ and self.previous_line
+ and self.previous_line.is_class
+ and current_line.is_comment
+ ):
+ return before, 0
+
if self.previous_line and self.previous_line.opens_block:
return 0, 0
return before, 0
@@ -691,15 +749,16 @@ class EmptyLineTracker:
return 0, 0
- if self.previous_line.depth < current_line.depth and (
- self.previous_line.is_class or self.previous_line.is_def
+ if len(self.previous_line.depth) < len(current_line.depth) and (
+ (not self.mode.is_pyink and self.previous_line.is_class)
+ or self.previous_line.is_def
):
return 0, 0
comment_to_add_newlines: Optional[LinesBlock] = None
if (
self.previous_line.is_comment
- and self.previous_line.depth == current_line.depth
+ and len(self.previous_line.depth) == len(current_line.depth)
and before == 0
):
slc = self.semantic_leading_comment
@@ -716,9 +775,9 @@ class EmptyLineTracker:
if self.mode.is_pyi:
if current_line.is_class or self.previous_line.is_class:
- if self.previous_line.depth < current_line.depth:
+ if len(self.previous_line.depth) < len(current_line.depth):
newlines = 0
- elif self.previous_line.depth > current_line.depth:
+ elif len(self.previous_line.depth) > len(current_line.depth):
newlines = 1
elif current_line.is_stub_class and self.previous_line.is_stub_class:
# No blank line between classes with an empty body
@@ -747,7 +806,7 @@ class EmptyLineTracker:
# Blank line between a block of functions (maybe with preceding
# decorators) and a block of non-functions
newlines = 1
- elif self.previous_line.depth > current_line.depth:
+ elif len(self.previous_line.depth) > len(current_line.depth):
newlines = 1
else:
newlines = 0
@@ -815,10 +874,14 @@ def is_line_short_enough( # noqa: C901
line_str = line_to_string(line)
width = str_width if mode.preview else len
+ if line.mode.is_pyink:
+ effective_length = width(line_str) - line.trailing_pragma_comment_length()
+ else:
+ effective_length = width(line_str)
if Preview.multiline_string_handling not in mode:
return (
- width(line_str) <= mode.line_length
+ effective_length <= mode.line_length
and "\n" not in line_str # multiline strings
and not line.contains_standalone_comments()
)
@@ -827,7 +890,7 @@ def is_line_short_enough( # noqa: C901
return False
if "\n" not in line_str:
# No multiline strings (MLS) present
- return width(line_str) <= mode.line_length
+ return effective_length <= mode.line_length
first, *_, last = line_str.split("\n")
if width(first) > mode.line_length or width(last) > mode.line_length:
@@ -1017,7 +1080,7 @@ def can_omit_invisible_parens(
def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
"""See `can_omit_invisible_parens`."""
remainder = False
- length = 4 * line.depth
+ length = line.indentation_spaces()
_index = -1
for _index, leaf, leaf_length in line.enumerate_with_length():
if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
@@ -1041,7 +1104,7 @@ def _can_omit_opening_paren(line: Line,
def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
"""See `can_omit_invisible_parens`."""
- length = 4 * line.depth
+ length = line.indentation_spaces()
seen_other_brackets = False
for _index, leaf, leaf_length in line.enumerate_with_length():
length += leaf_length
--- a/mode.py
+++ b/mode.py
@@ -8,7 +8,7 @@ from dataclasses import dataclass, field
from enum import Enum, auto
from hashlib import sha256
from operator import attrgetter
-from typing import Dict, Final, Set
+from typing import Dict, Final, Literal, Set
from warnings import warn
from pyink.const import DEFAULT_LINE_LENGTH
@@ -196,11 +196,33 @@ class Deprecated(UserWarning):
"""Visible deprecation warning."""
+class Quote(Enum):
+ SINGLE = "'"
+ DOUBLE = '"'
+
+ def cache_key(self) -> str:
+ # On Windows, paths can't contain a double quote.
+ if self == Quote.SINGLE:
+ return "0"
+ else:
+ return "1"
+
+
+class QuoteStyle(Enum):
+ SINGLE = auto()
+ DOUBLE = auto()
+ MAJORITY = auto()
+
+
@dataclass
class Mode:
target_versions: Set[TargetVersion] = field(default_factory=set)
line_length: int = DEFAULT_LINE_LENGTH
string_normalization: bool = True
+ # No effect if string_normalization is False
+ quote_style: QuoteStyle = QuoteStyle.DOUBLE
+ # Overridden later when quote_style is MAJORITY
+ majority_quote: Quote = Quote.DOUBLE
is_pyi: bool = False
is_ipynb: bool = False
skip_source_first_line: bool = False
@@ -208,6 +230,8 @@ class Mode:
experimental_string_processing: bool = False
python_cell_magics: Set[str] = field(default_factory=set)
preview: bool = False
+ is_pyink: bool = False
+ pyink_indentation: Literal[2, 4] = 4