blob: 6b373159cbc241cbdef5a36a5cb31b753fcc76bb [file] [log] [blame]
Azim Khanf0e42fb2017-08-02 14:47:13 +01001# Test suites code generator.
2#
3# Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18# This file is part of mbed TLS (https://tls.mbed.org)
19
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010020"""
Azim Khanf0e42fb2017-08-02 14:47:13 +010021Test Suite code generator.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010022
Azim Khanf0e42fb2017-08-02 14:47:13 +010023Generates a test source file using following input files:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010024
Azim Khanf0e42fb2017-08-02 14:47:13 +010025test_suite_xyz.function - Read test functions from test suite functions file.
26test_suite_xyz.data - Read test functions and their dependencies to generate
27 dispatch and dependency check code.
28main template - Substitute generated test function dispatch code, dependency
29 checking code.
30platform .function - Read host or target platform implementation for
31 dispatching test cases from .data file.
32helper .function - Read common reusable functions.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010033"""
34
Azim Khanf0e42fb2017-08-02 14:47:13 +010035
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010036import os
37import re
38import argparse
39import shutil
40
41
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010042BEGIN_HEADER_REGEX = '/\*\s*BEGIN_HEADER\s*\*/'
43END_HEADER_REGEX = '/\*\s*END_HEADER\s*\*/'
44
45BEGIN_DEP_REGEX = 'BEGIN_DEPENDENCIES'
46END_DEP_REGEX = 'END_DEPENDENCIES'
47
48BEGIN_CASE_REGEX = '/\*\s*BEGIN_CASE\s*(.*?)\s*\*/'
49END_CASE_REGEX = '/\*\s*END_CASE\s*\*/'
50
51
52class InvalidFileFormat(Exception):
53 """
54 Exception to indicate invalid file format.
55 """
56 pass
57
58
Azim Khan4b543232017-06-30 09:35:21 +010059class FileWrapper(file):
60 """
61 File wrapper class. Provides reading with line no. tracking.
62 """
63
64 def __init__(self, file_name):
65 """
66 Init file handle.
67
Azim Khanf0e42fb2017-08-02 14:47:13 +010068 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +010069 """
70 super(FileWrapper, self).__init__(file_name, 'r')
71 self.line_no = 0
72
73 def next(self):
74 """
75 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010076 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010077 """
78 line = super(FileWrapper, self).next()
79 if line:
80 self.line_no += 1
81 return line
82
83 def readline(self, limit=0):
84 """
85 Wrap the base class readline.
86
Azim Khanf0e42fb2017-08-02 14:47:13 +010087 :param limit: limit to match file.readline([limit])
88 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010089 """
90 return self.next()
91
92
93def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +010094 """
95 Split NOT character '!' from dependency. Used by gen_deps()
96
97 :param dep: Dependency list
98 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
99 """
Azim Khan4b543232017-06-30 09:35:21 +0100100 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
101
102
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100103def gen_deps(deps):
104 """
105 Generates dependency i.e. if def and endif code
106
Azim Khanf0e42fb2017-08-02 14:47:13 +0100107 :param deps: List of dependencies.
108 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100109 """
Azim Khan4b543232017-06-30 09:35:21 +0100110 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
111 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
112
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100113 return dep_start, dep_end
114
115
116def gen_deps_one_line(deps):
117 """
118 Generates dependency checks in one line. Useful for writing code in #else case.
119
Azim Khanf0e42fb2017-08-02 14:47:13 +0100120 :param deps: List of dependencies.
121 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100122 """
Azim Khan4b543232017-06-30 09:35:21 +0100123 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
124 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100125
126
Azim Khan4b543232017-06-30 09:35:21 +0100127def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100128 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100129 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100130
Azim Khanf0e42fb2017-08-02 14:47:13 +0100131 :param name: Test function name
132 :param locals: Local variables declaration code
133 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
134 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100135 """
136 # Then create the wrapper
137 wrapper = '''
138void {name}_wrapper( void ** params )
139{{
140 {unused_params}
Azim Khan2397bba2017-06-09 04:35:03 +0100141{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100142 {name}( {args} );
143}}
Azim Khan4b543232017-06-30 09:35:21 +0100144'''.format(name=name, unused_params='(void)params;' if len(args_dispatch) == 0 else '',
145 args=', '.join(args_dispatch),
146 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100147 return wrapper
148
149
150def gen_dispatch(name, deps):
151 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100152 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100153
Azim Khanf0e42fb2017-08-02 14:47:13 +0100154 :param name: Test function name
155 :param deps: List of dependencies
156 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100157 """
158 if len(deps):
159 ifdef = gen_deps_one_line(deps)
160 dispatch_code = '''
161{ifdef}
162 {name}_wrapper,
163#else
164 NULL,
165#endif
166'''.format(ifdef=ifdef, name=name)
167 else:
168 dispatch_code = '''
169 {name}_wrapper,
170'''.format(name=name)
171
172 return dispatch_code
173
174
Azim Khan4b543232017-06-30 09:35:21 +0100175def parse_suite_headers(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100176 """
177 Parses function headers.
178
Azim Khanf0e42fb2017-08-02 14:47:13 +0100179 :param funcs_f: file object for .functions file
180 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100181 """
Azim Khan4b543232017-06-30 09:35:21 +0100182 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100183 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100184 if re.search(END_HEADER_REGEX, line):
185 break
186 headers += line
187 else:
188 raise InvalidFileFormat("file: %s - end header pattern [%s] not found!" % (funcs_f.name, END_HEADER_REGEX))
189
Azim Khan4b543232017-06-30 09:35:21 +0100190 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100191
192
Azim Khan4b543232017-06-30 09:35:21 +0100193def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100194 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100195 Parses test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100196
Azim Khanf0e42fb2017-08-02 14:47:13 +0100197 :param funcs_f: file object for .functions file
198 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100199 """
200 deps = []
201 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100202 m = re.search('depends_on\:(.*)', line.strip())
203 if m:
204 deps += [x.strip() for x in m.group(1).split(':')]
205 if re.search(END_DEP_REGEX, line):
206 break
207 else:
208 raise InvalidFileFormat("file: %s - end dependency pattern [%s] not found!" % (funcs_f.name, END_DEP_REGEX))
209
Azim Khan4b543232017-06-30 09:35:21 +0100210 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100211
212
213def parse_function_deps(line):
214 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100215 Parses function dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100216
Azim Khanf0e42fb2017-08-02 14:47:13 +0100217 :param line: Line from .functions file that has dependencies.
218 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100219 """
220 deps = []
221 m = re.search(BEGIN_CASE_REGEX, line)
222 dep_str = m.group(1)
223 if len(dep_str):
224 m = re.search('depends_on:(.*)', dep_str)
225 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100226 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100227 return deps
228
229
230def parse_function_signature(line):
231 """
232 Parsing function signature
233
Azim Khanf0e42fb2017-08-02 14:47:13 +0100234 :param line: Line from .functions file that has a function signature.
235 :return: function name, argument list, local variables for wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100236 """
237 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100238 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100239 args_dispatch = []
240 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
241 if not m:
242 raise ValueError("Test function should return 'void'\n%s" % line)
243 name = m.group(1)
244 line = line[len(m.group(0)):]
245 arg_idx = 0
246 for arg in line[:line.find(')')].split(','):
247 arg = arg.strip()
248 if arg == '':
249 continue
250 if re.search('int\s+.*', arg.strip()):
251 args.append('int')
252 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
253 elif re.search('char\s*\*\s*.*', arg.strip()):
254 args.append('char*')
255 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100256 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100257 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100258 # create a structure
259 locals += """ HexParam_t hex%d = {%s, %s};
260""" % (arg_idx, '(uint8_t *) params[%d]' % arg_idx, '*( (uint32_t *) params[%d] )' % (arg_idx + 1))
261
262 args_dispatch.append('&hex%d' % arg_idx)
263 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100264 else:
Azim Khan4b543232017-06-30 09:35:21 +0100265 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100266 arg_idx += 1
267
Azim Khan4b543232017-06-30 09:35:21 +0100268 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100269
270
Azim Khan4b543232017-06-30 09:35:21 +0100271def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100272 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100273 Parses out a function from function file object and generates function and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100274
Azim Khanf0e42fb2017-08-02 14:47:13 +0100275 :param funcs_f: file object of the functions file.
276 :param deps: List of dependencies
277 :param suite_deps: List of test suite dependencies
278 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100279 """
Azim Khan4b543232017-06-30 09:35:21 +0100280 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100281 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100282 # Check function signature
283 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
284 if m:
285 # check if we have full signature i.e. split in more lines
286 if not re.match('.*\)', line):
287 for lin in funcs_f:
288 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100289 if re.search('.*?\)', line):
290 break
Azim Khan4b543232017-06-30 09:35:21 +0100291 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100292 code += line.replace(name, 'test_' + name)
293 name = 'test_' + name
294 break
295 else:
296 raise InvalidFileFormat("file: %s - Test functions not found!" % funcs_f.name)
297
298 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100299 if re.search(END_CASE_REGEX, line):
300 break
301 code += line
302 else:
303 raise InvalidFileFormat("file: %s - end case pattern [%s] not found!" % (funcs_f.name, END_CASE_REGEX))
304
305 # Add exit label if not present
306 if code.find('exit:') == -1:
307 s = code.rsplit('}', 1)
308 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100309 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100310 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100311}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100312
Azim Khan4b543232017-06-30 09:35:21 +0100313 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100314 ifdef, endif = gen_deps(deps)
315 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100316 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100317
318
319def parse_functions(funcs_f):
320 """
321 Returns functions code pieces
322
Azim Khanf0e42fb2017-08-02 14:47:13 +0100323 :param funcs_f: file object of the functions file.
324 :return: List of test suite dependencies, test function dispatch code, function code and
325 a dict with function identifiers and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100326 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100327 suite_headers = ''
328 suite_deps = []
329 suite_functions = ''
330 func_info = {}
331 function_idx = 0
332 dispatch_code = ''
333 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100334 if re.search(BEGIN_HEADER_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100335 headers = parse_suite_headers(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100336 suite_headers += headers
337 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100338 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100339 suite_deps += deps
340 elif re.search(BEGIN_CASE_REGEX, line):
341 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100342 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100343 suite_functions += func_code
344 # Generate dispatch code and enumeration info
345 assert func_name not in func_info, "file: %s - function %s re-declared at line %d" % \
Azim Khan4b543232017-06-30 09:35:21 +0100346 (funcs_f.name, func_name, funcs_f.line_no)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100347 func_info[func_name] = (function_idx, args)
348 dispatch_code += '/* Function Id: %d */\n' % function_idx
349 dispatch_code += func_dispatch
350 function_idx += 1
351
352 ifdef, endif = gen_deps(suite_deps)
Azim Khan13c6bfb2017-06-15 14:45:56 +0100353 func_code = ifdef + suite_headers + suite_functions + endif
354 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100355
356
357def escaped_split(str, ch):
358 """
359 Split str on character ch but ignore escaped \{ch}
Azim Khan599cd242017-07-06 17:34:27 +0100360 Since return value is used to write back to the intermediate data file.
361 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100362
Azim Khanf0e42fb2017-08-02 14:47:13 +0100363 :param str: String to split
364 :param ch: split character
365 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100366 """
367 if len(ch) > 1:
368 raise ValueError('Expected split character. Found string!')
369 out = []
370 part = ''
371 escape = False
372 for i in range(len(str)):
373 if not escape and str[i] == ch:
374 out.append(part)
375 part = ''
376 else:
Azim Khanacc54732017-07-03 14:06:45 +0100377 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100378 escape = not escape and str[i] == '\\'
379 if len(part):
380 out.append(part)
381 return out
382
383
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100384def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100385 """
386 Parses .data file
387
Azim Khanf0e42fb2017-08-02 14:47:13 +0100388 :param data_f: file object of the data file.
389 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100390 """
391 STATE_READ_NAME = 0
392 STATE_READ_ARGS = 1
393 state = STATE_READ_NAME
394 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100395 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100396 for line in data_f:
397 line = line.strip()
398 if len(line) and line[0] == '#': # Skip comments
399 continue
400
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100401 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100402 if len(line) == 0:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100403 assert state != STATE_READ_ARGS, "Newline before arguments. " \
404 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100405 continue
406
407 if state == STATE_READ_NAME:
408 # Read test name
409 name = line
410 state = STATE_READ_ARGS
411 elif state == STATE_READ_ARGS:
412 # Check dependencies
413 m = re.search('depends_on\:(.*)', line)
414 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100415 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100416 else:
417 # Read test vectors
418 parts = escaped_split(line, ':')
419 function = parts[0]
420 args = parts[1:]
421 yield name, function, deps, args
422 deps = []
423 state = STATE_READ_NAME
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100424 assert state != STATE_READ_ARGS, "Newline before arguments. " \
425 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100426
427
428def gen_dep_check(dep_id, dep):
429 """
430 Generate code for the dependency.
431
Azim Khanf0e42fb2017-08-02 14:47:13 +0100432 :param dep_id: Dependency identifier
433 :param dep: Dependency macro
434 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100435 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100436 assert dep_id > -1, "Dependency Id should be a positive integer."
437 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
438 assert len(dep) > 0, "Dependency should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100439 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100440 case {id}:
441 {{
Azim Khand61b8372017-07-10 11:54:01 +0100442#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100443 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100444#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100445 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100446#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100447 }}
448 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100449 return dep_check
450
451
452def gen_expression_check(exp_id, exp):
453 """
454 Generates code for expression check
455
Azim Khanf0e42fb2017-08-02 14:47:13 +0100456 :param exp_id: Expression Identifier
457 :param exp: Expression/Macro
458 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100459 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100460 assert exp_id > -1, "Expression Id should be a positive integer."
461 assert len(exp) > 0, "Expression should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100462 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100463 case {exp_id}:
464 {{
465 *out_value = {expression};
466 }}
467 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100468 return exp_code
469
470
Azim Khan599cd242017-07-06 17:34:27 +0100471def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100472 """
Azim Khan599cd242017-07-06 17:34:27 +0100473 Write dependencies to intermediate test data file.
474 It also returns dependency check code.
475
Azim Khanf0e42fb2017-08-02 14:47:13 +0100476 :param out_data_f: Output intermediate data file
477 :param test_deps: Dependencies
478 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
479 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100480 """
Azim Khan599cd242017-07-06 17:34:27 +0100481 dep_check_code = ''
482 if len(test_deps):
483 out_data_f.write('depends_on')
484 for dep in test_deps:
485 if dep not in unique_deps:
486 unique_deps.append(dep)
487 dep_id = unique_deps.index(dep)
488 dep_check_code += gen_dep_check(dep_id, dep)
489 else:
490 dep_id = unique_deps.index(dep)
491 out_data_f.write(':' + str(dep_id))
492 out_data_f.write('\n')
493 return dep_check_code
494
495
496def write_parameters(out_data_f, test_args, func_args, unique_expressions):
497 """
498 Writes test parameters to the intermediate data file.
499 Also generates expression code.
500
Azim Khanf0e42fb2017-08-02 14:47:13 +0100501 :param out_data_f: Output intermediate data file
502 :param test_args: Test parameters
503 :param func_args: Function arguments
504 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
505 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100506 """
507 expression_code = ''
508 for i in xrange(len(test_args)):
509 typ = func_args[i]
510 val = test_args[i]
511
512 # check if val is a non literal int val
513 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
514 typ = 'exp'
515 if val not in unique_expressions:
516 unique_expressions.append(val)
517 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
518 # use index().
519 exp_id = unique_expressions.index(val)
520 expression_code += gen_expression_check(exp_id, val)
521 val = exp_id
522 else:
523 val = unique_expressions.index(val)
524 out_data_f.write(':' + typ + ':' + str(val))
525 out_data_f.write('\n')
526 return expression_code
527
528
529def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
530 """
531 Adds preprocessor checks for test suite dependencies.
532
Azim Khanf0e42fb2017-08-02 14:47:13 +0100533 :param suite_deps: Test suite dependencies read from the .functions file.
534 :param dep_check_code: Dependency check code
535 :param expression_code: Expression check code
536 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100537 """
Azim Khan599cd242017-07-06 17:34:27 +0100538 if len(suite_deps):
539 ifdef = gen_deps_one_line(suite_deps)
540 dep_check_code = '''
541{ifdef}
542{code}
Azim Khan599cd242017-07-06 17:34:27 +0100543#endif
544'''.format(ifdef=ifdef, code=dep_check_code)
545 expression_code = '''
546{ifdef}
547{code}
Azim Khan599cd242017-07-06 17:34:27 +0100548#endif
549'''.format(ifdef=ifdef, code=expression_code)
550 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100551
552
Azim Khan13c6bfb2017-06-15 14:45:56 +0100553def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100554 """
555 Generates dependency checks, expression code and intermediate data file from test data file.
556
Azim Khanf0e42fb2017-08-02 14:47:13 +0100557 :param data_f: Data file object
558 :param out_data_f:Output intermediate data file
559 :param func_info: Dict keyed by function and with function id and arguments info
560 :param suite_deps: Test suite deps
561 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100562 """
563 unique_deps = []
564 unique_expressions = []
565 dep_check_code = ''
566 expression_code = ''
567 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
568 out_data_f.write(test_name + '\n')
569
Azim Khan599cd242017-07-06 17:34:27 +0100570 # Write deps
571 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100572
Azim Khan599cd242017-07-06 17:34:27 +0100573 # Write test function name
574 test_function_name = 'test_' + function_name
575 assert test_function_name in func_info, "Function %s not found!" % test_function_name
576 func_id, func_args = func_info[test_function_name]
577 out_data_f.write(str(func_id))
578
579 # Write parameters
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100580 assert len(test_args) == len(func_args), \
581 "Invalid number of arguments in test %s. See function %s signature." % (test_name, function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100582 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100583
Azim Khan599cd242017-07-06 17:34:27 +0100584 # Write a newline as test case separator
585 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100586
Azim Khan599cd242017-07-06 17:34:27 +0100587 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100588 return dep_check_code, expression_code
589
590
Azim Khan1de892b2017-06-09 15:02:36 +0100591def generate_code(funcs_file, data_file, template_file, platform_file, help_file, suites_dir, c_file, out_data_file):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100592 """
593 Generate mbed-os test code.
594
Azim Khanf0e42fb2017-08-02 14:47:13 +0100595 :param funcs_file: Functions file object
596 :param data_file: Data file object
597 :param template_file: Template file object
598 :param platform_file: Platform file object
599 :param help_file: Helper functions file object
600 :param suites_dir: Test suites dir
601 :param c_file: Output C file object
602 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100603 :return:
604 """
605 for name, path in [('Functions file', funcs_file),
606 ('Data file', data_file),
607 ('Template file', template_file),
608 ('Platform file', platform_file),
609 ('Help code file', help_file),
610 ('Suites dir', suites_dir)]:
611 if not os.path.exists(path):
612 raise IOError("ERROR: %s [%s] not found!" % (name, path))
613
614 snippets = {'generator_script' : os.path.basename(__file__)}
615
616 # Read helpers
617 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
618 snippets['test_common_helper_file'] = help_file
619 snippets['test_common_helpers'] = help_f.read()
620 snippets['test_platform_file'] = platform_file
621 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
622 out_data_file.replace('\\', '\\\\')) # escape '\'
623
624 # Function code
Azim Khanacc54732017-07-03 14:06:45 +0100625 with FileWrapper(funcs_file) as funcs_f, open(data_file, 'r') as data_f, open(out_data_file, 'w') as out_data_f:
Azim Khan13c6bfb2017-06-15 14:45:56 +0100626 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100627 snippets['functions_code'] = func_code
628 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100629 dep_check_code, expression_code = gen_from_test_data(data_f, out_data_f, func_info, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100630 snippets['dep_check_code'] = dep_check_code
631 snippets['expression_code'] = expression_code
632
633 snippets['test_file'] = c_file
634 snippets['test_main_file'] = template_file
635 snippets['test_case_file'] = funcs_file
636 snippets['test_case_data_file'] = data_file
637 # Read Template
638 # Add functions
639 #
640 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
641 line_no = 1
642 for line in template_f.readlines():
643 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
644 code = line.format(**snippets)
645 c_f.write(code)
646 line_no += 1
647
648
649def check_cmd():
650 """
651 Command line parser.
652
653 :return:
654 """
655 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
656
657 parser.add_argument("-f", "--functions-file",
658 dest="funcs_file",
659 help="Functions file",
660 metavar="FUNCTIONS",
661 required=True)
662
663 parser.add_argument("-d", "--data-file",
664 dest="data_file",
665 help="Data file",
666 metavar="DATA",
667 required=True)
668
669 parser.add_argument("-t", "--template-file",
670 dest="template_file",
671 help="Template file",
672 metavar="TEMPLATE",
673 required=True)
674
675 parser.add_argument("-s", "--suites-dir",
676 dest="suites_dir",
677 help="Suites dir",
678 metavar="SUITES",
679 required=True)
680
681 parser.add_argument("--help-file",
682 dest="help_file",
683 help="Help file",
684 metavar="HELPER",
685 required=True)
686
687 parser.add_argument("-p", "--platform-file",
688 dest="platform_file",
689 help="Platform code file",
690 metavar="PLATFORM_FILE",
691 required=True)
692
693 parser.add_argument("-o", "--out-dir",
694 dest="out_dir",
695 help="Dir where generated code and scripts are copied",
696 metavar="OUT_DIR",
697 required=True)
698
699 args = parser.parse_args()
700
701 data_file_name = os.path.basename(args.data_file)
702 data_name = os.path.splitext(data_file_name)[0]
703
704 out_c_file = os.path.join(args.out_dir, data_name + '.c')
705 out_data_file = os.path.join(args.out_dir, data_file_name)
706
707 out_c_file_dir = os.path.dirname(out_c_file)
708 out_data_file_dir = os.path.dirname(out_data_file)
709 for d in [out_c_file_dir, out_data_file_dir]:
710 if not os.path.exists(d):
711 os.makedirs(d)
712
Azim Khan1de892b2017-06-09 15:02:36 +0100713 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100714 args.help_file, args.suites_dir, out_c_file, out_data_file)
715
716
717if __name__ == "__main__":
718 check_cmd()