-
Notifications
You must be signed in to change notification settings - Fork 21
/
m_ast.py
3351 lines (2612 loc) · 109 KB
/
m_ast.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 python3
##############################################################################
## ##
## MATLAB Independent, Small & Safe, High Integrity Tools ##
## ##
## Copyright (C) 2019-2021, Florian Schanda ##
## ##
## This file is part of MISS_HIT. ##
## ##
## MATLAB Independent, Small & Safe, High Integrity Tools (MISS_HIT) is ##
## free software: you can redistribute it and/or modify it under the ##
## terms of the GNU General Public License as published by the Free ##
## Software Foundation, either version 3 of the License, or (at your ##
## option) any later version. ##
## ##
## MISS_HIT is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with MISS_HIT. If not, see <http://www.gnu.org/licenses/>. ##
## ##
##############################################################################
import subprocess
import re
import os
from copy import copy
from miss_hit_core.config import Config
from miss_hit_core.m_language import TOKEN_KINDS
from miss_hit_core.m_language_builtins import HIGH_IMPACT_BUILTIN_FUNCTIONS
from miss_hit_core.errors import Message_Handler, ICE, Location
##############################################################################
# Lexical tokens
##############################################################################
TOKENS_WITH_IMPLICIT_VALUE = frozenset([
"COMMA",
"SEMICOLON",
"COLON",
"BRA", "KET", # ( )
"C_BRA", "C_KET", # { }
"M_BRA", "M_KET", # [ ] for matrices
"A_BRA", "A_KET", # [ ] for assignment targets
"ASSIGNMENT",
"SELECTION",
"AT",
"METACLASS"
])
assert TOKENS_WITH_IMPLICIT_VALUE <= TOKEN_KINDS
class Autofix_Instruction:
def __init__(self):
self.ensure_trim_before = False
self.ensure_trim_after = False
self.ensure_ws_before = False
self.ensure_ws_after = False
# Control whitespace before/after token
self.ensure_maxgap_before = False
self.ensure_maxgap_after = False
# Make sure there is at most 1 whitespace around this token
self.delete = False
# Remove this token
self.correct_indent = None
# The correct level of indentation
self.replace_with_newline = False
# For CONTINUATION tokens. Means this continuation should be
# just a newline (or comment) instead.
self.change_to_semicolon = False
# Replace this (comma) token with a semicolon
self.add_semicolon_after = False
# Insert a new semicolon after this token
self.add_newline = False
# Insert a newline after this token.
# The following are not fixes as such, but extra annotation to
# produce fixes.
self.binary_operator = False
self.unary_operator = False
# Classification if this token is a unary or binary
# operator. Only set for OPERATOR tokens.
self.spurious = False
# Classification for spurious tokens. Specifically this can be
# set on commas so that mh_style can remove them.
self.statement_terminator = False
# Classification if this comma/semicolon token actually ends a
# statement. I.e. not true for the punctuation inside matrices
# or cells.
self.flag_continuations = False
# Set in cases where continuations following this token would
# be highly problematic
self.make_shortcircuit_explicit = False
# Set for & and | inside if/while guards to change them into
# the explicit short-circuit form && or ||
class MATLAB_Token:
def __init__(self,
kind,
raw_text,
location,
first_in_line,
first_in_statement,
value = None,
anonymous = False,
contains_quotes = False,
block_comment = False,
annotation = False):
assert kind in TOKEN_KINDS
assert isinstance(raw_text, str)
assert isinstance(location, Location)
assert isinstance(first_in_line, bool)
assert isinstance(first_in_statement, bool)
assert isinstance(anonymous, bool)
assert isinstance(contains_quotes, bool)
assert isinstance(block_comment, bool)
assert isinstance(annotation, bool)
assert not contains_quotes or kind in ("STRING", "CARRAY")
self.kind = kind
self.raw_text = raw_text
self.location = location
self.first_in_line = first_in_line
self.first_in_statement = first_in_statement
self.anonymous = anonymous
self.contains_quotes = contains_quotes
self.block_comment = block_comment
self.annotation = annotation
if value is None:
if self.kind in TOKENS_WITH_IMPLICIT_VALUE:
self.value = None
elif self.kind == "CONTINUATION":
self.value = self.raw_text[3:].strip()
elif self.kind == "COMMENT":
if self.block_comment:
self.value = self.raw_text.strip()
else:
self.value = self.raw_text[1:].strip()
elif self.kind in ("CARRAY", "STRING"):
if self.contains_quotes:
self.value = self.raw_text[1:-1]
else:
self.value = self.raw_text
elif self.kind == "BANG":
self.value = self.raw_text[1:]
else:
self.value = self.raw_text
else:
self.value = value
# A free-form dictionary where we can record autofix
# requirements.
self.fix = Autofix_Instruction()
# A link back to the AST so that we can identify to which node
# tokens nominally belong.
self.ast_link = None
def get_unstripped_comment(self):
assert self.kind == "COMMENT"
if self.block_comment:
return self.raw_text
else:
return self.raw_text[1:]
def set_ast(self, node):
assert isinstance(node, Node)
self.ast_link = node
def __repr__(self):
star = "*" if self.anonymous else ""
if self.value is None or self.kind == "NEWLINE":
return "Token%s(%s)" % (star, self.kind)
elif self.kind == "COMMENT" and self.block_comment:
return "Token%s(BLOCK%s, <<%s>>)" % (star, self.kind, self.value)
else:
return "Token%s(%s, <<%s>>)" % (star, self.kind, self.value)
##############################################################################
# AST
##############################################################################
NODE_UID = [0]
class AST_Visitor:
def visit(self, node, n_parent, relation):
pass
def visit_end(self, node, n_parent, relation):
pass
class Node:
""" Root class for AST. Everything is a Node. """
def __init__(self):
NODE_UID[0] += 1
self.uid = NODE_UID[0]
self.n_parent = None
def loc(self):
raise ICE("cannot produce error location")
def set_parent(self, n_parent):
assert isinstance(n_parent, Node)
self.n_parent = n_parent
def debug_parse_tree(self):
pass
def _visit(self, parent, function, relation):
# This function must not be overwritten
assert parent is None or isinstance(parent, Node)
assert isinstance(function, AST_Visitor)
assert isinstance(relation, str)
function.visit(self, parent, relation)
def _visit_end(self, parent, function, relation):
# This function must not be overwritten
assert parent is None or isinstance(parent, Node)
assert isinstance(function, AST_Visitor)
assert isinstance(relation, str)
function.visit_end(self, parent, relation)
def _visit_list(self, the_list, function, relation):
# This function must not be overwritten
for the_node in the_list:
the_node.visit(self, function, relation)
def visit(self, parent, function, relation):
# This function should be over-written by each node to
# implement the visitor pattern.
self._visit(parent, function, relation)
self._visit_end(parent, function, relation)
def pp_node(self, fd=None):
self.visit(None, Text_Visitor(fd), "Root")
def causes_indentation(self):
if isinstance(self, If_Statement):
# We do not indent for this, since the if actions
# indent instead.
return False
elif isinstance(self, (Action,
Special_Block,
Class_Definition,
Function_Definition,
Compound_Statement)):
return True
else:
return False
def get_indentation(self):
# Indentation is the same level as the parent. + 1 if the
# parent itself causes children to be indented.
if self.n_parent:
indent = self.n_parent.get_indentation()
if self.n_parent.causes_indentation():
indent += 1
else:
indent = 0
return indent
##############################################################################
# Some top-level groupings
##############################################################################
class Expression(Node):
def __init__(self):
super().__init__()
self.t_bracket_open = None
self.t_bracket_close = None
# Tokens for the () around this expression
def set_enclosing_brackets(self, t_open, t_close):
assert isinstance(t_open, MATLAB_Token)
assert isinstance(t_close, MATLAB_Token)
assert t_open.kind == "BRA"
assert t_close.kind == "KET"
self.t_bracket_open = t_open
self.t_bracket_open.set_ast(self)
self.t_bracket_close = t_close
self.t_bracket_close.set_ast(self)
def evaluate_static_string_expression(self):
raise ICE("not a static string expression")
class Name(Expression):
def is_simple_dotted_name(self):
return False
def sty_check_builtin_shadow(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
class Literal(Expression):
pass
class Definition(Node):
def __init__(self):
super().__init__()
self.n_docstring = None
# Optional docstring (the first set of unbroken
# comments). Note that this is not produced by the parser, but
# can be set by other (comment aware) tools such as MH Style.
def set_docstring(self, n_docstring):
assert isinstance(n_docstring, Docstring)
self.n_docstring = n_docstring
self.n_docstring.set_parent(self)
def get_local_name(self):
raise ICE("get_local_name not implemented")
class Pragma(Node):
def __init__(self, t_pragma, t_kind):
super().__init__()
assert isinstance(t_pragma, MATLAB_Token)
assert t_pragma.kind == "KEYWORD" and t_pragma.value == "pragma"
assert isinstance(t_kind, MATLAB_Token)
assert t_kind.kind == "IDENTIFIER"
self.t_pragma = t_pragma
self.t_pragma.set_ast(self)
# The pragma token
self.t_kind = t_kind
self.t_kind.set_ast(self)
# The pragma kind
def loc(self):
return self.t_pragma.location
def set_parent(self, n_parent):
assert isinstance(n_parent, (Sequence_Of_Statements,
Compilation_Unit))
super().set_parent(n_parent)
class Statement(Node):
def set_parent(self, n_parent):
assert isinstance(n_parent, Sequence_Of_Statements)
super().set_parent(n_parent)
class Simple_Statement(Statement):
pass
class Compound_Statement(Statement):
pass
class Compilation_Unit(Node):
# pylint: disable=unused-argument
def __init__(self, name, dirname, loc, file_length):
super().__init__()
assert isinstance(name, str)
assert isinstance(dirname, str)
assert isinstance(loc, Location)
assert isinstance(file_length, int) and file_length >= 0
self.name = name
# Not a node since it comes from the filename
self.dirname = dirname
# Name of the directory; relevant later to sort out which
# package we're part of
self.error_location = loc
# In case we need to attach a message to the compilation unit
# itself
self.file_length = file_length
# The number of lines in this file
self.scope = None
# Set by m_sem, will contain the symbol table for this unit
self.n_docstring = None
# Optional docstring (the first set of unbroken
# comments). Note that this is not produced by the parser, but
# can be set by other (comment aware) tools such as MH Style.
def loc(self):
return self.error_location
def set_parent(self, n_parent):
raise ICE("compilation unit cannot have a parent")
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
raise ICE("compilation unit root implements no checks")
def set_docstring(self, n_docstring):
assert isinstance(n_docstring, Docstring)
self.n_docstring = n_docstring
self.n_docstring.set_parent(self)
def get_name_prefix(self):
rv = ""
cdir = os.path.normpath(self.dirname)
while True:
dname = os.path.basename(cdir)
cdir = os.path.dirname(cdir)
if dname.startswith("+"):
rv = dname[1:] + "." + rv
elif dname.startswith("@"):
rv = dname[1:] + "::" + rv
else:
break
return rv
##############################################################################
# Compilation units
##############################################################################
class Script_File(Compilation_Unit):
def __init__(self,
name, dirname, loc, file_length,
n_statements, l_functions, l_pragmas):
super().__init__(name, dirname, loc, file_length)
assert isinstance(n_statements, Sequence_Of_Statements)
assert isinstance(l_functions, list)
for n_function in l_functions:
assert isinstance(n_function, Function_Definition)
assert isinstance(l_pragmas, list)
for n_pragma in l_pragmas:
assert isinstance(n_pragma, Pragma)
self.n_statements = n_statements
self.n_statements.set_parent(self)
# The main body of the script file
self.n_statements.prepend_pragmas(l_pragmas)
# The list of pragmas we found so far actually belongs to the
# statement list in this file.
self.l_functions = l_functions
for n_function in self.l_functions:
n_function.set_parent(self)
# Auxiliary functions the script may define.
def debug_parse_tree(self):
dotpr("scr_" + str(self.name) + ".dot", self.n_statements)
subprocess.run(["dot", "-Tpdf",
"scr_" + str(self.name) + ".dot",
"-oscr_" + str(self.name) + ".pdf"],
check=False)
for n_function in self.l_functions:
n_function.debug_parse_tree()
def visit(self, parent, function, relation):
self._visit(parent, function, relation)
self.n_statements.visit(self, function, "Statements")
self._visit_list(self.l_functions, function, "Functions")
self._visit_end(parent, function, relation)
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
for n_function in self.l_functions:
n_function.sty_check_naming(mh, cfg)
if cfg.active("naming_scripts"):
regex = cfg.style_config["regex_script_name"]
file_root = self.name.rsplit(".", 1)[0]
if not re.match("^(" + regex + ")$", file_root):
mh.style_issue(self.loc(),
"violates naming scheme for scripts")
def get_local_name(self):
return self.name.rsplit(".", 1)[0]
class Function_File(Compilation_Unit):
def __init__(self,
name, dirname, loc, file_length,
l_functions, is_separate, l_pragmas):
super().__init__(name, dirname, loc, file_length)
assert isinstance(l_functions, list)
assert len(l_functions) >= 1
for n_function in l_functions:
assert isinstance(n_function, Function_Definition)
assert isinstance(is_separate, bool)
assert isinstance(l_pragmas, list)
for n_pragma in l_pragmas:
assert isinstance(n_pragma, Pragma)
self.l_functions = l_functions
for n_function in self.l_functions:
n_function.set_parent(self)
# The list of functions we define. The first one is the entry
# point, the others are auxiliary (but not nested) functions.
self.is_separate = is_separate
# If true, then this compilation unit resides in a @ directory
# for classes.
self.l_pragmas = l_pragmas
for n_pragma in l_pragmas:
n_pragma.set_parent(self)
# A list of pragmas that applies to this compilation unit
def debug_parse_tree(self):
for n_function in self.l_functions:
n_function.debug_parse_tree()
def visit(self, parent, function, relation):
self._visit(parent, function, relation)
self._visit_list(self.l_pragmas, function, "Pragmas")
self._visit_list(self.l_functions, function, "Functions")
self._visit_end(parent, function, relation)
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
for n_function in self.l_functions:
n_function.sty_check_naming(mh, cfg)
class Class_File(Compilation_Unit):
def __init__(self,
name, dirname, loc, file_length,
n_classdef, l_functions, l_pragmas):
super().__init__(name, dirname, loc, file_length)
assert isinstance(n_classdef, Class_Definition)
assert isinstance(l_functions, list)
for n_function in l_functions:
assert isinstance(n_function, Function_Definition)
assert isinstance(l_pragmas, list)
for n_pragma in l_pragmas:
assert isinstance(n_pragma, Pragma)
self.n_classdef = n_classdef
self.n_classdef.set_parent(self)
# The single class definition for this unit
self.l_functions = l_functions
for n_function in self.l_functions:
n_function.set_parent(self)
# Auxiliary (but not nested) functions that can appear after
# the class definition.
self.l_pragmas = l_pragmas
for n_pragma in l_pragmas:
n_pragma.set_parent(self)
# A list of pragmas that applies to this compilation unit
def debug_parse_tree(self):
dotpr("cls_" + str(self.name) + ".dot", self.n_classdef)
subprocess.run(["dot", "-Tpdf",
"cls_" + str(self.name) + ".dot",
"-ocls_" + str(self.name) + ".pdf"],
check=False)
for n_function in self.l_functions:
n_function.debug_parse_tree()
for n_block in self.n_classdef.l_methods:
for n_item in n_block.l_items:
if isinstance(n_item, Function_Definition):
n_item.debug_parse_tree()
def visit(self, parent, function, relation):
self._visit(parent, function, relation)
self._visit_list(self.l_pragmas, function, "Pragmas")
self.n_classdef.visit(self, function, "Classdef")
self._visit_list(self.l_functions, function, "Functions")
self._visit_end(parent, function, relation)
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
self.n_classdef.sty_check_naming(mh, cfg)
for n_function in self.l_functions:
n_function.sty_check_naming(mh, cfg)
##############################################################################
# Definitions
##############################################################################
class Class_Definition(Definition):
def __init__(self, t_classdef):
super().__init__()
assert isinstance(t_classdef, MATLAB_Token)
assert t_classdef.kind == "KEYWORD" and \
t_classdef.value == "classdef"
self.entity = None
# Pointer to the class entity
self.t_classdef = t_classdef
self.t_classdef.set_ast(self)
# Token for the classdef
self.n_name = None
# Name of the class. Always a simple identifier, not even dots
# are allowed here.
self.n_constructor = None
self.n_constructor_sig = None
# Short-cut to constructor function (if it exists)
self.l_attr = []
# Optional list of class attributes
self.l_super = []
# Optional list of superclasses
self.l_properties = []
self.l_events = []
self.l_enumerations = []
self.l_methods = []
# List of special class blocks
def loc(self):
if self.n_name:
return self.n_name.loc()
else:
return self.t_classdef.location
def set_name(self, n_name):
assert isinstance(n_name, Identifier)
self.n_name = n_name
self.n_name.set_parent(self)
def set_attributes(self, l_attr):
assert isinstance(l_attr, list)
for n_attr in l_attr:
assert isinstance(n_attr, Name_Value_Pair)
self.l_attr = l_attr
for n_attr in self.l_attr:
n_attr.set_parent(self)
def get_attribute(self, name):
assert isinstance(name, str)
for n_nv_pair in self.l_attr:
if str(n_nv_pair.n_name) == name:
return n_nv_pair
return None
def set_super_classes(self, l_super):
assert isinstance(l_super, list)
for n_super in l_super:
assert isinstance(n_super, Name)
self.l_super = l_super
for n_superclass in self.l_super:
n_superclass.set_parent(self)
def set_parent(self, n_parent):
assert isinstance(n_parent, Class_File)
super().set_parent(n_parent)
def visit(self, parent, function, relation):
self._visit(parent, function, relation)
self.n_name.visit(self, function, "Name")
if self.n_constructor:
self.n_constructor.visit(self, function, "Constructor")
elif self.n_constructor_sig:
self.n_constructor_sig.visit(self,
function,
"Constructor Signature")
self._visit_list(self.l_super, function, "Superclasses")
self._visit_list(self.l_attr, function, "Attributes")
self._visit_list(self.l_properties, function, "Properties")
self._visit_list(self.l_events, function, "Events")
self._visit_list(self.l_enumerations, function, "Enumerations")
self._visit_list(self.l_methods, function, "Methods")
self._visit_end(parent, function, relation)
def add_block(self, mh, n_block):
assert isinstance(mh, Message_Handler)
assert isinstance(n_block, Special_Block)
if n_block.kind() == "properties":
self.l_properties.append(n_block)
elif n_block.kind() == "methods":
self.l_methods.append(n_block)
for n_item in n_block.l_items:
if isinstance(n_item, Function_Definition):
n_con = n_item
n_sig = n_item.n_sig
elif isinstance(n_item, Function_Signature):
n_con = None
n_sig = n_item
else:
raise ICE("%s item in method block is not function"
" signature or function definition" %
n_item.__class__.__name__)
if str(n_sig.n_name) == str(self.n_name):
if self.n_constructor_sig is None:
self.n_constructor = n_con
self.n_constructor_sig = n_sig
n_sig.is_constructor = True
else:
mh.error(n_item.loc(),
"class can only have one constructor,"
" previous declaration in line %u" %
self.n_constructor_sig.loc().line,
fatal=False)
elif n_block.kind() == "events":
self.l_events.append(n_block)
elif n_block.kind() == "enumeration":
self.l_enumerations.append(n_block)
else:
raise ICE("unexpected block kind %s" % n_block.kind())
n_block.set_parent(self)
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
if cfg.active("naming_classes"):
self.n_name.sty_check_naming(mh, cfg, "class")
for n_block in self.l_methods:
for n_function in n_block.l_items:
n_function.sty_check_naming(mh, cfg)
for n_block in self.l_enumerations:
for n_enum in n_block.l_items:
n_enum.sty_check_naming(mh, cfg)
def get_local_name(self):
if isinstance(self.n_parent, Class_File):
return str(self.n_name)
else:
raise ICE("logic error: parent of class is %s" %
self.n_parent.__class__.__name__)
class Function_Definition(Definition):
def __init__(self, t_fun, n_sig,
l_validation, n_body, l_nested):
super().__init__()
assert isinstance(t_fun, MATLAB_Token)
assert t_fun.kind == "KEYWORD" and t_fun.value == "function"
assert isinstance(n_sig, Function_Signature)
assert isinstance(l_validation, list)
for n in l_validation:
assert isinstance(n, Special_Block)
assert isinstance(n_body, Sequence_Of_Statements)
assert isinstance(l_nested, list)
for n in l_nested:
assert isinstance(n, Function_Definition)
self.t_fun = t_fun
self.t_fun.set_ast(self)
# The 'function' token
self.t_end = None
# The (optional) end token
self.n_sig = n_sig
self.n_sig.set_parent(self)
# The function signature i.e. name, inputs, and outputs
self.l_validation = l_validation
for n_block in self.l_validation:
n_block.set_parent(self)
# Optional list of function argument validation blocks (new in
# MATLAB 2019b).
self.n_body = n_body
self.n_body.set_parent(self)
# Function body
self.l_nested = l_nested
for n_fdef in self.l_nested:
n_fdef.set_parent(self)
# Optional list of nested functions
def loc(self):
if self.n_sig.n_name:
return self.n_sig.loc()
else:
return self.t_fun.location
def set_parent(self, n_parent):
assert isinstance(n_parent, (Compilation_Unit,
Special_Block,
Function_Definition))
super().set_parent(n_parent)
def set_end(self, t_end):
assert isinstance(t_end, MATLAB_Token)
assert t_end.kind == "KEYWORD" and t_end.value == "end"
self.t_end = t_end
self.t_end.set_ast(self)
def debug_parse_tree(self):
dotpr("fun_" + str(self.n_sig.n_name) + ".dot", self)
subprocess.run(["dot", "-Tpdf",
"fun_" + str(self.n_sig.n_name) + ".dot",
"-ofun_" + str(self.n_sig.n_name) + ".pdf"],
check=False)
for n_function in self.l_nested:
n_function.debug_parse_tree()
def visit(self, parent, function, relation):
self._visit(parent, function, relation)
self.n_sig.visit(self, function, "Signature")
self._visit_list(self.l_validation, function, "Validation")
self.n_body.visit(self, function, "Body")
self._visit_list(self.l_nested, function, "Nested")
self._visit_end(parent, function, relation)
def sty_check_naming(self, mh, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, Config)
self.n_sig.sty_check_naming(mh, cfg)
for n_function in self.l_nested:
n_function.sty_check_naming(mh, cfg)
def is_class_method(self):
# We're a class method in two scenarios:
#
# 1. We're directly in a class
#
# 2. We're the first function in a function file that is in a
# @ directory
return isinstance(self.n_parent, Special_Block) or \
(isinstance(self.n_parent, Function_File) and
self.n_parent.is_separate and
self.n_parent.l_functions[0] == self)
def get_local_name(self):
if isinstance(self.n_parent, Function_File):
return str(self.n_sig.n_name)
elif isinstance(self.n_parent, Compilation_Unit):
return "%s::%s" % (self.n_parent.name,
str(self.n_sig.n_name))
elif isinstance(self.n_parent, Special_Block):
return "%s::%s" % (self.n_parent.n_parent.get_local_name(),
str(self.n_sig.n_name))
elif isinstance(self.n_parent, Function_Definition):
return "%s::%s" % (self.n_parent.get_local_name(),
str(self.n_sig.n_name))
else:
raise ICE("logic error: parent of fn is %s" %
self.n_parent.__class__.__name__)
##############################################################################
# Nodes
##############################################################################
class Copyright_Info(Node):
def __init__(self, n_parent, t_comment, re_match):
super().__init__()
assert isinstance(t_comment, MATLAB_Token)
assert t_comment.kind == "COMMENT"
# assert isinstance(re_match, re.Match)
# In 3.6 this is a _sre.SRE_Match object; so we can't easily
# check for this...
self.t_comment = t_comment
self.match = re_match
self.set_parent(n_parent)
def is_block_comment(self):
return self.t_comment.block_comment
def get_copy_notice(self):
return self.match.group("copy")
def get_org(self):
return self.match.group("org")
def get_ystart(self):
return int(self.match.group("ystart"))
def get_yend(self):
return int(self.match.group("yend"))
def get_range(self):
if self.match.group("ystart"):
return (self.get_ystart(), self.get_yend())
else:
return (self.get_yend(), self.get_yend())
def get_comment_text_loc(self):
# Get a location for the actual text of the comment. We need
# to carefully shift to account for the stripped value
rv = copy(self.t_comment.location)
rv.col_start += (len(self.t_comment.raw_text.rstrip()) -
len(self.t_comment.value))
return rv
def loc_org(self):
rv = self.get_comment_text_loc()
rv.col_end = rv.col_start + (self.match.span("org")[1] - 1)
rv.col_start += self.match.span("org")[0]
return rv
def loc_yend(self):
rv = self.get_comment_text_loc()
rv.col_end = rv.col_start + (self.match.span("yend")[1] - 1)
rv.col_start += self.match.span("yend")[0]
return rv
def loc_ystart(self):
if self.match.group("ystart"):
rv = self.get_comment_text_loc()
rv.col_end = rv.col_start + (self.match.span("ystart")[1] - 1)
rv.col_start += self.match.span("ystart")[0]
return rv
else:
return self.loc_yend()
def set_parent(self, n_parent):
assert isinstance(n_parent, Docstring)
super().set_parent(n_parent)
class Docstring(Node):
def __init__(self, copyright_regex):
super().__init__()
assert isinstance(copyright_regex, str)
self.l_comments = []
self.re_copyright = re.compile(copyright_regex)
self.copyright_info = []
def loc(self):
if self.l_comments:
return self.l_comments[0].location
else:
return self.n_parent.loc()
def add_comment(self, t_comment):
assert isinstance(t_comment, MATLAB_Token)
assert t_comment.kind == "COMMENT"
assert t_comment.first_in_line
if self.l_comments:
assert self.l_comments[-1].location.line < t_comment.location.line
# Do not add block comment braces
if t_comment.block_comment and t_comment.value in ("{", "}"):
return
self.l_comments.append(t_comment)
t_comment.ast_link = self
match = self.re_copyright.search(t_comment.value)
if match:
self.copyright_info.append(Copyright_Info(self, t_comment, match))
def set_parent(self, n_parent):
assert isinstance(n_parent, (Definition,
Compilation_Unit))