1#!/bin/env python
2
3# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
4# other Axom Project Developers. See the top-level LICENSE file for details.
5#
6# SPDX-License-Identifier: (BSD-3-Clause)
7
8"""
9Attempt to convert about 70% of the way from C++ to Fortran
10doing mechanical transitions.
11"""
12
13from __future__ import print_function
14import re
15import tokenize
16import shlex
17
18# http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
19def un_camel(text):
20    """ Converts a CamelCase name into an under_score name.
21
22        >>> un_camel('CamelCase')
23        'camel_case'
24        >>> un_camel('getHTTPResponseCode')
25        'get_http_response_code'
26    """
27    result = []
28    pos = 0
29    while pos < len(text):
30        if text[pos].isupper():
31            if pos-1 > 0 and text[pos-1].islower() or pos-1 > 0 and \
32            pos+1 < len(text) and text[pos+1].islower():
33                result.append("_%s" % text[pos].lower())
34            else:
35                result.append(text[pos].lower())
36        else:
37            result.append(text[pos])
38        pos += 1
39    return "".join(result)
40
41def convert(filename):
42   print ("converting " + filename)
43   with open(filename) as fp:
44      for line in fp.readlines():
45
46         line = re.sub('->', '%', line)
47         line = re.sub('\[', '(', line)
48         line = re.sub('\]', ')', line)
49         line = re.sub(';', '', line)
50         line = re.sub('//', '!', line)
51         line = re.sub('EXPECT_TRUE', 'call assert_true', line)
52         line = re.sub('EXPECT_FALSE', 'call assert_true', line)
53         line = re.sub('EXPECT_EQ', 'call assert_equals', line)
54         line = re.sub('new DataStore', 'datastore_new', line)
55
56         m = re.search('TEST\(\w+,(\w+)\)', line)
57         if m:
58            tname = m.group(1)
59            print ('subroutine {}'.format(tname))
60            print ('call set_case_name("{}")'.format(tname))
61            print ('end subroutine {}'.format(tname))
62            continue
63
64         # convert camelCase to snake_case
65         def fixit(m):
66            s = m.group(0)
67            if s in [ 'DataStore', 'Group', 'View', 'Buffer']:
68               return s.lower()
69            return un_camel(m.group(0))
70         line = re.sub('\w+', fixit, line)
71
72         m = re.search('delete (\w+)', line)
73         if m:
74            name = m.group(1)
75            print('call {}%delete()'.format(name))
76            continue
77
78         # functions calls
79         m = re.match('(\s+)(\w+)%(.*)', line)
80         if m:
81            print('{}call {}%{}'.format(*m.groups()))
82            continue
83
84         # declaration calls  'type * name'
85         m = re.match('\s*(\w+)\s*\*\s*(\w+)(.*)', line)
86         if m:
87            print('type({}) {}'.format(m.group(1), m.group(2)))
88            print('{}{}'.format(m.group(2), m.group(3)))
89            continue
90
91         print(line, end='')
92
93def convert3(filename):
94   print ("converting " + filename)
95   with open(filename) as fp:
96      for line in fp.readlines():
97         lexer = shlex.shlex(line)
98         for token in lexer:
99            print (repr(token))
100
101def convert2(filename):
102   print ("converting " + filename)
103   result = []
104   with open(filename) as fp:
105      g = tokenize.generate_tokens(fp.readline)
106      for toknum, tokval, start, end, linenum in g:
107         print(toknum, tokval)
108
109      result.append((toknum, tokval))
110   s = tokenize.untokenize(result)
111
112if __name__ == '__main__':
113   import sys
114   if len(sys.argv) != 2:
115      print ("usage: {} filename".format(sys.argv[0]))
116      raise SystemExit
117   convert(sys.argv[1])
118