/
filters.py
1823 lines (1472 loc) · 64 KB
/
filters.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
# coding:utf-8
'''
@author: ota
'''
import math
import re
import sys
from sqlparse import sql, tokens as T, utils
from sqlparse.filters import StripWhitespaceFilter, ReindentFilter
from uroborosqlfmt import tokenutils as tu, grouping
from uroborosqlfmt.exceptions import SqlFormatterException
from uroborosqlfmt.sql import Phrase
class StripWhitespaceAndToTabFilter(StripWhitespaceFilter):
"""
連続したwhitespaceを除去し、
Punctuation前後のwhitespaceも除去する
またwhitespaceはTab文字で統一する
"""
def process(self, stack, stmt, depth=0):
SqlFormatterException.wrap_try_except(
super(StripWhitespaceAndToTabFilter, self).process,
stmt,
stack,
stmt,
depth
)
def __custom_stripws_tokenlist(self, tlist):
"""
コメントとラインコメントの間のスペースを除去
"""
last_token = None
ws_tokens = []
for token in tlist.tokens[:]:
if tu.is_line_comment(token) and last_token and tu.is_comment(last_token):
for tws in ws_tokens:
tlist.tokens.remove(tws)
last_token = token
ws_tokens = []
elif token.is_whitespace():
ws_tokens.append(token)
else:
last_token = token
ws_tokens = []
def _stripws_default(self, tlist):
last_was_ws = False
last_ws_token = None
last_was_punctuation = False
for token in tlist.tokens[:]:
if token.is_whitespace():
if last_was_ws or last_was_punctuation: # 前tokenがwhitespaceまたはPunctuationの場合、空白を除去
tlist.tokens.remove(token)
continue
else:
token.value = "\t"
if tu.is_punctuation(token):
if last_ws_token:
tlist.tokens.remove(last_ws_token) # Punctuation前のwhitespaceを除去
last_was_ws = token.is_whitespace()
last_ws_token = token if last_was_ws else None
last_was_punctuation = tu.is_punctuation(token)
self.__custom_stripws_tokenlist(tlist)
def _stripws_identifierlist(self, tlist):
super(StripWhitespaceAndToTabFilter, self)._stripws_identifierlist(tlist)
self.__custom_stripws_tokenlist(tlist)
def _stripws_parenthesis(self, tlist):
super(StripWhitespaceAndToTabFilter, self)._stripws_parenthesis(tlist)
self.__custom_stripws_tokenlist(tlist)
class GroupFilter(object):
"""
グルーピング関連
"""
def process(self, _, stmt):
grouping.re_group(stmt)
grouping.group(stmt)
class LineDescriptionLineCommentFilter(object):
"""
ラインコメント行の説明を成しているか、次の説明を成しているか振り分ける
"""
class Comment(sql.Comment):
"""
置き換え用コメントクラスのラッパー
"""
__slots__ = ('is_line_description')
def __init__(self, local_config):
self.local_config = local_config
self.is_line_description = False
def process(self, _, stmt):
def custom_flaten(token):
"""
コメントはflatenしないflaten
"""
if isinstance(token, sql.TokenList) and not tu.is_comment(token):
for tkn in token.tokens:
for item in custom_flaten(tkn):
yield item
else:
yield token
is_prev_cr = True
for token in custom_flaten(stmt):
if tu.is_plain_line_comment(token, self.local_config.comment_syntax):
# コメントクラス置き換え
parent = token.parent
index = parent.tokens.index(token)
comment = LineDescriptionLineCommentFilter.Comment(token.tokens)
for tkn in token.tokens:
tkn.parent = comment
comment.parent = parent
parent.tokens[index] = comment
# フラグセット
comment.is_line_description = not is_prev_cr # pylint: disable=attribute-defined-outside-init
elif token.is_whitespace():
if is_inc_cr(token):
is_prev_cr = True
else:
is_prev_cr = False
class AdjustGroupFilter(object):
"""
グルーピング調整
"""
def __init__(self, local_config):
self.comment_syntax = local_config.comment_syntax
def process(self, _, stmt):
grouping.adj_group(stmt, self.comment_syntax)
class _LineObject(object):
def _rstrip(self, target_tokens, base_token):
for tkn in target_tokens[::-1]:
if tkn.is_whitespace():
base_token.tokens.remove(tkn)
target_tokens.remove(tkn)
else:
break
def _remove_indent(self, lines, indent):
for i, line in enumerate(lines):
for cval in line[:indent]:
if cval == "\t":
lines[i] = lines[i][1:]
else:
break
def _right_tokens_between(self, base_token, separetor, line_comment):
start = base_token.token_next(separetor) if separetor else base_token.tokens[0]
if not line_comment:
return base_token.tokens_between(start, base_token.tokens[-1])
else:
return base_token.tokens_between(start, line_comment, exclude_end=True)
def _get_linecomment(self, base_token, comment_syntax):
first_line_comment = None
for tkn in base_token.tokens[::-1]:
if tu.is_line_description_line_comment(tkn, comment_syntax):
first_line_comment = tkn
continue
if tkn.is_whitespace():
continue
if tu.is_comment(tkn):
continue
return first_line_comment
return None
class _BaseIdentifierObject(_LineObject):
"""
Identifier内部のインデント調整用のObject
"""
def __init__(self, token, indent, local_config):
self.token = token
self.center_token = None
self.line_comment = None
self.left_tokens = []
self.right_tokens = []
self.left_lines = []
self.right_lines = []
self.width_left = 0
self.width_right = 0
self.line_comment = self._get_linecomment(token, local_config.comment_syntax)
separetor = self._get_separetor_token(token)
if separetor:
self.center_token = self._get_center_token(token)
self.left_tokens = token.tokens_between(token.tokens[0], separetor, exclude_end=True)
self.right_tokens = self._right_tokens_between(token, separetor, self.line_comment)
self._rstrip(self.left_tokens, token)
self._rstrip(self.right_tokens, token)
lefts = utils.split_unquoted_newlines("".join([str(t) for t in self.left_tokens]))
rights = utils.split_unquoted_newlines("".join([str(t) for t in self.right_tokens]))
self._remove_indent(lefts, indent)
self._remove_indent(rights, indent)
self.width_left = get_need_tab_char_width(lefts[-1])
self.width_right = get_need_tab_char_width(rights[-1])
self.left_lines = lefts
self.right_lines = rights
else:
self.left_tokens = self._right_tokens_between(token, None, self.line_comment)
self._rstrip(self.left_tokens, token)
lefts = utils.split_unquoted_newlines("".join([str(t) for t in self.left_tokens]))
self._remove_indent(lefts, indent)
self.width_left = get_need_tab_char_width(lefts[-1])
self.left_lines = lefts
def _get_center_token(self, token):
pass
def _get_separetor_token(self, token):
pass
def __str__(self, *args, **kwargs):
left = "".join(str(t) for t in self.left_tokens)
right = "".join(str(t) for t in self.right_tokens)
comment = str(self.line_comment)
return "left:" + left + "\nright:" + right + "\ncomment:" + comment
class _IdentifierObject(_BaseIdentifierObject):
def _get_separetor_token(self, token):
alias = self._get_alias(token)
if alias:
as_token = token.token_next_match(0, T.Keyword, "AS")
if as_token:
return as_token
else:
return token.token_prev(alias, skip_ws=False)
return None
def _get_center_token(self, token):
return token.token_next_match(0, T.Keyword, "AS")
def _get_alias(self, token):
tkw = token.token_next_match(0, T.Keyword, 'AS')
if tkw is not None:
return tu.token_next_enable(token, tkw)
left = tu.token_next_enable(token)
if not left:
return None
def is_space(tkn):
return tkn.is_whitespace() and tkn.value
spl = token.token_matching(token.token_index(left), [is_space])
if spl:
return tu.token_next_enable(token, spl)
if tu.is_parenthesis(left):
tkn = tu.token_next_enable(token, left)
if tkn and (tu.is_identifier(tkn) or (tkn.ttype in T.Name)):
# (・・・)ALIAS の場合
space = sql.Token(T.Whitespace, "\t") # スペースを付与
token.insert_after(left, space)
return tkn
return None
class _UpdIdentifierObject(_BaseIdentifierObject):
def _get_separetor_token(self, token):
comp = token.token_next_match(0, T.Comparison, "=")
if comp:
return comp
else:
second = tu.token_next_enable(token, tu.token_next_enable(token))
return token.token_prev(second, skip_ws=False)
return None
def _get_center_token(self, token):
return token.token_next_match(0, T.Comparison, "=")
class _ComparisonObject(_LineObject):
"""
Comparison内部のインデント調整用のObject
"""
def __init__(self, token, indent, local_config):
self.token = token
self.line_comment = None
self.left_tokens = []
self.right_tokens = []
self.operator_tokens = []
self.left_lines = []
self.right_lines = []
self.operator_string = ""
self.width_left = 0
self.width_right = 0
self.line_comment = self._get_linecomment(token, local_config.comment_syntax)
op_tokens = tu.find_comparison_operator_words(token.tokens)
if len(op_tokens) > 1:
self.operator_tokens = token.tokens_between(op_tokens[0], op_tokens[1])
for tkn in self.operator_tokens[1:-1]:
if tkn.is_whitespace():
tkn.value = " "
else:
self.operator_tokens = op_tokens
for tkn in self.operator_tokens:
if tkn.is_whitespace():
tkn.value = " "
self.operator_string = "".join(str(tkn) for tkn in self.operator_tokens)
tws = token.token_next(self.operator_tokens[-1], skip_ws=False)
if tws.is_whitespace():
# 比較演算の隣の空白を削除
token.tokens.remove(tws)
self.left_tokens = token.tokens_between(token.tokens[0], self.operator_tokens[0], exclude_end=True)
self.right_tokens = self._right_tokens_between(token, self.operator_tokens[-1], self.line_comment)
self._rstrip(self.left_tokens, token)
self._rstrip(self.right_tokens, token)
lefts = utils.split_unquoted_newlines("".join([str(tkn) for tkn in self.left_tokens]))
rights = utils.split_unquoted_newlines("".join([str(tkn) for tkn in self.right_tokens]))
self._remove_indent(lefts, indent)
self._remove_indent(rights, indent)
self.width_left = get_need_tab_char_width(lefts[-1])
self.width_right = get_need_tab_char_width(rights[-1])
self.width_operator = get_need_tab_char_width(self.operator_string)
self.left_lines = lefts
self.right_lines = rights
def __str__(self, *args, **kwargs):
left = "".join(str(t) for t in self.left_tokens)
right = "".join(str(t) for t in self.right_tokens)
comment = str(self.line_comment)
operator = str(self.operator_string)
return "left:" + left + "\noperator:" + operator + "\nright:" + right + "\ncomment:" + comment
class OperatorFilter(object):
"""
比較演算子の統一
"""
def __init__(self):
self._process = SqlFormatterException.to_wrap_try_except(self._process, 0)
def process(self, _, stmt):
self._process(stmt)
def _process(self, tlist): # pylint: disable=method-hidden
[self._process(sgroup) for sgroup in tlist.get_sublists()]
for token in tlist.tokens:
if tu.is_operator(token) and token.value in ("<>", "^="):
token.value = "!="
class MoveCommaFilter(object):
"""
カンマ位置調整
"""
def __init__(self, local_config):
self._process = SqlFormatterException.to_wrap_try_except(self._process, 0)
self.local_config = local_config
def process(self, _, stmt):
self._process(stmt, [])
def _process(self, tlist, parents): # pylint: disable=method-hidden
tps = [tlist] + parents
[self._process(sgroup, tps) for sgroup in tlist.get_sublists()]
for token in tlist.tokens[:]:
if tu.is_comma(token):
nxt = tlist.token_next(token)
if nxt:
prv = tlist.token_prev(token)
comment = hit_first(
nxt,
lambda t: tu.is_line_description_line_comment(t, self.local_config.comment_syntax)
)
if comment and not (prv \
and hit_last(
prv,
lambda t: tu.is_line_description_line_comment(t, self.local_config.comment_syntax)
)
):
self.__move_token(tlist, token, comment)
def __move_token(self, parent, token_a, token_b):
if token_b in parent.tokens:
idxa = parent.tokens.index(token_a)
idxb = parent.tokens.index(token_b)
parent.tokens[idxa] = token_b
parent.tokens[idxb] = token_a
else:
def remove_token(parent, token):
if token in parent.tokens:
parent.tokens.remove(token)
return True
else:
for tkn in parent.tokens:
if tkn.is_group() and remove_token(tkn, token):
return True
return False
remove_token(parent, token_b)
parent.insert_before(token_a, token_b)
token_b.parent = parent
class CustomReindentFilter(ReindentFilter):
"""
インデント処理
"""
def __init__(self, local_config):
super(CustomReindentFilter, self).__init__(1, "\t")
self.local_config = local_config
def process(self, stack, stmt):
super(CustomReindentFilter, self).process(stack, stmt)
flatten = list(tu.flatten(stmt))
if not flatten:
return
if tu.is_semicolon_punctuation(flatten[-1]):
tcr = self.cr()
flatten[-1].parent.insert_before(flatten[-1], tcr)
flatten = flatten[:-1] + [tcr] + flatten[-1:]
# 重複した改行を削除
# まずは空白を結合
pre = flatten[0]
for token in flatten[1:]:
if token.is_whitespace():
if pre.is_whitespace():
pre.value += token.value
token.value = ""
continue
pre = token
# 重複した改行の除去
pre = None
for token in flatten:
if token.is_whitespace():
text = str(token)
if not text:
continue
white_lines = utils.split_unquoted_newlines(str(token))
while len(white_lines) > 2:
del white_lines[1]
if pre:
if len(white_lines) > 1 and pre.parent and tu.is_line_comment(pre.parent):
# 行コメントの後なら自分の改行を除去
del white_lines[0]
else:
if len(white_lines) > 1:
# 最初の改行を削除
del white_lines[0]
token.value = "\n".join(white_lines)
pre = token
def _process(self, tlist):
SqlFormatterException.wrap_try_except(super(CustomReindentFilter, self)._process, tlist)
def __within_with_section(self, token):
return tu.within_with_section(self._curr_stmt, token)
def __within_select_statement(self, token):
return tu.within_select_statement(self._curr_stmt, token)
def __within_insert_statement(self, token):
return tu.within_insert_statement(self._curr_stmt, token)
def __within_merge_statement(self, token):
return tu.within_merge_statement(self._curr_stmt, token)
def __within_update_statement(self, token):
return tu.within_update_statement(self._curr_stmt, token)
def __within_update_set_section(self, token):
return tu.within_update_set_section(self._curr_stmt, token)
def __within_insert_values_section(self, token):
return tu.within_insert_values_section(self._curr_stmt, token)
def __within_insert_into_columns_section(self, token):
return tu.within_insert_into_columns_section(self._curr_stmt, token)
def __custom_process_list(self, tlist):
for token in tlist.tokens[:]:
if tu.is_dml(token):
tlist.insert_before(token, self.nl())
tlist.insert_after(token, self.nl())
elif tu.is_from_keyword(token):
tlist.insert_before(token, self.nl()) # DELETEの場合(?)_split_kwdsで戻されてしまうため2つ改行する
tlist.insert_before(token, self.nl())
tlist.insert_after(token, self.cr())
elif tu.is_wildcard(token) or tu.is_literal(token) or tu.is_function(token):
prev = tlist.token_prev(token, skip_ws=False)
if prev and tu.is_param_comment(prev, token, self.local_config.comment_syntax):
target = prev
else:
target = token
prev = tu.token_prev_enable(tlist, target)
if prev and hit_last(prev, tu.is_dml):
tlist.insert_before(target, self.nl_with_indent(1))
else:
tlist.insert_before(target, self.indent_space())
elif tu.is_identifier(token) or tu.is_parenthesis(token):
prev = tu.token_prev_enable(tlist, token)
def is_need_indent(tkn):
if tu.is_from_keyword(tkn):
return True
if tu.is_by_keyword(tkn):
return True
if tu.is_select_dml(tkn):
return True
if tu.is_update_dml(tkn):
return True
if tu.is_into_keyword(tkn) and (
self.__within_insert_statement(tkn) \
or self.__within_merge_statement(tkn)
):
return True
if tu.is_using_keyword(tkn) and self.__within_merge_statement(tkn):
return True
if tu.is_set_keyword(tkn) and self.__within_update_statement(tkn):
return True
return False
if prev and hit_last(prev, is_need_indent):
self.offset += 1
self.__custom_process_identifier(tlist, token)
self.offset -= 1
else:
self.__custom_process_identifier(tlist, token)
elif tu.is_distinct_keyword(token):
tlist.insert_before(token, self.nl_with_indent(1))
elif tu.is_into_keyword(token) and (
self.__within_insert_statement(token) \
or self.__within_merge_statement(token)
):
tlist.insert_before(token, self.nl())
elif tu.is_using_keyword(token) and self.__within_merge_statement(token):
tlist.insert_before(token, self.nl())
elif tu.is_keyword(token) and tu.endswith_ignore_case(token.value, "COUNT"): # 念のため現状はCOUNTのみ処理
# keyword として扱われたidentifierを処理
prev = tu.token_prev_enable(tlist, token)
def is_need_indent(tkn):
if tu.is_from_keyword(tkn):
return True
if tu.is_by_keyword(tkn):
return True
if tu.is_select_dml(tkn):
return True
if tu.is_update_dml(tkn):
return True
if tu.is_into_keyword(tkn) and (
self.__within_insert_statement(tkn) \
or self.__within_merge_statement(tkn)
):
return True
if tu.is_using_keyword(tkn) and self.__within_merge_statement(tkn):
return True
if tu.is_set_keyword(tkn) and self.__within_update_statement(tkn):
return True
return False
if prev and hit_last(prev, is_need_indent):
self.offset += 1
tlist.insert_before(token, self.nl())
self.offset -= 1
def __custom_process_identifier(self, parent, identifier):
parent.insert_before(identifier, self.nl())
# 一つだけなら改行+インデント要らない
# if tu.is_line_comment(identifier.tokens[-1]):
# identifier.tokens[-1].tokens[-1].value = identifier.tokens[-1].tokens[-1].value.rstrip("\t")
# else:
# parent.insert_after(identifier, self.nl_with_indent(-1))
def __custom_process_line_comment(self, comment):
tcm = comment.token_next_by_type(0, T.Comment)
text = tcm.value[2:]
text = text.strip()
tcm.value = "-- " + text + "\n"
def __custom_process_block_comment(self, comment, is_hint):
start = comment.token_matching(0, [lambda t: t.ttype in T.Comment and t.value == "/*"])
end = comment.token_matching(
comment.token_index(start) + 1,
[lambda t: t.ttype in T.Comment and t.value == "*/"]
)
tokens = comment.tokens_between(start, end)[1:-1]
if not tokens:
return
comment.insert_before(comment.tokens[0], self.nl())
text_token = tokens[0]
while len(tokens) > 1:
# コメントのノードが分かれていたら1つに結合する
tgt = tokens[1]
text_token.value += tgt.value
comment.tokens.remove(tgt)
tokens.remove(tgt)
if is_hint:
text_token.value = text_token.value[1:] # 一旦+を抜く
text = str(text_token)
lines = utils.split_unquoted_newlines(text)
def is_doc_comment(lines):
"""
/*
* この形式のコメントかどうか?
*/
"""
end = len(lines) if lines[-1].strip() else -1
tgtlines = lines[1:end]
if not tgtlines:
return False
for line in tgtlines:
if not line.lstrip().startswith("*"):
return False
return True
def is_separator_line_comment(lines):
"""
/******************/
"""
return len(lines) == 1 and lines[0] == ("*" * len(lines[0]))
def is_lines_doc_comment(lines):
"""
/******************
この形式のコメント
****************/
"""
if len(lines) < 2:
return False
fst = lines[0].strip()
if (not fst) or (fst != ("*" * len(fst))):
return False
lst = lines[-1].strip()
if (not lst) or (lst != ("*" * len(lst))):
return False
return True
def remove_blank_lines(lines):
# 前後の空行削除
while not lines[0].strip():
del lines[0]
while not lines[-1].strip():
del lines[-1]
def format_doc(lines):
remove_blank_lines(lines)
for i, value in enumerate(lines):
text = value.lstrip()
if not text.startswith("*"):
text = "* " + text
elif not text.startswith("* "):
text = text[0] + " " + text[1:]
lines[i] = str(self.indent_space()) + " " + text
lines += [str(self.indent_space()) + " "]
return "\n" + "\n".join(lines)
def format_hint(lines):
# hint句なら+を戻す
return "+" + format_normal(lines)
def format_normal(lines):
remove_blank_lines(lines)
for i, value in enumerate(lines):
lines[i] = str(self.indent_space(1)) + value.lstrip()
lines += [str(self.indent_space())]
return "\n" + "\n".join(lines)
def format_oneline(lines):
return "".join(lines)
def format_lines_doc(lines):
for i, value in enumerate(lines[:-1]):
if i:
lines[i] = str(self.indent_space(1)) + value.lstrip()
lines[-1] = str(self.indent_space()) + lines[-1].strip()
lines[0] = lines[0].lstrip()
return "\n".join(lines)
if is_doc_comment(lines):
text_token.value = format_doc(lines)
elif is_hint:
text_token.value = format_hint(lines)
elif is_separator_line_comment(lines):
text_token.value = format_oneline(lines)
elif is_lines_doc_comment(lines):
text_token.value = format_lines_doc(lines)
else:
text_token.value = format_normal(lines)
comment.insert_after(comment.tokens[-1], self.nl())
def __custom_process_inorder_function(self, function):
name_token = tu.token_next_enable(function)
parenthesis = tu.token_next_enable(function, name_token)
spaces = function.tokens_between(name_token, parenthesis)[1:-1]
for tkn in spaces:
if tkn.is_whitespace():
function.tokens.remove(tkn)
self.__custom_process_parenthesis_order(parenthesis)
def __custom_process_parenthesis_order(self, parenthesis):
open_punc = parenthesis.token_next_match(0, T.Punctuation, '(')
close_punc = parenthesis.token_next_match(open_punc, T.Punctuation, ')')
self.indent += 2
parenthesis.insert_after(open_punc, self.nl())
for token in parenthesis.tokens_between(open_punc, close_punc)[1:-1]:
if isinstance(token, Phrase):
parenthesis.insert_before(token, self.nl())
self._process_phrase(token, kwds=False)
parenthesis.insert_after(token, self.nl_with_indent(1))
elif isinstance(token, sql.Identifier) and len(token.tokens)==1 and isinstance(token.tokens[0], Phrase):
# 中がPhraseのIdentifier
child_token = token.tokens[0]
parenthesis.insert_before(token, self.nl())
self._process_phrase(child_token, kwds=False)
parenthesis.insert_after(token, self.nl_with_indent(1))
elif token.is_group():
self._process(token)
self.indent -= 1
parenthesis.insert_before(close_punc, self.nl())
self.indent -= 1
def __custom_process_insert_values_lr(self, tlist):
#INSERT の場合VALUES前後に空白1つをセット
values_token = tlist.token_next_match(0, T.Keyword, "VALUES")
if values_token:
prv = tlist.token_prev(values_token, skip_ws=False)
if prv and prv.is_whitespace():
prv.value = " "
prv = tlist.token_prev(prv, skip_ws=False)
while prv and prv.is_whitespace():
prv.value = ""
prv = tlist.token_prev(prv, skip_ws=False)
else:
tlist.insert_before(values_token, sql.Token(T.Whitespace, " "))
nxt = tlist.token_next(values_token, skip_ws=False)
if nxt and nxt.is_whitespace():
nxt.value = " "
nxt = tlist.token_next(nxt, skip_ws=False)
while nxt and nxt.is_whitespace():
nxt.value = ""
nxt = tlist.token_next(nxt, skip_ws=False)
else:
tlist.insert_after(values_token, sql.Token(T.Whitespace, " "))
def _process_statement(self, tlist):
self.__custom_process_list(tlist)
self._process_default(tlist)
tkn = tu.token_next_enable(tlist)
if tkn and tu.is_insert_dml(tkn):
self.__custom_process_insert_values_lr(tlist)
def _process_comment(self, tlist):
if tu.is_block_comment(tlist):
usql = tu.get_comment_type(tlist, self.local_config.comment_syntax)
if usql == tu.EngineComment.param:
pass
elif usql == tu.EngineComment.syntax:
tlist.insert_before(tlist.tokens[0], self.nl())
tlist.insert_after(tlist.tokens[-1], self.nl())
elif usql == tu.EngineComment.sql_identifier:
# 前の改行を削除。半角スペース開ける
whitespaces = []
for tkn in self._flatten_tokens_prev(tlist):
if tkn.is_whitespace():
whitespaces.append(tkn)
else:
break
if whitespaces:
whitespaces[-1].value = " "
for tws in whitespaces[:-1]:
tws.value = ""
tlist.insert_after(tlist.tokens[-1], self.nl())
elif tu.is_hint_block_comment(tlist):
self.__custom_process_block_comment(tlist, True)
else:
self.__custom_process_block_comment(tlist, False)
elif tu.is_line_comment(tlist):
self.__custom_process_line_comment(tlist)
for tkn in tlist.tokens[:]:
if tkn.is_whitespace():
tlist.tokens.remove(tkn)
usql = tu.get_comment_type(tlist, self.local_config.comment_syntax)
if usql != tu.EngineComment.none:
# Uroboroシンタックスのラインコメントなので改行を入れる
tlist.insert_before(tlist.tokens[0], self.nl())
elif not tu.is_line_description_line_comment(tlist, self.local_config.comment_syntax):
# もともと改行後のラインコメントだったので改行を入れる
tlist.insert_before(tlist.tokens[0], self.nl())
tlist.insert_after(tlist.tokens[-1], self.nl())
self._process_default(tlist)
def _process_identifierlist(self, tlist):
self._process_default(tlist)
if not self._is_format_target_identifire_list(tlist):
return
identifiers = list(tlist.get_identifiers())
self._adjust_identifiers_indent(identifiers)
if identifiers:
self.offset += 1
first = identifiers[0]
tlist.insert_before(first, self.nl())
tlist.insert_after(first, self.nl_with_indent(-1))
if len(identifiers) > 1:
for token in identifiers[1:-1]:
tlist.insert_before(token, self.one_indent_space())
tlist.insert_after(token, self.nl_with_indent(-1))
last = identifiers[-1]
tlist.insert_before(last, self.one_indent_space())
self.offset -= 1
def _process_when(self, tlist):
token = tlist.token_next_match(0, T.Keyword, 'WHEN')
try:
tlist.insert_before(token, self.nl())
tlist.insert_after(token, self.nl_with_indent(1))
except ValueError: # issue121, errors in statement
pass
self._process_default(tlist)
self._adjust_comparisons_indent(self._get_comparisons(tlist))
def _process_where(self, tlist):
token = tlist.token_next_match(0, T.Keyword, 'WHERE')
try:
tlist.insert_before(token, self.nl())
tlist.insert_after(token, self.nl_with_indent(1))
except ValueError: # issue121, errors in statement
pass
self._process_default(tlist)
self._adjust_comparisons_indent(self._get_comparisons(tlist))
def _process_having(self, tlist):
self._process_default(tlist)
token = tlist.token_next_match(0, T.Keyword, 'HAVING')
try:
tlist.insert_before(token, self.nl())
tlist.insert_after(token, self.nl_with_indent(1))
except ValueError: # issue121, errors in statement
pass
self._adjust_comparisons_indent(self._get_comparisons(tlist))
def _process_comparison(self, tlist):
# tlist.insert_before(tlist.tokens[0], self.indent_space(1))
self._process_default(tlist)
def _process_parenthesis(self, tlist):
def is_insert_parenthesis(tlist):
if not self.__within_insert_statement(tlist):
return False
if self.__within_insert_values_section(tlist): # insertのvaluesの処理
return True
if self.__within_insert_into_columns_section(tlist): # insertのinto columnsの処理
return True
return False
def is_include_join(tlist):
token = tu.tokens_parenthesis_inner(tlist)
for tkn in token:
if tu.is_join(tkn):
return True
return False
def is_with_query_cols(tlist):
"""
WITHのqueryカラム名括弧判定
"""
parent = tlist.parent
if parent and tu.is_identifier(parent):
nametoken = tu.token_prev_enable(parent, tlist)
if not nametoken:
return False
if not tu.is_identifier(nametoken) and not nametoken.ttype in T.Name:
return False
parent = parent.parent
if parent and tu.is_identifier_list(parent):
parent = parent.parent
if parent and tu.is_with(parent):
return True
return False
def is_need_shift(tlist):
"""
閉じ括弧「)」の前が改行されている場合shiftさせる
ただし開き括弧「(」の前が改行されている場合はshiftさせない
"""
# 開き括弧「(」の前が改行されているかどうか?
open_punc = tlist.token_next_match(0, T.Punctuation, '(')
exists = False
spaces = ""
for token in self._flatten_tokens_prev(open_punc):