Exemplo n.º 1
0
def _type2arg(typeObj, pointer=False):
    if (isinstance(typeObj, autosar.datatype.IntegerDataType)
            or isinstance(typeObj, autosar.datatype.BooleanDataType)):
        return C.variable('data', typeObj.name, pointer=pointer)
    else:
        pointer = True
        return C.variable('data', typeObj.name, pointer=pointer)
Exemplo n.º 2
0
 def __init__(self, event):      
    self.body = C.block(innerIndent = innerIndentDefault)
    self.calls = {}
    self.typename = 'Rte_ModeType_'+event.mode
    self.proto = C.function('Rte_SetMode_'+event.mode, 'void', args = [C.variable('newMode', self.typename)])
    self.static_var = C.variable('m_'+event.mode, self.typename, static=True)
    self._init_body(event)
Exemplo n.º 3
0
 def _generate_com_access(self):
     if self.com_config is not None:
         for element_name in self.partition.data_elements:
             if element_name in self.com_config.send:
                 data_element = self.partition.data_elements[element_name][
                     'element']
                 isPointer = True if data_element.dataType.isComplexType else False
                 self.com_access['send'][element_name] = C.function(
                     "%s_Send_%s" % (self.com_config.prefix, element_name),
                     'Std_ReturnType',
                     args=[
                         C.variable('value',
                                    data_element.dataType.name,
                                    pointer=isPointer)
                     ])
             elif element_name in self.com_config.receive:
                 data_element = self.partition.data_elements[element_name][
                     'element']
                 isPointer = True if data_element.dataType.isComplexType else False
                 self.com_access['receive'][element_name] = C.function(
                     "%s_Receive_%s" %
                     (self.com_config.prefix, element_name),
                     'Std_ReturnType',
                     args=[
                         C.variable('value',
                                    data_element.dataType.name,
                                    pointer=isPointer)
                     ])
             else:
                 self.local_elements.push(element_name)
Exemplo n.º 4
0
    def _create_operation_setter(self, component, port, operation,
                                 port_access):
        func_name = '%s_SetCallHandler_%s_%s_%s' % (
            self.prefix, component.name, port.name, operation.name)
        short_name = '%s_SetCallHandler_%s_%s' % (self.prefix, port.name,
                                                  operation.name)

        type_name = '%s_%s_ServerCallHandler_t' % (port.name, operation.name)
        var_name = 'm_ServerCallHandler_%s_%s_%s' % (component.name, port.name,
                                                     operation.name)
        port_func = port.portAPI['Rte_Call_%s_%s' %
                                 (port.name, operation.name)]
        tmp_proto = C.fptr.from_func(port_func.proto, type_name)

        self.typedefs[type_name] = 'typedef %s' % str(tmp_proto)
        proto = C.function(
            func_name,
            'void',
            args=[C.variable('handler_func', type_name, pointer=True)])
        func = autosar.rte.base.SetCallHandlerFunction(short_name, proto,
                                                       operation, var_name)
        self.extra_public_functions[short_name] = func
        static_var = C.variable(var_name, type_name, static=True, pointer=True)
        self.extra_static_vars[var_name] = static_var
        self.extra_rte_start.append(
            C.statement('%s = (%s*) 0' % (var_name, type_name)))
        body = self._createMockServerCallFunction(port_func.proto, var_name)
        self.extra_public_functions[
            port_func.proto.name] = autosar.rte.base.ServerCallFunction(
                port_func.proto, body)
Exemplo n.º 5
0
 def __init__(self, prefix, component, port, data_element):
    func_name='%s_SetReadResult_%s_%s_%s'%(prefix, component.name, port.name, data_element.name)
    shortname='%s_SetReadResult_%s_%s'%(prefix, port.name, data_element.name)
    proto=C.function(func_name, 'void')
    
    proto.add_arg(C.variable('value', 'Std_ReturnType'))
    self.shortname = shortname
    self.proto=proto
    self.data_element = data_element
    data_element.result_var = C.variable('m_ReadResult_%s_%s_%s'%(component.name, port.name, data_element.name), 'Std_ReturnType', static=True)
    self.static_var = data_element.result_var
    body = C.block(innerIndent=innerIndentDefault)
    body.append(C.statement('%s = %s'%(self.static_var.name, proto.args[0].name)))
    self.body=body
Exemplo n.º 6
0
Arquivo: base.py Projeto: ncs1/as
 def __init__(self, prefix, component, port, data_element, var_name):
     data_type = data_element.dataType
     func_name = '%s_SetReadData_%s_%s_%s' % (prefix, component.name,
                                              port.name, data_element.name)
     shortname = '%s_SetReadData_%s_%s' % (prefix, port.name,
                                           data_element.name)
     proto = C.function(func_name, 'void')
     proto.add_arg(
         C.variable('data', data_type.name,
                    pointer=data_type.isComplexType))
     self.shortname = shortname
     self.data_element = data_element
     self.proto = proto
     body = C.block(innerIndent=innerIndentDefault)
     if isinstance(data_type, autosar.datatype.ArrayDataType):
         body.append(
             C.statement('memcpy(&%s[0], %s, sizeof(%s)' %
                         (var_name, proto.args[0].name, var_name)))
     elif isinstance(data_type, autosar.datatype.RecordDataType):
         body.append(
             C.statement('memcpy(&%s, %s, sizeof(%s)' %
                         (var_name, proto.args[0].name, var_name)))
     else:
         body.append(C.statement('%s = %s' %
                                 (var_name, proto.args[0].name)))
     self.body = body
Exemplo n.º 7
0
 def _createDefaultFunction(self, component, port, operation):
     ws = component.swc.rootWS()
     assert (ws is not None)
     func_name = '_'.join([
         self.prefix, 'Call', component.swc.name, port.name, operation.name
     ])
     func = C.function(func_name, 'Std_ReturnType')
     portInterface = ws.find(port.portInterfaceRef)
     if portInterface is None:
         raise ValueError("Error: invalid port interface reference: " +
                          port.portInterfaceRef)
     for argument in operation.arguments:
         dataType = ws.find(argument.typeRef)
         if dataType is None:
             raise ValueError('Error: Invalid type reference: ' +
                              argument.typeRef)
         self.types.processType(ws, dataType)
         isPointer = False
         if dataType.isComplexType or (argument.direction
                                       == 'OUT') or (argument.direction
                                                     == 'INOUT'):
             isPointer = True
         func.add_arg(
             C.variable(argument.name, dataType.name, pointer=isPointer))
     return func
Exemplo n.º 8
0
 def OperationInvokedRunnable(cls, name, symbol, ws, port, operation):
     assert (ws is not None)
     returnType = 'void'
     if len(operation.errorRefs) > 0:
         returnType = 'Std_ReturnType'
     prototype = C.function(symbol, returnType)
     for argument in operation.arguments:
         dataType = ws.find(argument.typeRef)
         if dataType is None:
             raise ValueError('invalid type reference: ' + argument.typeRef)
         isPointer = False
         if isinstance(dataType,
                       autosar.datatype.RecordDataType) or isinstance(
                           dataType,
                           autosar.datatype.ArrayDataType) or isinstance(
                               dataType, autosar.datatype.ArrayDataType):
             isPointer = True
         if (isPointer == False) and (argument.direction == 'OUT') or (
                 argument.direction == 'INOUT'):
             isPointer = True
         prototype.add_arg(
             C.variable(argument.name, dataType.name, pointer=isPointer))
     self = cls(name, symbol, prototype)
     self.isServerRunnable = True
     self.serverPortInterface = ws.find(port.portInterfaceRef)
     self.serverOperation = operation
     return self
Exemplo n.º 9
0
 def __init__(self, task):
    init_delay=0 #FIXME: allow users to select this at a later time
    self.decl = C.variable('os_alarm_cfg_%s'%task.name, 'os_alarm_cfg_t', static=True, const=True, array='OS_NUM_ALARMS_%s'%task.name)
    self.body = C.block(innerIndent=innerIndentDefault)
    self.body.append(C.linecomment('OS Task,       Event ID,                     Init Delay (ms),  Period (ms)'))
    for event in task.timer_events:
       self.body.append(C.line('{'+'{0: >10},{1: >50},{2: >5},{3: >5}'.format(
          '&m_os_task_'+task.name, 'EVENT_MASK_%s_%s'%(task.name,event.name), init_delay, event.inner.period)+'},'))
Exemplo n.º 10
0
Arquivo: generator.py Projeto: ncs1/as
 def _create_static_vars(self):
     for os_task in self.cfg.tasks:
         static_var = C.variable('m_os_task_' + os_task.name,
                                 'os_task_t',
                                 static=True)
         self.static_vars[static_var.name] = static_var
         if len(os_task.timer_events) > 0:
             self.alarm_vars.append(AlarmVariable(os_task))
Exemplo n.º 11
0
 def _write_local_vars(self, fp):
     fp.write('\n'.join(_genCommentHeader('Local Variables')) + '\n')
     code = C.sequence()
     for data_element in sorted(self.partition.data_element_map.values(),
                                key=lambda x: x.symbol):
         var = C.variable(data_element.symbol, data_element.dataType.name,
                          True)
         code.append(C.statement(var))
     for key in sorted(self.extra_static_vars.keys()):
         code.append(C.statement(self.extra_static_vars[key]))
     fp.write('\n'.join(code.lines()) + '\n\n')
Exemplo n.º 12
0
 def __init__(self, tasks):
    self.decl = C.variable('os_task_cfg', 'os_task_elem_t', static=True, const=True, array='OS_NUM_TASKS')
    self.body = C.block(innerIndent=innerIndentDefault)
    for task in tasks:
       fmt='{0: >25},{1: >15},{2: >30},{3: >30}'
       if len(task.timer_events)>0:
          self.body.append(C.line('{'+fmt.format(
             '&m_os_task_'+task.name, task.name, '&os_alarm_cfg_%s[0]'%task.name, 'OS_NUM_ALARMS_%s'%task.name)+'},'))
       else:
          self.body.append(C.line('{'+fmt.format(
             '&m_os_task_'+task.name, task.name, '(os_alarm_cfg_t*) 0', '0')+'},'))
Exemplo n.º 13
0
Arquivo: partition.py Projeto: ncs1/as
 def _generate_com_access(self):
     for component in self.components:
         if isinstance(component.inner, autosar.bsw.com.ComComponent):
             for port in component.requirePorts:
                 for remote_port in port.connectors:
                     for data_element in remote_port.data_elements:
                         isPointer = True if data_element.dataType.isComplexType else False
                         proto = C.function(
                             "%s_Send_%s_%s" %
                             (component.inner.name, remote_port.name,
                              data_element.name),
                             'Std_ReturnType',
                             args=[
                                 C.variable('value',
                                            data_element.dataType.name,
                                            pointer=isPointer)
                             ])
                         data_element.com_access['Send'] = proto
                         component.inner.addSendInterface(
                             proto, port, data_element)
             for port in component.providePorts:
                 for data_element in port.data_elements:
                     isPointer = True
                     proto = C.function(
                         "%s_Receive_%s_%s" %
                         (component.inner.name, remote_port.name,
                          data_element.name),
                         'Std_ReturnType',
                         args=[
                             C.variable('value',
                                        data_element.dataType.name,
                                        pointer=isPointer)
                         ])
                     data_element.com_access['Receive'] = proto
                     component.inner.addReceiveInterface(
                         proto, port, data_element)
                     #remove from internal RTE variables
                     symbol = data_element.symbol
                     data_element.symbol = None
                     if symbol in self.data_element_map:
                         del self.data_element_map[symbol]
Exemplo n.º 14
0
def _printf():
    print("Generate printf function...")
    body = C.block(innerIndent=3)
    body.append(C.statement(C.fcall('printf').add_arg('\"%d\"').add_arg('p0')))
    head = C.function(
        'f_printf',
        'void',
    ).add_param(C.variable('p0', 'int'))
    func = C.sequence()
    func.append(head)
    func.append(body)
    print(str(func))
    return func
Exemplo n.º 15
0
def _scanf_no_pointer():
    print("Generate scanf function...")
    body = C.block(innerIndent=3)
    body.append(C.statement(C.variable('var0', 'int')))
    body.append(
        C.statement(C.fcall('scanf').add_arg('\"%d\"').add_arg('&var0')))
    body.append(C.statement("return var0"))
    head = C.function(
        'f_scanf_nop',
        'int',
    )
    func = C.sequence()
    func.append(head)
    func.append(body)
    print(str(func))
    return func
Exemplo n.º 16
0
Arquivo: base.py Projeto: cogu/autosar
 def __init__(self, prefix, component, port, data_element, var_name):
    data_type = data_element.dataType
    func_name='%s_SetReadData_%s_%s_%s'%(prefix, component.name, port.name, data_element.name)
    shortname='%s_SetReadData_%s_%s'%(prefix, port.name, data_element.name)
    proto=C.function(func_name, 'void')
    proto.add_arg(C.variable('data', data_type.name, pointer=data_type.isComplexType))
    self.shortname = shortname
    self.data_element = data_element
    self.proto=proto
    body = C.block(innerIndent=innerIndentDefault)
    if isinstance(data_type, autosar.datatype.ArrayDataType):               
       body.append(C.statement('memcpy(&%s[0], %s, sizeof(%s)'%(var_name, proto.args[0].name, var_name)))
    elif isinstance(data_type, autosar.datatype.RecordDataType):               
       body.append(C.statement('memcpy(&%s, %s, sizeof(%s)'%(var_name, proto.args[0].name, var_name)))
    else:
       body.append(C.statement('%s = %s'%(var_name, proto.args[0].name)))
    self.body=body
Exemplo n.º 17
0
   def __init__(self, ws, ar_port, parent):
      self.ws = ws
      self.name = ar_port.name
      self.ar_port = ar_port
      self.parent = parent
      self.connectors=[] #list of connected ports
      self.portAPI={}
      self.data_elements = []
      self.operations = []
      self.mode_groups = []

      port_interface = ws.find(ar_port.portInterfaceRef)
      if port_interface is None:
         raise ValueError("Error: invalid port interface reference: "+ar_port.portInterfaceRef)
      if isinstance(port_interface, autosar.portinterface.SenderReceiverInterface):
         for data_element in port_interface.dataElements:
            data_type=ws.find(data_element.typeRef)
            if data_type is None:
               raise ValueError('Error: Invalid data type reference: %s'%data_element.typeRef)
            initValue = None
            queueLength = None
            if len(ar_port.comspec)>0:
               for comspec in ar_port.comspec:
                  if (comspec.name == data_element.name) and (comspec.initValueRef is not None):
                     initValue = ws.find(comspec.initValueRef)
            self.data_elements.append(DataElement(data_element.name, self, data_type, initValue, data_element.isQueued))
         if port_interface.modeGroups is not None:
            for group in port_interface.modeGroups:
               data_type=ws.find(group.typeRef)
               if data_type is None:
                  raise ValueError('Error: Invalid data type reference: %s'%group.typeRef)
               self.mode_groups.append(ModeGroup(group.name, self, data_type))
               
      elif isinstance(port_interface, autosar.portinterface.ClientServerInterface):
         for operation in port_interface.operations:
            arguments = []
            for argument in operation.arguments:
               dataType = ws.find(argument.typeRef)
               if dataType is None:
                  raise ValueError('Error: Invalid type reference: '+argument.typeRef)
               isPointer = False
               if dataType.isComplexType or (argument.direction == 'OUT') or (argument.direction == 'INOUT'):
                  isPointer = True
               arguments.append(C.variable(argument.name, dataType.name, pointer=isPointer))
            self.operations.append(Operation(operation.name, self, arguments, operation))
Exemplo n.º 18
0
Arquivo: generator.py Projeto: ncs1/as
 def __init__(self, task):
     init_delay = 0  #FIXME: allow users to select this at a later time
     self.decl = C.variable('os_alarm_cfg_%s' % task.name,
                            'os_alarm_cfg_t',
                            static=True,
                            const=True,
                            array='OS_NUM_ALARMS_%s' % task.name)
     self.body = C.block(innerIndent=innerIndentDefault)
     self.body.append(
         C.linecomment(
             'OS Task,       Event ID,                     Init Delay (ms),  Period (ms)'
         ))
     for event in task.timer_events:
         self.body.append(
             C.line('{' + '{0: >10},{1: >50},{2: >5},{3: >5}'.format(
                 '&m_os_task_' + task.name, 'EVENT_MASK_%s_%s' %
                 (task.name, event.name), init_delay, event.inner.period) +
                    '},'))
Exemplo n.º 19
0
Arquivo: generator.py Projeto: ncs1/as
 def __init__(self, tasks):
     self.decl = C.variable('os_task_cfg',
                            'os_task_elem_t',
                            static=True,
                            const=True,
                            array='OS_NUM_TASKS')
     self.body = C.block(innerIndent=innerIndentDefault)
     for task in tasks:
         fmt = '{0: >25},{1: >15},{2: >30},{3: >30}'
         if len(task.timer_events) > 0:
             self.body.append(
                 C.line('{' + fmt.format('&m_os_task_' + task.name,
                                         task.name, '&os_alarm_cfg_%s[0]' %
                                         task.name, 'OS_NUM_ALARMS_%s' %
                                         task.name) + '},'))
         else:
             self.body.append(
                 C.line('{' +
                        fmt.format('&m_os_task_' + task.name, task.name,
                                   '(os_alarm_cfg_t*) 0', '0') + '},'))
Exemplo n.º 20
0
def _func(funcname):
    print(f"Generate {funcname}...")
    para_count = random.randint(0, 3)
    local_count = 3
    local_const = 2
    body = C.block(innerIndent=3)
    for i in range(local_count):
        body.append(
            C.statement(
                f"{C.variable(f'var{i}', 'int')} = {C.fcall(random.choice(['f_rand', 'f_scanf_nop']))}"
            ))
    for i in range(local_const):
        body.append(
            C.statement(
                f"{C.variable(f'var{i+local_count}', 'int')} = {random.randint(-1000, 1000)}"
            ))

    all_vars = [f'var{i}' for i in range(local_const + local_count)
                ] + [f'p{i}' for i in range(para_count)]
    op_seq = ['+', '-', '*', '/', '<<', '>>']
    # print(all_vars)
    max_iter = 5
    targets = []
    for i in range(4):
        trg = random.choice(all_vars)
        expr = _expression(all_vars, op_seq, trg)
        body.append(C.statement(f"{trg} = {expr}"))
        targets.append(trg)
    ret_var = random.choice(all_vars)
    ret_expr = _expression(targets, op_seq, ret_var)
    body.append(C.statement(f"{ret_var} = {ret_expr}"))
    body.append(C.statement(f'return {ret_var}'))
    head = C.function(funcname, 'int')
    for i in range(para_count):
        head.add_param(C.variable(f'p{i}', 'int'))
    func = C.sequence()
    func.append(head)
    func.append(body)
    print(str(func))
    return func
Exemplo n.º 21
0
    def _generate_task_body(self, task):
        code = C.block(innerIndent=innerIndentDefault)
        isRunning = C.variable('isRunning', 'boolean')
        code.append(C.statement('{0} = TRUE'.format(str(isRunning))))
        code.append(C.statement('os_task_t *self = (os_task_t*)arg'))
        code.append('')
        code.append(C.line('if (self == 0)'))
        body = C.block(innerIndent=innerIndentDefault)
        body.append(C.statement('THREAD_RETURN(1)'))
        code.append(body)
        code.append('')
        code.append(C.line('while (isRunning == TRUE)'))

        while_block = C.block(innerIndent=innerIndentDefault)

        while_block.append(C.statement('uint32 eventMask'))
        while_block.append(
            C.statement('int8_t result = os_task_waitEvent(self, &eventMask)'))
        while_block.append(C.line('if (result == 0)'))
        if_block = C.block(innerIndent=innerIndentDefault)
        if_block.extend(self._generate_event_mask_triggers(task))
        while_block.append(if_block)
        while_block.append(C.line('else if(result > 0)'))
        if_block = C.block(innerIndent=innerIndentDefault)
        if_block.append(C.statement('printf("%s_QuitEvent\\n")' % task.name))
        if_block.append(C.statement('isRunning = false'))
        while_block.append(if_block)
        while_block.append(C.line('else'))
        if_block = C.block(innerIndent=innerIndentDefault)
        if_block.append(
            C.statement(r'fprintf(stderr, "os_task_waitEvent failed\n")'))
        while_block.append(if_block)

        code.append(while_block)
        code.append('')
        code.append(C.statement('THREAD_RETURN(0)'))
        return code
Exemplo n.º 22
0
    def create_server_call_point(self, ws, port, operation):
        shortname = '_'.join(
            [self.rte_prefix, 'Call', port.name, operation.name])
        func = C.function(shortname, 'Std_ReturnType')
        portInterface = ws.find(port.portInterfaceRef)
        if portInterface is None:
            raise ValueError("Error: invalid port interface reference: " +
                             port.portInterfaceRef)
        for argument in operation.arguments:
            dataType = ws.find(argument.typeRef)
            if dataType is None:
                raise ValueError('Error: Invalid type reference: ' +
                                 argument.typeRef)
            isPointer = False
            if dataType.isComplexType or (argument.direction
                                          == 'OUT') or (argument.direction
                                                        == 'INOUT'):
                isPointer = True
            func.add_arg(
                C.variable(argument.name, dataType.name, pointer=isPointer))

            rte_port_func = CallPortFunction(shortname, func, portInterface,
                                             operation)
            self.clientAPI.call[shortname] = rte_port_func
Exemplo n.º 23
0
import cfile as C
hello = C.cfile('hello.c')
hello.code.append(C.sysinclude('stdio.h'))
hello.code.append(C.blank())
hello.code.append(
    C.function(
        'main',
        'int',
    ).add_param(C.variable('argc', 'int')).add_param(
        C.variable('argv', 'char', pointer=2)))
body = C.block(innerIndent=3)
body.append(C.statement(C.fcall('printf').add_arg(r'"Hello World!\n"')))
body.append(C.statement('return 0'))
hello.code.append(body)
print(str(hello))
Exemplo n.º 24
0
 def _create_static_vars(self):
    for os_task in self.cfg.tasks:
       static_var = C.variable('m_os_task_'+os_task.name, 'os_task_t', static=True)
       self.static_vars[static_var.name]=static_var
       if len(os_task.timer_events)>0:
          self.alarm_vars.append(AlarmVariable(os_task))
Exemplo n.º 25
0
Arquivo: base.py Projeto: cogu/autosar
def type2arg(typeObj, pointer=False, name='data'):
   return C.variable(name,typeObj.name,pointer=pointer)
Exemplo n.º 26
0
    def generate(self, dest_dir='.', file_name='Rte_Type.h'):
        """
      Generates Rte_Type.h
      Note: The last argument has been deprecated and is no longer in use
      """
        if self.partition.isFinalized == False:
            self.partition.finalize()
        file_path = os.path.join(dest_dir, file_name)
        with io.open(file_path, 'w', newline='\n') as fp:
            hfile = C.hfile(file_name)
            hfile.code.extend(
                [C.line(x) for x in _genCommentHeader('Includes')])
            hfile.code.append(C.include("Std_Types.h"))
            hfile.code.append(C.blank())
            (basicTypes, complexTypes,
             modeTypes) = self.partition.types.getTypes()
            hfile.code.extend([
                C.line(x) for x in _genCommentHeader('Data Type Definitions')
            ])
            hfile.code.append(C.blank())
            ws = self.partition.ws
            unusedDefaultTypes = self._findUnusedDefaultTypes(ws, basicTypes)

            first = True
            for ref in sorted(basicTypes) + sorted(complexTypes):
                dataType = ws.find(ref)
                if dataType is not None:
                    typedef = None
                    if first:
                        first = False
                    else:
                        hfile.code.append(C.blank())
                    hfile.code.append('#define Rte_TypeDef_%s' % dataType.name)
                    if isinstance(dataType, autosar.datatype.BooleanDataType):
                        typedef = C.typedef('boolean', dataType.name)
                        hfile.code.append(C.statement(typedef))
                    elif isinstance(dataType,
                                    autosar.datatype.IntegerDataType):
                        valrange = dataType.maxVal - dataType.minVal
                        bitcount = valrange.bit_length()
                        typename = dataType.name
                        basetype = self._typename(bitcount, dataType.minVal)
                        typedef = C.typedef(basetype, typename)
                        hfile.code.append(C.statement(typedef))
                        isUnsigned = True if basetype in ('uint8', 'uint16',
                                                          'uint32') else False
                        if isUnsigned:
                            minval = str(dataType.minVal) + 'u'
                            maxval = str(dataType.maxVal) + 'u'
                        else:
                            minval = str(dataType.minVal)
                            maxval = str(dataType.maxVal)
                        hfile.code.append('#define %s_LowerLimit ((%s)%s)' %
                                          (typename, typename, minval))
                        hfile.code.append('#define %s_UpperLimit ((%s)%s)' %
                                          (typename, typename, maxval))
                        if dataType.compuMethodRef is not None:
                            compuMethod = ws.find(dataType.compuMethodRef)
                            if compuMethod is not None:
                                lines1 = []
                                lines2 = []
                                if isinstance(
                                        compuMethod,
                                        autosar.datatype.CompuMethodConst):
                                    for elem in compuMethod.elements:
                                        if isUnsigned:
                                            value = str(elem.upperLimit) + 'u'
                                        else:
                                            value = str(elem.upperLimit)
                                        lines1.append(
                                            '#define RTE_CONST_%s (%s)' %
                                            (elem.textValue, value))
                                        lines2.append(
                                            '#define %s ((%s)%s)' %
                                            (elem.textValue, typename, value))
                                if len(lines2) > 0:
                                    tmp = lines1 + [C.blank()] + lines2
                                else:
                                    tmp = lines1
                                for line in tmp:
                                    hfile.code.append(line)
                            else:
                                raise ValueError(dataType.compuMethodRef)
                    elif isinstance(dataType, autosar.datatype.RecordDataType):
                        body = C.block(innerIndent=innerIndentDefault)
                        for elem in dataType.elements:
                            childType = ws.find(elem.typeRef, role='DataType')
                            body.append(
                                C.statement(
                                    C.variable(elem.name, childType.name)))
                        struct = C.struct(None, body, typedef=dataType.name)
                        hfile.code.append(C.statement(struct))
                    elif isinstance(dataType, autosar.datatype.StringDataType):
                        hfile.code.append('typedef uint8 %s[%d];' %
                                          (dataType.name, dataType.length + 1))
                    elif isinstance(dataType, autosar.datatype.ArrayDataType):
                        childType = ws.find(dataType.typeRef, role='DataType')
                        if childType is None:
                            raise ValueError('invalid type reference: ' +
                                             dataType.typeRef)
                        hfile.code.append(
                            'typedef %s %s[%d];' %
                            (childType.name, dataType.name, dataType.length))
                    elif isinstance(dataType, autosar.datatype.RealDataType):
                        if dataType.encoding == 'DOUBLE':
                            platform_typename = 'float64'
                        else:
                            platform_typename = 'float32'
                        hfile.code.append('typedef %s %s;' %
                                          (platform_typename, dataType.name))
                    else:
                        raise NotImplementedError(type(dataType))
                        #sys.stderr.write('not implemented: %s\n'%str(type(dataType)))
                else:
                    raise ValueError(ref)

            if len(modeTypes) > 0:
                lines = _genCommentHeader('Mode Types')
                tmp = []
                hfile.code.extend(lines)
                first = True
                for ref in modeTypes:
                    if first:
                        first = False
                    else:
                        tmp.append(C.blank())
                    modeType = ws.find(ref)
                    hfile.code.append(
                        C.statement(
                            C.typedef('uint8',
                                      'Rte_ModeType_' + modeType.name)))

                    for i, elem in enumerate(modeType.modeDeclarations):
                        # define RTE_MODE_EcuM_Mode_POST_RUN ((Rte_ModeType_EcuM_Mode)0)
                        tmp.append(
                            C.define(
                                'RTE_MODE_%s_%s' % (modeType.name, elem.name),
                                '((Rte_ModeType_EcuM_Mode)%d)' % i))

                hfile.code.append(C.blank())
                hfile.code.extend(tmp)
            if len(unusedDefaultTypes) > 0:
                hfile.code.append(C.blank(2))
                hfile.code.append(
                    C.line('#ifndef RTE_SUPPRESS_UNUSED_DATATYPES'))
                for name in sorted(unusedDefaultTypes):
                    hfile.code.append(C.blank())
                    hfile.code.extend(self.defaultTypes[name])
                hfile.code.append(C.blank())
                hfile.code.append(C.line('#endif'))
            fp.write('\n'.join(hfile.lines()))
            fp.write('\n')
Exemplo n.º 27
0
Arquivo: base.py Projeto: ncs1/as
def type2arg(typeObj, pointer=False, name='data'):
    return C.variable(name, typeObj.name, pointer=pointer)