-
Notifications
You must be signed in to change notification settings - Fork 21
/
m_parser.py
2268 lines (1892 loc) · 80.1 KB
/
m_parser.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-2023, Florian Schanda ##
## Copyright (C) 2019-2020, Zenuity AB ##
## ##
## 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 os
from miss_hit_core import pathutil
from miss_hit_core.config import Config, METRICS
from miss_hit_core.errors import ICE, Message_Handler
from miss_hit_core.m_ast import *
from miss_hit_core.m_language import Language
from miss_hit_core.m_lexer import Token_Generator
IGNORED_TOKENS = frozenset(["COMMENT"])
# A general note on the embedded grammar fragments: we're using Ada RM
# style grammar. This means:
#
# ::= indicates a production
# [ grammar ] means zero or one
# { grammar } means zero or more repeating
# ( grammar ) groups a grammar fragment (usually a disjunction)
# '{' means the token {
# | means an alternative production
# Operator precedence as of MATLAB 2019b
# https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html
#
# 1. Parentheses ()
#
# 2. Transpose (.'), power (.^), complex conjugate transpose ('),
# matrix power (^)
#
# 3. Power with unary minus (.^-), unary plus (.^+), or logical
# negation (.^~) as well as matrix power with unary minus (^-), unary
# plus (^+), or logical negation (^~).
#
# Note: Although most operators work from left to right, the
# operators (^-), (.^-), (^+), (.^+), (^~), and (.^~) work from
# second from the right to left. It is recommended that you use
# parentheses to explicitly specify the intended precedence of
# statements containing these operator combinations.
#
# 4. Unary plus (+), unary minus (-), logical negation (~)
#
# 5. Multiplication (.*), right division (./), left division (.\),
# matrix multiplication (*), matrix right division (/), matrix left
# division (\)
#
# 6. Addition (+), subtraction (-)
#
# 7. Colon operator (:)
#
# 8. Less than (<), less than or equal to (<=), greater than (>),
# greater than or equal to (>=), equal to (==), not equal to (~=)
#
# 9. Element-wise AND (&)
#
# 10. Element-wise OR (|)
#
# 11. Short-circuit AND (&&)
#
# 12. Short-circuit OR (||)
class MATLAB_Parser:
def __init__(self, mh, lexer, cfg):
assert isinstance(mh, Message_Handler)
assert isinstance(lexer, Token_Generator)
assert isinstance(cfg, Config)
self.lexer = lexer
self.language = self.lexer.language
self.mh = mh
self.cfg = cfg
self.context = []
self.functions_require_end = False
# If true, we have encountered a function with end. This means
# all of them must have an end.
self.in_shortcircuit_context = False
# Some places change the meaning of & and |, we use this to
# keep track of it.
#
# Note: this is not always correct, in some cases & means &
# even inside a top level if. Specifically if either operand
# is an array (see test parser/bug_139). For now this does not
# matter (the style rule that would make use of this has been
# disabled) but we need to sort this out in semantic analysis.
#
# Curiously mlint seems to share this bug.
# pylint: disable=invalid-name
self.ct = None
self.nt = None
self.nnt = None
# pylint: enable=invalid-name
self.debug_tree = False
self.skip()
self.skip()
def sc_context(self, enabled):
assert isinstance(enabled, bool)
class CM:
def __init__(self, parser, current_value, new_value):
self.parser = parser
self.old_value = current_value
self.new_value = new_value
def __enter__(self):
self.parser.in_shortcircuit_context = self.new_value
def __exit__(self, exc_type, exc_val, exc_tb):
self.parser.in_shortcircuit_context = self.old_value
return CM(self, self.in_shortcircuit_context, enabled)
def push_context(self, kind):
assert kind in ("function", "classdef",
"loop", "if", "switch",
"block")
self.context.append(kind)
def pop_context(self):
if self.context:
self.context.pop()
else:
raise ICE("context is empty")
def in_context(self, kind):
assert kind in ("function", "classdef",
"loop", "if", "switch",
"block")
for k in reversed(self.context):
if kind == k:
return True
elif k in ("function", "classdef"):
return False
return False
def skip(self):
def should_skip(token):
# Returns true iff this token should be completely passed
# over by the parser. We do this since the lexer produces
# tokens for whitespace and comments (needed for pretty
# printing in mh_style).
if not token:
# Never skip EOF
return False
elif token.kind in ("COMMENT",
"CONTINUATION",
"ANNOTATION"):
# Skip all of these in all cases
return True
elif token.annotation and token.kind == "NEWLINE":
# In MATLAB newlines are important. In MISS_HIT
# annotations they are not, so if we're in an
# annotation we can just ignore them.
return True
else:
# Otherwise don't skip
return False
self.ct = self.nt
self.nt = self.nnt
self.nnt = self.lexer.token()
while self.nnt:
# Skip comments, continuations and annotation indications
while should_skip(self.nnt):
self.nnt = self.lexer.token()
# Join new-lines
if (self.nnt and
self.nt and
self.nnt.kind == "NEWLINE" and
self.nt.kind == "NEWLINE"):
self.nnt = self.lexer.token()
else:
break
def match(self, kind, value=None):
assert kind in self.language.token_kinds
self.skip()
if self.ct is None:
self.mh.error(self.lexer.get_file_loc(),
"expected %s, reached EOF instead" % kind)
elif self.ct.annotation:
self.mh.error(self.ct.location,
"expected %s, "
"found miss_hit annotation instead" %
kind)
elif self.ct.kind != kind:
if value:
self.mh.error(self.ct.location,
"expected %s(%s), found %s instead" %
(kind, value, self.ct.kind))
else:
self.mh.error(self.ct.location,
"expected %s, found %s instead" % (kind,
self.ct.kind))
elif value and self.ct.value != value:
self.mh.error(self.ct.location,
"expected %s(%s), found %s(%s) instead" %
(kind, value, self.ct.kind, self.ct.value))
def amatch(self, kind, value=None):
assert kind in self.language.token_kinds
self.skip()
if self.ct is None:
self.mh.error(self.lexer.get_file_loc(),
"expected %s, reached EOF instead" % kind)
elif not self.ct.annotation:
self.mh.error(self.ct.location,
"expected %s annotation, "
"found normal program text instead" %
kind)
elif self.ct.kind != kind:
if value:
self.mh.error(self.ct.location,
"expected %s(%s), found %s instead" %
(kind, value, self.ct.kind))
else:
self.mh.error(self.ct.location,
"expected %s, found %s instead" % (kind,
self.ct.kind))
elif value and self.ct.value != value:
self.mh.error(self.ct.location,
"expected %s(%s), found %s(%s) instead" %
(kind, value, self.ct.kind, self.ct.value))
def match_eof(self):
self.skip()
if self.ct is not None:
if self.ct.annotation:
self.mh.error(self.ct.location,
"expected end of file, "
"found annotation %s instead" %
self.ct.kind)
else:
self.mh.error(self.ct.location,
"expected end of file, found %s instead" %
self.ct.kind)
def peek_annotation(self):
return self.nt and self.nt.annotation
def peek(self, kind, value=None):
assert kind in self.language.token_kinds
if self.nt and \
self.nt.kind == kind and \
not self.nt.annotation:
if value is None:
return True
else:
return self.nt.value == value
else:
return False
def peek2(self, kind, value=None):
assert kind in self.language.token_kinds
if self.nnt and \
self.nnt.kind == kind and \
not self.nnt.annotation:
if value is None:
return True
else:
return self.nnt.value == value
else:
return False
def apeek(self, kind, value=None):
assert kind in self.language.token_kinds
if self.nt and \
self.nt.kind == kind and \
self.nt.annotation:
if value is None:
return True
else:
return self.nt.value == value
else:
return False
def peek_eof(self):
return self.nt is None
##########################################################################
# Some style-related helper functions
def set_expression_brackets(self, n_expr, t_open, t_close):
assert isinstance(n_expr, Expression)
# We already have brackets, so any old ones are redundant
self.check_redundant_brackets(n_expr)
n_expr.set_enclosing_brackets(t_open, t_close)
def check_redundant_brackets(self, n_expr):
assert isinstance(n_expr, Expression), \
"required expression, not %s" % n_expr.__class__.__name__
if self.cfg.active("redundant_brackets") and \
n_expr.t_bracket_open:
self.mh.style_issue(n_expr.t_bracket_open.location,
"redundant parenthesis",
"redundant_brackets",
True)
n_expr.t_bracket_open.fix.delete = True
n_expr.t_bracket_close.fix.delete = True
##########################################################################
# Parsing
def peek_eos(self):
return self.peek("SEMICOLON") or \
self.peek("COMMA") or \
self.peek("NEWLINE")
def match_eos(self, n_ast, semi = "", allow_nothing = False):
"""Match end-of-statement
This generally matches a newline. If semi is set to ";", then
it matches a semicolon followed by a newline. Anything that
deviates from this will create style issues.
Any termination tokens are attached to the node given by
n_ast.
A syntax error is raised if ot statement terminator is found,
unless allow_nothing is set to true.
"""
assert isinstance(n_ast, Node)
assert semi in ("", ";")
assert isinstance(allow_nothing, bool)
ending_token = self.ct
# The last token of the previous thing. We might need it later
# to attach error messages or to record autofix instructions.
# Get all terminator tokens that follow our ending token.
terminator_tokens = []
first_newline = None
while self.peek_eos():
self.skip()
self.ct.set_ast(n_ast)
self.ct.fix.statement_terminator = True
terminator_tokens.append(self.ct)
if self.ct.kind == "NEWLINE" and first_newline is None:
first_newline = len(terminator_tokens) - 1
break
while self.peek_eos(): # and not self.peek("NEWLINE"):
self.skip()
self.ct.set_ast(n_ast)
self.ct.fix.statement_terminator = True
terminator_tokens.append(self.ct)
if not terminator_tokens:
# We found nothing. This is actually a syntax error in
# most cases.
if allow_nothing:
ending_token.fix.flag_continuations = True
if self.cfg.active("end_of_statements"):
if semi:
ending_token.add_semicolon_after = True
if self.cfg.active("indentation"):
ending_token.fix.add_newline = True
self.mh.style_issue(ending_token.location,
"end this with a ; and newline",
"end_of_statements",
True)
else:
fixed = False
if self.cfg.active("indentation"):
ending_token.fix.add_newline = True
fixed = True
self.mh.style_issue(ending_token.location,
"end statement with a newline",
"end_of_statements",
fixed)
return
elif self.peek_eof():
# EOF is also a valid (but rude) terminator
return
else:
self.mh.error(self.nt.location,
"expected end of statement,"
" found %s instead" % self.nt.kind)
raise ICE("logic error")
assert len(terminator_tokens) >= 1
if not self.cfg.active("end_of_statements"):
return
if semi:
# Exactly two tokens are required and useful. The first
# semicolon, and the first new_line.
if terminator_tokens[0].kind == "SEMICOLON":
pass
elif terminator_tokens[0].kind == "COMMA":
self.mh.style_issue(terminator_tokens[0].location,
"end this with a semicolon"
" instead of a comma",
"end_of_statements",
True)
terminator_tokens[0].fix.change_to_semicolon = True
else:
assert terminator_tokens[0].kind == "NEWLINE"
self.mh.style_issue(ending_token.location,
"end statement with a semicolon",
"end_of_statements",
True)
ending_token.fix.add_semicolon_after = True
if first_newline is None:
fixed = False
if self.cfg.active("indentation"):
terminator_tokens[0].fix.add_newline = True
fixed = True
self.mh.style_issue(terminator_tokens[0].location,
"end statement with a newline",
"end_of_statements",
fixed)
else:
# Exactly one token is required and useful. The first new
# line.
if not self.cfg.active("indentation") and \
terminator_tokens[0].kind == "COMMA":
# The statement was ended with a comma. Ideally we
# just have a newline, but since we're not fixing
# indetation we can't fix it. Complain instead about
# the comma
self.mh.style_issue(ending_token.location,
"end this with just a newline",
"end_of_statements",
False)
if first_newline is None:
terminator_tokens[0].fix.change_to_semicolon = True
elif terminator_tokens[0].kind != "NEWLINE":
fixed = False
if first_newline is None:
# We can only fix a missing newline if indentation
# fixing is active.
if self.cfg.active("indentation"):
terminator_tokens[0].fix.delete = True
ending_token.fix.add_newline = True
fixed = True
else:
terminator_tokens[0].fix.delete = True
fixed = True
self.mh.style_issue(terminator_tokens[0].location,
"end this with just a newline",
"end_of_statements",
fixed)
for terminator in terminator_tokens[1:]:
if terminator.kind != "NEWLINE":
self.mh.style_issue(terminator.location, # Molten steel?
"unnecessary statement terminator",
"end_of_statements",
True)
terminator.fix.delete = True
def parse_identifier(self, allow_void, allow_some_keywords=False):
# identifier ::= <IDENTIFIER>
#
# void_or_identifier ::= identifier
# | '~'
#
# If allow_some_keywords is true, we permit some keywords that
# are normally reserved to be identifiers. This is to allow
# class methods called 'end' or 'methods'.
#
# The exception to this is 'end', since that is generally
# allowed since it makes parsing expressions using ranges much
# easier.
if self.peek("OPERATOR", "~") and allow_void:
self.match("OPERATOR")
elif self.peek("KEYWORD", "end"):
self.match("KEYWORD", "end")
elif allow_some_keywords and self.peek("KEYWORD", "import"):
self.match("KEYWORD", "import")
elif allow_some_keywords and self.peek("KEYWORD", "arguments"):
self.match("KEYWORD", "arguments")
else:
self.match("IDENTIFIER")
return Identifier(self.ct)
def parse_name(self, allow_void):
# superclass_ref ::= simple_name '@' function_reference
#
# simple_name ::= identifier
# | simple_name '.' identifier
#
# function_reference ::= simple_name
# | simple_name '(' expression_list ')'
#
# name ::= superclass_ref
# | simple_name
# | name '.' identifier
# | name '.' '(' expression ')'
# | name '(' expression_list ')'
# | name '{' expression_list '}'
#
# Note that we can only resolve the ambiguity between
# metaclass, simplename or any of the others late (but we can
# always resolve it).
#
# expression_list ::= <>
# | expression { ',' expression }
# First we parse as much as possible as a simple name.
rv = self.parse_simple_name(allow_void)
# Then we can see if we have a superclass reference. What
# follows are pretty different parse rules for the two cases.
if self.peek("AT"):
self.match("AT")
t_at = self.ct
at_prefix = rv
at_suffix = self.parse_simple_name()
if self.peek("BRA"):
at_suffix = Reference(at_suffix)
at_suffix.set_arguments(self.parse_argument_list(at_suffix))
return Superclass_Reference(t_at, at_prefix, at_suffix)
else:
while (self.peek("SELECTION") or
self.peek("BRA") or
self.peek("C_BRA")):
if self.peek("SELECTION"):
self.match("SELECTION")
tok = self.ct
if self.peek("BRA"):
self.match("BRA")
t_open = self.ct
dyn_field = self.parse_expression()
self.match("KET")
t_close = self.ct
rv = Dynamic_Selection(tok, rv, dyn_field)
t_open.set_ast(rv)
t_close.set_ast(rv)
else:
field = self.parse_identifier(allow_void=False)
rv = Selection(tok, rv, field)
elif self.peek("BRA"):
rv = Reference(rv)
rv.set_arguments(self.parse_argument_list(rv))
elif self.peek("C_BRA"):
rv = self.parse_cell_reference(rv)
else:
raise ICE("impossible path (nt.kind = %s)" % self.nt.kind)
return rv
def parse_simple_name(self, allow_void=False, allow_some_keywords=False):
# reference ::= identifier
# | reference '.' identifier
rv = self.parse_identifier(allow_void=allow_void,
allow_some_keywords=allow_some_keywords)
# We need to lookahead 2 here to avoid parsing dynamic fields
while self.peek("SELECTION") and not self.peek2("BRA"):
if self.peek("SELECTION"):
self.match("SELECTION")
tok = self.ct
field = self.parse_identifier(
allow_void=allow_void,
allow_some_keywords=allow_some_keywords)
rv = Selection(tok, rv, field)
else:
raise ICE("impossible path (nt.kind = %s)" % self.nt.kind)
return rv
def parse_file(self):
# This is the top-level parse function. First we need to
# figure out exactly what kind of file we're dealing
# with. This also hilariously depends on the file name.
# File can start with pragmas or newlines. We need to process
# them first until we arrive at the first interesting thing
# that helps us decide.
l_pragmas = []
while self.peek("NEWLINE") or self.apeek("KEYWORD", "pragma"):
if self.peek("NEWLINE"):
self.skip()
else:
l_pragmas.append(self.parse_annotation_pragma())
if self.peek("KEYWORD", "function"):
l_functions, l_more_pragmas = self.parse_function_list()
cunit = Function_File(os.path.basename(self.lexer.filename),
os.path.dirname(
pathutil.abspath(self.lexer.filename)),
self.lexer.get_file_loc(),
self.lexer.line_count(),
l_functions,
self.lexer.in_class_directory,
l_pragmas + l_more_pragmas)
elif self.peek("KEYWORD", "classdef"):
cunit = self.parse_class_file(l_pragmas)
elif self.language.script_global_functions:
cunit = self.parse_octave_script_file(l_pragmas)
else:
cunit = self.parse_matlab_script_file(l_pragmas)
# Special detection of Octave inline globals in MATLAB
# mode (to improve the messages produced in #198).
if not self.peek_eof() and cunit.l_functions:
self.mh.error(cunit.l_functions[0].loc(),
"script-global functions are an Octave-specific"
" feature; move your functions to the end of"
" the script file or use an Octave language")
if self.debug_tree:
cunit.debug_parse_tree()
self.match_eof()
return cunit
def parse_matlab_script_file(self, l_pragmas):
# A MATLAB script file is a bunch of statements, followed by
# zero or more private functions. This is distinct from Octave
# script files, which allow you to sprinkle functions anywhere
# in the top-level context.
# At least in MATLAB 2017b script files cannot use the
# non-ended chained functions.
self.functions_require_end = True
statements = []
while not self.peek_eof():
if self.peek("KEYWORD", "function"):
break
else:
statements.append(self.parse_statement())
l_functions, l_more_pragmas = self.parse_function_list()
return Script_File(os.path.basename(self.lexer.filename),
os.path.dirname(
pathutil.abspath(self.lexer.filename)),
self.lexer.get_file_loc(),
self.lexer.line_count(),
Sequence_Of_Statements(statements),
l_functions,
l_pragmas + l_more_pragmas)
def parse_octave_script_file(self, l_pragmas):
# An Octave script file is very similar to a MATLAB one,
# except they allow you to put functions everywhere (as long
# as it's not the first thing, because then you have a
# function file again). The semantics are weird as well,
# because all functions encountered this way are made global,
# as if they were in their own function files.
self.functions_require_end = True
statements = []
l_functions = []
l_more_pragmas = []
if not self.peek_eof():
# Script files _have_ to start with a statment
statements.append(self.parse_statement())
# Otherwise, in Octave, script files are a sequence of
# statements intermixed with (global) function definitions
while not self.peek_eof():
if self.peek("KEYWORD", "function"):
l_functions.append(self.parse_function_def(in_class = False))
elif self.peek("KEYWORD", "pragma"):
l_more_pragmas.append(self.parse_annotation_pragma())
else:
statements.append(self.parse_statement())
return Script_File(os.path.basename(self.lexer.filename),
os.path.dirname(
pathutil.abspath(self.lexer.filename)),
self.lexer.get_file_loc(),
self.lexer.line_count(),
Sequence_Of_Statements(statements),
l_functions,
l_pragmas + l_more_pragmas)
def parse_class_file(self, l_pragmas):
self.functions_require_end = True
n_classdef = self.parse_classdef()
if self.language.allow_classdef_subfunctions:
l_functions, l_more_pragmas = self.parse_function_list()
else:
l_functions = []
l_more_pragmas = []
return Class_File(os.path.basename(self.lexer.filename),
os.path.dirname(
pathutil.abspath(self.lexer.filename)),
self.lexer.get_file_loc(),
self.lexer.line_count(),
n_classdef,
l_functions,
l_pragmas + l_more_pragmas)
def parse_function_list(self):
l_functions = []
l_pragmas = []
while self.peek("KEYWORD", "function") or \
self.apeek("KEYWORD", "pragma"):
if self.peek("KEYWORD", "function"):
l_functions.append(self.parse_function_def(in_class = False))
else:
l_pragmas.append(self.parse_annotation_pragma())
if not self.functions_require_end and l_functions:
if len(l_functions) > 1:
raise ICE("logic error")
l_functions = self.reorder_as_function_list(l_functions[0])
return l_functions, l_pragmas
def reorder_as_function_list(self, n_fdef):
# To deal with the special case where none of the functions
# are terminated by end we need to flatten out the list we
# have.
assert isinstance(n_fdef, Function_Definition)
functions = []
while n_fdef:
functions.append(n_fdef)
if len(n_fdef.l_nested) == 1:
n_fdef = n_fdef.l_nested.pop()
elif len(n_fdef.l_nested) > 1:
raise ICE("logic error")
else:
break
return functions
def parse_function_signature(self, in_class):
assert isinstance(in_class, bool)
rv = Function_Signature()
# Parse returns. Either 'x' or a list '[x, y]'
l_outputs = []
if self.peek("A_BRA"):
out_brackets = True
self.match("A_BRA")
self.ct.set_ast(rv)
if not self.peek("A_KET"):
while True:
l_outputs.append(self.parse_identifier(allow_void=True))
if self.peek("COMMA"):
self.match("COMMA")
self.ct.set_ast(rv)
else:
break
self.match("A_KET")
self.ct.set_ast(rv)
else:
out_brackets = False
l_outputs.append(self.parse_simple_name())
if self.peek("BRA") and len(l_outputs) == 1 and not out_brackets:
# This is a function that doesn't return anything, so
# function foo(...
n_name = l_outputs[0]
l_outputs = []
elif self.peek("NEWLINE") and len(l_outputs) == 1 and not out_brackets:
# As above, but without the brackets
n_name = l_outputs[0]
l_outputs = []
else:
# This is a normal function, so something like
# function [a, b] = potato...
# function a = potato...
self.match("ASSIGNMENT")
self.ct.set_ast(rv)
n_name = self.parse_simple_name(allow_some_keywords=True)
l_inputs = []
if self.peek("BRA"):
self.match("BRA")
self.ct.set_ast(rv)
if not self.peek("KET"):
while True:
l_inputs.append(self.parse_identifier(allow_void=True))
if self.peek("COMMA"):
self.match("COMMA")
self.ct.set_ast(rv)
else:
break
self.match("KET")
self.ct.set_ast(rv)
if isinstance(n_name, Selection) and not in_class:
self.mh.error(n_name.loc(),
"dotted name is not permitted outside class")
rv.set_name(n_name)
rv.set_inputs(l_inputs)
rv.set_outputs(l_outputs)
self.match_eos(rv)
return rv
def parse_function_def(self, in_class):
assert isinstance(in_class, bool)
self.match("KEYWORD", "function")
self.push_context("function")
t_fun = self.ct
n_sig = self.parse_function_signature(in_class)
l_body = []
l_nested = []
l_argval = []
# First, deal with any argument validation blocks
while self.peek("KEYWORD", "arguments"):
l_argval.append(self.parse_validation_block())
# Then, process the rest of the function
while not self.peek("KEYWORD", "end") and not self.peek_eof():
item = self.parse_statement()
if isinstance(item, Function_Definition):
l_nested.append(item)
else:
l_body.append(item)
rv = Function_Definition(t_fun, n_sig,
l_argval,
Sequence_Of_Statements(l_body),
l_nested)
if self.peek_eof() and self.functions_require_end:
self.mh.error(t_fun.location,
"this function must be terminated with end")
elif self.peek_eof():
# TODO: style issue
pass
else:
self.functions_require_end = True
self.match("KEYWORD", "end")
rv.set_end(self.ct)
self.match_eos(rv)
self.pop_context()
return rv
def parse_name_value_pair_list(self, n_ast):
assert isinstance(n_ast, Node)
properties = []
if self.peek("BRA"):
self.match("BRA")
self.ct.set_ast(n_ast)
while True:
n_pair = Name_Value_Pair(
self.parse_identifier(allow_void=False))
if self.peek("ASSIGNMENT"):
self.match("ASSIGNMENT")
t_eq = self.ct
n_value = self.parse_expression()
n_pair.set_value(t_eq, n_value)
properties.append(n_pair)
if self.peek("COMMA"):
self.match("COMMA")
self.ct.set_ast(n_ast)
else:
break
self.match("KET")
self.ct.set_ast(n_ast)
return properties
def parse_validation_block(self):
# See
# https://uk.mathworks.com/help/matlab/matlab_oop/validate-property-values.html
# https://uk.mathworks.com/help/matlab/matlab_oop/property-validator-functions.html
# https://www.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html
if self.peek("KEYWORD", "arguments"):
self.match("KEYWORD", "arguments")
else:
self.match("KEYWORD", "properties")
t_kw = self.ct
rv = Special_Block(t_kw)
rv.set_attributes(self.parse_name_value_pair_list(rv))
self.match_eos(rv)
while not self.peek("KEYWORD", "end"):
# First the name we refer to
if t_kw.value == "arguments":
n_name = self.parse_simple_name(allow_void=True)
else:
n_name = self.parse_identifier(allow_void=False)
# We can have a delegation, or (more likely) an ordinary
# constraint.
if t_kw.value == "arguments" and self.peek("NVP_DELEGATE"):
self.match("NVP_DELEGATE")
delegation = Argument_Validation_Delegation(self.ct)
delegation.set_name(n_name)
delegation.set_class_name(self.parse_simple_name())
self.match_eos(delegation)
rv.add_delegation(delegation)
else:
cons = Entity_Constraints()
cons.set_name(n_name)
# All other validation options are optional. Historically
# this is likely because the properties block used to be
# just a list of class properties, and then it evolved
# (and eventually got re-used in function argument
# validation blocks).
# Dimension validation
val_dim = []
if self.peek("BRA"):
self.match("BRA")
self.ct.set_ast(cons)
while True:
if self.peek("NUMBER"):
self.match("NUMBER")
val_dim.append(self.ct)
elif self.peek("COLON"):
self.match("COLON")
val_dim.append(self.ct)
else:
self.mh.error(self.nt.location,
"dimension validation may contain"
" only integral numbers or :")
if self.peek("COMMA"):
self.match("COMMA")
self.ct.set_ast(cons)
else: