Debian Codegraph @

tools/cmake2meson.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: Apache-2.0
3 # Copyright 2014 Jussi Pakkanen
4
5 import typing as T
6 from pathlib import Path
7 import sys
8 import re
9 import argparse
10
11
12 class Token:
13 def __init__(self, tid: str, value: str):
14 self.tid = tid
15 self.value = value
16 self.lineno = 0
17 self.colno = 0
18
19 class Statement:
20 def __init__(self, name: str, args: list):
21 self.name = name.lower()
22 self.args = args
23
24 class Lexer:
25 def __init__(self) -> None:
26 self.token_specification = [
27 # Need to be sorted longest to shortest.
28 ('ignore', re.compile(r'[ \t]')),
29 ('string', re.compile(r'"([^\\]|(\\.))*?"', re.M)),
30 ('varexp', re.compile(r'\${[-_0-9a-z/A-Z.]+}')),
31 ('id', re.compile('''[,-><${}=+_0-9a-z/A-Z|@.*]+''')),
32 ('eol', re.compile(r'\n')),
33 ('comment', re.compile(r'#.*')),
34 ('lparen', re.compile(r'\(')),
35 ('rparen', re.compile(r'\)')),
36 ]
37
38 def lex(self, code: str) -> T.Iterator[Token]:
39 lineno = 1
40 line_start = 0
41 loc = 0
42 col = 0
43 while loc < len(code):
44 matched = False
45 for (tid, reg) in self.token_specification:
46 mo = reg.match(code, loc)
47 if mo:
48 col = mo.start() - line_start
49 matched = True
50 loc = mo.end()
51 match_text = mo.group()
52 if tid == 'ignore':
53 continue
54 if tid == 'comment':
55 yield(Token('comment', match_text))
56 elif tid == 'lparen':
57 yield(Token('lparen', '('))
58 elif tid == 'rparen':
59 yield(Token('rparen', ')'))
60 elif tid == 'string':
61 yield(Token('string', match_text[1:-1]))
62 elif tid == 'id':
63 yield(Token('id', match_text))
64 elif tid == 'eol':
65 # yield('eol')
66 lineno += 1
67 col = 1
68 line_start = mo.end()
69 elif tid == 'varexp':
70 yield(Token('varexp', match_text[2:-1]))
71 else:
72 raise ValueError(f'lex: unknown element {tid}')
73 break
74 if not matched:
75 raise ValueError('Lexer got confused line %d column %d' % (lineno, col))
76
77 class Parser:
78 def __init__(self, code: str) -> None:
79 self.stream = Lexer().lex(code)
80 self.getsym()
81
82 def getsym(self) -> None:
83 try:
84 self.current = next(self.stream)
85 except StopIteration:
86 self.current = Token('eof', '')
87
88 def accept(self, s: str) -> bool:
89 if self.current.tid == s:
90 self.getsym()
91 return True
92 return False
93
94 def expect(self, s: str) -> bool:
95 if self.accept(s):
96 return True
97 raise ValueError(f'Expecting {s} got {self.current.tid}.', self.current.lineno, self.current.colno)
98
99 def statement(self) -> Statement:
100 cur = self.current
101 if self.accept('comment'):
102 return Statement('_', [cur.value])
103 self.accept('id')
104 self.expect('lparen')
105 args = self.arguments()
106 self.expect('rparen')
107 return Statement(cur.value, args)
108
109 def arguments(self) -> T.List[T.Union[Token, T.Any]]:
110 args: T.List[T.Union[Token, T.Any]] = []
111 if self.accept('lparen'):
112 args.append(self.arguments())
113 self.expect('rparen')
114 arg = self.current
115 if self.accept('comment'):
116 rest = self.arguments()
117 args += rest
118 elif self.accept('string') \
119 or self.accept('varexp') \
120 or self.accept('id'):
121 args.append(arg)
122 rest = self.arguments()
123 args += rest
124 return args
125
126 def parse(self) -> T.Iterator[Statement]:
127 while not self.accept('eof'):
128 yield(self.statement())
129
130 def token_or_group(arg: T.Union[Token, T.List[Token]]) -> str:
131 if isinstance(arg, Token):
132 return ' ' + arg.value
133 elif isinstance(arg, list):
134 line = ' ('
135 for a in arg:
136 line += ' ' + token_or_group(a)
137 line += ' )'
138 return line
139 raise RuntimeError('Conversion error in token_or_group')
140
141 class Converter:
142 ignored_funcs = {'cmake_minimum_required': True,
143 'enable_testing': True,
144 'include': True}
145
146 def __init__(self, cmake_root: str):
147 self.cmake_root = Path(cmake_root).expanduser()
148 self.indent_unit = ' '
149 self.indent_level = 0
150 self.options: T.List[T.Tuple[str, str, T.Optional[str]]] = []
151
152 def convert_args(self, args: T.List[Token], as_array: bool = True) -> str:
153 res = []
154 if as_array:
155 start = '['
156 end = ']'
157 else:
158 start = ''
159 end = ''
160 for i in args:
161 if i.tid == 'id':
162 res.append("'%s'" % i.value)
163 elif i.tid == 'varexp':
164 res.append('%s' % i.value.lower())
165 elif i.tid == 'string':
166 res.append("'%s'" % i.value)
167 else:
168 raise ValueError(f'Unknown arg type {i.tid}')
169 if len(res) > 1:
170 return start + ', '.join(res) + end
171 if len(res) == 1:
172 return res[0]
173 return ''
174
175 def write_entry(self, outfile: T.TextIO, t: Statement) -> None:
176 if t.name in Converter.ignored_funcs:
177 return
178 preincrement = 0
179 postincrement = 0
180 if t.name == '_':
181 line = t.args[0]
182 elif t.name == 'add_subdirectory':
183 line = "subdir('" + t.args[0].value + "')"
184 elif t.name == 'pkg_search_module' or t.name == 'pkg_search_modules':
185 varname = t.args[0].value.lower()
186 mods = ["dependency('%s')" % i.value for i in t.args[1:]]
187 if len(mods) == 1:
188 line = '{} = {}'.format(varname, mods[0])
189 else:
190 line = '{} = [{}]'.format(varname, ', '.join(["'%s'" % i for i in mods]))
191 elif t.name == 'find_package':
192 line = "{}_dep = dependency('{}')".format(t.args[0].value, t.args[0].value)
193 elif t.name == 'find_library':
194 line = "{} = find_library('{}')".format(t.args[0].value.lower(), t.args[0].value)
195 elif t.name == 'add_executable':
196 line = '{}_exe = executable({})'.format(t.args[0].value, self.convert_args(t.args, False))
197 elif t.name == 'add_library':
198 if t.args[1].value == 'SHARED':
199 libcmd = 'shared_library'
200 args = [t.args[0]] + t.args[2:]
201 elif t.args[1].value == 'STATIC':
202 libcmd = 'static_library'
203 args = [t.args[0]] + t.args[2:]
204 else:
205 libcmd = 'library'
206 args = t.args
207 line = '{}_lib = {}({})'.format(t.args[0].value, libcmd, self.convert_args(args, False))
208 elif t.name == 'add_test':
209 line = 'test(%s)' % self.convert_args(t.args, False)
210 elif t.name == 'option':
211 optname = t.args[0].value
212 description = t.args[1].value
213 if len(t.args) > 2:
214 default = t.args[2].value
215 else:
216 default = None
217 self.options.append((optname, description, default))
218 return
219 elif t.name == 'project':
220 pname = t.args[0].value
221 args = [pname]
222 for l in t.args[1:]:
223 l = l.value.lower()
224 if l == 'cxx':
225 l = 'cpp'
226 args.append(l)
227 args = ["'%s'" % i for i in args]
228 line = 'project(' + ', '.join(args) + ", default_options : ['default_library=static'])"
229 elif t.name == 'set':
230 varname = t.args[0].value.lower()
231 line = '{} = {}\n'.format(varname, self.convert_args(t.args[1:]))
232 elif t.name == 'if':
233 postincrement = 1
234 try:
235 line = 'if %s' % self.convert_args(t.args, False)
236 except AttributeError: # complex if statements
237 line = t.name
238 for arg in t.args:
239 line += token_or_group(arg)
240 elif t.name == 'elseif':
241 preincrement = -1
242 postincrement = 1
243 try:
244 line = 'elif %s' % self.convert_args(t.args, False)
245 except AttributeError: # complex if statements
246 line = t.name
247 for arg in t.args:
248 line += token_or_group(arg)
249 elif t.name == 'else':
250 preincrement = -1
251 postincrement = 1
252 line = 'else'
253 elif t.name == 'endif':
254 preincrement = -1
255 line = 'endif'
256 else:
257 line = '''# {}({})'''.format(t.name, self.convert_args(t.args))
258 self.indent_level += preincrement
259 indent = self.indent_level * self.indent_unit
260 outfile.write(indent)
261 outfile.write(line)
262 if not(line.endswith('\n')):
263 outfile.write('\n')
264 self.indent_level += postincrement
265
266 def convert(self, subdir: Path = None) -> None:
267 if not subdir:
268 subdir = self.cmake_root
269 cfile = Path(subdir).expanduser() / 'CMakeLists.txt'
270 try:
271 with cfile.open(encoding='utf-8') as f:
272 cmakecode = f.read()
273 except FileNotFoundError:
274 print('\nWarning: No CMakeLists.txt in', subdir, '\n', file=sys.stderr)
275 return
276 p = Parser(cmakecode)
277 with (subdir / 'meson.build').open('w', encoding='utf-8') as outfile:
278 for t in p.parse():
279 if t.name == 'add_subdirectory':
280 # print('\nRecursing to subdir',
281 # self.cmake_root / t.args[0].value,
282 # '\n')
283 self.convert(subdir / t.args[0].value)
284 # print('\nReturning to', self.cmake_root, '\n')
285 self.write_entry(outfile, t)
286 if subdir == self.cmake_root and len(self.options) > 0:
287 self.write_options()
288
289 def write_options(self) -> None:
290 filename = self.cmake_root / 'meson_options.txt'
291 with filename.open('w', encoding='utf-8') as optfile:
292 for o in self.options:
293 (optname, description, default) = o
294 if default is None:
295 typestr = ''
296 defaultstr = ''
297 else:
298 if default == 'OFF':
299 typestr = ' type : \'boolean\','
300 default = 'false'
301 elif default == 'ON':
302 default = 'true'
303 typestr = ' type : \'boolean\','
304 else:
305 typestr = ' type : \'string\','
306 defaultstr = ' value : %s,' % default
307 line = "option({!r},{}{} description : '{}')\n".format(optname,
308 typestr,
309 defaultstr,
310 description)
311 optfile.write(line)
312
313 if __name__ == '__main__':
314 p = argparse.ArgumentParser(description='Convert CMakeLists.txt to meson.build and meson_options.txt')
315 p.add_argument('cmake_root', help='CMake project root (where top-level CMakeLists.txt is)')
316 P = p.parse_args()
317
318 Converter(P.cmake_root).convert()