ogAST.py 32.9 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""

    OpenGEODE - A tiny SDL Editor for TASTE

    AST that can be used to write SDL backends (code generators, etc.)
    In all classes the 'inputString' field corresponds to the exact
    text from the PR file; line and charPositionInLine refer to the
    location of the string in the input PR stream.
    The 'coordinates' field corresponds to the CIF information.
    To use the AST, you must import ogAST and ogParser
    Example of code:

    import ogParser
    import ogAST

    ast = ogParser.parse_pr(files=['file1.pr', ...], string='...')

    -> ast is of type AST (see below)

    Design note:
        classes are used here only for the purpose of convenient
        reading of the AST. There is no object-orientation needed or
        used here.

    See AdaGenerator.py for an example of use.

30
    Copyright (c) 2012-2020 European Space Agency
Maxime Perrotin's avatar
Maxime Perrotin committed
31
32
33
34
35
36
37

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int
"""

import logging
38
import operator
39
from collections import defaultdict
Maxime Perrotin's avatar
Maxime Perrotin committed
40
41
42
LOG = logging.getLogger(__name__)


43
class Expression:
Maxime Perrotin's avatar
Maxime Perrotin committed
44
45
    ''' AST Entry for expressions - Always use subtype '''
    is_raw = False
Maxime Perrotin's avatar
Maxime Perrotin committed
46

Maxime Perrotin's avatar
Maxime Perrotin committed
47
48
49
50
51
    def __init__(self, inputString='', line=-1, charPositionInLine=-1):
        ''' Initialize Expression attributes '''
        self.inputString = inputString
        self.line = line
        self.charPositionInLine = charPositionInLine
52
53
        # Binary expressions have two sides
        self.right = self.left = None
Maxime Perrotin's avatar
Maxime Perrotin committed
54
        # Unary expressions (NOT and NEG) are stored in "expr"
55
        self.expr = None
dbarbera's avatar
dbarbera committed
56

Maxime Perrotin's avatar
Maxime Perrotin committed
57
58
59
60
61
        # exprType is an ASN.1 type (as exported by asn1scc)
        self.exprType = None
        # Hint for code generators: intermediate storage identifier
        self.tmpVar = -1

Maxime Perrotin's avatar
Maxime Perrotin committed
62
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
63
        ''' Debug output for an expression '''
Maxime Perrotin's avatar
Maxime Perrotin committed
64
        return u'{exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
65
66
67
68
69
70
                                        l=self.line,
                                        c=self.charPositionInLine)


class ExprPlus(Expression):
    operand = '+'
71
    op = operator.add
Maxime Perrotin's avatar
Maxime Perrotin committed
72
73
74
75


class ExprMul(Expression):
    operand = '*'
76
    op = operator.mul
Maxime Perrotin's avatar
Maxime Perrotin committed
77
78
79
80


class ExprMinus(Expression):
    operand = '-'
81
    op = operator.sub
Maxime Perrotin's avatar
Maxime Perrotin committed
82
83
84
85


class ExprOr(Expression):
    operand = 'or'
86
87
    # Indicate that short circuit form is used ("or else")
    shortcircuit = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
88
89
90
91


class ExprAnd(Expression):
    operand = 'and'
92
93
    # Indicate that short circuit form is used ("and then")
    shortcircuit = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
94
95
96
97


class ExprXor(Expression):
    operand = 'xor'
98
    shortcircuit = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
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


class ExprEq(Expression):
    operand = '='


class ExprNeq(Expression):
    operand = '/='


class ExprGt(Expression):
    operand = '>'


class ExprGe(Expression):
    operand = '>='


class ExprLt(Expression):
    operand = '<'


class ExprLe(Expression):
    operand = '<='


class ExprDiv(Expression):
    operand = '/'
Maxime Perrotin's avatar
Maxime Perrotin committed
127
    op = operator.truediv  # python3 only
Maxime Perrotin's avatar
Maxime Perrotin committed
128
129
130
131


class ExprMod(Expression):
    operand = 'mod'
132
    op = operator.mod
Maxime Perrotin's avatar
Maxime Perrotin committed
133
134
135


class ExprRem(Expression):
dbarbera's avatar
dbarbera committed
136
    operand = 'rem'
137
    op = operator.mod
Maxime Perrotin's avatar
Maxime Perrotin committed
138
139


dbarbera's avatar
dbarbera committed
140
141
142
143
144
145
146
class ExprNot(Expression):
    operand = 'not'


class ExprNeg(Expression):
    operand = '-'

147
148
149
150
151
    @property
    def is_raw(self):
        ''' Redefine is_raw - check the actual element '''
        return self.expr.is_raw

dbarbera's avatar
dbarbera committed
152

Maxime Perrotin's avatar
Maxime Perrotin committed
153
154
155
156
class ExprAssign(Expression):
    operand = ':='


Maxime Perrotin's avatar
Maxime Perrotin committed
157
158
159
160
161
162
163
164
165
166
167
class ExprAppend(Expression):
    pass


class ExprIn(Expression):
    pass


class ExprImplies(Expression):
    pass

Maxime Perrotin's avatar
Maxime Perrotin committed
168
169
170
171
172
173
174

class Primary(Expression):
    '''
        AST entry for a primary construction (that is a terminal expression)
        Abstract class, never used directly, see subtypes below
    '''
    is_raw = True
Maxime Perrotin's avatar
Maxime Perrotin committed
175

Maxime Perrotin's avatar
Maxime Perrotin committed
176
    def __init__(self, inputString='', line=-1, charPositionInLine=-1,
177
                 primary=None, debugLine=-1):
Maxime Perrotin's avatar
Maxime Perrotin committed
178
        ''' Initialize common primary attributes '''
179
        self.debugLine = debugLine
Maxime Perrotin's avatar
Maxime Perrotin committed
180
181
182
183
184
185
186
187
188
189
190
191
192
        if primary:
            self.inputString = primary.inputString
            self.line = primary.line
            self.charPositionInLine = primary.charPositionInLine
            self.value = primary.value
            self.exprType = primary.exprType
        else:
            self.inputString = inputString
            self.line = line
            self.charPositionInLine = charPositionInLine
            self.value = None
            self.exprType = None

Maxime Perrotin's avatar
Maxime Perrotin committed
193
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
194
        ''' Debug output for a primary '''
Maxime Perrotin's avatar
Maxime Perrotin committed
195
        return u'PRIMARY : {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
196
197
                l=self.line, c=self.charPositionInLine)

Maxime Perrotin's avatar
Maxime Perrotin committed
198

dbarbera's avatar
dbarbera committed
199
class PrimCall(Primary):
Maxime Perrotin's avatar
Maxime Perrotin committed
200
201
    is_raw = False

Maxime Perrotin's avatar
Maxime Perrotin committed
202

dbarbera's avatar
dbarbera committed
203
204
class PrimIndex(Primary):
    is_raw = False
205
206


dbarbera's avatar
dbarbera committed
207
208
class PrimSubstring(Primary):
    is_raw = False
209
210


dbarbera's avatar
dbarbera committed
211
212
class PrimSelector(Primary):
    is_raw = False
213
214


dbarbera's avatar
dbarbera committed
215
216
class PrimVariable(Primary):
    is_raw = False
Maxime Perrotin's avatar
Maxime Perrotin committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238


class PrimFPAR(PrimVariable):
    pass


class PrimEnumeratedValue(Primary):
    pass


class PrimInteger(Primary):
    pass


class PrimReal(Primary):
    pass


class PrimBoolean(Primary):
    pass


239
240
241
class PrimNull(Primary):
    pass

242

Maxime Perrotin's avatar
Maxime Perrotin committed
243
244
class PrimConstant(Primary):
    is_raw = False
245
246
247
    # other attributes set by the parser:
    # constant_c_name : string
    # constant_value : raw value from ASN.1
Maxime Perrotin's avatar
Maxime Perrotin committed
248
249


250
251
252
253
254
255
256
class PrimStateReference(Primary):
    ''' This primary ("state" keyword) is used only in stop conditions and
    possibly in the future in observers, to reference the state of the system
    '''
    is_raw = False


Maxime Perrotin's avatar
Maxime Perrotin committed
257
258
259
260
261
262
263
264
class PrimBitStringLiteral(Primary):
    ''' Not supported yet '''
    pass


class PrimOctetStringLiteral(Primary):
    ''' Not supported yet '''
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
265
266


267
class PrimConditional(Primary):
Maxime Perrotin's avatar
Maxime Perrotin committed
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
    ''' value is a dictionnary:
        { 'if': Expression, 'then': Expression,
        'else': Expression, 'tmpVar': integer}
        tmpVar can be used if the backend needs a temporary variable
        to process the ifThenElse
    '''
    pass


class PrimStringLiteral(Primary):
    ''' Value is a string with quotes '''
    @property
    def exprType(self):
        return self._exprType

    @exprType.setter
    def exprType(self, val):
#       name = getattr(self, 'value', self.inputString)
#       import traceback
#       traceback.print_stack()
#       print 'SET type of', name, 'to', val
        self._exprType = val


class PrimMantissaBaseExp(Primary):
    ''' Value is a dict: {'mantissa': int, 'base': int, 'exponent': int} '''
    pass


Maxime Perrotin's avatar
Maxime Perrotin committed
297
298
class PrimEmptyString(Primary):
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
299
300
301
302
303
304
305


class PrimChoiceItem(Primary):
    ''' Value is a dict : {'choice': string, 'value': Expression} '''
    pass


Maxime Perrotin's avatar
Maxime Perrotin committed
306
307
class PrimChoiceDeterminant(Primary):
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
308
309
310
311
312
313
314
315
316
317
318


class PrimSequenceOf(Primary):
    ''' Value is a list of Primary '''


class PrimSequence(Primary):
    ''' Value is a dict : { field1: Expression, field2: Expression } '''
    pass


319
class Decision:
Maxime Perrotin's avatar
Maxime Perrotin committed
320
321
322
323
324
325
    ''' AST Entry for a decision '''
    def __init__(self):
        ''' A DECISION statement '''
        self.inputString = ''
        self.line = None
        self.charPositionInLine = None
326
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        self.width = 70
        self.height = 50
        # kind can be 'any', 'informal_text', or 'question'
        self.kind = None
        # question is an Expression
        self.question = None
        # informalText is a string (when kind == 'informal_text')
        self.informalText = None
        # list of type Answer
        self.answers = []
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
        # hint for backends needing a temporary variable to hold the question
        self.tmpVar = -1

Maxime Perrotin's avatar
Maxime Perrotin committed
344
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
345
        ''' Debug output for a decision '''
Maxime Perrotin's avatar
Maxime Perrotin committed
346
        return u'DECISION {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
347
348
349
                l=self.line, c=self.charPositionInLine)


350
class Answer:
Maxime Perrotin's avatar
Maxime Perrotin committed
351
352
353
    ''' AST Entry for a decision answer '''
    def __init__(self):
        ''' One ANSWER of a DECISION '''
354
        self.inputString = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
355
356
        self.line = None
        self.charPositionInLine = None
357
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
358
        self.width = 70
Maxime Perrotin's avatar
Maxime Perrotin committed
359
        self.height = 23
Maxime Perrotin's avatar
Maxime Perrotin committed
360
361
362
363
364
365
366
367
368
369
370
371
        # one of 'closed_range' 'constant' 'open_range' 'else' 'informal_text'
        self.kind = None
        # informalText is a string, when kind == 'informal_text'
        self.informalText = None
        # closedRange is a set of two numbers
        self.closedRange = []
        # constant is an Expression
        #    (contains 'open_range' and 'constant' kinds corresponding value)
        self.constant = None
        # one of ExprEq, ExprNeq, ExprGt, ExprGe, ExprLt, ExprLe (types)
        self.openRangeOp = None
        # transition is of type Transition
372
        self.transition : Transition = None
Maxime Perrotin's avatar
Maxime Perrotin committed
373
374
375
376
377
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None

Maxime Perrotin's avatar
Maxime Perrotin committed
378
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
379
        ''' Debug output for an answer '''
Maxime Perrotin's avatar
Maxime Perrotin committed
380
        return u'ANSWER {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
381
382
383
                l=self.line, c=self.charPositionInLine)


384
class Task:
Maxime Perrotin's avatar
Maxime Perrotin committed
385
386
387
    ''' AST Entry for TASKS '''
    def __init__(self):
        ''' Initialize TASK attributes (set of ASSIGN statements) '''
388
        self.inputString = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
389
390
        self.line = None
        self.charPositionInLine = None
391
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
392
393
394
395
396
397
398
399
        self.width = 70
        self.height = 35
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
        self.elems = []

Maxime Perrotin's avatar
Maxime Perrotin committed
400
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
401
        ''' Debug output for a task '''
Maxime Perrotin's avatar
Maxime Perrotin committed
402
        return u'TASK {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
                l=self.line, c=self.charPositionInLine)


class TaskAssign(Task):
    ''' 'elems' contains a list of ExprAssign expressions '''
    pass


class TaskInformalText(Task):
    ''' 'elems' contains a list of strings '''
    pass


class TaskForLoop(Task):
    '''
        'elems' is a list of for-loops:{'var': string, 'type': Asn1SccType,
        'list': Primary, 'range': {'start': expression, 'stop': expression,
        'step' : int}, 'transition': Transition }
    '''
    pass

Maxime Perrotin's avatar
Maxime Perrotin committed
424

425
class Output:
Maxime Perrotin's avatar
Maxime Perrotin committed
426
    ''' AST Entry for OUTPUT statements '''
427
    def __init__(self, defName=''):
Maxime Perrotin's avatar
Maxime Perrotin committed
428
429
        ''' Set of OUTPUT statements '''
        self.inputString = defName
430
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
431
432
433
434
435
436
437
438
439
440
441
        self.width = 70
        self.height = 35
        self.line = None
        self.charPositionInLine = None
        # list of {'outputName':ID, 'params':list of Expression, 'tmpVars':[]}
        self.output = []
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None

Maxime Perrotin's avatar
Maxime Perrotin committed
442
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
443
        ''' Debug output for an Output symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
444
        return u'{exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
445
446
447
448
                l=self.line, c=self.charPositionInLine)


class ProcedureCall(Output):
449
450
451
452
453
454
455
    ''' Procedure calls content is identical to Outputs
    with exception that it may have a return type (exprType) '''
    def __init__(self, defName=''):
        super().__init__(defName)
        # exprType is an ASN.1 type (as exported by asn1scc)
        self.exprType = None
        self.is_raw = False
Maxime Perrotin's avatar
Maxime Perrotin committed
456
457


458
class Terminator:
Maxime Perrotin's avatar
Maxime Perrotin committed
459
    ''' Terminator elements (join, nextstate, stop, return) '''
460
    def __init__(self, defName=''):
Maxime Perrotin's avatar
Maxime Perrotin committed
461
462
463
464
465
466
467
468
        ''' Initialize terminator attributes '''
        self.inputString = defName
        self.pos_x = None
        self.pos_y = None
        self.width = 70
        self.height = 35
        self.line = None
        self.charPositionInLine = None
469
        # one of 'next_state' 'join' 'stop', 'return'
Maxime Perrotin's avatar
Maxime Perrotin committed
470
471
472
473
474
475
476
        self.kind = None
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
        # optional Label instance (to be placed just before the terminator)
        self.label = None
477
478
479
        # Return expression
        self.return_expr = None
        # via clause, used for entering nested state with an entry point
Maxime Perrotin's avatar
Maxime Perrotin committed
480
        # 'via' is the string for the renderer (e.g. "via foo")
481
        self.via = None
Maxime Perrotin's avatar
Maxime Perrotin committed
482
483
        # 'entrypoint' is the string of the entry point (e.g. "foo")
        self.entrypoint = None
484
485
        # some transitions can be chained, when entering/leaving nested states
        self.next_id = -1
486
487
488
        # Pointer to the next transition, when using return/connect
        self.next_trans = None
        # List of State that can lead to this terminator
489
        # There can be several if terminator follows a floating label
490
        # Note, this field is updated by the Helper.flatten function
491
        self.possible_states = []
Maxime Perrotin's avatar
Maxime Perrotin committed
492
493
        # optional composite state content (type CompositeState)
        self.composite = None
Maxime Perrotin's avatar
Maxime Perrotin committed
494
        # Flag to indicate if the nextstate is a state aggregation
495
        self.next_is_aggregation = False
496
497
498
499
        # List of sibling states if terminator is within a state aggregation
        # (list of strings with all parallel states of the aggregation)
        # Used by backend to synchronise parallel state terminations
        self.siblings = []
Maxime Perrotin's avatar
Maxime Perrotin committed
500
501
502
        # If this terminator is within a state aggregation, store the name
        # of the parallel substate (set by Helper.state_aggregations)
        self.substate = ''
503
504
505
506
507
508
        # candidate_id: {transition_id: [states]}
        # field is set by Helper.py/flatten, in case of "nextstate -"
        # there is a list of states that set transition_id to -1 : the standard
        # states ; and there are the composite states, that set a different
        # id corresponding to the start transition of the state.
        self.candidate_id = defaultdict(list)
Maxime Perrotin's avatar
Maxime Perrotin committed
509

Maxime Perrotin's avatar
Maxime Perrotin committed
510
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
511
        ''' Debug output for terminators '''
Maxime Perrotin's avatar
Maxime Perrotin committed
512
        return u'{kind} {exp} ({l},{c}) at {x}, {y}'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
513
514
515
516
517
                exp=self.inputString,
                kind=self.kind.upper(), l=self.line, c=self.charPositionInLine,
                x=self.pos_x, y=self.pos_y)


518
class Label:
Maxime Perrotin's avatar
Maxime Perrotin committed
519
520
521
522
    ''' AST Entry for a Label '''
    def __init__(self):
        ''' Initialize the label attributes '''
        # inputString holds the label name
523
        self.inputString = ''
524
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
525
526
527
528
529
530
531
532
533
534
535
536
537
538
        self.pos_y = 0
        self.width = 70
        self.height = 35
        self.line = None
        self.charPositionInLine = None
        # optional hyperlink
        self.hyperlink = None
        # No comment for labels - keep to None
        self.comment = None
        # List of terminators following this label
        self.terminators = []
        # Transition is used for floating labels (see AST entry)
        self.transition = None

Maxime Perrotin's avatar
Maxime Perrotin committed
539
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
540
        ''' Debug output for a label '''
Maxime Perrotin's avatar
Maxime Perrotin committed
541
        return u'LABEL {label} ({l},{c})'.format(label=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
542
543
544
                l=self.line, c=self.charPositionInLine)


545
class Floating_label(Label):
Maxime Perrotin's avatar
Maxime Perrotin committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
    ''' AST Entry for a floating label '''
    def __init__(self, label=None):
        ''' Initialize the floating label attributes '''
        super(Floating_label, self).__init__()
        if label:
            self.inputString = label.inputString
            self.pos_x = label.pos_x
            self.pos_y = label.pos_y
            self.width = label.width
            self.height = label.height
            self.line = label.line
            self.charPositionInLine = label.charPositionInLine
            self.terminators = label.terminators
            self.transition = label.transition

Maxime Perrotin's avatar
Maxime Perrotin committed
561
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
562
        ''' Debug output for a label (used by code generator) '''
Maxime Perrotin's avatar
Maxime Perrotin committed
563
        return u'CONNECTION {label} ({l},{c})'.format(label=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
564
565
566
                l=self.line, c=self.charPositionInLine)


567
class Transition:
Maxime Perrotin's avatar
Maxime Perrotin committed
568
569
570
571
572
573
574
575
576
    ''' AST Entry for a complete transition '''
    def __init__(self):
        ''' Initialize the transition attributes '''
        # list of either Label, Output, Task, Decision
        self.actions = []
        # terminator is of type Terminator (it is optional)
        self.terminator = None
        # All Terminators of this transition
        self.terminators = []
577
        # List of states (string) that can lead to this transition
578
579
580
581
582
        # There can be several if state has multiple names (e.g. STATE a, b)
        # Note, this field is updated by the Helper.flatten function
        # and is needed to properly know when to call a nested state exit
        # procedure when the model is flattened.
        self.possible_states = []
Maxime Perrotin's avatar
Maxime Perrotin committed
583

Maxime Perrotin's avatar
Maxime Perrotin committed
584
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
585
        ''' Debug output: display all actions '''
Maxime Perrotin's avatar
Maxime Perrotin committed
586
        data = [action.trace() for action in self.actions]
Maxime Perrotin's avatar
Maxime Perrotin committed
587
        if self.terminator:
Maxime Perrotin's avatar
Maxime Perrotin committed
588
            data.append(self.terminator.trace())
Maxime Perrotin's avatar
Maxime Perrotin committed
589
        return u'\n'.join(data)
Maxime Perrotin's avatar
Maxime Perrotin committed
590
591


592
class Input:
Maxime Perrotin's avatar
Maxime Perrotin committed
593
594
595
596
    ''' AST Entry for the INPUT symbol '''
    def __init__(self):
        ''' Initialize the Input attributes '''
        # inputString is the user text, it can contain several inputs
597
        self.inputString = ''
598
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
        self.width = 70
        self.height = 35
        self.line = None
        self.charPositionInLine = None
        # provided clause (not supported yet)
        self.provided = None
        # transition is of type Transition
        self.transition = None
        # List of input parameters (strings: each param is a variable)
        # (If there are several inputs in the symbol, there are no parameters)
        self.parameters = []
        # list of input signal names
        self.inputlist = []
        # transition_id is an index of the process.transitions list
        self.transition_id = -1
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
        # list of terminators following the input symbol
        self.terminators = []

Maxime Perrotin's avatar
Maxime Perrotin committed
621
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
622
        ''' Debug output for an INPUT symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
623
        return u'INPUT {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
624
625
626
                l=self.line, c=self.charPositionInLine)


Maxime Perrotin's avatar
Maxime Perrotin committed
627
628
629
630
631
632
633
634
635
class Connect(Input):
    ''' AST Entry for the CONNECT part (transition below a nested state) '''
    def __init__(self):
        ''' Only one difference with INPUT: the connect_list attribute '''
        super(Connect, self).__init__()
        # List of strings
        self.connect_list = []
        self.width = 1

Maxime Perrotin's avatar
Maxime Perrotin committed
636
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
637
        ''' Debug output for a CONNECT symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
638
        return u'CONNECT {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
639
640
                l=self.line, c=self.charPositionInLine)

641
642
643
644
645
class ContinuousSignal(Input):
    ''' AST Entry for the Continuous Signal '''
    def __init__(self):
        ''' Difference with Input: trigger is an expression '''
        super(ContinuousSignal, self).__init__()
646
        # Decision triggering the transition
647
648
649
650
651
652
653
654
655
        self.trigger = None
        # Priority (integer)
        self.priority = 0

    def trace(self):
        ''' Debug output for a Continuous signal '''
        return u'PROVIDED {exp} ({l},{c})'.format(exp=self.inputString,
                l=self.line, c=self.charPositionInLine)

Maxime Perrotin's avatar
Maxime Perrotin committed
656

657
class Start:
Maxime Perrotin's avatar
Maxime Perrotin committed
658
659
660
661
    ''' AST Entry for the START symbol '''
    def __init__(self):
        ''' Initialize the Start symbol attributes '''
        self.inputString = ''
662
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
663
664
665
666
667
668
669
670
671
672
673
        self.width = 70
        self.height = 35
        # start transition is of type Transition
        self.transition = None
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
        # list of terminators following the start symbol
        self.terminators = []

Maxime Perrotin's avatar
Maxime Perrotin committed
674
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
675
        ''' Debug output for a START symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
676
        return u'START {}'.format(self.inputString)
Maxime Perrotin's avatar
Maxime Perrotin committed
677
678
679
680
681
682
683


class Procedure_start(Start):
    ''' Procedure start symbol - inherits from Start '''
    pass


684
685
686
687
688
class CompositeState_start(Start):
    ''' Composite state start symbol - inherits from Start, can have a name '''
    pass


689
class Comment:
Maxime Perrotin's avatar
Maxime Perrotin committed
690
691
692
693
694
    ''' AST Entry for COMMENT symbols '''
    def __init__(self):
        ''' Comment symbol '''
        # inputString is the comment value itself
        self.inputString = ''
695
696
        self.pos_x = None
        self.pos_y = None
Maxime Perrotin's avatar
Maxime Perrotin committed
697
698
699
700
701
702
703
        self.width = 70
        self.height = 35
        self.line = None
        self.charPositionInLine = None
        # optional hyperlink
        self.hyperlink = None

Maxime Perrotin's avatar
Maxime Perrotin committed
704
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
705
        ''' Debug output for a COMMENT symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
706
707
        return u'COMMENT {exp} ({l},{c})'.format(
                exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
708
709
710
                l=self.line, c=self.charPositionInLine)


711
class State:
Maxime Perrotin's avatar
Maxime Perrotin committed
712
713
714
715
716
717
718
719
720
    ''' AST Entry for STATE symbols '''
    def __init__(self, defName=''):
        ''' Used only for rendering backends - not for code generation '''
        # inputString contains possibly several states (and asterisk)
        self.inputString = defName
        # List of state names contained in the symbol
        self.statelist = []
        self.line = None
        self.charPositionInLine = None
721
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
722
723
724
725
726
        self.pos_y = 0
        self.width = 70
        self.height = 35
        # list of type Input
        self.inputs = []
Maxime Perrotin's avatar
Maxime Perrotin committed
727
728
        # list of type Connect (connection below a nested state)
        self.connects = []
729
        # list of ContinuousSignal (provided clauses below a state)
Maxime Perrotin's avatar
Maxime Perrotin committed
730
        self.continuous_signals = []
Maxime Perrotin's avatar
Maxime Perrotin committed
731
732
733
734
        # optional comment symbol
        self.comment = None
        # optional hyperlink
        self.hyperlink = None
735
736
        # optional composite state content (type CompositeState)
        self.composite = None
737
738
739
        # via clause, used for entering nested state with an entry point
        # 'via' is the string for the renderer (e.g. "hello via foo")
        self.via = None
740
741
        # a state can be an instance of a state stype
        self.instance_of = None
Maxime Perrotin's avatar
Maxime Perrotin committed
742

Maxime Perrotin's avatar
Maxime Perrotin committed
743
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
744
        ''' Debug output for a STATE symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
745
        return u'STATE {exp} ({l},{c}) at {x},{y}'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
746
747
748
749
                l=self.line, c=self.charPositionInLine,
                x=self.pos_x, y=self.pos_y)


750
class TextArea:
Maxime Perrotin's avatar
Maxime Perrotin committed
751
752
753
    ''' AST Entry for text areas (containing declarations/comments) '''
    def __init__(self):
        ''' Text area (raw content for rendering only) '''
754
        self.inputString = '-- Text area for declarations and comments\n\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
755
756
757
        self.line = None
        self.charPositionInLine = None
        # Set default coordinates and width/height
758
        self.pos_x, self.pos_y = None, None
Maxime Perrotin's avatar
Maxime Perrotin committed
759
760
        self.width = 170
        self.height = 140
761
762
763
764
765
        # DCL variables in the text area {name: (sort, default_value), ...}
        self.variables = {}
        # fpar and timers are also listed, useful when using autocompletion
        self.fpar = []
        self.timers = []
766
767
768
769
770
771
        # signals can be declared in a text area (structure: see System class)
        self.signals = []
        # USE construct can be declared in a text area (list of strings)
        # asn1_files lists optional COMMENT strings of USE constructs
        self.use_clauses = []
        self.asn1_files = []
772
773
        # inner procedures - useful to get autocompletion params
        self.procedures = []
Maxime Perrotin's avatar
Maxime Perrotin committed
774
775
776
        # optional hyperlink
        self.hyperlink = None

Maxime Perrotin's avatar
Maxime Perrotin committed
777
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
778
        ''' Debug output for a text area '''
Maxime Perrotin's avatar
Maxime Perrotin committed
779
        return u'TEXTAREA {exp} ({l},{c})'.format(exp=self.inputString,
Maxime Perrotin's avatar
Maxime Perrotin committed
780
781
782
                l=self.line, c=self.charPositionInLine)


783
class Automaton:
784
    ''' Elements contained in a process, procedure or composite state'''
Maxime Perrotin's avatar
Maxime Perrotin committed
785
786
787
788
789
790
791
792
    def __init__(self, parent=None):
        ''' AST grouping the elements that can be rendered graphically '''
        self.parent = parent
        self.textAreas = []
        self.inner_procedures = []
        self.start = None
        self.floating_labels = []
        self.states = []
793
        self.named_start = []
Maxime Perrotin's avatar
Maxime Perrotin committed
794
795


796
class Procedure:
Maxime Perrotin's avatar
Maxime Perrotin committed
797
798
799
    ''' Internal procedure definition '''
    def __init__(self):
        ''' Procedure AST default value '''
800
        self.inputString = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
801
802
803
        self.line = None
        self.charPositionInLine = None
        # Set default coordinates and width/height
804
        self.pos_x = self.pos_y = None
Maxime Perrotin's avatar
Maxime Perrotin committed
805
806
807
808
809
810
        self.width = 70
        self.height = 35
        # Optional hyperlink
        self.hyperlink = None
        # Local variables dictionnary (see Process)
        self.variables = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
811
812
        self.timers = []
        # Inherited variables and timers from all levels above
Maxime Perrotin's avatar
Maxime Perrotin committed
813
        self.global_variables = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
814
        self.global_timers = []
Maxime Perrotin's avatar
Maxime Perrotin committed
815
816
817
        # Formal parameters - list of dict:
        # [{'name': str, 'direction': 'in'/'out', 'type': str}]
        self.fpar = []
818
819
        # return type (ASN.1)
        self.return_type = None
820
821
        # when procedure has a RETURN it can also contain a variable name
        self.return_var = None
822
        # start, terminators, text areas, floating_labels (see Process)
Maxime Perrotin's avatar
Maxime Perrotin committed
823
824
825
826
827
828
829
        #self.start = None
        #self.states = []
        self.terminators = []
        #self.textAreas = []
        # Keep a list of labels and floating labels - useful for backends
        self.labels = []
        #self.floating_labels = []
830
831
832
        # Inherited procedures and operators
        self.procedures = []
        self.operators = []
Maxime Perrotin's avatar
Maxime Perrotin committed
833
834
835
836
837
838
839
840
        # inner procedures and operators (see Process for format)
        #self.inner_procedures = []
        self.inner_operators = []
        # mapping, transitions: see Process
        self.mapping = {}
        self.transitions = []
        # Determine if a procedure is externally defined
        self.external = False
841
842
        # Determine if a procedure is a remote procedure
        self.exported = False
Maxime Perrotin's avatar
Maxime Perrotin committed
843
844
845
846
        # Optional comment
        self.comment = None
        # Set of symbols contained in the procedure (type Automaton)
        self.content = Automaton(parent=self)
847
848
849
        # input/output signal lists - unused but for context information
        self.input_signals = []
        self.output_signals = []
Maxime Perrotin's avatar
Maxime Perrotin committed
850
851


852
class Process:
Maxime Perrotin's avatar
Maxime Perrotin committed
853
854
855
856
857
858
    ''' SDL Process entry point '''
    def __init__(self):
        ''' Process AST default values '''
        self.processName = None
        # Optional filename containing this process (PR file)
        self.filename = None
859
860
861
862
863
        # Optional type of this process instance (name = string, ref = Process)
        self.instance_of_name = None
        self.instance_of_ref  = None
        # A process may be a process type (boolean)
        self.process_type = False
Maxime Perrotin's avatar
Maxime Perrotin committed
864
865
866
867
868
869
        # Process parent context (Block or AST if defined at root level)
        self.parent = None
        # A process can be referenced (externally defined)
        self.referenced = False
        # variables: dictionnary: {variable1Name: (asn1SccType, default value)}
        self.variables = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
870
        # global variables and timers can be used to inherit from a level above
Maxime Perrotin's avatar
Maxime Perrotin committed
871
        self.global_variables = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
872
        self.global_timers = []
873
        # Set default coordinates and width/height
874
875
        self.pos_x = 250
        self.pos_y = 150
876
877
878
879
880
881
        self.width = 150
        self.height = 75
        # Optional hyperlink
        self.hyperlink = None
        # Optional comment
        self.comment = None
Maxime Perrotin's avatar
Maxime Perrotin committed
882
883
884
885

        # dataview: complete AST of the ASN.1 types
        self.asn1Modules = None
        self.dataview = None
886
887
        # Reference to the Python module containing the ASN.1 AST
        self.DV = None
888
889
        # user-defined datatypes (using "newtype" SDL keyword)
        self.user_defined_types = dict()
Maxime Perrotin's avatar
Maxime Perrotin committed
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904

        # input and output signal lists:
        # [{'name': str, 'type': str, 'direction':'in'/'out'}]
        self.input_signals = []
        self.output_signals = []

        # terminators are useful for rendering backends
        self.terminators = []

        # Keep a list of labels and floating labels - useful for backends
        # List of Label
        self.labels = []

        # list of operators (not supported) and procedures
        self.operators = {}
905
        # list of Procedure (external and inner procedures)
Maxime Perrotin's avatar
Maxime Perrotin committed
906
907
908
909
910
911
912
        self.procedures = []

        # The Mapping structure should be used for code generation backends
        # dictionnary: {'stateName': [class Input1, Input2,...], ...}
        # then Input contains the inputs list and corresponding transition
        self.mapping = {}

913
914
915
        # Similar mapping for continuous signals
        self.cs_mapping = defaultdict(list)

Maxime Perrotin's avatar
Maxime Perrotin committed
916
917
918
        # list of type Transition - use 'mapping' to map index to inputs/states
        self.transitions = []

919
920
921
        # list of type CompositeState
        self.composite_states = []

Maxime Perrotin's avatar
Maxime Perrotin committed
922
923
924
925
        # Set of symbols contained in the process (type Automaton)
        # (Includes inner procedures)
        self.content = Automaton(parent=self)

926
927
928
929
        # Process formal parameters - list of dict:
        # [{'name': str, 'type': str}]
        self.fpar = []

Maxime Perrotin's avatar
Maxime Perrotin committed
930
931
932
        # List of timers (strings) declared in the process
        self.timers = []

Maxime Perrotin's avatar
Maxime Perrotin committed
933
934
935
        # list of processes used for context management of the GUI
        self.processes = []

Maxime Perrotin's avatar
Maxime Perrotin committed
936

937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
class CompositeState(Process):
    '''
        Composite states: the difference with Process is that they can have:
        - several START elements, that correspond to state entry points,
        - state exit points (with RETURN terminators)
        - entry and exit procedures
    '''
    def __init__(self):
        super(CompositeState, self).__init__()
        self.statename = ''
        self.state_entrypoints = []
        self.state_exitpoints = []
        # Special entry and exit procedures (named "entry" and "exit")
        self.entry_procedure = None
        self.exit_procedure = None
        # Body can contain text areas, procedures, composite states,
        # one nameless START, named START (one per entrypoint), states,
Maxime Perrotin's avatar
Maxime Perrotin committed
954
955
        # amd floating labels

Maxime Perrotin's avatar
Maxime Perrotin committed
956
    def trace(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
957
        ''' Debug output for composite state '''
Maxime Perrotin's avatar
Maxime Perrotin committed
958
        return u'COMPOSITE STATE {exp} ({l},{c})'.format(exp=self.statename,
Maxime Perrotin's avatar
Maxime Perrotin committed
959
                l=self.line, c=self.charPositionInLine)
960
961


962
963
964
965
966
967
968
969
970
class StateAggregation(CompositeState):
    '''
        State Aggregation (Parallel states) are supported since SDL2000
        These states can only contain (in the self.content field):
            text areas
            procedure definitions
            composite states (including sub-state aggregations)
        But no state machine definition
    '''
971
972
973
974
975
976
977
    def __init__(self):
        super(StateAggregation, self).__init__()
        # List of partition connections:
        # [{'outer': {'state_part_id': str, 'point': str},
        #   'inner': {'state_part_id': str, 'point': str}}]
        self.state_partition_connections = []

978
979
980
981
982
983
    def trace(self):
        ''' Debug output for state aggregation '''
        return u'STATE AGGREGATION {exp} ({l},{c})'.format(exp=self.statename,
                l=self.line, c=self.charPositionInLine)


984
class Block:
Maxime Perrotin's avatar
Maxime Perrotin committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
    ''' AST for a BLOCK entity '''
    def __init__(self):
        '''
            Blocks can contain signal declarations, signalroutes,
            connections, inner block definitions, and process
            definitions.
        '''
        # Block name
        self.name = ''
        # Parent block or system
        self.parent = None
        # list of signal declarations - see class System for the structure
        self.signals = []
        # signalroutes: see self.channels in class System for the structure
        self.signalroutes = []
        # connections are between a channel and signalroute
        # [{'channel': str, 'signalroute': str}]
        self.connections = []
        # list of class Block
        self.blocks = []
1005
        # list of class Process / with separate process_types
Maxime Perrotin's avatar
Maxime Perrotin committed
1006
        self.processes = []
1007
        self.process_types = []
1008
1009
        # list of ogAST.Procedure
        self.procedures = []
1010
1011
1012
        # Block formal parameters - list of dict (unused)
        # [{'name': str, 'type': str}]
        self.fpar = []
Maxime Perrotin's avatar
Maxime Perrotin committed
1013
1014


1015
class System:
Maxime Perrotin's avatar
Maxime Perrotin committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
    ''' AST for a SYSTEM entity '''
    def __init__(self):
        '''
            Create system default values
            contains blocks, procedures, channels and signal declarations
        '''
        # System name
        self.name = ''
        # Optional filename containing this system (PR file)
        self.filename = None
        # Reference to top-level AST
        self.ast = None
1028
        # list of SIGNAL declarations: [{'name': str, 'type': asn1type}]
Maxime Perrotin's avatar
Maxime Perrotin committed
1029
1030
1031
1032
        # (Supporting only one parameter)
        self.signals = []
        # list of ogAST.Procedure
        self.procedures = []
Maxime Perrotin's avatar
Maxime Perrotin committed
1033
        # channels: [{'name':str, 'routes':[{'source': str, 'dest': str,
Maxime Perrotin's avatar
Maxime Perrotin committed
1034
1035
1036
        # 'signals': ['sig1', .. ]}]
        self.channels = []
        self.blocks = []
1037
        self.text_areas = []
Maxime Perrotin's avatar
Maxime Perrotin committed
1038
1039


1040
class AST:
Maxime Perrotin's avatar
Maxime Perrotin committed
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    ''' Top-level AST entry point '''
    def __init__(self):
        '''
            AST entries are systems, processes, and USE clauses
            (cf. ANTLR grammar, production "pr_file")
        '''
        # Set of input files the AST was created from
        self.pr_files = set()
        # USE clauses: list of strings (eg. "DataView")
        self.use_clauses = []
        # Optional list of ASN.1 filenames (defined in CIF of USE clauses)
        self.asn1_filenames = []
        # Refs to the ASN.1 dataview AST (set with USE clauses)
        self.dataview = None
        self.asn1Modules = None
Maxime Perrotin's avatar
Maxime Perrotin committed
1056
1057
        # DV is the Asn1scc imported module
        self.DV = None
1058
        # ASN.1-defined constants (constants in Ada but variables in C)
1059
        # dictionnary: {ConstantName: type } - copied from dataview.py
Maxime Perrotin's avatar
Maxime Perrotin committed
1060
        self.asn1_constants = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
1061
1062
1063
1064
1065

        # List of System
        self.systems = []
        # List of Process
        self.processes = []
1066
1067
1068

        # List of Process types
        self.process_types = []