コード例 #1
0
def _GetLabelNames(config, label_name):
    """Gets a bunch of useful strings and names associated with a label.

  Args:
    config: A NetworkConfig.
    label_name: The kind name in snake_case.
  Returns:
    Dict { 'labels': A sorted list of label names.
           'nodes': A sorted list of AioNode names.
           'camel_suffixes': A sorted list of camel-cased short names.
           'force_signed_label': 'kFooLabelForceSigned' for kind 'foo'.
           'label_count': 'kNumFoos' for kind 'foo'.
           'camel_name': The name of kind in CamelCase.
           'snake_name': The name of kind in snake_case.
         }
  """

    camel_name = string_util.SnakeToCamel(label_name)
    label_count = 'kNum%s' % string_util.GetPlural(camel_name)
    force_signed_label = 'k%sLabelForceSigned' % camel_name

    instances = config.GetAioNodesByLabel(label_name)
    if next(iter(instances)).snake_name.startswith(label_name):
        snake_prefix = label_name
    else:
        snake_prefix = os.path.commonprefix([n.snake_name for n in instances])
    camel_prefix = string_util.SnakeToCamel(snake_prefix)
    snake_suffixes = [n.snake_name[len(snake_prefix):] for n in instances]
    camel_suffixes = [string_util.SnakeToCamel(s) for s in snake_suffixes]
    if any(not x for x in camel_suffixes):
        # This only happens on unique items.
        assert len(camel_suffixes) == 1
        camel_suffixes = [camel_prefix]
        nodes = ['kAioNode%s' % camel_prefix]
        labels = ['k%s' % camel_prefix]
    else:
        nodes = []
        labels = []
        for i in range(len(camel_suffixes)):
            camel = camel_suffixes[i]
            nodes.append('kAioNode%s%s' % (camel_prefix, camel))
            labels.append('k%s%s' % (camel_name, camel))
    return {
        'labels': labels,
        'nodes': nodes,
        'camel_suffixes': camel_suffixes,
        'force_signed_label': force_signed_label,
        'label_count': label_count,
        'camel_name': camel_name,
        'snake_name': label_name,
    }
コード例 #2
0
ファイル: registers.py プロジェクト: yhppark902/makani
    def OpenRegister(self, name, base, repeat, stride, indexing):
        """Start a new register entry."""
        self.register_name = name
        self.register_repeat = repeat
        self.typedef_name = string_util.SnakeToCamel(
            name.lower(), validate=False) + 'Registers'

        if repeat == 1:
            name_index = name
            index_str = '0'
        else:
            name_index = name + '(i)'
            if stride < 0:
                if indexing == 0:
                    index_str = '-(i)'
                else:
                    index_str = '{} - (i)'.format(indexing)
            else:
                if indexing == 0:
                    index_str = '(i)'
                else:
                    index_str = '(i) - {}'.format(indexing)
        self.output.write(
            '#define {} (((volatile {} *)0x{:08X})[{}])\n'.format(
                name_index, self.typedef_name, base, index_str))
        self.output.write('typedef struct {\n')
コード例 #3
0
def _LoadParamFromNet(node, section):
    if string_util.IsSnakeCase(node):
        node = string_util.SnakeToCamel(node)
    if node not in aio_node_helper:
        ValueError('%s is not a valid aio node.' % node)
    c = client.Client()
    return c.GetSection(aio_node_helper.Value(node), _SECTION_MAP[section])
コード例 #4
0
    def _ParseNetworkConfigTag(self, tag):
        """From a network tag, return category, aio_node, and port.

    Args:
      tag: The network tag of a port.

    Returns:
      A tuple of category, aio_node, and port. Port is None if not present.

    Raises:
      NetworkLayoutError: Raised if parsing failed.
    """

        items = tag.split('.')
        if len(items) == 2:
            items.append(None)
        elif len(items) == 3:
            # Port number.
            items[2] = int(items[2])
        else:
            raise NetworkLayoutError('Cannot parse network config tag: %s.' %
                                     tag)

        # Set AIO node name to camel case.
        items[1] = string_util.SnakeToCamel(items[1], False)
        return tuple(items)
コード例 #5
0
ファイル: string_util_test.py プロジェクト: yhppark902/makani
 def testSnakeToCamel(self):
     self.assertEqual(string_util.SnakeToCamel('apple_bee'), 'AppleBee')
     self.assertEqual(string_util.SnakeToCamel('aa12_bb34'), 'Aa12Bb34')
     with self.assertRaises(AssertionError):
         string_util.SnakeToCamel('Orange')
     with self.assertRaises(AssertionError):
         string_util.SnakeToCamel('orangeFarm')
     with self.assertRaises(AssertionError):
         string_util.SnakeToCamel('Orange_Farm')
     self.assertEqual(string_util.SnakeToCamel('Orange', False), 'Orange')
     self.assertEqual(string_util.SnakeToCamel('orangeFarm', False),
                      'OrangeFarm')
     self.assertEqual(string_util.SnakeToCamel('Orange_Farm', False),
                      'OrangeFarm')
     self.assertEqual(string_util.SnakeToCamel('AB12cd', False), 'AB12cd')
コード例 #6
0
 def _LinkToString(link):
     return textwrap.dedent("""\
     {{
       .local_port = {local_port},
       .remote_port = {remote_port},
       .remote_name = "{remote_name}",
       .remote_aio = {remote_aio},
       .link_name = {link_name},
     }}""").format(local_port=link[0],
                   remote_port=link[2],
                   remote_name=string_util.SnakeToCamel(link[1]),
                   remote_aio=str(link[3]).lower(),
                   link_name=('"%s"' % link[4]) if link[4] else 'NULL')
コード例 #7
0
ファイル: hardware_db.py プロジェクト: yhppark902/makani
def TranslateYamlStyleToSqlStyle(snake_dict):
  """Translate Google YAML style to Google SQL style."""
  return {string_util.SnakeToCamel(key): value
          for (key, value) in snake_dict.iteritems()}
コード例 #8
0
 def _GetLinkName(switch, port):
     if 'port_names' not in switch:
         return None
     if port not in switch['port_names']:
         return None
     return string_util.SnakeToCamel(switch['port_names'][port])
コード例 #9
0
def _WriteAioNodeSource(script_name, file_without_extension, rel_path, config,
                        locations):
    """Write aio_node.c.

  Args:
    script_name: This script's filename.
    file_without_extension: The full path to the output file, missing the '.c'.
    rel_path: The relative path from the autogenerated files root to our output
              file.
    config: A NetworkConfig.
    locations: The location:nodes dict from node_locations.
  """
    parts = [
        textwrap.dedent("""
      // Generated by {name}; do not edit.

      #include "{header}"

      #include <assert.h>
      #include <stdbool.h>
      #include <string.h>

      #include "common/macros.h"

      const char *AioNodeToString(AioNode node) {{
        switch (node) {{
          // Fall-through intentional.
          default:
          case kAioNodeForceSigned:
          case kNumAioNodes:
            assert(false);
            return "<error>";"""[1:]).format(name=script_name,
                                             header=rel_path + '.h')
    ]

    for node in config.aio_nodes:
        parts.append('    case %s:' % node.enum_name)
        parts.append('      return "%s";' % node.enum_name)

    parts.append(
        textwrap.dedent("""
        }
      }

      const char *AioNodeToShortString(AioNode node) {
        if (0 <= node && node < kNumAioNodes) {
          return AioNodeToString(node) + ARRAYSIZE("kAioNode") - 1;
        } else {
          return "<error>";
        }
      }

      AioNode StringToAioNode(const char *str) {
        for (AioNode node = 0; node < kNumAioNodes; ++node) {
          const char *name = AioNodeToString(node);
          if (name != NULL && !strcmp(str, name)) {
            return node;
          }
          name = AioNodeToShortString(node);
          if (name != NULL && !strcmp(str, name)) {
            return node;
          }
        }
        return kAioNodeForceSigned;
      }"""[1:]))

    parts.append(
        textwrap.dedent("""
      bool IsQ7Node(AioNode node) {
        switch (node) {"""))
    for node in config.aio_nodes:
        parts.append('    case %s:' % node.enum_name)
        parts.append('      return %s;' %
                     ('true' if node.q7_node else 'false'))

    parts.append(
        textwrap.dedent("""
          case kAioNodeForceSigned:
          case kNumAioNodes:
          default:
            return false;
        }
      }

      bool IsTms570Node(AioNode node) {
        switch (node) {"""[1:]))
    for node in config.aio_nodes:
        parts.append('    case %s:' % node.enum_name)
        parts.append('      return %s;' %
                     ('true' if node.tms570_node else 'false'))

    parts.append(
        textwrap.dedent("""
          case kAioNodeForceSigned:
          case kNumAioNodes:
          default:
            return false;
        }
      }

      bool IsValidNode(AioNode node) {
        return IsTms570Node(node) || IsQ7Node(node);
      }"""[1:]))

    for label in config.aio_labels:
        instances = config.GetAioNodesByLabel(label)
        if len(instances) == 1:
            parts.append(
                textwrap.dedent("""
          bool Is{kind}Node(AioNode node) {{
            return node == {node};
          }}""").format(kind=string_util.SnakeToCamel(label),
                        node=instances[0].enum_name))
        else:
            parts.append(
                textwrap.dedent("""
          bool Is{kind}Node(AioNode node) {{
            return (node >= {first}) &&
                   (node <= {last});
          }}""").format(kind=string_util.SnakeToCamel(label),
                        first=instances[0].enum_name,
                        last=instances[-1].enum_name))

    for location_name, location_nodes in locations.iteritems():
        is_map = [
            str(node in location_nodes).lower() for node in config.aio_nodes
        ]
        map_str = '    ' + '\n    '.join(textwrap.wrap(', '.join(is_map), 76))
        parts.append(
            textwrap.dedent("""
        bool Is{location}Node(AioNode node) {{
          const bool kMap[kNumAioNodes] = {{
        {map}
          }};
          return (0 <= node && node < kNumAioNodes) ? kMap[node] : false;
        }}""").format(location=string_util.SnakeToCamel(location_name),
                      map=map_str))

    with open(file_without_extension + '.c', 'w') as f:
        f.write('\n'.join(parts) + '\n')
コード例 #10
0
def _WriteAioNodeHeader(script_name, file_without_extension, rel_path, config,
                        locations):
    """Write aio_node.h.

  Args:
    script_name: This script's filename.
    file_without_extension: The full path to the output file, missing the '.h'.
    rel_path: The relative path from the autogenerated files root to
        file_without_extension.
    config: A NetworkConfig
    locations: The location:nodes dict from node_locations.
  """
    header_guard = re.sub('[/.]', '_', rel_path.upper()) + '_H_'
    parts = [
        textwrap.dedent("""
      #ifndef {guard}
      #define {guard}

      // Generated by {name}; do not edit.

      #include <stdbool.h>

      #ifdef __cplusplus
      extern "C" {{
      #endif

      typedef enum {{
        kAioNodeForceSigned = -1,"""[1:]).format(name=script_name,
                                                 guard=header_guard)
    ]
    for node in config.aio_nodes:
        if node.snake_name == 'unknown':
            parts.append(
                '  kAioNodeUnknown = 0,  // Reserved.  Default AioNode '
                'for invalid configuration.')
        else:
            parts.append('  %s = %d,' % (node.enum_name, node.enum_value))

    parts.append(
        textwrap.dedent("""\
        kNumAioNodes
      } AioNode;

      const char *AioNodeToString(AioNode node);
      const char *AioNodeToShortString(AioNode node);
      AioNode StringToAioNode(const char *str);
      bool IsQ7Node(AioNode node);
      bool IsTms570Node(AioNode node);
      bool IsValidNode(AioNode node);"""))

    for location in locations:
        parts.append('bool Is{location}Node(AioNode node);'.format(
            location=string_util.SnakeToCamel(location)))

    for label in config.aio_labels:
        parts.append('bool Is%sNode(AioNode node);' %
                     string_util.SnakeToCamel(label))

    parts.append(
        textwrap.dedent("""
      #ifdef __cplusplus
      }}  // extern "C"
      #endif

      #endif  // {guard}
      """).format(guard=header_guard))

    with open(file_without_extension + '.h', 'w') as f:
        f.write('\n'.join(parts))
コード例 #11
0
def _WriteAioLabelsHeader(script_name, file_without_extension, rel_path,
                          config):
    """Write aio_labels.h.

  Args:
    script_name: This script's filename.
    file_without_extension: The full path to the output file, missing the '.h'.
    rel_path: The relative path from the autogenerated files root to our output
              file.
    config: A NetworkConfig.
  """
    header_guard = re.sub('[/.]', '_', rel_path.upper()) + '_H_'
    parts = [
        textwrap.dedent("""
      #ifndef {guard}
      #define {guard}

      // Generated by {name}; do not edit.

      #include "avionics/network/aio_node.h"

      #ifdef __cplusplus
      extern "C" {{
      #endif
      """[1:]).format(name=script_name, guard=header_guard)
    ]

    for label in config.aio_labels:
        if label == 'unknown':
            continue
        info = _GetLabelNames(config, label)
        parts.append('typedef enum {')
        parts.append('  %s = -1,' % info['force_signed_label'])
        for label in info['labels']:
            parts.append('  %s,' % label)
        parts.append('  %s' % info['label_count'])
        parts.append('} %sLabel;\n' % info['camel_name'])

    for label in config.aio_labels:
        if label == 'unknown':
            continue
        parts.append(
            textwrap.dedent("""
        AioNode {0}LabelTo{0}AioNode({0}Label {1}_label);
        {0}Label {0}AioNodeTo{0}Label(AioNode {1}_node);"""[1:]).format(
                string_util.SnakeToCamel(label), label))

    for label in config.aio_labels:
        if label == 'unknown':
            continue
        parts.append(
            textwrap.dedent("""
        const char *{0}LabelToString({0}Label {1}_label);"""[1:]).format(
                string_util.SnakeToCamel(label), label))

    parts.append(
        textwrap.dedent("""
      #ifdef __cplusplus
      }}  // extern "C"
      #endif

      #endif  // {guard}
      """[1:]).format(guard=header_guard))

    with open(file_without_extension + '.h', 'w') as f:
        f.write('\n'.join(parts))
コード例 #12
0
 def camel_name(self):
     return string_util.SnakeToCamel(self.snake_name)