blob: 3ff7a41d98362587ff2c12988a047c4e726496bb [file] [log] [blame]
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +01001#!/usr/bin/env python3
Azim Khanf0e42fb2017-08-02 14:47:13 +01002# Test suites code generator.
3#
Mohammad Azim Khan78befd92018-03-06 11:49:41 +00004# Copyright (C) 2018, ARM Limited, All Rights Reserved
Azim Khanf0e42fb2017-08-02 14:47:13 +01005# SPDX-License-Identifier: Apache-2.0
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# This file is part of mbed TLS (https://tls.mbed.org)
20
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010021"""
Azim Khanf0e42fb2017-08-02 14:47:13 +010022Test Suite code generator.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010023
Azim Khanf0e42fb2017-08-02 14:47:13 +010024Generates a test source file using following input files:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010025
Azim Khanf0e42fb2017-08-02 14:47:13 +010026test_suite_xyz.function - Read test functions from test suite functions file.
27test_suite_xyz.data - Read test functions and their dependencies to generate
28 dispatch and dependency check code.
29main template - Substitute generated test function dispatch code, dependency
30 checking code.
31platform .function - Read host or target platform implementation for
32 dispatching test cases from .data file.
33helper .function - Read common reusable functions.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010034"""
35
Azim Khanf0e42fb2017-08-02 14:47:13 +010036
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010037import io
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010038import os
39import re
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010040import sys
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010041import argparse
42import shutil
43
44
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010045BEGIN_HEADER_REGEX = '/\*\s*BEGIN_HEADER\s*\*/'
46END_HEADER_REGEX = '/\*\s*END_HEADER\s*\*/'
47
Mohammad Azim Khanb5229292018-02-06 13:08:01 +000048BEGIN_SUITE_HELPERS_REGEX = '/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
49END_SUITE_HELPERS_REGEX = '/\*\s*END_SUITE_HELPERS\s*\*/'
50
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010051BEGIN_DEP_REGEX = 'BEGIN_DEPENDENCIES'
52END_DEP_REGEX = 'END_DEPENDENCIES'
53
54BEGIN_CASE_REGEX = '/\*\s*BEGIN_CASE\s*(.*?)\s*\*/'
55END_CASE_REGEX = '/\*\s*END_CASE\s*\*/'
56
57
58class InvalidFileFormat(Exception):
59 """
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010060 Exception to indicate invalid file format.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010061 """
62 pass
63
64
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010065class FileWrapper(io.FileIO):
Azim Khan4b543232017-06-30 09:35:21 +010066 """
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010067 File wrapper class. Provides reading with line no. tracking.
Azim Khan4b543232017-06-30 09:35:21 +010068 """
69
70 def __init__(self, file_name):
71 """
72 Init file handle.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010073
Azim Khanf0e42fb2017-08-02 14:47:13 +010074 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +010075 """
76 super(FileWrapper, self).__init__(file_name, 'r')
77 self.line_no = 0
78
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010079 def __next__(self):
Azim Khan4b543232017-06-30 09:35:21 +010080 """
81 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010082 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010083 """
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010084 line = super(FileWrapper, self).__next__()
Azim Khan4b543232017-06-30 09:35:21 +010085 if line:
86 self.line_no += 1
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010087 # Convert byte array to string with correct encoding
88 return line.decode(sys.getdefaultencoding())
89 return None
Azim Khan4b543232017-06-30 09:35:21 +010090
91
92def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +010093 """
94 Split NOT character '!' from dependency. Used by gen_deps()
95
96 :param dep: Dependency list
97 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
98 """
Azim Khan4b543232017-06-30 09:35:21 +010099 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
100
101
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100102def gen_deps(deps):
103 """
104 Generates dependency i.e. if def and endif code
105
Azim Khanf0e42fb2017-08-02 14:47:13 +0100106 :param deps: List of dependencies.
107 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100108 """
Azim Khan4b543232017-06-30 09:35:21 +0100109 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
110 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
111
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100112 return dep_start, dep_end
113
114
115def gen_deps_one_line(deps):
116 """
117 Generates dependency checks in one line. Useful for writing code in #else case.
118
Azim Khanf0e42fb2017-08-02 14:47:13 +0100119 :param deps: List of dependencies.
120 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100121 """
Azim Khan4b543232017-06-30 09:35:21 +0100122 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
123 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100124
125
Azim Khan4b543232017-06-30 09:35:21 +0100126def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100127 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100128 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100129
Azim Khanf0e42fb2017-08-02 14:47:13 +0100130 :param name: Test function name
131 :param locals: Local variables declaration code
132 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
133 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100134 """
135 # Then create the wrapper
136 wrapper = '''
137void {name}_wrapper( void ** params )
138{{
139 {unused_params}
Azim Khan2397bba2017-06-09 04:35:03 +0100140{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100141 {name}( {args} );
142}}
Azim Khan4b543232017-06-30 09:35:21 +0100143'''.format(name=name, unused_params='(void)params;' if len(args_dispatch) == 0 else '',
144 args=', '.join(args_dispatch),
145 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100146 return wrapper
147
148
149def gen_dispatch(name, deps):
150 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100151 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100152
Azim Khanf0e42fb2017-08-02 14:47:13 +0100153 :param name: Test function name
154 :param deps: List of dependencies
155 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100156 """
157 if len(deps):
158 ifdef = gen_deps_one_line(deps)
159 dispatch_code = '''
160{ifdef}
161 {name}_wrapper,
162#else
163 NULL,
164#endif
165'''.format(ifdef=ifdef, name=name)
166 else:
167 dispatch_code = '''
168 {name}_wrapper,
169'''.format(name=name)
170
171 return dispatch_code
172
173
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000174def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100175 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000176 Parses function headers or helper code until end pattern.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100177
Azim Khanf0e42fb2017-08-02 14:47:13 +0100178 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000179 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100180 :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 Khanb5229292018-02-06 13:08:01 +0000184 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100185 break
186 headers += line
187 else:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000188 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100189
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 Khanb73159d2018-06-13 16:31:26 +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 Khanb73159d2018-06-13 16:31:26 +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
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100233
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 Khanb73159d2018-06-13 16:31:26 +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
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100322
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 = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000328 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100329 suite_deps = []
330 suite_functions = ''
331 func_info = {}
332 function_idx = 0
333 dispatch_code = ''
334 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100335 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000336 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100337 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000338 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
339 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
340 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100341 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100342 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100343 suite_deps += deps
344 elif re.search(BEGIN_CASE_REGEX, line):
345 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100346 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100347 suite_functions += func_code
348 # Generate dispatch code and enumeration info
349 assert func_name not in func_info, "file: %s - function %s re-declared at line %d" % \
Azim Khan4b543232017-06-30 09:35:21 +0100350 (funcs_f.name, func_name, funcs_f.line_no)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100351 func_info[func_name] = (function_idx, args)
352 dispatch_code += '/* Function Id: %d */\n' % function_idx
353 dispatch_code += func_dispatch
354 function_idx += 1
355
356 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000357 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100358 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100359
360
361def escaped_split(str, ch):
362 """
363 Split str on character ch but ignore escaped \{ch}
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100364 Since return value is used to write back to the intermediate data file.
Azim Khan599cd242017-07-06 17:34:27 +0100365 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100366
Azim Khanf0e42fb2017-08-02 14:47:13 +0100367 :param str: String to split
368 :param ch: split character
369 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100370 """
371 if len(ch) > 1:
372 raise ValueError('Expected split character. Found string!')
373 out = []
374 part = ''
375 escape = False
376 for i in range(len(str)):
377 if not escape and str[i] == ch:
378 out.append(part)
379 part = ''
380 else:
Azim Khanacc54732017-07-03 14:06:45 +0100381 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100382 escape = not escape and str[i] == '\\'
383 if len(part):
384 out.append(part)
385 return out
386
387
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100388def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100389 """
390 Parses .data file
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100391
Azim Khanf0e42fb2017-08-02 14:47:13 +0100392 :param data_f: file object of the data file.
393 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100394 """
395 STATE_READ_NAME = 0
396 STATE_READ_ARGS = 1
397 state = STATE_READ_NAME
398 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100399 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100400 for line in data_f:
401 line = line.strip()
402 if len(line) and line[0] == '#': # Skip comments
403 continue
404
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100405 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100406 if len(line) == 0:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100407 assert state != STATE_READ_ARGS, "Newline before arguments. " \
408 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100409 continue
410
411 if state == STATE_READ_NAME:
412 # Read test name
413 name = line
414 state = STATE_READ_ARGS
415 elif state == STATE_READ_ARGS:
416 # Check dependencies
417 m = re.search('depends_on\:(.*)', line)
418 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100419 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100420 else:
421 # Read test vectors
422 parts = escaped_split(line, ':')
423 function = parts[0]
424 args = parts[1:]
425 yield name, function, deps, args
426 deps = []
427 state = STATE_READ_NAME
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100428 assert state != STATE_READ_ARGS, "Newline before arguments. " \
429 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100430
431
432def gen_dep_check(dep_id, dep):
433 """
434 Generate code for the dependency.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100435
Azim Khanf0e42fb2017-08-02 14:47:13 +0100436 :param dep_id: Dependency identifier
437 :param dep: Dependency macro
438 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100439 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100440 assert dep_id > -1, "Dependency Id should be a positive integer."
441 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
442 assert len(dep) > 0, "Dependency should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100443 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100444 case {id}:
445 {{
Azim Khand61b8372017-07-10 11:54:01 +0100446#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100447 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100448#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100449 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100450#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100451 }}
452 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100453 return dep_check
454
455
456def gen_expression_check(exp_id, exp):
457 """
458 Generates code for expression check
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100459
Azim Khanf0e42fb2017-08-02 14:47:13 +0100460 :param exp_id: Expression Identifier
461 :param exp: Expression/Macro
462 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100463 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100464 assert exp_id > -1, "Expression Id should be a positive integer."
465 assert len(exp) > 0, "Expression should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100466 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100467 case {exp_id}:
468 {{
469 *out_value = {expression};
470 }}
471 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100472 return exp_code
473
474
Azim Khan599cd242017-07-06 17:34:27 +0100475def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100476 """
Azim Khan599cd242017-07-06 17:34:27 +0100477 Write dependencies to intermediate test data file.
478 It also returns dependency check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100479
Azim Khanf0e42fb2017-08-02 14:47:13 +0100480 :param out_data_f: Output intermediate data file
481 :param test_deps: Dependencies
482 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
483 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100484 """
Azim Khan599cd242017-07-06 17:34:27 +0100485 dep_check_code = ''
486 if len(test_deps):
487 out_data_f.write('depends_on')
488 for dep in test_deps:
489 if dep not in unique_deps:
490 unique_deps.append(dep)
491 dep_id = unique_deps.index(dep)
492 dep_check_code += gen_dep_check(dep_id, dep)
493 else:
494 dep_id = unique_deps.index(dep)
495 out_data_f.write(':' + str(dep_id))
496 out_data_f.write('\n')
497 return dep_check_code
498
499
500def write_parameters(out_data_f, test_args, func_args, unique_expressions):
501 """
502 Writes test parameters to the intermediate data file.
503 Also generates expression code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100504
Azim Khanf0e42fb2017-08-02 14:47:13 +0100505 :param out_data_f: Output intermediate data file
506 :param test_args: Test parameters
507 :param func_args: Function arguments
508 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
509 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100510 """
511 expression_code = ''
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100512 for i in range(len(test_args)):
Azim Khan599cd242017-07-06 17:34:27 +0100513 typ = func_args[i]
514 val = test_args[i]
515
516 # check if val is a non literal int val
517 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
518 typ = 'exp'
519 if val not in unique_expressions:
520 unique_expressions.append(val)
521 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
522 # use index().
523 exp_id = unique_expressions.index(val)
524 expression_code += gen_expression_check(exp_id, val)
525 val = exp_id
526 else:
527 val = unique_expressions.index(val)
528 out_data_f.write(':' + typ + ':' + str(val))
529 out_data_f.write('\n')
530 return expression_code
531
532
533def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
534 """
535 Adds preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100536
Azim Khanf0e42fb2017-08-02 14:47:13 +0100537 :param suite_deps: Test suite dependencies read from the .functions file.
538 :param dep_check_code: Dependency check code
539 :param expression_code: Expression check code
540 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100541 """
Azim Khan599cd242017-07-06 17:34:27 +0100542 if len(suite_deps):
543 ifdef = gen_deps_one_line(suite_deps)
544 dep_check_code = '''
545{ifdef}
546{code}
Azim Khan599cd242017-07-06 17:34:27 +0100547#endif
548'''.format(ifdef=ifdef, code=dep_check_code)
549 expression_code = '''
550{ifdef}
551{code}
Azim Khan599cd242017-07-06 17:34:27 +0100552#endif
553'''.format(ifdef=ifdef, code=expression_code)
554 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100555
556
Azim Khan13c6bfb2017-06-15 14:45:56 +0100557def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100558 """
559 Generates dependency checks, expression code and intermediate data file from test data file.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100560
Azim Khanf0e42fb2017-08-02 14:47:13 +0100561 :param data_f: Data file object
562 :param out_data_f:Output intermediate data file
563 :param func_info: Dict keyed by function and with function id and arguments info
564 :param suite_deps: Test suite deps
565 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100566 """
567 unique_deps = []
568 unique_expressions = []
569 dep_check_code = ''
570 expression_code = ''
571 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
572 out_data_f.write(test_name + '\n')
573
Azim Khan599cd242017-07-06 17:34:27 +0100574 # Write deps
575 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100576
Azim Khan599cd242017-07-06 17:34:27 +0100577 # Write test function name
578 test_function_name = 'test_' + function_name
579 assert test_function_name in func_info, "Function %s not found!" % test_function_name
580 func_id, func_args = func_info[test_function_name]
581 out_data_f.write(str(func_id))
582
583 # Write parameters
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100584 assert len(test_args) == len(func_args), \
585 "Invalid number of arguments in test %s. See function %s signature." % (test_name, function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100586 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100587
Azim Khan599cd242017-07-06 17:34:27 +0100588 # Write a newline as test case separator
589 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100590
Azim Khan599cd242017-07-06 17:34:27 +0100591 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100592 return dep_check_code, expression_code
593
594
Azim Khan1de892b2017-06-09 15:02:36 +0100595def 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 +0100596 """
597 Generate mbed-os test code.
598
Azim Khanf0e42fb2017-08-02 14:47:13 +0100599 :param funcs_file: Functions file object
600 :param data_file: Data file object
601 :param template_file: Template file object
602 :param platform_file: Platform file object
603 :param help_file: Helper functions file object
604 :param suites_dir: Test suites dir
605 :param c_file: Output C file object
606 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100607 :return:
608 """
609 for name, path in [('Functions file', funcs_file),
610 ('Data file', data_file),
611 ('Template file', template_file),
612 ('Platform file', platform_file),
613 ('Help code file', help_file),
614 ('Suites dir', suites_dir)]:
615 if not os.path.exists(path):
616 raise IOError("ERROR: %s [%s] not found!" % (name, path))
617
618 snippets = {'generator_script' : os.path.basename(__file__)}
619
620 # Read helpers
621 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
622 snippets['test_common_helper_file'] = help_file
623 snippets['test_common_helpers'] = help_f.read()
624 snippets['test_platform_file'] = platform_file
625 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
626 out_data_file.replace('\\', '\\\\')) # escape '\'
627
628 # Function code
Azim Khanacc54732017-07-03 14:06:45 +0100629 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 +0100630 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100631 snippets['functions_code'] = func_code
632 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100633 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 +0100634 snippets['dep_check_code'] = dep_check_code
635 snippets['expression_code'] = expression_code
636
637 snippets['test_file'] = c_file
638 snippets['test_main_file'] = template_file
639 snippets['test_case_file'] = funcs_file
640 snippets['test_case_data_file'] = data_file
641 # Read Template
642 # Add functions
643 #
644 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
645 line_no = 1
646 for line in template_f.readlines():
647 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
648 code = line.format(**snippets)
649 c_f.write(code)
650 line_no += 1
651
652
653def check_cmd():
654 """
655 Command line parser.
656
657 :return:
658 """
659 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
660
661 parser.add_argument("-f", "--functions-file",
662 dest="funcs_file",
663 help="Functions file",
664 metavar="FUNCTIONS",
665 required=True)
666
667 parser.add_argument("-d", "--data-file",
668 dest="data_file",
669 help="Data file",
670 metavar="DATA",
671 required=True)
672
673 parser.add_argument("-t", "--template-file",
674 dest="template_file",
675 help="Template file",
676 metavar="TEMPLATE",
677 required=True)
678
679 parser.add_argument("-s", "--suites-dir",
680 dest="suites_dir",
681 help="Suites dir",
682 metavar="SUITES",
683 required=True)
684
685 parser.add_argument("--help-file",
686 dest="help_file",
687 help="Help file",
688 metavar="HELPER",
689 required=True)
690
691 parser.add_argument("-p", "--platform-file",
692 dest="platform_file",
693 help="Platform code file",
694 metavar="PLATFORM_FILE",
695 required=True)
696
697 parser.add_argument("-o", "--out-dir",
698 dest="out_dir",
699 help="Dir where generated code and scripts are copied",
700 metavar="OUT_DIR",
701 required=True)
702
703 args = parser.parse_args()
704
705 data_file_name = os.path.basename(args.data_file)
706 data_name = os.path.splitext(data_file_name)[0]
707
708 out_c_file = os.path.join(args.out_dir, data_name + '.c')
709 out_data_file = os.path.join(args.out_dir, data_file_name)
710
711 out_c_file_dir = os.path.dirname(out_c_file)
712 out_data_file_dir = os.path.dirname(out_data_file)
713 for d in [out_c_file_dir, out_data_file_dir]:
714 if not os.path.exists(d):
715 os.makedirs(d)
716
Azim Khan1de892b2017-06-09 15:02:36 +0100717 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100718 args.help_file, args.suites_dir, out_c_file, out_data_file)
719
720
721if __name__ == "__main__":
722 check_cmd()