Helper.py 19.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    OpenGEODE - A tiny SDL Editor for TASTE

    This module provides helper functions typically used by backends:

        flatten(ast) : transform a model with nested states to a flat model
        rename_everything(ast, from_name, to_name) : rename symbols
Maxime Perrotin's avatar
Maxime Perrotin committed
11
        inner_labels_to_floating(process) : remove labels from transitions
Maxime Perrotin's avatar
Maxime Perrotin committed
12
13
        map_input_state(process) -> mapping: create a mapping
                                    input-state-transition
14
15
        sorted_fields(SEQ/CHOICE) : returns the ordered list of fields
                                    of an ASN.1 SEQUENCE or CHOICE type
16
17
18
19
20
21
22
23

    Copyright (c) 2012-2014 European Space Agency

    Designed and implemented by Maxime Perrotin

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

24
import operator
25
26
import logging
from itertools import chain
27
from collections import defaultdict
28
29
30
31
32
33
34

from singledispatch import singledispatch

import ogAST

LOG = logging.getLogger(__name__)

Maxime Perrotin's avatar
Maxime Perrotin committed
35
__all__ = ['flatten', 'rename_everything', 'inner_labels_to_floating',
36
           'map_input_state', 'sorted_fields']
Maxime Perrotin's avatar
Maxime Perrotin committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53


def map_input_state(process):
    ''' Create a mapping dict {input1: {state1: transition, ...}, ...} '''
    mapping = defaultdict(dict)
    input_signals = [sig['name'] for sig in process.input_signals]
    # Add timers to the mapping
    input_signals.extend(process.timers)
    for input_signal in input_signals:
        for state_name, input_symbols in process.mapping.viewitems():
            if isinstance(input_symbols, list):
                # Start symbols have no list of inputs
                for i in input_symbols:
                    if input_signal.lower() in (inp.lower() for
                                               inp in i.inputlist):
                        mapping[input_signal][state_name] = i
    return mapping
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69


def inner_labels_to_floating(process):
    '''
        Transform inner labels of both floating labels and transitions
        into new floating labels, so that they can be generated in a separate
        section of code, where they are in the scope of everybody
        Works with processes, procedures and nested states
    '''
    for idx in xrange(len(process.content.floating_labels)):
        for new_floating in find_labels(
                      process.content.floating_labels[idx].transition):
            process.content.floating_labels.append(new_floating)
    for proc_tr in process.transitions:
        for new_floating in find_labels(proc_tr):
            process.content.floating_labels.append(new_floating)
Maxime Perrotin's avatar
Maxime Perrotin committed
70
71
72
    if process.content.start:
        for new_floating in find_labels(process.content.start.transition):
            process.content.floating_labels.append(new_floating)
73
74
75
76
77
    for each in process.content.named_start:
        for new_floating in find_labels(each.transition):
            process.content.floating_labels.append(new_floating)


Maxime Perrotin's avatar
Maxime Perrotin committed
78
def flatten(process, sep=u'_'):
79
    ''' In-place update of the AST: flatten a model with nested states
80
81
        Rename inner states, procedures, etc. and move them to process level
    '''
Maxime Perrotin's avatar
Maxime Perrotin committed
82
    def update_terminator(context, term, process):
83
84
85
86
        '''Set next_id, identifying the next transition to run '''
        if term.inputString.lower() in (st.statename.lower()
                                for st in context.composite_states):
            if not term.via:
Maxime Perrotin's avatar
Maxime Perrotin committed
87
                term.next_id = term.inputString.lower() + sep + u'START'
88
            else:
Maxime Perrotin's avatar
Maxime Perrotin committed
89
                term.next_id = u'{term}{sep}{entry}_START'.format(
90
                        term=term.inputString, entry=term.entrypoint, sep=sep)
91
92
93
        elif term.inputString.strip() == '-':
            term.candidate_id = defaultdict(list)
            for each in term.possible_states:
94
                if each.lower() in (st.statename.lower()
95
                            for st in context.composite_states):
Maxime Perrotin's avatar
Maxime Perrotin committed
96
                    term.candidate_id[each + sep + u'START'] = \
97
98
                                       [st for st in process.mapping.viewkeys()
                                        if st.startswith(each)
Maxime Perrotin's avatar
Maxime Perrotin committed
99
                                        and not st.endswith(u'START')]
100
101
                else:
                    term.candidate_id[-1].append(each)
102
103
104
105
106
107

    def update_composite_state(state, process):
        ''' Rename inner states, recursively, and add inner transitions
            to process, updating indexes, and update terminators
        '''
        trans_idx = len(process.transitions)
108
        prefix = state.statename + sep
109
        set_terminator_states(state, prefix)
110
111
        set_transition_states(state, prefix)

Maxime Perrotin's avatar
Maxime Perrotin committed
112
        state.mapping = {prefix + key: state.mapping.pop(key)
113
114
115
116
117
118
119
120
121
122
                         for key in state.mapping.keys()}
        process.transitions.extend(state.transitions)

        # Add prefix to local variable names and push them at process level
        for dcl in state.variables.viewkeys():
            rename_everything(state.content, dcl, prefix + dcl)
        state.variables = {prefix + key: state.variables.pop(key)
                           for key in state.variables.keys()}
        process.variables.update(state.variables)

123
124
125
126
127
128
129
130
131
        # Update return transition indices
        for each in state.terminators:
            if each.kind == 'return':
                for idx, trans in enumerate(process.transitions):
                    if trans == each.next_trans:
                        each.next_id = idx
                        break

        values = []
132
133
134
135
136
        for key, value in state.mapping.viewitems():
            # Update transition indices
            if isinstance(value, int):
                state.mapping[key] = value + trans_idx
            else:
137
138
139
140
141
142
143
144
                values.extend(value)

        for inp in set(values):
            # values may contain duplicate entries if an input corresponds
            # to multiple states. In that case we must update the index of the
            # input only once, thus the set().
            inp.transition_id += trans_idx

145
146
147
148
149
150
151
152
        process.mapping.update(state.mapping)

        # If composite state has entry procedures, add the call
        if state.entry_procedure:
            for each in (trans for trans in state.mapping.viewvalues()
                         if isinstance(trans, int)):
                call_entry = ogAST.ProcedureCall()
                call_entry.inputString = 'entry'
153
154
                entryproc = u'{pre}entry'.format(pre=prefix)
                call_entry.output = [{'outputName': entryproc,
155
156
157
158
159
160
161
162
163
164
                                     'params': [], 'tmpVars': []}]
                process.transitions[each].actions.insert(0, call_entry)

        # If composite state has exit procedure, add the call
        if state.exit_procedure:
            for each in chain(state.transitions, (lab.transition for lab in
                                              state.content.floating_labels)):
                if each.terminator.kind == 'return':
                    call_exit = ogAST.ProcedureCall()
                    call_exit.inputString = 'exit'
165
166
167
                    exitproc = u'{pre}exit'.format(pre=prefix)
                    call_exit.output = [{'outputName': exitproc,
                                         'params': [], 'tmpVars': []}]
168
169
170
171
172
173
                    each.actions.append(call_exit)

        for inner in state.composite_states:
            # Go recursively in inner composite states
            inner.statename = prefix + inner.statename
            update_composite_state(inner, process)
174
175
176
177
178
179
            propagate_inputs(inner, process)
            try:
                del process.mapping[inner.statename]
            except KeyError:
                # KeyError in case of state aggregation
                pass
180
181
182
183
184
        for each in state.terminators:
            # Give prefix to terminators
            if each.label:
                each.label.inputString = prefix + each.label.inputString
            if each.kind == 'next_state':
185
186
                if each.inputString.strip() != '-':
                    each.inputString = prefix + each.inputString
187
                # Set next transition id
Maxime Perrotin's avatar
Maxime Perrotin committed
188
                update_terminator(context=state, term=each, process=process)
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
            elif each.kind == 'join':
                rename_everything(state.content,
                                  each.inputString,
                                  prefix + each.inputString)
        for each in state.labels:
            # Give prefix to labels in transitions
            rename_everything(state.content,
                              each.inputString,
                              prefix + each.inputString)
        # Add prefixed floating labels of the composite state to the process
        process.content.floating_labels.extend(state.content.floating_labels)
        # Rename inner procedures
        for each in state.content.inner_procedures:
            rename_everything(state.content, each.inputString,
                              prefix + each.inputString)
            each.inputString = prefix + each.inputString
        process.content.inner_procedures.extend(state.content.inner_procedures)

207
    def propagate_inputs(nested_state, context):
208
209
210
211
212
213
214
        ''' Nested states: Inputs at level N must be handled at level N-1
            that is, all inputs of a composite states (the ones that allow
            to exit the composite state from the outer scope) must be
            processed by each of the substates.
        '''
        for _, val in nested_state.mapping.viewitems():
            try:
215
                inputlist = context.mapping[nested_state.statename]
216
                val.extend(inputlist)
217
218
            except (AttributeError, KeyError):
                # KeyError in case of StateAggregation
219
220
221
                pass
        for each in nested_state.composite_states:
            # do the same recursively
222
            propagate_inputs(each, nested_state)
Maxime Perrotin's avatar
Maxime Perrotin committed
223
            #del nested_state.mapping[each.statename]
224

225
226
227
228
229
230
231
232
233
    def set_terminator_states(context, prefix=''):
        ''' Associate state to terminators, needed to process properly
            a history nextstates (dash nextstate) in code generators '''
        for each in context.content.states:
            for inp in each.inputs:
                for term in inp.terminators:
                    term.possible_states.extend(prefix + name.lower()
                                                for name in each.statelist)

234
235
236
237
238
239
240
241
    def set_transition_states(context, prefix=''):
        ''' Associate state to transitions, needed to process properly
            the call to the exit procedure of a nested state '''
        for each in context.content.states:
            for inp in each.inputs:
                inp.transition.possible_states.extend(prefix + name.lower()
                                                for name in each.statelist)

242
    set_terminator_states(process)
243
    set_transition_states(process)
244

245
246
    for each in process.composite_states:
        update_composite_state(each, process)
247
        propagate_inputs(each, process)
248
249
250
251
252
        del process.mapping[each.statename]

    # Update terminators at process level
    for each in process.terminators:
        if each.kind == 'next_state':
Maxime Perrotin's avatar
Maxime Perrotin committed
253
            update_terminator(process, each, process)
254
255
256
257
258
259
260
261
262
263
264
265
266


@singledispatch
def rename_everything(ast, from_name, to_name):
    '''
        Rename in all symbols all occurences of name_ref into new_name.
        This is used to avoid name clashes in nested diagrams when they get
        flattened. For example rename all accesses to a variable declared
        in the scope of a composite state, so that they do not overwrite
        a variable with the same name declared at a higher scope.
    '''
    _, _, _ = ast, from_name, to_name

Maxime Perrotin's avatar
Maxime Perrotin committed
267

268
269
270
271
272
273
274
275
276
277
278
279
280
281
@rename_everything.register(ogAST.Automaton)
def _rename_automaton(ast, from_name, to_name):
    ''' Renaming at Automaton top level (content of digragrams) '''
    if ast.start:
        rename_everything(ast.start.transition, from_name, to_name)
    for each in ast.named_start:
        rename_everything(each.transition, from_name, to_name)
    for each in ast.floating_labels:
        rename_everything(each, from_name, to_name)
    for each in ast.states:
        for inp in each.inputs:
            rename_everything(inp.transition, from_name, to_name)
            for idx, param in enumerate(inp.parameters):
                if param.lower() == from_name.lower():
282
                    inp.parameters[idx] = to_name
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
        if each.composite:
            rename_everything(each.composite.content, from_name, to_name)
    for each in ast.inner_procedures:
        # Check that from_name is not a redefined variable in the procedure
        for varname in each.variables.viewkeys():
            if varname.lower() == from_name:
                break
        else:
            rename_everything(each.content, from_name, to_name)


@rename_everything.register(ogAST.Output)
@rename_everything.register(ogAST.ProcedureCall)
def _rename_output(ast, from_name, to_name):
    ''' Rename actual parameter names in output/procedure calls
        and possibly the procedure name '''
    for each in ast.output:
        if each['outputName'].lower() == from_name.lower():
            each['outputName'] = to_name
        for param in each['params']:
            rename_everything(param, from_name, to_name)


@rename_everything.register(ogAST.Label)
def _rename_label(ast, from_name, to_name):
    ''' Rename elements in the transition following a label '''
    if ast.inputString.lower() == from_name.lower():
        ast.inputString = to_name
    rename_everything(ast.transition, from_name, to_name)

Maxime Perrotin's avatar
Maxime Perrotin committed
313

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
@rename_everything.register(ogAST.Decision)
def _rename_decision(ast, from_name, to_name):
    ''' Rename elements in decision '''
    if ast.kind == 'question':
        rename_everything(ast.question, from_name, to_name)
    for each in ast.answers:
        rename_everything(each, from_name, to_name)


@rename_everything.register(ogAST.Answer)
def _rename_answer(ast, from_name, to_name):
    ''' Rename elements in an answer branch '''
    if ast.kind in ('constant', 'open_range'):
        rename_everything(ast.constant, from_name, to_name)
    elif ast.kind == 'closed_range':
Maxime Perrotin's avatar
Maxime Perrotin committed
329
        pass  # TODO when supported
330
331
332
333
334
335
336
337
338
339
    rename_everything(ast.transition, from_name, to_name)


@rename_everything.register(ogAST.Transition)
def _rename_transition(ast, from_name, to_name):
    ''' Rename in all symbols of a transition '''
    for each in chain(ast.actions, ast.terminators):
        # Label, output, task, decision, terminators
        rename_everything(each, from_name, to_name)

Maxime Perrotin's avatar
Maxime Perrotin committed
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@rename_everything.register(ogAST.Terminator)
def _rename_terminator(ast, from_name, to_name):
    ''' Rename terminators: join/labels, next_state '''
    if ast.inputString.lower() == from_name.lower():
        ast.inputString = to_name
    rename_everything(ast.label, from_name, to_name)
    rename_everything(ast.return_expr, from_name, to_name)


@rename_everything.register(ogAST.TaskAssign)
def _rename_task_assign(ast, from_name, to_name):
    ''' List of assignments '''
    for each in ast.elems:
        rename_everything(each, from_name, to_name)

Maxime Perrotin's avatar
Maxime Perrotin committed
356

357
358
359
360
361
362
363
364
365
@rename_everything.register(ogAST.TaskForLoop)
def _rename_forloop(ast, from_name, to_name):
    ''' List of FOR loops '''
    for each in ast.elems:
        rename_everything(each['list'], from_name, to_name)
        rename_everything(each['range']['start'], from_name, to_name)
        rename_everything(each['range']['stop'], from_name, to_name)
        rename_everything(each['transition'], from_name, to_name)

Maxime Perrotin's avatar
Maxime Perrotin committed
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
@rename_everything.register(ogAST.ExprPlus)
@rename_everything.register(ogAST.ExprMul)
@rename_everything.register(ogAST.ExprMinus)
@rename_everything.register(ogAST.ExprEq)
@rename_everything.register(ogAST.ExprNeq)
@rename_everything.register(ogAST.ExprGt)
@rename_everything.register(ogAST.ExprGe)
@rename_everything.register(ogAST.ExprLt)
@rename_everything.register(ogAST.ExprLe)
@rename_everything.register(ogAST.ExprDiv)
@rename_everything.register(ogAST.ExprMod)
@rename_everything.register(ogAST.ExprRem)
@rename_everything.register(ogAST.ExprAssign)
@rename_everything.register(ogAST.ExprOr)
@rename_everything.register(ogAST.ExprIn)
@rename_everything.register(ogAST.ExprAnd)
@rename_everything.register(ogAST.ExprXor)
@rename_everything.register(ogAST.ExprAppend)
@rename_everything.register(ogAST.ExprAssign)
def _rename_expr(ast, from_name, to_name):
    ''' Two-sided expressions '''
    rename_everything(ast.left, from_name, to_name)
    rename_everything(ast.right, from_name, to_name)

Maxime Perrotin's avatar
Maxime Perrotin committed
391

392
393
394
395
396
397
@rename_everything.register(ogAST.PrimVariable)
def _rename_path(ast, from_name, to_name):
    ''' Ultimate seek point for the renaming: primary path/variables '''
    if ast.value[0].lower() == from_name.lower():
        ast.value[0] = to_name

Maxime Perrotin's avatar
Maxime Perrotin committed
398

399
@rename_everything.register(ogAST.PrimConditional)
400
def _rename_ifhthenelse(ast, from_name, to_name):
401
    ''' Rename expressions in Conditional expression construct '''
402
403
    for expr in ('if', 'then', 'else'):
        rename_everything(ast.value[expr], from_name, to_name)
404

Maxime Perrotin's avatar
Maxime Perrotin committed
405

406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def find_labels(trans):
    '''
        Yield a list of transition actions whenever a label is found
        Used to transform labels into floating labels so that the gotos
        in a backend can be contained within a single scope.
    '''
    if not trans:
        return
    # Terminators can have a label - add it to the transition actions
    # (to trigger a goto at code generation)
    if trans.terminator and trans.terminator.label:
        trans.actions.append(trans.terminator.label)
        trans.terminator.label = None
    # Then for each action, check if there are labels and yield
    # a new transition with the remaining actions (following the label)
    for idx, action in enumerate(trans.actions):
        if isinstance(action, ogAST.Label):
            new_trans = ogAST.Transition()
            # Create a floating label
            flab = ogAST.Floating_label(label=action)
Maxime Perrotin's avatar
Maxime Perrotin committed
426
427
            new_trans.actions = \
                    trans.actions[slice(idx + 1, len(trans.actions))]
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
            new_trans.terminator = trans.terminator
            new_trans.terminators = trans.terminators
            flab.transition = new_trans
            # Transform the label into a JOIN in the original transition
            trans.actions[idx:] = []
            trans.terminator = ogAST.Terminator()
            trans.terminator.inputString = action.inputString
            trans.terminator.kind = 'join'
            # Recursively find labels in the new transition
            for flabel in find_labels(flab.transition):
                yield flabel
            # Then yield the new transition
            yield flab
        elif isinstance(action, ogAST.Decision):
            for answer in action.answers:
                for new_fl in find_labels(answer.transition):
                    # Append the remaining actions of the transition
                    if not new_fl.transition.terminator:
Maxime Perrotin's avatar
Maxime Perrotin committed
446
447
                        new_fl.transition.actions.extend(trans.actions
                                          [slice(idx + 1, len(trans.actions))])
448
449
                        new_fl.transition.terminator = trans.terminator
                    yield new_fl
450
451
452
453
454
455
456
457
458


def sorted_fields(atype):
    ''' Return the sorted list of a SEQUENCE or CHOICE type fields '''
    if atype.kind not in ('SequenceType', 'ChoiceType'):
        raise TypeError('Not a SEQUENCE nor a CHOICE')
    tmp = ([k, val.Line, val.CharPositionInLine]
             for k, val in atype.Children.viewitems())
    return (x[0] for x in sorted(tmp, key=operator.itemgetter(1,2)))