-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwalrus.py
More file actions
2069 lines (1598 loc) · 78.5 KB
/
walrus.py
File metadata and controls
2069 lines (1598 loc) · 78.5 KB
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
# -*- coding: utf-8 -*-
"""Back-port compiler for Python 3.8 assignment expressions."""
import argparse
import os
import pathlib
import re
import sys
import traceback
from typing import Dict, Generator, List, Optional, Union
import f2format
import parso.python.tree
import parso.tree
import tbtrim
from bpc_utils import (BaseContext, BPCSyntaxError, Config, TaskLock, archive_files,
detect_encoding, detect_files, detect_indentation, detect_linesep,
first_non_none, get_parso_grammar_versions, map_tasks, parse_boolean_state,
parse_indentation, parse_linesep, parse_positive_integer, parso_parse,
recover_files)
from bpc_utils import Linesep
from typing_extensions import Literal, TypedDict, final
__all__ = ['main', 'walrus', 'convert']
# version string
__version__ = '0.1.5'
###############################################################################
# Types for annotation
ScopeKeyword = Literal['global', 'nonlocal']
class WalrusConfig(Config):
indentation = '' # type: str
linesep = '\n' # type: Literal[Linesep]
pep8 = True # type: bool
filename = None # Optional[str]
source_version = None # Optional[str]
FunctionEntry = TypedDict('FunctionEntry', {
'name': str,
'uuid': str,
'scope_keyword': ScopeKeyword,
})
LambdaEntry = TypedDict('LambdaEntry', {
'param': str,
'suite': str,
'uuid': str,
})
###############################################################################
# Auxiliaries
#: Get supported source versions.
#:
#: .. seealso:: :func:`bpc_utils.get_parso_grammar_versions`
WALRUS_SOURCE_VERSIONS = get_parso_grammar_versions(minimum='3.8')
# option default values
#: Default value for the ``quiet`` option.
_default_quiet = False
#: Default value for the ``concurrency`` option.
_default_concurrency = None # auto detect
#: Default value for the ``do_archive`` option.
_default_do_archive = True
#: Default value for the ``archive_path`` option.
_default_archive_path = 'archive'
#: Default value for the ``source_version`` option.
_default_source_version = WALRUS_SOURCE_VERSIONS[-1]
#: Default value for the ``linesep`` option.
_default_linesep = None # auto detect
#: Default value for the ``indentation`` option.
_default_indentation = None # auto detect
#: Default value for the ``pep8`` option.
_default_pep8 = True
# option getter utility functions
# option value precedence is: explicit value (CLI/API arguments) > environment variable > default value
def _get_quiet_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``quiet`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``quiet`` option
:Environment Variables:
:envvar:`WALRUS_QUIET` -- the value in environment variable
See Also:
:data:`_default_quiet`
"""
# We need short circuit evaluation, so first_non_none(a, b, c) does not work here
# with PEP 505 we can simply write a ?? b ?? c
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('WALRUS_QUIET'))
yield _default_quiet
return first_non_none(_option_layers())
def _get_concurrency_option(explicit: Optional[int] = None) -> Optional[int]:
"""Get the value for the ``concurrency`` option.
Args:
explicit (Optional[int]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[int]: the value for the ``concurrency`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`WALRUS_CONCURRENCY` -- the value in environment variable
See Also:
:data:`_default_concurrency`
"""
return parse_positive_integer(explicit or os.getenv('WALRUS_CONCURRENCY') or _default_concurrency)
def _get_do_archive_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``do_archive`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``do_archive`` option
:Environment Variables:
:envvar:`WALRUS_DO_ARCHIVE` -- the value in environment variable
See Also:
:data:`_default_do_archive`
"""
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('WALRUS_DO_ARCHIVE'))
yield _default_do_archive
return first_non_none(_option_layers())
def _get_archive_path_option(explicit: Optional[str] = None) -> str:
"""Get the value for the ``archive_path`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
str: the value for the ``archive_path`` option
:Environment Variables:
:envvar:`WALRUS_ARCHIVE_PATH` -- the value in environment variable
See Also:
:data:`_default_archive_path`
"""
return explicit or os.getenv('WALRUS_ARCHIVE_PATH') or _default_archive_path
def _get_source_version_option(explicit: Optional[str] = None) -> Optional[str]:
"""Get the value for the ``source_version`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
str: the value for the ``source_version`` option
:Environment Variables:
:envvar:`WALRUS_SOURCE_VERSION` -- the value in environment variable
See Also:
:data:`_default_source_version`
"""
return explicit or os.getenv('WALRUS_SOURCE_VERSION') or _default_source_version
def _get_linesep_option(explicit: Optional[str] = None) -> Optional[Linesep]:
r"""Get the value for the ``linesep`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[Literal['\\n', '\\r\\n', '\\r']]: the value for the ``linesep`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`WALRUS_LINESEP` -- the value in environment variable
See Also:
:data:`_default_linesep`
"""
return parse_linesep(explicit or os.getenv('WALRUS_LINESEP') or _default_linesep)
def _get_indentation_option(explicit: Optional[Union[str, int]] = None) -> Optional[str]:
"""Get the value for the ``indentation`` option.
Args:
explicit (Optional[Union[str, int]]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[str]: the value for the ``indentation`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`WALRUS_INDENTATION` -- the value in environment variable
See Also:
:data:`_default_indentation`
"""
return parse_indentation(explicit or os.getenv('WALRUS_INDENTATION') or _default_indentation)
def _get_pep8_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``pep8`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``pep8`` option
:Environment Variables:
:envvar:`WALRUS_PEP8` -- the value in environment variable
See Also:
:data:`_default_pep8`
"""
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('WALRUS_PEP8'))
yield _default_pep8
return first_non_none(_option_layers())
###############################################################################
# Traceback Trimming (tbtrim)
# root path
ROOT = pathlib.Path(__file__).resolve().parent
def predicate(filename: str) -> bool:
return pathlib.Path(filename).parent == ROOT
tbtrim.set_trim_rule(predicate, strict=True, target=BPCSyntaxError)
###############################################################################
# Main Conversion Implementation
# walrus wrapper template
NAME_TEMPLATE = '''\
if False:
%(indentation)s%(name_list)s = NotImplemented
'''.splitlines() # `str.splitlines` will remove trailing newline
CALL_TEMPLATE = '_walrus_wrapper_%(name)s_%(uuid)s(%(expr)s)'
FUNC_TEMPLATE = '''\
def _walrus_wrapper_%(name)s_%(uuid)s(expr):
%(indentation)s"""Wrapper function for assignment expression."""
%(indentation)s%(scope_keyword)s %(name)s
%(indentation)s%(name)s = expr
%(indentation)sreturn %(name)s
'''.splitlines() # `str.splitlines` will remove trailing newline
# special template for lambda
LAMBDA_CALL_TEMPLATE = '_walrus_wrapper_lambda_%(uuid)s'
LAMBDA_FUNC_TEMPLATE = '''\
def _walrus_wrapper_lambda_%(uuid)s(%(param)s):
%(indentation)s"""Wrapper function for lambda definitions."""
%(indentation)s%(suite)s
'''.splitlines() # `str.splitlines` will remove trailing newline
# special templates for ClassVar
CLS_TEMPLATE = "(__import__('builtins').locals().__setitem__(%(name)r, %(expr)s), %(name)s)[1]"
class Context(BaseContext):
"""General conversion context.
Args:
node (parso.tree.NodeOrLeaf): parso AST
config (Config): conversion configurations
Keyword Args:
indent_level (int): current indentation level
scope_keyword (Optional[Literal['global', 'nonlocal']]): scope keyword for wrapper function
context (Optional[List[str]]): global context (:term:`namespace`)
raw (bool): raw processing flag
Important:
``raw`` should be :data:`True` only if the ``node`` is in the clause of another *context*,
where the converted wrapper functions should be inserted.
Typically, only if ``node`` is an assignment expression (:token:`namedexpr_test`) node,
``raw`` will be set as :data:`True`, in consideration of nesting assignment expressions.
For the :class:`Context` class of :mod:`walrus` module,
it will process nodes with following methods:
* :token:`suite`
- :meth:`Context._process_suite_node`
- :meth:`ClassContext._process_suite_node`
* :token:`namedexpr_test`
- :meth:`Context._process_namedexpr_test`
- :meth:`ClassContext._process_namedexpr_test`
* :token:`global_stmt`
- :meth:`Context._process_global_stmt`
- :meth:`ClassContext._process_global_stmt`
* :token:`classdef`
- :meth:`Context._process_classdef`
* :token:`funcdef`
- :meth:`Context._process_funcdef`
* :token:`lambdef`
- :meth:`Context._process_lambdef`
* :token:`if_stmt`
- :meth:`Context._process_if_stmt`
* :token:`while_stmt`
- :meth:`Context._process_while_stmt`
* :token:`for_stmt`
- :meth:`Context._process_for_stmt`
* :token:`with_stmt`
- :meth:`Context._process_with_stmt`
* :token:`try_stmt`
- :meth:`Context._process_try_stmt`
* :token:`argument`
- :meth:`Context._process_argument`
* :token:`name`
- :meth:`ClassContext._process_defined_name`
* :token:`nonlocal_stmt`
- :meth:`ClassContext._process_nonlocal_stmt`
* :token:`stringliteral`
* :meth:`Context._process_strings`
* :meth:`Context._process_string_context`
* :meth:`ClassContext._process_strings`
* :meth:`ClassContext._process_string_context`
* :token:`f_string`
* :meth:`Context._process_fstring`
* :meth:`ClassContext._process_fstring`
"""
@final
@property
def lambdef(self) -> List[LambdaEntry]:
"""Lambda definitions (:attr:`self._lamb <walrus.Context._lamb>`).
:rtype: List[LambdaEntry]
"""
return self._lamb
@final
@property
def variables(self) -> List[str]:
"""Assignment expression variable records (:attr:`self._vars <walrus.Context._vars>`).
The variables are the *left-hand-side* variable name of the assignment expressions.
:rtype: List[str]
"""
return self._vars
@final
@property
def functions(self) -> List[FunctionEntry]:
"""Assignment expression wrapper function records (:attr:`self._func <walrus.ontext._func>`).
:rtype: List[FunctionEntry]
"""
return self._func
@final
@property
def global_stmt(self) -> List[str]:
"""List of variables declared in the :token:`global <global_stmt>` statements.
If current root node (:attr:`self._root <walrus.Context._root>`) is a function definition
(:class:`parso.python.tree.Function`), then returns an empty list; else returns
:attr:`self._context <walrus.Context._context>`.
:rtype: List[str]
"""
if self._root.type == 'funcdef':
return []
return self._context
def __init__(self, node: parso.tree.NodeOrLeaf, config: WalrusConfig, *,
indent_level: int = 0, scope_keyword: Optional[ScopeKeyword] = None,
context: Optional[List[str]] = None, raw: bool = False):
if scope_keyword is None:
scope_keyword = self.determine_scope_keyword(node)
if context is None:
context = []
#: Literal['global', 'nonlocal']:
#: The :token:`global <global_stmt>` / :token:`nonlocal <nonlocal_stmt>` keyword.
self._scope_keyword = scope_keyword # type: ScopeKeyword
#: List[str]: Variable names in :token:`global <global_stmt>` statements.
self._context = list(context) # type: List[str]
#: List[str]: Original *left-hand-side* variable names in assignment expressions.
self._vars = [] # type: List[str]
#: List[LambdaEntry]: Converted *lambda* expressions described as :class:`LambdaEntry`.
self._lamb = [] # type: List[LambdaEntry]
#: List[FunctionEntry]: Converted wrapper functions described as :class:`FunctionEntry`.
self._func = [] # type: List[FunctionEntry]
# call super init
super().__init__(node, config, indent_level=indent_level, raw=raw)
def _process_suite_node(self, node: parso.tree.NodeOrLeaf, func: bool = False,
raw: bool = False, cls_ctx: Optional[str] = None) -> None:
"""Process indented suite (:token:`suite` or others).
Args:
node (parso.tree.NodeOrLeaf): suite node
func (bool): if ``node`` is suite from function definition
raw (bool): raw processing flag
cls_ctx (Optional[str]): class name if ``node`` is in class context
This method first checks if ``node`` contains assignment expression.
If not, it will not perform any processing, rather just append the
original source code to context buffer.
If ``node`` contains assignment expression, then it will initialise another
:class:`Context` instance to perform the conversion process on such
``node``; whilst if ``cls_ctx`` is provided, then it will initialise a
:class:`ClassContext` instance instead.
Note:
If ``func`` is True, when initiating the :class:`Context` instance,
``scope_keyword`` will be set as ``'nonlocal'``, as in the wrapper function
it will refer the original *left-hand-side* variable from the outer
function scope rather than global namespace.
The method will keep *global* statements (:meth:`Context.global_stmt`)
from the temporary :class:`Context` (or :class:`ClassContext`) instance in the
current instance.
And if ``raw`` is set as :data:`True`, the method will keep records of converted wrapper
functions (:meth:`Context.functions`), converted *lambda* expressions (:meth:`Context.lambdef`)
and *left-hand-side* variable names (:meth:`Context.variables`) into current instance as well.
Important:
``raw`` should be :data:`True` only if the ``node`` is in the clause of another *context*,
where the converted wrapper functions should be inserted.
"""
if not self.has_expr(node):
self += node.get_code()
return
indent = self._indent_level + 1
self += self._linesep + self._indentation * indent
if func:
scope_keyword = 'nonlocal' # type: ScopeKeyword
else:
scope_keyword = self._scope_keyword
# process suite
if cls_ctx is None:
ctx = Context(node=node, config=self.config, # type: ignore[arg-type]
context=self._context, indent_level=indent,
scope_keyword=scope_keyword, raw=raw)
else:
ctx = ClassContext(cls_ctx=cls_ctx,
node=node, config=self.config, # type: ignore[arg-type]
context=self._context, indent_level=indent,
scope_keyword=scope_keyword, raw=raw)
self += ctx.string.lstrip()
# keep records
if raw:
self._lamb.extend(ctx.lambdef)
self._vars.extend(ctx.variables)
self._func.extend(ctx.functions)
self._context.extend(ctx.global_stmt)
def _process_string_context(self, node: parso.python.tree.PythonNode) -> None:
"""Process string contexts (:token:`stringliteral`).
Args:
node (parso.python.tree.PythonNode): string literals node
This method first checks if ``node`` contains assignment expression.
If not, it will not perform any processing, rather just append the
original source code to context buffer. Later it will check if
``node`` contains *debug f-string*. If not, it will process the
*regular* processing on each child of such ``node``.
See Also:
The method calls :meth:`f2format.Context.has_debug_fstring`
to detect *debug f-strings*.
Otherwise, it will initialise a new :class:`StringContext` instance
to perform the conversion process on such ``node``, which will first
use :mod:`f2format` to convert those formatted string literals.
Important:
When initialisation, ``raw`` parameter **must** be set to :data:`True`;
as the converted wrapper functions should be inserted in the *outer*
context, rather than the new :class:`StringContext` instance.
After conversion, the method will keep records of converted wrapper
functions (:meth:`Context.functions`), converted *lambda* expressions (:meth:`Context.lambdef`)
and *left-hand-side* variable names (:meth:`Context.variables`) into current instance as well.
"""
if not self.has_expr(node):
self += node.get_code()
return
if not f2format.Context.has_debug_fstring(node):
for child in node.children:
self._process(child)
return
# initialise new context
ctx = StringContext(node=node, config=self.config, context=self._context, # type: ignore[arg-type]
indent_level=self._indent_level, scope_keyword=self._scope_keyword, raw=True)
self += ctx.string
# keep record
self._lamb.extend(ctx.lambdef)
self._vars.extend(ctx.variables)
self._func.extend(ctx.functions)
self._context.extend(ctx.global_stmt)
def _process_namedexpr_test(self, node: parso.python.tree.PythonNode) -> None:
"""Process assignment expression (:token:`namedexpr_test`).
Args:
node (parso.python.tree.PythonNode): assignment expression node
This method converts the assignment expression into wrapper function
and extracts related records for inserting converted code.
* The *left-hand-side* variable name will be recorded in
:attr:`self._vars <walrus.Context._vars>`.
* The *right-hand-side* expression will be converted using another
:class:`Context` instance and replaced with a wrapper function call
rendered from :data:`CALL_TEMPLATE`; information described as
:class:`FunctionEntry` will be recorded into :attr:`self._func <walrus.Context._func>`.
"""
# split assignment expression
node_name, _, node_expr = node.children
name = node_name.value
nuid = self._uuid_gen.gen()
# calculate expression string
ctx = Context(node=node_expr, config=self.config, # type: ignore[arg-type]
context=self._context, indent_level=self._indent_level,
scope_keyword=self._scope_keyword, raw=True)
expr = ctx.string.strip()
self._vars.extend(ctx.variables)
self._func.extend(ctx.functions)
# replacing code
code = CALL_TEMPLATE % dict(name=name, uuid=nuid, expr=expr)
prefix, suffix = self.extract_whitespaces(node.get_code())
self += prefix + code + suffix
self._context.extend(ctx.global_stmt)
if name in self._context:
scope_keyword = 'global' # type: ScopeKeyword
else:
scope_keyword = self._scope_keyword
# keep records
self._vars.append(name)
self._func.append(dict(name=name, uuid=nuid, scope_keyword=scope_keyword))
def _process_global_stmt(self, node: parso.python.tree.GlobalStmt) -> None:
"""Process function definition (:token:`global_stmt`).
Args:
node (parso.python.tree.GlobalStmt): global statement node
This method records all variables declared in a *global* statement
into :attr:`self._context <walrus.Context._context>`.
"""
children = iter(node.children)
# <Keyword: global>
next(children)
# <Name: ...>
name = next(children)
self._context.append(name.value)
while True:
try:
# <Operator: ,>
next(children)
except StopIteration:
break
# <Name: ...>
name = next(children)
self._context.append(name.value)
# process code
self += node.get_code()
def _process_classdef(self, node: parso.python.tree.Class) -> None:
"""Process class definition (:token:`classdef`).
Args:
node (parso.python.tree.Class): class node
This method converts the whole class suite context with
:meth:`~Context._process_suite_node` through
:class:`ClassContext` respectively.
"""
# <Name: ...>
name = node.name
# <Keyword: class>
# <Name: ...>
# [<Operator: (>, PythonNode(arglist, [...]]), <Operator: )>]
# <Operator: :>
for child in node.children[:-1]:
self._process(child)
# PythonNode(suite, [...]) / PythonNode(simple_stmt, [...])
suite = node.children[-1]
self._process_suite_node(suite, cls_ctx=name.value)
def _process_funcdef(self, node: parso.python.tree.Function) -> None:
"""Process function definition (:token:`funcdef`).
Args:
node (parso.python.tree.Function): function node
This method converts the function suite with
:meth:`~Context._process_suite_node`.
"""
# 'def' NAME '(' PARAM ')' [ '->' NAME ] ':' SUITE
for child in node.children[:-1]:
self._process(child)
self._process_suite_node(node.children[-1], func=True)
def _process_lambdef(self, node: parso.python.tree.Lambda) -> None:
"""Process lambda definition (``lambdef``).
Args:
node (parso.python.tree.Lambda): lambda node
This method first checks if ``node`` contains assignment expressions.
If not, it will append the original source code directly to the buffer.
For *lambda* expressions with assignment expressions, this method
will extract the parameter list and initialise a :class:`LambdaContext`
instance to convert the lambda suite. Such information will be recorded
as :class:`LambdaEntry` in :attr:`self._lamb <Context._lamb>`.
.. note:: For :class:`LambdaContext`, ``scope_keyword`` should always be ``'nonlocal'``.
Then it will replace the original lambda expression with a wrapper function
call rendered from :data:`LAMBDA_CALL_TEMPLATE`.
"""
if not self.has_expr(node):
self += node.get_code()
return
children = iter(node.children)
# <Keyword: lambda>
next(children)
# vararglist
para_list = []
for child in children:
if child.type == 'operator' and child.value == ':':
break
para_list.append(child)
param = ''.join(map(lambda n: n.get_code(), para_list))
# test_nocond | test
indent = self._indent_level + 1
ctx = LambdaContext(node=next(children), config=self.config, # type: ignore[arg-type]
context=self._context, indent_level=indent,
scope_keyword='nonlocal')
suite = ctx.string.strip()
# keep record
nuid = self._uuid_gen.gen()
self._lamb.append(dict(param=param, suite=suite, uuid=nuid))
# replacing lambda
self += LAMBDA_CALL_TEMPLATE % dict(uuid=nuid)
def _process_if_stmt(self, node: parso.python.tree.IfStmt) -> None:
"""Process if statement (:token:`if_stmt`).
Args:
node (parso.python.tree.IfStmt): if node
This method processes each indented suite under the *if*, *elif*,
and *else* statements.
"""
children = iter(node.children)
# <Keyword: if>
self._process(next(children))
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
while True:
try:
# <Keyword: elif | else>
key = next(children)
except StopIteration:
break
self._process(key)
if key.value == 'elif':
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
continue
if key.value == 'else':
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
continue
def _process_while_stmt(self, node: parso.python.tree.WhileStmt) -> None:
"""Process while statement (:token:`while_stmt`).
Args:
node (parso.python.tree.WhileStmt): while node
This method processes the indented suite under the *while* and optional
*else* statements.
"""
children = iter(node.children)
# <Keyword: while>
self._process(next(children))
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
try:
key = next(children)
except StopIteration:
return
# <Keyword: else>
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _process_for_stmt(self, node: parso.python.tree.ForStmt) -> None:
"""Process for statement (:token:`for_stmt`).
Args:
node (parso.python.tree.ForStmt): for node
This method processes the indented suite under the *for* and optional
*else* statements.
"""
children = iter(node.children)
# <Keyword: for>
self._process(next(children))
# exprlist
self._process(next(children))
# <Keyword: in>
self._process(next(children))
# testlist
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
try:
key = next(children)
except StopIteration:
return
# <Keyword: else>
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _process_with_stmt(self, node: parso.python.tree.WithStmt) -> None:
"""Process with statement (:token:`with_stmt`).
Args:
node (parso.python.tree.WithStmt): with node
This method processes the indented suite under the *with* statement.
"""
children = iter(node.children)
# <Keyword: with>
self._process(next(children))
while True:
# with_item | <Operator: ,>
item = next(children)
self._process(item)
# <Operator: :>
if item.type == 'operator' and item.value == ':':
break
# suite
self._process_suite_node(next(children))
def _process_try_stmt(self, node: parso.python.tree.TryStmt) -> None:
"""Process try statement (:token:`try_stmt`).
Args:
node (parso.python.tree.TryStmt): try node
This method processes the indented suite under the *try*, *except*,
*else*, and *finally* statements.
"""
children = iter(node.children)
while True:
try:
key = next(children)
except StopIteration:
break
# <Keyword: try | else | finally> | PythonNode(except_clause, [...]
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _process_argument(self, node: parso.python.tree.PythonNode) -> None:
"""Process function argument (:token:`argument`).
Args:
node (parso.python.tree.PythonNode): argument node
This method processes arguments from function argument list.
"""
children = iter(node.children)
# test
test = next(children)
try:
# <Operator: :=>
op = next(children)
except StopIteration:
self._process(test)
return
if self.is_walrus(op):
self._process_namedexpr_test(node)
return
# not walrus
self._process(test)
self._process(op)
for child in children:
self._process(child)
def _process_strings(self, node: parso.python.tree.PythonNode) -> None:
"""Process concatenable strings (:token:`stringliteral`).
Args:
node (parso.python.tree.PythonNode): concatentable strings node
As in Python, adjacent string literals can be concatenated in certain
cases, as described in the `documentation`_. Such concatenable strings
may contain formatted string literals (:term:`f-string`) within its scope.
_documentation: https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation
"""
self._process_string_context(node)
def _process_fstring(self, node: parso.python.tree.PythonNode) -> None:
"""Process formatted strings (:token:`f_string`).
Args:
node (parso.python.tree.PythonNode): formatted strings node
"""
self._process_string_context(node)
def _concat(self) -> None:
"""Concatenate final string.
This method tries to inserted the recorded wrapper functions and variables
at the very location where starts to contain assignment expressions, i.e.
between the converted code as :attr:`self._prefix <Context._prefix>` and
:attr:`self._suffix <Context._suffix>`.
The inserted code include variable declaration rendered from
:data:`NAME_TEMPLATE`, wrapper function definitions rendered from
:data:`FUNC_TEMPLATE` and extracted *lambda* expressions rendered from
:data:`LAMBDA_FUNC_TEMPLATE`. If :attr:`self._pep8 <Context._pep8>` is
:data:`True`, it will insert the code in compliance with :pep:`8`.
"""
flag = any((self._vars, self._func, self._lamb)) # if have code to insert
# strip suffix comments
prefix, suffix = self.split_comments(self._suffix, self._linesep)
match = re.match(r'^(?P<linesep>(%s)*)' % self._linesep, suffix, flags=re.ASCII)
suffix_linesep = match.group('linesep') if match is not None else ''