-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
compiler.py
2002 lines (1810 loc) · 83.5 KB
/
compiler.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------------------------------------------------
# INFO:
# -----------------------------------------------------------------------------------------------------------------------
"""
Author: Evan Hubinger
License: Apache 2.0
Description: Compiles Coconut code into Python code.
"""
# Table of Contents:
# - Imports
# - Handlers
# - Compiler
# - Processors
# - Parser Handlers
# - Checking Handlers
# - Endpoints
# -----------------------------------------------------------------------------------------------------------------------
# IMPORTS:
# -----------------------------------------------------------------------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
from coconut.root import * # NOQA
import sys
from contextlib import contextmanager
from functools import partial
from coconut.myparsing import (
ParseBaseException,
col,
line as getline,
lineno,
nums,
)
from coconut.constants import (
get_target_info,
specific_targets,
targets,
pseudo_targets,
default_encoding,
hash_sep,
openindent,
closeindent,
strwrapper,
lnwrapper,
unwrapper,
holds,
tabideal,
tabworth,
match_to_var,
match_to_args_var,
match_to_kwargs_var,
match_check_var,
match_err_var,
lazy_chain_var,
import_as_var,
yield_from_var,
yield_item_var,
raise_from_var,
stmt_lambda_var,
tre_mock_var,
tre_store_var,
tre_check_var,
py3_to_py2_stdlib,
checksum,
reserved_prefix,
case_check_var,
)
from coconut.exceptions import (
CoconutException,
CoconutSyntaxError,
CoconutParseError,
CoconutStyleError,
CoconutTargetError,
CoconutInternalException,
CoconutSyntaxWarning,
CoconutDeferredSyntaxError,
clean,
internal_assert,
)
from coconut.terminal import logger, trace, complain
from coconut.compiler.matching import Matcher
from coconut.compiler.grammar import (
Grammar,
lazy_list_handle,
get_infix_items,
match_handle,
)
from coconut.compiler.util import (
addskip,
count_end,
paren_change,
ind_change,
rem_comment,
split_comment,
attach,
split_leading_indent,
split_trailing_indent,
split_leading_trailing_indent,
match_in,
transform,
ignore_transform,
parse,
get_target_info_len2,
split_leading_comment,
compile_regex,
keyword,
append_it,
)
from coconut.compiler.header import (
minify,
getheader,
)
# end: IMPORTS
# -----------------------------------------------------------------------------------------------------------------------
# HANDLERS:
# -----------------------------------------------------------------------------------------------------------------------
def set_to_tuple(tokens):
"""Converts set literal tokens to tuples."""
internal_assert(len(tokens) == 1, "invalid set maker tokens", tokens)
if "comp" in tokens or "list" in tokens:
return "(" + tokens[0] + ")"
elif "test" in tokens:
return "(" + tokens[0] + ",)"
else:
raise CoconutInternalException("invalid set maker item", tokens[0])
def import_stmt(imp_from, imp, imp_as):
"""Generate an import statement."""
return (
("from " + imp_from + " " if imp_from is not None else "")
+ "import " + imp
+ (" as " + imp_as if imp_as is not None else "")
)
def single_import(path, imp_as):
"""Generate import statements from a fully qualified import and the name to bind it to."""
out = []
parts = path.split("./") # denotes from ... import ...
if len(parts) == 1:
imp_from, imp = None, parts[0]
else:
imp_from, imp = parts
if imp == imp_as:
imp_as = None
elif imp.endswith("." + imp_as):
if imp_from is None:
imp_from = ""
imp_from += imp.rsplit("." + imp_as, 1)[0]
imp, imp_as = imp_as, None
if imp_from is None and imp == "sys":
out.append((imp_as if imp_as is not None else imp) + " = _coconut_sys")
elif imp_as is not None and "." in imp_as:
fake_mods = imp_as.split(".")
out.append(import_stmt(imp_from, imp, import_as_var))
for i in range(1, len(fake_mods)):
mod_name = ".".join(fake_mods[:i])
out.extend((
"try:",
openindent + mod_name,
closeindent + "except:",
openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")',
closeindent + "else:",
openindent + "if not _coconut.isinstance(" + mod_name + ", _coconut.types.ModuleType):",
openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")' + closeindent * 2,
))
out.append(".".join(fake_mods) + " = " + import_as_var)
else:
out.append(import_stmt(imp_from, imp, imp_as))
return out
def universal_import(imports, imp_from=None, target=""):
"""Generate code for a universal import of imports from imp_from on target.
imports = [[imp1], [imp2, as], ...]"""
importmap = [] # [((imp | old_imp, imp, version_check), imp_as), ...]
for imps in imports:
if len(imps) == 1:
imp, imp_as = imps[0], imps[0]
else:
imp, imp_as = imps
if imp_from is not None:
imp = imp_from + "./" + imp # marker for from ... import ...
old_imp = None
path = imp.split(".")
for i in reversed(range(1, len(path) + 1)):
base, exts = ".".join(path[:i]), path[i:]
clean_base = base.replace("/", "")
if clean_base in py3_to_py2_stdlib:
old_imp, version_check = py3_to_py2_stdlib[clean_base]
if exts:
old_imp += "."
if "/" in base and "/" not in old_imp:
old_imp += "/" # marker for from ... import ...
old_imp += ".".join(exts)
break
if old_imp is None:
paths = (imp,)
elif not target: # universal compatibility
paths = (old_imp, imp, version_check)
elif get_target_info_len2(target) >= version_check: # if lowest is above, we can safely use new
paths = (imp,)
elif target.startswith("2"): # "2" and "27" can safely use old
paths = (old_imp,)
elif get_target_info(target) < version_check: # "3" should be compatible with all 3+
paths = (old_imp, imp, version_check)
else: # "35" and above can safely use new
paths = (imp,)
importmap.append((paths, imp_as))
stmts = []
for paths, imp_as in importmap:
if len(paths) == 1:
more_stmts = single_import(paths[0], imp_as)
stmts.extend(more_stmts)
else:
first, second, version_check = paths
stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
first_stmts = single_import(first, imp_as)
first_stmts[0] = openindent + first_stmts[0]
first_stmts[-1] += closeindent
stmts.extend(first_stmts)
stmts.append("else:")
second_stmts = single_import(second, imp_as)
second_stmts[0] = openindent + second_stmts[0]
second_stmts[-1] += closeindent
stmts.extend(second_stmts)
return "\n".join(stmts)
def imported_names(imports):
"""Yields all the names imported by imports = [[imp1], [imp2, as], ...]."""
for imp in imports:
yield imp[-1].split(".", 1)[0]
def split_args_list(tokens, loc):
"""Splits function definition arguments."""
req_args, def_args, star_arg, kwd_args, dubstar_arg = [], [], None, [], None
pos = 0
for arg in tokens:
if len(arg) == 1:
if arg[0] == "*":
# star sep (pos = 3)
if pos >= 3:
raise CoconutDeferredSyntaxError("star separator at invalid position in function definition", loc)
pos = 3
else:
# pos arg (pos = 0)
if pos > 0:
raise CoconutDeferredSyntaxError("positional arguments must come first in function definition", loc)
req_args.append(arg[0])
elif len(arg) == 2:
if arg[0] == "*":
# star arg (pos = 2)
if pos >= 2:
raise CoconutDeferredSyntaxError("star argument at invalid position in function definition", loc)
pos = 2
star_arg = arg[1]
elif arg[0] == "**":
# dub star arg (pos = 4)
if pos == 4:
raise CoconutDeferredSyntaxError("double star argument at invalid position in function definition", loc)
pos = 4
dubstar_arg = arg[1]
else:
# def arg (pos = 1)
if pos <= 1:
pos = 1
def_args.append((arg[0], arg[1]))
# kwd arg (pos = 3)
elif pos <= 3:
pos = 3
kwd_args.append((arg[0], arg[1]))
else:
raise CoconutDeferredSyntaxError("invalid default argument in function definition", loc)
else:
raise CoconutInternalException("invalid function definition argument", arg)
return req_args, def_args, star_arg, kwd_args, dubstar_arg
def match_case_tokens(loc, tokens, check_var, top):
"""Build code for matching the given case."""
if len(tokens) == 2:
matches, stmts = tokens
cond = None
elif len(tokens) == 3:
matches, cond, stmts = tokens
else:
raise CoconutInternalException("invalid case match tokens", tokens)
matching = Matcher(loc, check_var)
matching.match(matches, match_to_var)
if cond:
matching.add_guard(cond)
return matching.build(stmts, set_check_var=top)
# end: HANDLERS
# -----------------------------------------------------------------------------------------------------------------------
# COMPILER:
# -----------------------------------------------------------------------------------------------------------------------
class Compiler(Grammar):
"""The Coconut compiler."""
preprocs = [
lambda self: self.prepare,
lambda self: self.str_proc,
lambda self: self.passthrough_proc,
lambda self: self.ind_proc,
]
postprocs = [
lambda self: self.stmt_lambda_proc,
lambda self: self.reind_proc,
lambda self: self.repl_proc,
lambda self: self.header_proc,
lambda self: self.polish,
]
replprocs = [
lambda self: self.endline_repl,
lambda self: self.passthrough_repl,
lambda self: self.str_repl,
]
def __init__(self, *args, **kwargs):
"""Creates a new compiler with the given parsing parameters."""
self.setup(*args, **kwargs)
def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False):
"""Initializes parsing parameters."""
if target is None:
target = ""
else:
target = str(target).replace(".", "")
if target in pseudo_targets:
target = pseudo_targets[target]
if target not in targets:
raise CoconutException(
"unsupported target Python version " + ascii(target),
extra="supported targets are " + ', '.join(ascii(t) for t in specific_targets) + ", or leave blank for universal",
)
logger.log_vars("Compiler args:", locals())
self.target, self.strict, self.minify, self.line_numbers, self.keep_lines, self.no_tco = (
target, strict, minify, line_numbers, keep_lines, no_tco,
)
def __reduce__(self):
"""Return pickling information."""
return (Compiler, (self.target, self.strict, self.minify, self.line_numbers, self.keep_lines, self.no_tco))
def genhash(self, package, code):
"""Generate a hash from code."""
return hex(checksum(
hash_sep.join(
str(item) for item in (VERSION_STR,)
+ self.__reduce__()[1]
+ (package, code)
).encode(default_encoding),
))
def reset(self):
"""Resets references."""
self.indchar = None
self.comments = {}
self.refs = []
self.set_skips([])
self.docstring = ""
self.ichain_count = 0
self.tre_store_count = 0
self.case_check_count = 0
self.stmt_lambdas = []
if self.strict:
self.unused_imports = set()
self.bind()
def bind(self):
"""Binds reference objects to the proper parse actions."""
self.endline <<= attach(self.endline_ref, self.endline_handle)
self.moduledoc_item <<= trace(attach(self.moduledoc, self.set_docstring))
self.name <<= trace(attach(self.base_name, self.name_check))
# comments are evaluated greedily because we need to know about them even if we're going to suppress them
self.comment <<= trace(attach(self.comment_ref, self.comment_handle, greedy=True))
self.set_literal <<= trace(attach(self.set_literal_ref, self.set_literal_handle))
self.set_letter_literal <<= trace(attach(self.set_letter_literal_ref, self.set_letter_literal_handle))
self.classlist <<= trace(attach(self.classlist_ref, self.classlist_handle))
self.import_stmt <<= trace(attach(self.import_stmt_ref, self.import_handle))
self.complex_raise_stmt <<= trace(attach(self.complex_raise_stmt_ref, self.complex_raise_stmt_handle))
self.augassign_stmt <<= trace(attach(self.augassign_stmt_ref, self.augassign_handle))
self.dict_comp <<= trace(attach(self.dict_comp_ref, self.dict_comp_handle))
self.destructuring_stmt <<= trace(attach(self.destructuring_stmt_ref, self.destructuring_stmt_handle))
self.name_match_funcdef <<= trace(attach(self.name_match_funcdef_ref, self.name_match_funcdef_handle))
self.op_match_funcdef <<= trace(attach(self.op_match_funcdef_ref, self.op_match_funcdef_handle))
self.yield_from <<= trace(attach(self.yield_from_ref, self.yield_from_handle))
self.exec_stmt <<= trace(attach(self.exec_stmt_ref, self.exec_stmt_handle))
self.stmt_lambdef <<= trace(attach(self.stmt_lambdef_ref, self.stmt_lambdef_handle))
self.typedef <<= trace(attach(self.typedef_ref, self.typedef_handle))
self.typedef_default <<= trace(attach(self.typedef_default_ref, self.typedef_handle))
self.unsafe_typedef_default <<= trace(attach(self.unsafe_typedef_default_ref, self.unsafe_typedef_handle))
self.return_typedef <<= trace(attach(self.return_typedef_ref, self.typedef_handle))
self.typed_assign_stmt <<= trace(attach(self.typed_assign_stmt_ref, self.typed_assign_stmt_handle))
self.datadef <<= trace(attach(self.datadef_ref, self.data_handle))
self.with_stmt <<= trace(attach(self.with_stmt_ref, self.with_stmt_handle))
self.await_item <<= trace(attach(self.await_item_ref, self.await_item_handle))
self.ellipsis <<= trace(attach(self.ellipsis_ref, self.ellipsis_handle))
self.case_stmt <<= trace(attach(self.case_stmt_ref, self.case_stmt_handle))
self.decoratable_normal_funcdef_stmt <<= trace(attach(
self.decoratable_normal_funcdef_stmt_ref,
self.decoratable_funcdef_stmt_handle,
))
self.decoratable_async_funcdef_stmt <<= trace(attach(
self.decoratable_async_funcdef_stmt_ref,
partial(self.decoratable_funcdef_stmt_handle, is_async=True),
))
self.u_string <<= attach(self.u_string_ref, self.u_string_check)
self.matrix_at <<= attach(self.matrix_at_ref, self.matrix_at_check)
self.nonlocal_stmt <<= attach(self.nonlocal_stmt_ref, self.nonlocal_check)
self.star_assign_item <<= attach(self.star_assign_item_ref, self.star_assign_item_check)
self.classic_lambdef <<= attach(self.classic_lambdef_ref, self.lambdef_check)
self.star_expr <<= attach(self.star_expr_ref, self.star_expr_check)
self.dubstar_expr <<= attach(self.dubstar_expr_ref, self.star_expr_check)
self.star_sep_arg <<= attach(self.star_sep_arg_ref, self.star_sep_check)
self.star_sep_vararg <<= attach(self.star_sep_vararg_ref, self.star_sep_check)
self.endline_semicolon <<= attach(self.endline_semicolon_ref, self.endline_semicolon_check)
self.async_stmt <<= attach(self.async_stmt_ref, self.async_stmt_check)
self.async_comp_for <<= attach(self.async_comp_for_ref, self.async_comp_check)
self.f_string <<= attach(self.f_string_ref, self.f_string_check)
def copy_skips(self):
"""Copy the line skips."""
return self.skips[:]
def set_skips(self, skips):
"""Set the line skips."""
skips.sort()
internal_assert(lambda: len(set(skips)) == len(skips), "duplicate line skip(s) in skips", skips)
self.skips = skips
def adjust(self, ln):
"""Converts a parsing line number into an original line number."""
adj_ln = ln
need_unskipped = 0
for i in self.skips:
if i <= ln:
need_unskipped += 1
elif adj_ln + need_unskipped < i:
break
else:
need_unskipped -= i - adj_ln - 1
adj_ln = i
return adj_ln + need_unskipped
def reformat(self, snip, index=None):
"""Post process a preprocessed snippet."""
if index is not None:
return self.reformat(snip), len(self.reformat(snip[:index]))
else:
return self.repl_proc(snip, reformatting=True, log=False)
def eval_now(self, code):
"""Reformat and evaluate a code snippet and return code for the result."""
result = eval(self.reformat(code))
if result is None or isinstance(result, (bool, int, float, complex)):
return repr(result)
elif isinstance(result, bytes):
return "b" + self.wrap_str_of(result)
elif isinstance(result, str):
return self.wrap_str_of(result)
else:
return None
def make_err(self, errtype, message, original, loc, ln=None, reformat=True, *args, **kwargs):
"""Generate an error of the specified type."""
if ln is None:
ln = self.adjust(lineno(loc, original))
errstr, index = getline(loc, original), col(loc, original) - 1
if reformat:
errstr, index = self.reformat(errstr, index)
return errtype(message, errstr, index, ln, *args, **kwargs)
def strict_err_or_warn(self, *args, **kwargs):
"""Raises an error if in strict mode, otherwise raises a warning."""
if self.strict:
raise self.make_err(CoconutStyleError, *args, **kwargs)
else:
logger.warn_err(self.make_err(CoconutSyntaxWarning, *args, **kwargs))
def add_ref(self, reftype, data):
"""Add a reference and returns the identifier."""
ref = (reftype, data)
try:
index = self.refs.index(ref)
except ValueError:
self.refs.append(ref)
index = len(self.refs) - 1
return str(index)
def get_ref(self, reftype, index):
"""Retrieve a reference."""
try:
got_reftype, data = self.refs[int(index)]
except (IndexError, ValueError):
raise CoconutInternalException("no reference at invalid index", index)
internal_assert(got_reftype == reftype, "wanted " + reftype + " reference; got " + got_reftype + " reference")
return data
def wrap_str(self, text, strchar, multiline=False):
"""Wrap a string."""
if multiline:
strchar *= 3
return strwrapper + self.add_ref("str", (text, strchar)) + unwrapper
def wrap_str_of(self, text):
"""Wrap a string of a string."""
text_repr = ascii(text)
internal_assert(text_repr[0] == text_repr[-1] and text_repr[0] in ("'", '"'), "cannot wrap str of", text)
return self.wrap_str(text_repr[1:-1], text_repr[-1])
def wrap_passthrough(self, text, multiline=True):
"""Wrap a passthrough."""
if not multiline:
text = text.lstrip()
if multiline:
out = "\\"
else:
out = "\\\\"
out += self.add_ref("passthrough", text) + unwrapper
if not multiline:
out += "\n"
return out
def wrap_comment(self, text, reformat=True):
"""Wrap a comment."""
if reformat:
text = self.reformat(text)
return "#" + self.add_ref("comment", text) + unwrapper
def wrap_line_number(self, ln):
"""Wrap a line number."""
return "#" + self.add_ref("ln", ln) + lnwrapper
def apply_procs(self, procs, kwargs, inputstring, log=True):
"""Apply processors to inputstring."""
for get_proc in procs:
proc = get_proc(self)
inputstring = proc(inputstring, **kwargs)
if log:
logger.log_tag(proc.__name__, inputstring, multiline=True)
return inputstring
def pre(self, inputstring, **kwargs):
"""Perform pre-processing."""
out = self.apply_procs(self.preprocs, kwargs, str(inputstring))
logger.log_tag("skips", self.skips)
return out
def post(self, result, **kwargs):
"""Perform post-processing."""
internal_assert(isinstance(result, str), "got non-string parse result", result)
return self.apply_procs(self.postprocs, kwargs, result)
def getheader(self, which, use_hash=None, polish=True):
"""Get a formatted header."""
header = getheader(
which,
use_hash=use_hash,
target=self.target,
no_tco=self.no_tco,
strict=self.strict,
)
if polish:
header = self.polish(header)
return header
@property
def target_info(self):
"""Return information on the current target as a version tuple."""
return get_target_info(self.target)
def make_syntax_err(self, err, original):
"""Make a CoconutSyntaxError from a CoconutDeferredSyntaxError."""
msg, loc = err.args
return self.make_err(CoconutSyntaxError, msg, original, loc)
def make_parse_err(self, err, reformat=True, include_ln=True):
"""Make a CoconutParseError from a ParseBaseException."""
err_line = err.line
err_index = err.col - 1
err_lineno = err.lineno if include_ln else None
if reformat:
err_line, err_index = self.reformat(err_line, err_index)
if err_lineno is not None:
err_lineno = self.adjust(err_lineno)
return CoconutParseError(None, err_line, err_index, err_lineno)
def parse(self, inputstring, parser, preargs, postargs):
"""Use the parser to parse the inputstring with appropriate setup and teardown."""
self.reset()
pre_procd = None
with logger.gather_parsing_stats():
try:
pre_procd = self.pre(inputstring, **preargs)
parsed = parse(parser, pre_procd)
out = self.post(parsed, **postargs)
except ParseBaseException as err:
raise self.make_parse_err(err)
except CoconutDeferredSyntaxError as err:
internal_assert(pre_procd is not None, "invalid deferred syntax error in pre-processing", err)
raise self.make_syntax_err(err, pre_procd)
except RuntimeError as err:
raise CoconutException(
str(err), extra="try again with --recursion-limit greater than the current "
+ str(sys.getrecursionlimit()),
)
if self.strict:
for name in self.unused_imports:
if name != "*":
logger.warn("found unused import", name, extra="disable --strict to dismiss")
return out
# end: COMPILER
# -----------------------------------------------------------------------------------------------------------------------
# PROCESSORS:
# -----------------------------------------------------------------------------------------------------------------------
def prepare(self, inputstring, strip=False, nl_at_eof_check=False, **kwargs):
"""Prepare a string for processing."""
if self.strict and nl_at_eof_check and inputstring and not inputstring.endswith("\n"):
end_index = len(inputstring) - 1 if inputstring else 0
raise self.make_err(CoconutStyleError, "missing new line at end of file", inputstring, end_index)
original_lines = inputstring.splitlines()
if self.keep_lines:
self.original_lines = original_lines
inputstring = "\n".join(original_lines)
if strip:
inputstring = inputstring.strip()
return inputstring
def str_proc(self, inputstring, **kwargs):
"""Process strings and comments."""
out = []
found = None # store of characters that might be the start of a string
hold = None
# hold = [_comment]:
_comment = 0 # the contents of the comment so far
# hold = [_contents, _start, _stop]:
_contents = 0 # the contents of the string so far
_start = 1 # the string of characters that started the string
_stop = 2 # store of characters that might be the end of the string
skips = self.copy_skips()
x = 0
while x <= len(inputstring):
try:
c = inputstring[x]
except IndexError:
internal_assert(x == len(inputstring), "invalid index in str_proc", x)
c = "\n"
if hold is not None:
if len(hold) == 1: # hold == [_comment]
if c == "\n":
if self.minify:
if out:
lines = "".join(out).splitlines()
lines[-1] = lines[-1].rstrip()
out = ["\n".join(lines)]
out.append(c)
else:
out.append(self.wrap_comment(hold[_comment], reformat=False) + c)
hold = None
else:
hold[_comment] += c
elif hold[_stop] is not None:
if c == "\\":
hold[_contents] += hold[_stop] + c
hold[_stop] = None
elif c == hold[_start][0]:
hold[_stop] += c
elif len(hold[_stop]) > len(hold[_start]):
raise self.make_err(CoconutSyntaxError, "invalid number of string closes", inputstring, x, reformat=False)
elif hold[_stop] == hold[_start]:
out.append(self.wrap_str(hold[_contents], hold[_start][0], True))
hold = None
x -= 1
else:
if c == "\n":
if len(hold[_start]) == 1:
raise self.make_err(CoconutSyntaxError, "linebreak in non-multiline string", inputstring, x, reformat=False)
else:
skips = addskip(skips, self.adjust(lineno(x, inputstring)))
hold[_contents] += hold[_stop] + c
hold[_stop] = None
elif count_end(hold[_contents], "\\") % 2 == 1:
if c == "\n":
skips = addskip(skips, self.adjust(lineno(x, inputstring)))
hold[_contents] += c
elif c == hold[_start]:
out.append(self.wrap_str(hold[_contents], hold[_start], False))
hold = None
elif c == hold[_start][0]:
hold[_stop] = c
else:
if c == "\n":
if len(hold[_start]) == 1:
raise self.make_err(CoconutSyntaxError, "linebreak in non-multiline string", inputstring, x, reformat=False)
else:
skips = addskip(skips, self.adjust(lineno(x, inputstring)))
hold[_contents] += c
elif found is not None:
if c == found[0]:
found += c
elif len(found) == 1: # found == "_"
if c == "\n":
raise self.make_err(CoconutSyntaxError, "linebreak in non-multiline string", inputstring, x, reformat=False)
else:
hold = [c, found, None] # [_contents, _start, _stop]
found = None
elif len(found) == 2: # found == "__"
out.append(self.wrap_str("", found[0], False))
found = None
x -= 1
elif len(found) == 3: # found == "___"
if c == "\n":
skips = addskip(skips, self.adjust(lineno(x, inputstring)))
hold = [c, found, None] # [_contents, _start, _stop]
found = None
else:
raise self.make_err(CoconutSyntaxError, "invalid number of string starts", inputstring, x, reformat=False)
elif c == "#":
hold = [""] # [_comment]
elif c in holds:
found = c
else:
out.append(c)
x += 1
if hold is not None or found is not None:
raise self.make_err(CoconutSyntaxError, "unclosed string", inputstring, x, reformat=False)
else:
self.set_skips(skips)
return "".join(out)
def passthrough_proc(self, inputstring, **kwargs):
"""Process python passthroughs."""
out = []
found = None # store of characters that might be the start of a passthrough
hold = None # the contents of the passthrough so far
count = None # current parenthetical level (num closes - num opens)
multiline = None # if in a passthrough, is it a multiline passthrough
skips = self.copy_skips()
for i, c in enumerate(append_it(inputstring, "\n")):
if hold is not None:
# we specify that we only care about parens, not brackets or braces
count += paren_change(c, opens="(", closes=")")
if count >= 0 and c == hold:
out.append(self.wrap_passthrough(found, multiline))
found = None
hold = None
count = None
multiline = None
else:
if c == "\n":
skips = addskip(skips, self.adjust(lineno(i, inputstring)))
found += c
elif found:
if c == "\\":
found = ""
hold = "\n"
count = 0
multiline = False
elif c == "(":
found = ""
hold = ")"
count = -1
multiline = True
else:
out.append("\\" + c)
found = None
elif c == "\\":
found = True
else:
out.append(c)
if hold is not None or found is not None:
raise self.make_err(CoconutSyntaxError, "unclosed passthrough", inputstring, i)
self.set_skips(skips)
return "".join(out)
def leading_whitespace(self, inputstring):
"""Count leading whitespace."""
count = 0
for i, c in enumerate(inputstring):
if c == " ":
count += 1
elif c == "\t":
count += tabworth - (i % tabworth)
else:
break
if self.indchar is None:
self.indchar = c
elif c != self.indchar:
self.strict_err_or_warn("found mixing of tabs and spaces", inputstring, i)
return count
def ind_proc(self, inputstring, **kwargs):
"""Process indentation."""
lines = inputstring.splitlines()
new = [] # new lines
opens = [] # (line, col, adjusted ln) at which open parens were seen, newest first
current = None # indentation level of previous line
levels = [] # indentation levels of all previous blocks, newest at end
skips = self.copy_skips()
for ln in range(1, len(lines) + 1): # ln is 1-indexed
line = lines[ln - 1] # lines is 0-indexed
line_rstrip = line.rstrip()
if line != line_rstrip:
if self.strict:
raise self.make_err(CoconutStyleError, "found trailing whitespace", line, len(line), self.adjust(ln))
line = line_rstrip
last = rem_comment(new[-1]) if new else None
if not line or line.lstrip().startswith("#"): # blank line or comment
if opens: # inside parens
skips = addskip(skips, self.adjust(ln))
else:
new.append(line)
elif last is not None and last.endswith("\\"): # backslash line continuation
if self.strict:
raise self.make_err(CoconutStyleError, "found backslash continuation", last, len(last), self.adjust(ln - 1))
skips = addskip(skips, self.adjust(ln))
new[-1] = last[:-1] + " " + line
elif opens: # inside parens
skips = addskip(skips, self.adjust(ln))
new[-1] = last + " " + line
else:
check = self.leading_whitespace(line)
if current is None:
if check:
raise self.make_err(CoconutSyntaxError, "illegal initial indent", line, 0, self.adjust(ln))
else:
current = 0
elif check > current:
levels.append(current)
current = check
line = openindent + line
elif check in levels:
point = levels.index(check) + 1
line = closeindent * (len(levels[point:]) + 1) + line
levels = levels[:point]
current = levels.pop()
elif current != check:
raise self.make_err(CoconutSyntaxError, "illegal dedent to unused indentation level", line, 0, self.adjust(ln))
new.append(line)
count = paren_change(line) # num closes - num opens
if count > len(opens):
raise self.make_err(CoconutSyntaxError, "unmatched close parenthesis", new[-1], 0, self.adjust(len(new)))
elif count > 0: # closes > opens
for _ in range(count):
opens.pop()
elif count < 0: # opens > closes
opens += [(new[-1], self.adjust(len(new)))] * (-count)
self.set_skips(skips)
if new:
last = rem_comment(new[-1])
if last.endswith("\\"):
raise self.make_err(CoconutSyntaxError, "illegal final backslash continuation", new[-1], len(new[-1]), self.adjust(len(new)))
if opens:
line, adj_ln = opens[0]
raise self.make_err(CoconutSyntaxError, "unclosed open parenthesis", line, 0, adj_ln)
new.append(closeindent * len(levels))
return "\n".join(new)
def stmt_lambda_proc(self, inputstring, **kwargs):
"""Add statement lambda definitions."""
regexes = []
for i in range(len(self.stmt_lambdas)):
name = self.stmt_lambda_name(i)
regex = compile_regex(r"\b%s\b" % (name,))
regexes.append(regex)
out = []
for line in inputstring.splitlines():
for i, regex in enumerate(regexes):
if regex.search(line):
indent, line = split_leading_indent(line)
out.append(indent + self.stmt_lambdas[i])
out.append(line)
return "\n".join(out)
@property
def tabideal(self):
"""Local tabideal."""
return 1 if self.minify else tabideal
def reind_proc(self, inputstring, **kwargs):
"""Add back indentation."""
out = []
level = 0
for line in inputstring.splitlines():
line, comment = split_comment(line.strip())
indent, line = split_leading_indent(line)
level += ind_change(indent)
if line:
line = " " * self.tabideal * level + line
line, indent = split_trailing_indent(line)
level += ind_change(indent)
line = (line + comment).rstrip()
out.append(line)
if level != 0:
complain(CoconutInternalException("non-zero final indentation level", level))
return "\n".join(out)
def ln_comment(self, ln):
"""Get an end line comment. CoconutInternalExceptions should always be caught and complained."""
if self.keep_lines:
if not 1 <= ln <= len(self.original_lines) + 1:
raise CoconutInternalException(
"out of bounds line number", ln,
"not in range [1, " + str(len(self.original_lines) + 1) + "]",
)
elif ln == len(self.original_lines) + 1: # trim too large
lni = -1
else:
lni = ln - 1
if self.line_numbers and self.keep_lines:
if self.minify:
comment = str(ln) + " " + self.original_lines[lni]
else:
comment = " line " + str(ln) + ": " + self.original_lines[lni]
elif self.keep_lines:
if self.minify:
comment = self.original_lines[lni]
else:
comment = " " + self.original_lines[lni]
elif self.line_numbers:
if self.minify:
comment = str(ln)
else:
comment = " line " + str(ln)
else:
return ""
return self.wrap_comment(comment, reformat=False)
def endline_repl(self, inputstring, reformatting=False, **kwargs):
"""Add end of line comments."""
out = []
ln = 1 # line number
for line in inputstring.splitlines():
add_one_to_ln = False
try:
if line.endswith(lnwrapper):
line, index = line[:-1].rsplit("#", 1)
new_ln = self.get_ref("ln", index)
if new_ln < ln:
raise CoconutInternalException("line number decreased", (ln, new_ln))
ln = new_ln
line = line.rstrip()
add_one_to_ln = True
if not reformatting or add_one_to_ln: # add_one_to_ln here is a proxy for whether there was a ln comment or not
line += self.comments.get(ln, "")
if not reformatting and line.rstrip() and not line.lstrip().startswith("#"):
line += self.ln_comment(ln)
except CoconutInternalException as err:
complain(err)
out.append(line)
if add_one_to_ln:
ln += 1
return "\n".join(out)
def passthrough_repl(self, inputstring, **kwargs):
"""Add back passthroughs."""