AdaGenerator.py 143 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1
#!/usr/bin/env python3
Maxime Perrotin's avatar
Maxime Perrotin committed
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-

"""
    OpenGEODE - A tiny SDL Editor for TASTE

    This module generates Ada code from SDL process models.
    The Ada code is compliant with the TASTE interfaces, and is
    using the ASN.1 "Space-Certified" compiler for data type definition.
    (See TASTE documentation for more information)

Maxime Perrotin's avatar
Maxime Perrotin committed
12
    The design is flexible and can be used as basis for other backends.
Maxime Perrotin's avatar
Maxime Perrotin committed
13
14
15
16
17
18
19
20
21
22
23

    Entry point:
    The AST of the model that is parsed is described in ogAST.py

    A Visitor Pattern using Python's "singledispatch" mechanism is used
    to go through the AST and generate code for each SDL construct.

    There is a single function called "generate", decorated with the
    singledispatch mechanism, that needs to be called to generate the code
    of any AST element.

Maxime Perrotin's avatar
Maxime Perrotin committed
24
25
26
    The generate function returns two values: "code" and "local_decl",
    containing a set of statements and a set of local variables
    (that can be later placed anywhere in the code).
Maxime Perrotin's avatar
Maxime Perrotin committed
27

Maxime Perrotin's avatar
Maxime Perrotin committed
28
29
30
31
32
    Expressions (all classes derived from ogAST.Expression) are generated
    using the "expression" visitor (singledispatch set of function).

    Expressions return three values: "code", "ada_string" and "local_decl".
    The "ada_string" value is the usable string that corresponds
Maxime Perrotin's avatar
Maxime Perrotin committed
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
    to the result of the expression evaluation.

    For example, take the SDL statement "OUTPUT hello(a+5)"

    This results (in TASTE terminology) in calling the required interface
    called "hello" and passing a parameter of an ASN.1 type (say MyInteger).
    The parameter is always passed by reference.

    It is therefore necessary to build a temporary variable to hold the result
    of the "a+5" expression.

    In this example, the "generate" function will return:
    local_decl = ["tmp01 : MyInteger;"]
    (The template backend can then place it wherever appropriate)

    and code = ["tmp01 := a + 5;", "hello(tmp01);"]
    (The template will then do a '\n'.join(code) - and add indents, etc.)

    To know about "tmp01" and generate the code "hello(tmp01);",
    the function will recursively call "generate" and
    pass a+5 as parameter. The call will return the tuple:

    local_decl = ["tmp01 : MyInteger;"]
    code = ["tmp01 := a + 5;"]
    ada_string = "tmp01"

    This design allows to have any level of complexity in the embedded
    expression in a way that is easy to handle (adding constructs with
    this pattern is straightforward, once the generate function for each AST
    entry is properly implemented).

64
    Copyright (c) 2012-2020 European Space Agency
Maxime Perrotin's avatar
Maxime Perrotin committed
65
66
67
68
69
70
71
72

    Designed and implemented by Maxime Perrotin

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


import logging
73
import traceback
74
import os
75
import stat
76
from itertools import chain, product
Maxime Perrotin's avatar
Maxime Perrotin committed
77
from functools import singledispatch
Maxime Perrotin's avatar
Maxime Perrotin committed
78

Maxime Perrotin's avatar
Maxime Perrotin committed
79
from . import ogAST, Helper
Maxime Perrotin's avatar
Maxime Perrotin committed
80
81
82
83
84

LOG = logging.getLogger(__name__)

__all__ = ['generate']

85
86
87

PROCESS_NAME = ""

Maxime Perrotin's avatar
Maxime Perrotin committed
88
89
# reference to the ASN.1 Data view and to the visible variables (in scope)
TYPES = None
90
91
92
93

# look-up table to find the module name containing a type
MAPPING_SORT_MODULE = dict()

Maxime Perrotin's avatar
Maxime Perrotin committed
94
95
96
97
98
99
VARIABLES = {}
LOCAL_VAR = {}
# List of output signals and procedures
OUT_SIGNALS = []
PROCEDURES = []

100
101
102
# Specify that the target is a shared library
SHARED_LIB = False

Maxime Perrotin's avatar
Maxime Perrotin committed
103
104
105
#SEPARATOR = u'\u00dc'
# Avoid Unicode characters, they cause occasional annoying issues
SEPARATOR = "_0_"
106
107
LPREFIX = 'ctxt'
ASN1SCC = 'asn1Scc'
Maxime Perrotin's avatar
Maxime Perrotin committed
108

109
110
111
112
113
114
115
116
117
118

def is_numeric(string):
    ''' Return true if value is a number '''
    try:
        float(string)
    except ValueError:
        return False
    return True


119
120
121
122
123
def external_ri_list(process):
    ''' Helper function: create a list of RI with proper signature
    Used for the formal parameters of generic packages when using process type
    '''
    result = []
124
    #print process.fpar
125
    for signal in process.output_signals:
126
        param_name = signal.get('param_name') or f'{signal["name"]}_param'
127
128
129
        param_spec = ''
        if 'type' in signal:
            typename = type_name(signal['type'])
130
131
            param_spec = f'({param_name}: in out {typename})'
        result.append(f"procedure RI{SEPARATOR}{signal['name']}{param_spec}")
132
    for proc in (proc for proc in process.procedures if proc.external):
133
        ri_header = f'procedure RI{SEPARATOR}{proc.inputString}'
134
135
136
137
        params = []
        params_spec = ''
        for param in proc.fpar:
            typename = type_name(param['type'])
138
139
140
141
142
            if param['direction'] == 'in':
                direct = 'in out'
            else:
                direct = 'out'
            params.append(f'{param["name"]} : {direct} {typename}')
143
144
145
146
        if params:
            params_spec = u"({})".format("; ".join(params))
            ri_header += params_spec
        result.append(ri_header)
147
148

    for timer in process.timers:
149
        result.append(
150
                f"procedure Set_{timer} (Val : in out {ASN1SCC}T_Uint32)")
151
        result.append(f"procedure Reset_{timer}")
152
153
154
    return result


Maxime Perrotin's avatar
Maxime Perrotin committed
155
@singledispatch
156
def generate(*args, **kwargs):
Maxime Perrotin's avatar
Maxime Perrotin committed
157
    ''' Generate the code for an item of the AST '''
158
    raise TypeError('Incorrect, unsupported or missing data in model AST')
159
    return [], []
Maxime Perrotin's avatar
Maxime Perrotin committed
160
161


Maxime Perrotin's avatar
Maxime Perrotin committed
162
# Processing of the AST
Maxime Perrotin's avatar
Maxime Perrotin committed
163
@generate.register(ogAST.Process)
164
def _process(process, simu=False, instance=False, taste=False, **kwargs):
165
166
167
168
    ''' Generate the code for a complete process (AST Top level)
        use instance=True to generate the code for a process type instance
        rather than the process type itself.
    '''
169
    # support generation of code of a process type
170
171
172
173
174
175
176
177
178
179
    if not instance:
        process_name = process.instance_of_name or process.processName
        generic = process.instance_of_name  #  shortcut
        process_instance = process
        process = process.instance_of_ref or process
    else:
        process_name = process.processName
        generic = False
        process_instance = process

180
181
182
    global PROCESS_NAME
    PROCESS_NAME = process_name

183
184
    if process_instance is not process:
        # Generate an instance of the process type, too.
185
186
187
        # First copy the list of timers to the instance (otherwise the
        # instance would miss some PIs and RIs to set the actual timers)
        process_instance.timers = process.timers
Maxime Perrotin's avatar
Maxime Perrotin committed
188
        generate(process_instance, simu, instance=True, taste=taste)
189

Maxime Perrotin's avatar
Maxime Perrotin committed
190
191
192
193
194
195
    global TYPES
    TYPES = process.dataview
    del OUT_SIGNALS[:]
    del PROCEDURES[:]
    OUT_SIGNALS.extend(process.output_signals)
    PROCEDURES.extend(process.procedures)
196
    global SHARED_LIB
197
    global LPREFIX
198
199
    if simu:
        SHARED_LIB = True
200
        LPREFIX = f'{process_name}_ctxt'
Maxime Perrotin's avatar
Maxime Perrotin committed
201

202
203
204
    for each in PROCEDURES:
        process.random_generator.update(each.random_generator)

205
206
    # taste-properties module-specific flag for the Ada backend:
    # import the state data from an external module
207
    stop_condition = kwargs["ppty_check"] if "ppty_check" in kwargs else ""
208

209
210
211
212
213
214
215
216
217
218
219
    # When building a shared library (with simu=True), generate a "mini-cv"
    # for aadl2glueC to create the code interfacing with asn1scc
    minicv = ['-- Automatically generated by OpenGEODE - do NOT modify!']
    def aadl_template(sp_name, io_param, pi_or_ri):
        ''' AADL mini-cv code in case of shared library
            sp_name  : name of the PI or RI
            io_param : list of (param_name, type_name, direction)
            pi_or_ri : string "PI" or "RI" depending on the direction
            return a string
        '''
        res = []
220
221
222
223
224
        if not io_param:
            LOG.info('Parameterless interface "{}" will not appear in the'
                     ' AADL file but will be handled directly by the GUI'
                     .format(sp_name))
            return ''
225
226
227
228
229
230
        # In case of shared library, generate the AADL "mini-cv" code
        res.append('SUBPROGRAM {}'.format(sp_name))
        if io_param:
            res.append('FEATURES')
            for param_name, sort, direction in io_param:
                res.append('    {pname}: {io} PARAMETER DataView::{sort} '
231
232
233
                          '{{encoding=>Native;}};'.format(pname=param_name,
                                                          sort=sort,
                                                          io=direction))
234
235
236
237
238
239
240
241
242
        res.append('END {};\n'.format(sp_name))
        res.append('SUBPROGRAM IMPLEMENTATION {}.GUI_{}'
                      .format(sp_name, pi_or_ri))
        res.append('PROPERTIES')
        res.append('    FV_Name => "{}";'.format(process_name))
        res.append('    Source_Language => GUI_{};'.format(pi_or_ri))
        res.append('END {}.GUI_{};\n'.format(sp_name, pi_or_ri))
        return '\n'.join(res)

243
    # bash script to simulate the system (TEMPORARY)
244
245
246
247
248
249
250

    # go up to the root of the AST to get the list of ASN.1 files
    parent = process.parent
    while hasattr(parent, 'parent') and parent.parent:
        parent = parent.parent
    if isinstance(parent, ogAST.System):
        parent = parent.ast
251
252
    asn1_filenames = (f"{' '.join(parent.asn1_filenames)} "
                      f"{process_name.lower()}_datamodel.asn")
Maxime Perrotin's avatar
Maxime Perrotin committed
253
    asn1_uniq = ' '.join(each for each in parent.asn1_filenames
254
                         if not each.endswith('dataview-uniq.asn'))
255
    asn1_uniq += f" {process_name.lower()}_datamodel.asn"
256
    pr_path = ' '.join(parent.pr_files) if None not in parent.pr_files else ''
257
258
    pr_names = ' '.join(
                      os.path.basename(pr_file) for pr_file in parent.pr_files)
Maxime Perrotin's avatar
Maxime Perrotin committed
259
    asn1_modules_o = (name.lower().replace('-', '_') + '.o'
260
261
                    for name in process.asn1Modules)

Maxime Perrotin's avatar
Maxime Perrotin committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    asn1_mods = ("\"{}\"".format(mod.lower().replace('-', '_'))
                for mod in process.asn1Modules)

    #  Create a .gpr to build the library for the simulator
    lib_gpr = '''project {pr}_Lib is
   for Languages use ("Ada");
   for Library_Name use "{pr}";
   for Library_Interface use ("{pr}", "adaasn1rtl", {other_asn1_modules});
   for Object_Dir use "obj";
   for Library_Dir use "lib";
   for Library_Standalone use "encapsulated";
   for Library_Kind use "dynamic";
   for Source_Dirs use (".");
end {pr}_Lib;'''.format(pr=process_name.lower(),
                        other_asn1_modules=", ".join(asn1_mods))

    #  Create a .gpr to build the Ada generated code
    ada_gpr = '''project {pr}_Ada is
   for Languages use ("Ada");
Maxime Perrotin's avatar
Maxime Perrotin committed
281
      for Source_Dirs use (".") & External_As_List ("CODE_PATH", ":");
282
      for Object_Dir use "../obj";
Maxime Perrotin's avatar
Maxime Perrotin committed
283
284
   end {pr}_Ada;'''.format(pr=process_name.lower())

285
286
    pr = process_name.lower()
    simu_script = f'''#!/bin/bash -e
287
mkdir -p {pr}_simu
288
cp {pr_path} {asn1_filenames} {pr}_simu
289
290
cd {pr}_simu
opengeode {pr_names} --shared
291
292
293
294
295
296
cat {asn1_uniq} >> dataview-uniq.asn

mono $(which asn1.exe) -Ada -typePrefix {ASN1SCC} -equal dataview-uniq.asn
mono $(which asn1.exe) -c -typePrefix {ASN1SCC} -equal dataview-uniq.asn

gprbuild -p -P {process_name.lower()}_lib.gpr
297
rm -f dataview-uniq.c dataview-uniq.h
298
asn2aadlPlus dataview-uniq.asn DataView.aadl
299
aadl2glueC DataView.aadl {process_name.lower()}_interface.aadl
300
301
asn2dataModel -toPython dataview-uniq.asn
make -f Makefile.python
302
echo "errCodes=$(taste-asn1-errCodes ./dataview-uniq.h)" >>datamodel.py
303
LD_LIBRARY_PATH=./lib:.:$LD_LIBRARY_PATH opengeode-simulator
304
'''
305

Maxime Perrotin's avatar
Maxime Perrotin committed
306
307
    LOG.info('Generating Ada code for process ' + str(process_name))

308
    # In case model has nested states, flatten everything
Maxime Perrotin's avatar
Maxime Perrotin committed
309
    Helper.flatten(process, sep=SEPARATOR)
310

311
    # Process State aggregations (Parallel states) XXX Add to C backend
312

313
314
    # Find recursively in the AST all state aggregations
    # Format: {'aggregation_name' : [list of ogAST.CompositeState]
315
    aggregates = Helper.state_aggregations(process)
316

317
318
319
    # Extract the list of parallel states names inside the composite states
    # of state aggregations XXX add to C generator
    parallel_states = Helper.parallel_states(aggregates)
320

Maxime Perrotin's avatar
Maxime Perrotin committed
321
322
323
324
    # Make an maping {input: {state: transition...}} in order to easily
    # generate the lookup tables for the state machine runtime
    mapping = Helper.map_input_state(process)

Maxime Perrotin's avatar
Maxime Perrotin committed
325
326
327
    VARIABLES.update(process.variables)

    process_level_decl = []
328

329
    # Establish the list of states (excluding START states) XXX update C backend
Maxime Perrotin's avatar
Maxime Perrotin committed
330
    full_statelist = set(chain(aggregates.keys(),
Maxime Perrotin's avatar
Maxime Perrotin committed
331
                               (name for name in process.mapping.keys()
332
                                    if not name.endswith(u'START'))))
333
    reduced_statelist = {s for s in full_statelist if s not in parallel_states}
334

Maxime Perrotin's avatar
Maxime Perrotin committed
335
    if aggregates:
336
        # Parallel states in a state aggregation may terminate
337
338
        full_statelist.add(f'state{SEPARATOR}end')

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
    #  When a signal is sent from the model a call to a function is emitted
    #  This function has to be provided - either by TASTE (kazoo), or by
    #  the user. Opengeode will generate a stub package for this.
    ri_stub_ads = []
    ri_stub_adb = []

    # Generate an ASN.1 model containing:
    # - the state definition
    # - a type describing the SDL context
    # - all user-defined SDL type (NEWTYPEs...)
    process_asn1 = process_name.capitalize().replace('_', '-')
    asn1_template = [f'{process_asn1}-Datamodel DEFINITIONS ::=',
                      'BEGIN']

    # The ASN.1 module must import the types from other asn1 modules
    types_with_proper_case = []
    imports = []
    for moduleName, sorts in process.DV.exportedTypes.items():
        actual_sorts = []
        for each in sorts:
            MAPPING_SORT_MODULE[each] = moduleName
            if process.DV.types[each].AddedType == "False":
                actual_sorts.append(each)
                types_with_proper_case.append (each)
        sortsAsList = ", ".join(actual_sorts)
        if sortsAsList:
            imports.append(f'{sortsAsList} FROM {moduleName}')
    if types_with_proper_case:
        asn1_template.append(
                "IMPORTS\n   " + "\n   ".join(imports) + ";")

370
371
372
373
374
375
376
377
    # Format the state list with ASN.1-compatible syntax
    statelist_asn1 = (state.lower().replace('_', '-')
                      for state in full_statelist)
    states_asn1 = ", ".join(statelist_asn1) \
            or f'{process_asn1.lower()}-has-no-state'
    # Create an ASN.1 definition of the list of states, instead of
    # a native Ada type - this allows external tools to access
    # information about the model without having to parse SDL
378
    asn1_states_def = f"\n{process_asn1}-States ::= ENUMERATED" \
379
                      f" {{{states_asn1}}}"
380

381
    asn1_template.append(asn1_states_def)
382

383
384
385
386
387
388
389
    # Template to generate the full SDL context as a single ASN.1 type
    # This is very useful then to manipulate it from C, Ada or Python as
    # it is then directly accessible and uPER-encodable
    context_elems = []
    if full_statelist:
        # Some systems may have no states - only a start transition
        context_elems.append(f'   state {process_asn1}-States')
390

391
392
393
394
395
396
397
398
399
400
401
402
    context_elems.append ('init-done BOOLEAN')
    # State aggregation: add list of substates
    for substates in aggregates.values():
        for each in substates:
            context_elems.append(f'{each.statename.lower()}{SEPARATOR}state {process_asn1}-States')

    for var_name, (var_type, def_value) in process.variables.items():
        context_elems.append(f'{var_name.lower()} {type_name(var_type, False)}')

    asn1_context = (f'\n{process_asn1}-Context ::='' SEQUENCE {\n'
            + ",\n   ".join(line.replace("_", "-").replace("'", '"') for line in context_elems)
            + "\n}\n")
Maxime Perrotin's avatar
Maxime Perrotin committed
403

404
405
406
407
408
409
    asn1_template.append(asn1_context)

    # Add user-defined NEWTYPEs and CHOICE selector types
    choice_selections = []
    for sortname, sortdef in process.user_defined_types.items():
        if sortdef.type.kind == "SequenceOfType":
410
411
412
413
414
415
416
417
            rangeMin = sortdef.type.Min
            rangeMax = sortdef.type.Max
            refType  = sortdef.type.type.ReferencedTypeName
            for refTypeCase in types_with_proper_case:
                if refTypeCase.lower().replace('-', '_') == \
                        refType.lower().replace('-', '_'):
                    break
            asn1_template.append(
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
                    f'{sortname.replace("_", "-")} ::= SEQUENCE '
                    f'(SIZE ({rangeMin} .. {rangeMax})) OF '
                    f'{refTypeCase.replace("_", "-")}')
        elif sortdef.type.kind == "EnumeratedType":
            keys = []
            for idx, key in enumerate(sortdef.type.EnumValues.keys()):
                # give an index to the enumerations to align with -selection
                # types used in choice index
                keys.append(f'{key}-present({idx+1})')
            asn1_template.append(
                    f'{sortname} ::= ENUMERATED {{' + ", ".join(keys) + '}')
            # We need to convert from the ASN.1 enumerated to the one we created
            choiceTypeModule = MAPPING_SORT_MODULE[sortdef.ChoiceTypeName].replace('-', '_')
            sortAda = sortname.replace('-', '_')
            fromMod = f'{choiceTypeModule}.{ASN1SCC}{sortAda}'
            toMod = f'{process_name}_Datamodel.{ASN1SCC}{sortAda}'
            choice_selections.append(
                    f'function To_{sortAda} (Src : {fromMod}) return {toMod} '
                    f"is ({toMod}'Enum_Val (Src'Enum_Rep));")

438
439
    asn1_template.append('END')

440
    # Write the ASN.1 file (not in case of Stop Condition)
441
    if not stop_condition:
442
443
        with open(process_name.lower() + '_datamodel.asn', 'w') as asn1_file:
            asn1_file.write('\n'.join(asn1_template))
444

445
    # Generate the code to declare process-level context
446
    context_decl = []
447
    if not stop_condition:
448
449
450
        # but not in stop condition code, since we reuse the context type
        # of the state machine being observed

451
452
453
454
        ctxt = (f'{LPREFIX} : aliased {ASN1SCC}{process_name.capitalize()}_Context :=\n'
                '      (Init_Done => False,\n       ')
        initial_values = []
        # some parts of the context may have initial values
455
456
457
458
459
460
461
462
463
464
        for var_name, (var_type, def_value) in process.variables.items():
            if def_value:
                # Expression must be a ground expression, i.e. must not
                # require temporary variable to store computed result
                dst, dstr, dlocal = expression(def_value)
                varbty = find_basic_type(var_type)
                if varbty.kind in ('SequenceOfType', 'OctetStringType'):
                    dstr = array_content(def_value, dstr, varbty)
                assert not dst and not dlocal,\
                        'DCL: Expecting a ground expression'
465
466
467
468
469
470
471
472
473
474
                initial_values.append(f'{var_name} => {dstr}')

        if initial_values:
            ctxt += ",\n       ".join(initial_values) + ",\n      "
        ctxt += "others => <>);"
        context_decl.append(ctxt)

        # The choice selections will allow to use the present operator
        # together with a variable of the -selection type
        context_decl.extend(choice_selections)
475
    if stop_condition:
476
477
        #  code of stop conditions must use the same type as the main process
        context_decl.append(
478
479
480
                f'{LPREFIX} : {ASN1SCC}{stop_condition}_Context '
                f'renames {stop_condition}.{stop_condition}_ctxt;')
    if simu and not stop_condition:
481
482
        # Export the context, so that it can be manipulated from outside
        # (in practice used by the "properties" module.
483
        context_decl.append(f'pragma export (C, {LPREFIX}, "{LPREFIX}");')
484
        # Exhaustive simulation needs a backup of the context to quickly undo
485
        context_decl.append(f'{LPREFIX}_bk: {ASN1SCC}{process_name.capitalize()}_Context;')
Maxime Perrotin's avatar
Maxime Perrotin committed
486

487
    aggreg_start_proc = []
Maxime Perrotin's avatar
Maxime Perrotin committed
488
489
490
    start_transition = []
    # Continuous State transition id
    if not instance:
491
        process_level_decl.append('CS_Only : constant := {};'
Maxime Perrotin's avatar
Maxime Perrotin committed
492
493
                                  .format(len(process.transitions)))

Maxime Perrotin's avatar
Maxime Perrotin committed
494
        for name, val in process.mapping.items():
Maxime Perrotin's avatar
Maxime Perrotin committed
495
496
497
498
499
500
501
502
503
            # Test val, in principle there is a value but if the code targets
            # generation of properties, the model may have been cleant up and
            # in that case no value would be set..
            if name.endswith(u'START') and name != u'START' and val:
                process_level_decl.append(u'{name} : constant := {val};'
                                          .format(name=name, val=str(val)))

        # Declare start procedure for aggregate states XXX add in C generator
        # should create one START per "via" clause, TODO later
Maxime Perrotin's avatar
Maxime Perrotin committed
504
        for name, substates in aggregates.items():
505
506
507
            proc_name = f'procedure {name}{SEPARATOR}START'
            process_level_decl.append(f'{proc_name};')
            aggreg_start_proc.extend([f'{proc_name} is',
Maxime Perrotin's avatar
Maxime Perrotin committed
508
                                      'begin'])
509
            aggreg_start_proc.extend(u'Execute_Transition ({sub}{sep}START);'
Maxime Perrotin's avatar
Maxime Perrotin committed
510
                                     .format(sub=subname.statename,
Maxime Perrotin's avatar
Maxime Perrotin committed
511
                                             sep=SEPARATOR)
Maxime Perrotin's avatar
Maxime Perrotin committed
512
                                     for subname in substates)
513
            aggreg_start_proc.extend([f'end {name}{SEPARATOR}START;',
Maxime Perrotin's avatar
Maxime Perrotin committed
514
515
                                     '\n'])

516
        # Add the declaration of the Execute_Transition procedure
517
        process_level_decl.append(
518
                'procedure Execute_Transition (Id : Integer);')
Maxime Perrotin's avatar
Maxime Perrotin committed
519
520

        # Generate the code of the start transition (if process not empty)
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
        Init_Done = f'{LPREFIX}.Init_Done := True;'
        rand_reset_decl = []
        for rand_g in process.random_generator:
            rand_reset_decl.append(f'Rand_{rand_g}_Pkg.Reset (Gen_{rand_g});');

        start_transition = [
                'procedure Startup is',
                'begin',
                *rand_reset_decl,
                'Execute_Transition (0);'
                if process.transitions else 'null;',
                Init_Done,
                'end Startup;',
                '',
                'begin',
                'Startup;']
537

Maxime Perrotin's avatar
Maxime Perrotin committed
538
539
540
541
542
    # Generate the TASTE template
    try:
        asn1_modules = '\n'.join(['with {dv};\nuse {dv};'.format(
            dv=dv.replace('-', '_'))
            for dv in process.asn1Modules])
543
544
        if process.asn1Modules:
            asn1_modules += '\nwith adaasn1rtl;\nuse adaasn1rtl;'
Maxime Perrotin's avatar
Maxime Perrotin committed
545
546
    except TypeError:
        asn1_modules = '--  No ASN.1 data types are used in this model'
547

548
    taste_template = [f'''\
Maxime Perrotin's avatar
Maxime Perrotin committed
549
-- This file was generated automatically by OpenGEODE: DO NOT MODIFY IT !
Maxime Perrotin's avatar
Maxime Perrotin committed
550
551
552
553

with System.IO;
use System.IO;

554
with Ada.Unchecked_Conversion;
555
with Ada.Numerics.Generic_Elementary_Functions;
556

557
package body {process_name} is'''
558
559
    if not instance else f'''--  Package body for instance - Generated by OpenGEODE (DO NOT EDIT)
package body {process_name} is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
560

561
    generic_spec, instance_decl = "", ""
562
    if generic:
563
        generic_spec = "generic\n"
564
565
        ri_list = external_ri_list(process)
        if ri_list:
566
            generic_spec += "    with " + ";\n    with ".join(ri_list) + ';'
567
    if instance:
568
        instance_decl = f"with {process.instance_of_name};"
569

570
571
572
    # print process.fpar
    # FPAR could be set for Context Parameters. They are available here

Maxime Perrotin's avatar
Maxime Perrotin committed
573
    # Generate the source file (.ads) header
574
575

    # Stop conditions must import the SDL model they observe
576
577
    imp_str = f"with {stop_condition}; use {stop_condition};" \
            if stop_condition else ''
578

579
    imp_datamodel = (f"with {process_name}_Datamodel; "
580
                     f"use {process_name}_Datamodel;") \
581
582
583
584
                             if not stop_condition and not instance else (
                                     f"with {stop_condition}_Datamodel; "
                                     f"use {stop_condition}_Datamodel;"
                                     if stop_condition else "")
585

Maxime Perrotin's avatar
Maxime Perrotin committed
586
    imp_ri = f"with {process_name}_RI;" if not simu and not generic else ""
587

588
589
590
591
592
593
594
595
596
597
598
    rand = ('with Ada.Numerics.Discrete_Random;'
            if process.random_generator else "")
    rand_decl = []
    for each in process.random_generator:
        rand_decl.extend([
            f'type Rand_{each}_ty is new Integer range 1 .. {each};',
            f'package Rand_{each}_Pkg is new  Ada.Numerics.Discrete_Random'\
                    f' (Rand_{each}_ty);',
            f'Gen_{each} : Rand_{each}_Pkg.Generator;',
            f'Num_{each} : Rand_{each}_ty;'])

599
    ads_template = [f'''\
Maxime Perrotin's avatar
Maxime Perrotin committed
600
-- This file was generated automatically by OpenGEODE: DO NOT MODIFY IT !
Maxime Perrotin's avatar
Maxime Perrotin committed
601

602
603
604
605
606
607
608
609
610
with Interfaces,
     Interfaces.C.Strings,
     Ada.Characters.Handling;

use Interfaces,
    Interfaces.C.Strings,
    Ada.Characters.Handling;

{asn1_modules}
611
{imp_datamodel}
612
{imp_str}
613
{imp_ri}
614
{instance_decl}
615
{rand}
Maxime Perrotin's avatar
Maxime Perrotin committed
616
{generic_spec}'''.strip() + f'''
617
package {process_name} with Elaborate_Body is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
618

Maxime Perrotin's avatar
Maxime Perrotin committed
619
    ri_stub_ads = [f'''\
Maxime Perrotin's avatar
Maxime Perrotin committed
620
621
--  This file is a stub for the implementation of the required interfaces
--  It is normally overwritten by TASTE with the actual connection to the
Maxime Perrotin's avatar
Maxime Perrotin committed
622
623
624
--  middleware. If you use Opengeode independently from TASTE you must
--  edit the .adb (body) with your own implementation of these functions.
--  The body stub will be generated only once.
Maxime Perrotin's avatar
Maxime Perrotin committed
625
626
627
628

{asn1_modules}

package {process_name}_RI is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
629
630
631
632
    ri_stub_adb = [f'''--  Stub generated by OpenGEODE.
--  You can edit this file, it will not be overwritten

package body {process_name}_RI is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
633

Maxime Perrotin's avatar
Maxime Perrotin committed
634
    dll_api = []
635
    ads_template.extend(rand_decl)
636
    if not instance:
Maxime Perrotin's avatar
Maxime Perrotin committed
637
        ads_template.extend(context_decl)
638
    if not generic and not instance and not stop_condition:
639
640
641
        # Add function allowing to trace current state as a string
        ads_template.append(
                f"function Get_State return chars_ptr "
642
643
                f"is (New_String "
                f"({ASN1SCC}{process_name}_States'Image ({LPREFIX}.State)))"
644
645
646
                f" with Export, Convention => C, "
                f'Link_Name => "{process_name.lower()}_state";')

647
    # Declare procedure Startup in .ads
648
649
650
651
652
653
654
655
    if not generic:
        ads_template.append(f'procedure Startup'
                            f' with Export, Convention => C,'
                            f' Link_Name => "{process_name}_startup";')
    else:  # function type
        ads_template.append(f'procedure Startup;')

    if simu and not stop_condition:
656
657
        ads_template.append('--  API for simulation via DLL')
        dll_api.append('-- API to remotely change internal data')
658

659
        # Save/restore state allow one step undo, as needed for model checking
660
661
662
663
        save_state_decl = 'procedure Save_Context with Export, Convention => C, Link_Name => "_save_context";'
        ads_template.append(save_state_decl)
        restore_state_decl = 'procedure Restore_Context with Export, Convention => C, Link_Name => "_restore_context";'
        ads_template.append(restore_state_decl)
664
665
666
667
668
669
670
671
672
673
674
        dll_api.extend([
             "procedure Save_Context is",
             "begin",
            f"{LPREFIX}_bk := {LPREFIX};",
             "end Save_Context;",
             "",
             "procedure Restore_Context is",
             "begin",
            f"{LPREFIX} := {LPREFIX}_bk;",
             "end Restore_Context;",
             ""])
675

676
        # Functions to get global context
677
        ads_template.append(
678
679
                f"function Get_Context return access {ASN1SCC}{process_name}_Context is ({LPREFIX}'access)\n"
                f'   with Export, Convention => C, Link_Name => "{process_name.lower()}_context";')
680
681
682
683
684
685
686
687
688
689
690
691
        ads_template.append(
                f"procedure Set_Context (Context : access {ASN1SCC}{process_name}_Context)\n"
                f'   with Export, Convention => C, Link_Name => "set_{process_name.lower()}_context";')

        dll_api.extend([
                f"procedure Set_Context (Context : access {ASN1SCC}{process_name}_Context) is",
                 "begin",
                f"{LPREFIX} := Context.all;",
                 '--  System.IO.Put_Line ("Changed context. State = " & Context.state\'Img);',
                 "end Set_Context;",
                 ""])

Maxime Perrotin's avatar
Maxime Perrotin committed
692
693
694
695
696
697
    # Generate the the code of the procedures
    inner_procedures_code = []
    for proc in process.content.inner_procedures:
        proc_code, proc_local = generate(proc)
        process_level_decl.extend(proc_local)
        inner_procedures_code.extend(proc_code)
698
699
700
        if proc.exported:
            # Exported procedures must be declared in the .ads
            pi_header = procedure_header(proc)
701
            ads_template.append(f'{pi_header};')
702
            if not proc.external and not generic:
703
704
                ads_template.append(
                   f'pragma Export (C, p{SEPARATOR}{proc.inputString}, "_{proc.inputString}");')
Maxime Perrotin's avatar
Maxime Perrotin committed
705
706
707
708
709
710
711

    # Generate the code for the process-level variable declarations
    taste_template.extend(process_level_decl)

    # Add the code of the procedures definitions
    taste_template.extend(inner_procedures_code)

712
713
714
715
    # Generate the code of the START procedures of state aggregations
    # XXX to be added to C generator
    taste_template.extend(aggreg_start_proc)

716
717
718
    # Add the code of the DLL interface
    taste_template.extend(dll_api)

Maxime Perrotin's avatar
Maxime Perrotin committed
719
720
    # Generate the code for each input signal (provided interface) and timers
    for signal in process.input_signals + [
Maxime Perrotin's avatar
Maxime Perrotin committed
721
                        {'name': timer} for timer in process.timers]:
722
        if stop_condition:
723
724
725
            # dont generate anything in stop_condition functions
            break

726
727
        signame = signal.get('name', 'START')
        if signame == 'START':
Maxime Perrotin's avatar
Maxime Perrotin committed
728
            continue
729
730
        pi_header = f'procedure {signame}'
        param_name = signal.get('param_name') or f'{signame}_param'
Maxime Perrotin's avatar
Maxime Perrotin committed
731
732
        # Add (optional) PI parameter (only one is possible in TASTE PI)
        if 'type' in signal:
Maxime Perrotin's avatar
Maxime Perrotin committed
733
            typename = type_name(signal['type'])
734
            pi_header += f'({param_name}: in out {typename})'
Maxime Perrotin's avatar
Maxime Perrotin committed
735
736

        # Add declaration of the provided interface in the .ads file
737
        ads_template.append(f'--  Provided interface "{signame}"')
Maxime Perrotin's avatar
Maxime Perrotin committed
738
        ads_template.append(pi_header + ';')
739
        if not generic:
740
            ads_template.append(
741
                    f'pragma Export(C, {signame}, "{process_name.lower()}_PI_{signame}");')
742
743
744
745
746

        if simu:
            # Generate code for the mini-cv template
            params = [(param_name, type_name(signal['type'], use_prefix=False),
                      'IN')] if 'type' in signal else []
747
            minicv.append(aadl_template(signame, params, 'RI'))
Maxime Perrotin's avatar
Maxime Perrotin committed
748
749
750
751

        pi_header += ' is'
        taste_template.append(pi_header)
        taste_template.append('begin')
752
753
754
755

        def execute_transition(state):
            ''' Generate the code that triggers the transition for the current
                state/input combination '''
756
            input_def = mapping[signame].get(state)
757
758
759
            # Check for nested states to call optional exit procedures
            # (we may exit from more than one state, the exit procedures must
            #  be called in the right order)
Maxime Perrotin's avatar
Maxime Perrotin committed
760
            state_tree = state.split(SEPARATOR)
Maxime Perrotin's avatar
Maxime Perrotin committed
761
            context = process
762
763
764
765
766
767
            exitlist = []
            current = ''
            trans = input_def and process.transitions[input_def.transition_id]
            while state_tree:
                current = current + state_tree.pop(0)
                for comp in context.composite_states:
768
                    if current.lower() == comp.statename.lower():
769
770
771
                        if comp.exit_procedure:
                            exitlist.append(current)
                        context = comp
Maxime Perrotin's avatar
Maxime Perrotin committed
772
                        current = current + SEPARATOR
773
774
                        break
            for each in reversed(exitlist):
775
776
777
778
779
780
781
                # Here we add a call to the exit procedure of nested states
                # when we exit the state due to a transition in the superstate
                # not due to a return statement from within the substate
                # this other case is handled in Helper.py when flattening
                # the model.
                # The exit here is added only for transitions triggered by an
                # INPUT. The continuous signals are not processed here
782
783
                if trans and all(each.startswith(trans_st)
                                 for trans_st in trans.possible_states):
784
                    taste_template.append(f'p{SEPARATOR}{each}{SEPARATOR}exit;')
785

Maxime Perrotin's avatar
Maxime Perrotin committed
786
787
788
789
            if input_def:
                for inp in input_def.parameters:
                    # Assign the (optional and unique) parameter
                    # to the corresponding process variable
790
                    taste_template.append(f'{LPREFIX}.{inp} := {param_name};')
Maxime Perrotin's avatar
Maxime Perrotin committed
791
792
                # Execute the correponding transition
                if input_def.transition:
793
794
                    taste_template.append(u'Execute_Transition ({idx});'
                            .format(idx=input_def.transition_id))
Maxime Perrotin's avatar
Maxime Perrotin committed
795
                else:
796
                    taste_template.append('Execute_Transition (CS_Only);')
Maxime Perrotin's avatar
Maxime Perrotin committed
797
            else:
798
                taste_template.append('Execute_Transition (CS_Only);')
799

Maxime Perrotin's avatar
Maxime Perrotin committed
800
801
        if not instance:
            taste_template.append('case {}.state is'.format(LPREFIX))
802
803
804
805
806
807
808

        def case_state(state):
            ''' Recursive function (in case of state aggregation) to generate
                the code that calls the proper transition according
                to the current state
                The input name is in signame
            '''
809
            if state.endswith(u'START'):
810
                return
811
            taste_template.append(f'when {ASN1SCC}{state} =>')
812
            input_def = mapping[signame].get(state)
Maxime Perrotin's avatar
Maxime Perrotin committed
813
            if state in aggregates.keys():
814
                # State aggregation:
Maxime Perrotin's avatar
Maxime Perrotin committed
815
816
                # - find which substate manages this input
                # - add a swich case on the corresponding substate
817
818
                taste_template.append(u'-- this is a state aggregation')
                for sub in aggregates[state]:
Maxime Perrotin's avatar
Maxime Perrotin committed
819
820
                    if [a for a in sub.mapping.keys()
                            if a in mapping[signame].keys()]:
821
822
823
824
                        taste_template.append(u'case '
                                              u'{ctxt}.{sub}{sep}state is'
                                              .format(ctxt=LPREFIX,
                                                     sub=sub.statename,
Maxime Perrotin's avatar
Maxime Perrotin committed
825
                                                     sep=SEPARATOR))
Maxime Perrotin's avatar
Maxime Perrotin committed
826
                        for par in sub.mapping.keys():
827
                            case_state(par)
828
829
830
831
                        taste_template.append('when others =>')
                        taste_template.append('null;')
                        taste_template.append('end case;')
                        break
832
833
                else:
                    # Input is not managed in the state aggregation
834
835
836
                    if input_def:
                        # check if it is managed one level above
                        execute_transition(state)
837
                    taste_template.append('null;')
Maxime Perrotin's avatar
Maxime Perrotin committed
838
839
            else:
                execute_transition(state)
840

Maxime Perrotin's avatar
Maxime Perrotin committed
841
        if not instance:
Maxime Perrotin's avatar
Maxime Perrotin committed
842
843
            for each_state in reduced_statelist:
                case_state(each_state)
Maxime Perrotin's avatar
Maxime Perrotin committed
844
            taste_template.append('when others =>')
845
            taste_template.append('Execute_Transition (CS_Only);')
Maxime Perrotin's avatar
Maxime Perrotin committed
846
847
            taste_template.append('end case;')
        else:
Maxime Perrotin's avatar
Maxime Perrotin committed
848
            inst_call = f"{process_name}_Instance.{signame}"
Maxime Perrotin's avatar
Maxime Perrotin committed
849
            if 'type' in signal:
Maxime Perrotin's avatar
Maxime Perrotin committed
850
851
                inst_call += f" ({param_name})"
            taste_template.append(f"{inst_call};")
852

Maxime Perrotin's avatar
Maxime Perrotin committed
853
        taste_template.append(f'end {signame};')
Maxime Perrotin's avatar
Maxime Perrotin committed
854
855
        taste_template.append('\n')

856
857
858
859
860
861
862
863
    #  add call to startup function for instances
    if instance:
        taste_template.extend(['procedure Startup is',
                               'begin',
                               f'{process_name}_Instance.Startup;',
                               'end Startup;',
                               ''])

Maxime Perrotin's avatar
Maxime Perrotin committed
864
865
866
    # for the .ads file, generate the declaration of the required interfaces
    # output signals are the asynchronous RI - only one parameter
    for signal in process.output_signals:
867
868
        sig = signal['name']
        param_name = signal.get('param_name') or f'{sig}_param'
Maxime Perrotin's avatar
Maxime Perrotin committed
869
        # Add (optional) RI parameter
870
871
872
        # Paramless TMs: when targetting simulation, the name of the TM is
        # passed as single parameter. This allows the simualor to handle them
        # dynamically, with a single callback function for all TMs
Maxime Perrotin's avatar
Maxime Perrotin committed
873
        param_spec = '' if not simu else " (TM : chars_ptr)"
Maxime Perrotin's avatar
Maxime Perrotin committed
874
        if 'type' in signal:
Maxime Perrotin's avatar
Maxime Perrotin committed
875
            typename = type_name(signal['type'])
876
            param_spec = f' ({param_name} : in out {typename}{"; Size : Integer" if SHARED_LIB else ""})'
877
878
879
        if not generic:
            ads_template.append(u'--  {}equired interface "{}"'
                                .format("Paramless r" if not 'type' in signal
880
                                    else "R", sig))
881
882
        if simu:
            # When generating a shared library, we need a callback mechanism
883
            code = [f'type {sig}_T is access procedure{param_spec};',
Maxime Perrotin's avatar
Maxime Perrotin committed
884
                    f'pragma Convention (Convention => C, Entity => {sig}_T);',
885
886
887
888
                    f'RI{SEPARATOR}{sig} : {sig}_T;',
                    f'procedure Register_{sig} (Callback : {sig}_T);',
                    f'pragma Export(C, Register_{sig}, "register_{sig}");']
            ads_template.extend(code)
889
890

            # Generate code for the mini-cv template
891
892
            params = [(param_name,
                       type_name(signal['type'], use_prefix=False),
893
                      'IN')] if 'type' in signal else []
894
895
896
897
898
899
900
901
902

            minicv.append(aadl_template(sig, params, 'PI'))

            code = [f'procedure Register_{sig} (Callback : {sig}_T) is',
                     'begin',
                    f'RI{SEPARATOR}{sig} := Callback;',
                    f'end Register_{sig};',
                    '']
            taste_template.extend(code)
903
        elif not generic:
904
905
            ads_template.append(f'procedure RI{SEPARATOR}{sig}{param_spec} '
                    f'renames {process_name}_RI.{sig};')
Maxime Perrotin's avatar
Maxime Perrotin committed
906
907
            ri_stub_ads.append(f'procedure {sig}{param_spec};')
            ri_stub_adb.append(f'procedure {sig}{param_spec} is null;')
908
909
910
            #  TASTE generates the pragma import in <function>_ri.ads
            #  therefore do not generate it in the .ads
            # ads_template.append(f'pragma Import (C, RI{SEPARATOR}{sig}, "{process_name.lower()}_RI_{sig}");')
Maxime Perrotin's avatar
Maxime Perrotin committed
911
912

    # for the .ads file, generate the declaration of the external procedures
913
    for proc in (proc for proc in process.procedures if proc.external):
914
915
        sig = proc.inputString
        ri_header = f'procedure RI{SEPARATOR}{sig}'
Maxime Perrotin's avatar
Maxime Perrotin committed
916
        params = []
917
        params_spec = ""
918
919
        if simu:
            # For simulators: add the TM name as first parameter
920
            params.append("TM : chars_ptr")
Maxime Perrotin's avatar
Maxime Perrotin committed
921
        for param in proc.fpar:
Maxime Perrotin's avatar
Maxime Perrotin committed
922
            typename = type_name(param['type'])
923
            name     = param['name']
924
925
926
927
            if param['direction'] == 'in':
                direct = 'in out'
            else:
                direct = 'out'
928
929
930
            shared=f"; {name}_Size : Integer" if SHARED_LIB else ""

            params.append(f'{name} : {direct} {typename}{shared}')
Maxime Perrotin's avatar
Maxime Perrotin committed
931
        if params:
932
            params_spec = " ({})".format("; ".join(params))
933
            ri_header += params_spec
934
        ads_template.append(f'--  Sync required interface "{sig}"')
935
936
        if simu:
            # As for async TM, generate a callback mechanism
Maxime Perrotin's avatar
Maxime Perrotin committed
937
            code = [f"type {sig}_T is access procedure{params_spec};",
938
939
940
941
942
943
944
945
946
947
948
949
950
                    f'pragma Convention(Convention => C, Entity => {sig}_T);',
                    f'RI{SEPARATOR}{sig} : {sig}_T;',
                    f'procedure Register_{sig}(Callback: {sig}_T);',
                    f'pragma Export(C, Register_{sig}, "register_{sig}");']

            ads_template.extend(code)

            code = [f'procedure Register_{sig} (Callback : {sig}_T) is',
                     'begin',
                    f'RI{SEPARATOR}{sig} := Callback;',
                    f'end Register_{sig};',
                     '']
            taste_template.extend(code)
951

952
        elif not generic:
953
            ads_template.append(f'{ri_header} renames {process_name}_RI.{sig};')
Maxime Perrotin's avatar
Maxime Perrotin committed
954
955
            ri_stub_ads.append(f'procedure {sig}{params_spec};')
            ri_stub_adb.append(f'procedure {sig}{params_spec} is null;')
Maxime Perrotin's avatar
Maxime Perrotin committed
956
957
958

    # for the .ads file, generate the declaration of timers set/reset functions
    for timer in process.timers:
959
        if stop_condition:
Maxime Perrotin's avatar
Maxime Perrotin committed
960
961
962
            # don't generte timer code for stop conditions
            break
        ads_template.append(f'--  Timer {timer} SET and RESET functions')
963
964
965
        if simu:
            # Declare callback registration for the SET and RESET functions
            ads_template.append(u'type SET_{}_T is access procedure'
966
                                 '(name: chars_ptr; duration: Asn1Int);'
967
                                .format(timer))
Maxime Perrotin's avatar
Maxime Perrotin committed
968
969
            ads_template.append(u'type RESET_{}_T is access procedure'
                                '(name: chars_ptr);'.format(timer))
970
            for each in ('', 'RE'):
Maxime Perrotin's avatar
Maxime Perrotin committed
971
                ads_template.append(u'pragma Convention (Convention => C,'
972
                                    u' Entity => {re}SET_{t}_T);'
973
                                    .format(re=each, t=timer))
974
                ads_template.append(u'{re}SET_{t} : {re}SET_{t}_T;'
975
                                    .format(re=each, t=timer))
976
977
                ads_template.append(u'procedure Register_{re}SET_{t}'
                                    u'(Callback: {re}SET_{t}_T);'
978
                                    .format(re=each, t=timer))
979
980
                ads_template.append(u'pragma Export(C, Register_{re}SET_{t},'
                                    u' "register_{re}SET_{t}");'
981
982
983
                                    .format(re=each, t=timer))
            # Code for the SET/RESET timer callback registration
            for each in ('', 'RE'):
984
985
                taste_template.append(u'procedure Register_{re}SET_{t}'
                                      u'(Callback:{re}SET_{t}_T) is'
986
                                      .format(re=each, t=timer))
987
988
                taste_template.append(u'begin')
                taste_template.append(u'{re}SET_{t} := Callback;'
989
                                      .format(re=each, t=timer))
990
                taste_template.append(u'end Register_{re}SET_{t};'
991
992
993
                                      .format(re=each, t=timer))
                taste_template.append('')

994
        elif not generic:
995
            procname = process_name.lower()
996
            ads_template.append(
997
998
               f'procedure SET_{timer} (Val : in out asn1SccT_UInt32) '
               f'renames {process_name}_RI.Set_{timer};')
Maxime Perrotin's avatar
Maxime Perrotin committed
999
1000
            ri_stub_ads.append(f'procedure SET_{timer} (Val : in out asn1SccT_UInt32);')
            ri_stub_adb.append(f'procedure SET_{timer} (Val : in out asn1SccT_UInt32) is null;')
For faster browsing, not all history is shown. View entire blame