AdaGenerator.py 142 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 207 208
    # taste-properties module-specific flag for the Ada backend:
    # import the state data from an external module
    import_context = kwargs["ppty_check"] if "ppty_check" in kwargs else ""

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:. 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 441 442 443
    # Write the ASN.1 file (not in case of Stop Condition)
    if not import_context:
        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 448 449 450
    if not import_context:
        # 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 476 477
    if import_context:
        #  code of stop conditions must use the same type as the main process
        context_decl.append(
478
                f'{LPREFIX} : {ASN1SCC}{import_context}_Context '
479
                f'renames {import_context}.{import_context}_ctxt;')
Maxime Perrotin's avatar
Maxime Perrotin committed
480
    if simu and not import_context:
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 517
        # Add the declaration of the Execute_Transition  procedure
        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 537 538 539 540 541 542
        Init_Done = f'{LPREFIX}.Init_Done := True;'
#       if not simu:
#           start_transition = ['begin']
#           if process.transitions:
#               start_transition.append('Execute_Transition (0);')
#           start_transition.append(Init_Done)
#       else:
        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;']
543

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

554
    taste_template = [f'''\
Maxime Perrotin's avatar
Maxime Perrotin committed
555
-- This file was generated automatically by OpenGEODE: DO NOT MODIFY IT !
Maxime Perrotin's avatar
Maxime Perrotin committed
556 557 558 559

with System.IO;
use System.IO;

560
with Ada.Unchecked_Conversion;
561
with Ada.Numerics.Generic_Elementary_Functions;
562

563
package body {process_name} is'''
564
    if not instance else u"package body {} is".format(process_name)]
Maxime Perrotin's avatar
Maxime Perrotin committed
565

566
    generic_spec, instance_decl = "", ""
567 568 569 570 571
    if generic:
        generic_spec = u"generic\n"
        ri_list = external_ri_list(process)
        if ri_list:
            generic_spec += u"    with " + u";\n    with ".join(ri_list) + ';'
572 573 574
    if instance:
        instance_decl = u"with {};".format(process.instance_of_name)

575 576 577
    # print process.fpar
    # FPAR could be set for Context Parameters. They are available here

Maxime Perrotin's avatar
Maxime Perrotin committed
578
    # Generate the source file (.ads) header
579 580 581 582 583

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

584
    imp_datamodel = (f"with {process_name}_Datamodel; "
585
                     f"use {process_name}_Datamodel;") \
586 587
                             if not import_context and not instance else (
                                     f"with {import_context}_Datamodel; "
Maxime Perrotin's avatar
Maxime Perrotin committed
588 589
                                     f"use {import_context}_Datamodel;"
                                     if import_context else "")
590

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

593 594 595 596 597 598 599 600 601 602 603
    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;'])

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

607 608 609 610 611 612 613 614 615
with Interfaces,
     Interfaces.C.Strings,
     Ada.Characters.Handling;

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

{asn1_modules}
616
{imp_datamodel}
617
{imp_str}
618
{imp_ri}
619
{instance_decl}
620
{rand}
Maxime Perrotin's avatar
Maxime Perrotin committed
621
{generic_spec}'''.strip() + f'''
622
package {process_name} with Elaborate_Body is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
623

Maxime Perrotin's avatar
Maxime Perrotin committed
624
    ri_stub_ads = [f'''\
Maxime Perrotin's avatar
Maxime Perrotin committed
625 626
--  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
627 628 629
--  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
630 631 632 633

{asn1_modules}

package {process_name}_RI is''']
Maxime Perrotin's avatar
Maxime Perrotin committed
634 635 636 637
    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
638

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

Maxime Perrotin's avatar
Maxime Perrotin committed
652
    if simu and not import_context:   # import_context = stop condition
653 654
        ads_template.append('--  API for simulation via DLL')
        dll_api.append('-- API to remotely change internal data')
655

656
        # Save/restore state allow one step undo, as needed for model checking
657 658 659 660
        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)
661 662 663 664 665 666 667 668 669 670 671
        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;",
             ""])
672

673
        # Declare procedure Startup in .ads
674
        ads_template.append(f'procedure Startup with Export, Convention => C, Link_Name => "{process_name}_startup";')
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 723 724 725
        if import_context:
            # 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 856 857 858
        taste_template.append('\n')

    # 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:
859 860
        sig = signal['name']
        param_name = signal.get('param_name') or f'{sig}_param'
Maxime Perrotin's avatar
Maxime Perrotin committed
861
        # Add (optional) RI parameter
862 863 864
        # 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
865
        param_spec = '' if not simu else " (TM : chars_ptr)"
Maxime Perrotin's avatar
Maxime Perrotin committed
866
        if 'type' in signal:
Maxime Perrotin's avatar
Maxime Perrotin committed
867
            typename = type_name(signal['type'])
868
            param_spec = f' ({param_name} : in out {typename}{"; Size : Integer" if SHARED_LIB else ""})'
869 870 871
        if not generic:
            ads_template.append(u'--  {}equired interface "{}"'
                                .format("Paramless r" if not 'type' in signal
872
                                    else "R", sig))
873 874
        if simu:
            # When generating a shared library, we need a callback mechanism
875
            code = [f'type {sig}_T is access procedure{param_spec};',
Maxime Perrotin's avatar
Maxime Perrotin committed
876
                    f'pragma Convention (Convention => C, Entity => {sig}_T);',
877 878 879 880
                    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)
881 882

            # Generate code for the mini-cv template
883 884
            params = [(param_name,
                       type_name(signal['type'], use_prefix=False),
885
                      'IN')] if 'type' in signal else []
886 887 888 889 890 891 892 893 894

            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)
895
        elif not generic:
896 897
            ads_template.append(f'procedure RI{SEPARATOR}{sig}{param_spec} '
                    f'renames {process_name}_RI.{sig};')
Maxime Perrotin's avatar
Maxime Perrotin committed
898 899
            ri_stub_ads.append(f'procedure {sig}{param_spec};')
            ri_stub_adb.append(f'procedure {sig}{param_spec} is null;')
900 901 902
            #  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
903 904

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

            params.append(f'{name} : {direct} {typename}{shared}')
Maxime Perrotin's avatar
Maxime Perrotin committed
923
        if params:
924
            params_spec = " ({})".format("; ".join(params))
925
            ri_header += params_spec
926
        ads_template.append(f'--  Sync required interface "{sig}"')
927 928
        if simu:
            # As for async TM, generate a callback mechanism
Maxime Perrotin's avatar
Maxime Perrotin committed
929
            code = [f"type {sig}_T is access procedure{params_spec};",
930 931 932 933 934 935 936 937 938 939 940 941 942
                    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}{