blob: ccb2d5fe17654c282baa70089b96b2a67a4c6afd [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 Khan3b06f222018-06-26 14:35:25 +010065class GeneratorInputError(Exception):
66 """
67 Exception to indicate error in the input to the generator.
68 """
69 pass
70
71
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010072class FileWrapper(io.FileIO):
Azim Khan4b543232017-06-30 09:35:21 +010073 """
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010074 File wrapper class. Provides reading with line no. tracking.
Azim Khan4b543232017-06-30 09:35:21 +010075 """
76
77 def __init__(self, file_name):
78 """
79 Init file handle.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010080
Azim Khanf0e42fb2017-08-02 14:47:13 +010081 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +010082 """
83 super(FileWrapper, self).__init__(file_name, 'r')
84 self.line_no = 0
85
Gilles Peskine667f7f82018-06-18 17:51:56 +020086 # Override the generator function in a way that works in both Python 2
87 # and Python 3.
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010088 def __next__(self):
Azim Khan4b543232017-06-30 09:35:21 +010089 """
90 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010091 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010092 """
Gilles Peskine667f7f82018-06-18 17:51:56 +020093 parent = super(FileWrapper, self)
94 if hasattr(parent, '__next__'):
95 line = parent.__next__() # Python 3
96 else:
97 line = parent.next() # Python 2
Azim Khan4b543232017-06-30 09:35:21 +010098 if line:
99 self.line_no += 1
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100100 # Convert byte array to string with correct encoding
101 return line.decode(sys.getdefaultencoding())
102 return None
Gilles Peskine667f7f82018-06-18 17:51:56 +0200103 next = __next__
Azim Khan4b543232017-06-30 09:35:21 +0100104
105
106def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100107 """
108 Split NOT character '!' from dependency. Used by gen_deps()
109
110 :param dep: Dependency list
111 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
112 """
Azim Khan4b543232017-06-30 09:35:21 +0100113 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
114
115
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100116def gen_deps(deps):
117 """
118 Generates dependency i.e. if def and endif code
119
Azim Khanf0e42fb2017-08-02 14:47:13 +0100120 :param deps: List of dependencies.
121 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100122 """
Azim Khan4b543232017-06-30 09:35:21 +0100123 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
124 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
125
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100126 return dep_start, dep_end
127
128
129def gen_deps_one_line(deps):
130 """
131 Generates dependency checks in one line. Useful for writing code in #else case.
132
Azim Khanf0e42fb2017-08-02 14:47:13 +0100133 :param deps: List of dependencies.
134 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100135 """
Azim Khan4b543232017-06-30 09:35:21 +0100136 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
137 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100138
139
Azim Khan4b543232017-06-30 09:35:21 +0100140def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100141 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100142 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100143
Azim Khanf0e42fb2017-08-02 14:47:13 +0100144 :param name: Test function name
145 :param locals: Local variables declaration code
146 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
147 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100148 """
149 # Then create the wrapper
150 wrapper = '''
151void {name}_wrapper( void ** params )
152{{
Gilles Peskine77761412018-06-18 17:51:40 +0200153{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100154 {name}( {args} );
155}}
Gilles Peskine77761412018-06-18 17:51:40 +0200156'''.format(name=name,
Mohammad Azim Khanc3521df2018-06-26 14:06:52 +0100157 unused_params='' if args_dispatch else ' (void)params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100158 args=', '.join(args_dispatch),
159 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100160 return wrapper
161
162
163def gen_dispatch(name, deps):
164 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100165 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100166
Azim Khanf0e42fb2017-08-02 14:47:13 +0100167 :param name: Test function name
168 :param deps: List of dependencies
169 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100170 """
171 if len(deps):
172 ifdef = gen_deps_one_line(deps)
173 dispatch_code = '''
174{ifdef}
175 {name}_wrapper,
176#else
177 NULL,
178#endif
179'''.format(ifdef=ifdef, name=name)
180 else:
181 dispatch_code = '''
182 {name}_wrapper,
183'''.format(name=name)
184
185 return dispatch_code
186
187
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000188def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100189 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000190 Parses function headers or helper code until end pattern.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100191
Azim Khanf0e42fb2017-08-02 14:47:13 +0100192 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000193 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100194 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100195 """
Azim Khan4b543232017-06-30 09:35:21 +0100196 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100197 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000198 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100199 break
200 headers += line
201 else:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000202 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100203
Azim Khan4b543232017-06-30 09:35:21 +0100204 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100205
206
Azim Khan4b543232017-06-30 09:35:21 +0100207def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100208 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100209 Parses test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100210
Azim Khanf0e42fb2017-08-02 14:47:13 +0100211 :param funcs_f: file object for .functions file
212 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100213 """
214 deps = []
215 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100216 m = re.search('depends_on\:(.*)', line.strip())
217 if m:
218 deps += [x.strip() for x in m.group(1).split(':')]
219 if re.search(END_DEP_REGEX, line):
220 break
221 else:
222 raise InvalidFileFormat("file: %s - end dependency pattern [%s] not found!" % (funcs_f.name, END_DEP_REGEX))
223
Azim Khan4b543232017-06-30 09:35:21 +0100224 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100225
226
227def parse_function_deps(line):
228 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100229 Parses function dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100230
Azim Khanf0e42fb2017-08-02 14:47:13 +0100231 :param line: Line from .functions file that has dependencies.
232 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100233 """
234 deps = []
235 m = re.search(BEGIN_CASE_REGEX, line)
236 dep_str = m.group(1)
237 if len(dep_str):
238 m = re.search('depends_on:(.*)', dep_str)
239 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100240 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100241 return deps
242
243
244def parse_function_signature(line):
245 """
246 Parsing function signature
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100247
Azim Khanf0e42fb2017-08-02 14:47:13 +0100248 :param line: Line from .functions file that has a function signature.
249 :return: function name, argument list, local variables for wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100250 """
251 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100252 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100253 args_dispatch = []
254 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
255 if not m:
256 raise ValueError("Test function should return 'void'\n%s" % line)
257 name = m.group(1)
258 line = line[len(m.group(0)):]
259 arg_idx = 0
260 for arg in line[:line.find(')')].split(','):
261 arg = arg.strip()
262 if arg == '':
263 continue
264 if re.search('int\s+.*', arg.strip()):
265 args.append('int')
266 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
267 elif re.search('char\s*\*\s*.*', arg.strip()):
268 args.append('char*')
269 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100270 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100271 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100272 # create a structure
273 locals += """ HexParam_t hex%d = {%s, %s};
274""" % (arg_idx, '(uint8_t *) params[%d]' % arg_idx, '*( (uint32_t *) params[%d] )' % (arg_idx + 1))
275
276 args_dispatch.append('&hex%d' % arg_idx)
277 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100278 else:
Azim Khan4b543232017-06-30 09:35:21 +0100279 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100280 arg_idx += 1
281
Azim Khan4b543232017-06-30 09:35:21 +0100282 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100283
284
Azim Khan4b543232017-06-30 09:35:21 +0100285def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100286 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100287 Parses out a function from function file object and generates function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100288
Azim Khanf0e42fb2017-08-02 14:47:13 +0100289 :param funcs_f: file object of the functions file.
290 :param deps: List of dependencies
291 :param suite_deps: List of test suite dependencies
292 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100293 """
Azim Khan4b543232017-06-30 09:35:21 +0100294 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100295 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100296 # Check function signature
297 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
298 if m:
299 # check if we have full signature i.e. split in more lines
300 if not re.match('.*\)', line):
301 for lin in funcs_f:
302 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100303 if re.search('.*?\)', line):
304 break
Azim Khan4b543232017-06-30 09:35:21 +0100305 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100306 code += line.replace(name, 'test_' + name)
307 name = 'test_' + name
308 break
309 else:
310 raise InvalidFileFormat("file: %s - Test functions not found!" % funcs_f.name)
311
312 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100313 if re.search(END_CASE_REGEX, line):
314 break
315 code += line
316 else:
317 raise InvalidFileFormat("file: %s - end case pattern [%s] not found!" % (funcs_f.name, END_CASE_REGEX))
318
319 # Add exit label if not present
320 if code.find('exit:') == -1:
321 s = code.rsplit('}', 1)
322 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100323 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100324 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100325}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100326
Azim Khan4b543232017-06-30 09:35:21 +0100327 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100328 ifdef, endif = gen_deps(deps)
329 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100330 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100331
332
333def parse_functions(funcs_f):
334 """
335 Returns functions code pieces
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100336
Azim Khanf0e42fb2017-08-02 14:47:13 +0100337 :param funcs_f: file object of the functions file.
338 :return: List of test suite dependencies, test function dispatch code, function code and
339 a dict with function identifiers and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100340 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100341 suite_headers = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000342 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100343 suite_deps = []
344 suite_functions = ''
345 func_info = {}
346 function_idx = 0
347 dispatch_code = ''
348 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100349 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000350 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100351 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000352 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
353 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
354 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100355 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100356 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100357 suite_deps += deps
358 elif re.search(BEGIN_CASE_REGEX, line):
359 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100360 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100361 suite_functions += func_code
362 # Generate dispatch code and enumeration info
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100363 if func_name in func_info:
364 raise GeneratorInputError(
365 "file: %s - function %s re-declared at line %d" % \
366 (funcs_f.name, func_name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100367 func_info[func_name] = (function_idx, args)
368 dispatch_code += '/* Function Id: %d */\n' % function_idx
369 dispatch_code += func_dispatch
370 function_idx += 1
371
372 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000373 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100374 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100375
376
377def escaped_split(str, ch):
378 """
379 Split str on character ch but ignore escaped \{ch}
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100380 Since return value is used to write back to the intermediate data file.
Azim Khan599cd242017-07-06 17:34:27 +0100381 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100382
Azim Khanf0e42fb2017-08-02 14:47:13 +0100383 :param str: String to split
384 :param ch: split character
385 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100386 """
387 if len(ch) > 1:
388 raise ValueError('Expected split character. Found string!')
389 out = []
390 part = ''
391 escape = False
392 for i in range(len(str)):
393 if not escape and str[i] == ch:
394 out.append(part)
395 part = ''
396 else:
Azim Khanacc54732017-07-03 14:06:45 +0100397 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100398 escape = not escape and str[i] == '\\'
399 if len(part):
400 out.append(part)
401 return out
402
403
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100404def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100405 """
406 Parses .data file
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100407
Azim Khanf0e42fb2017-08-02 14:47:13 +0100408 :param data_f: file object of the data file.
409 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100410 """
411 STATE_READ_NAME = 0
412 STATE_READ_ARGS = 1
413 state = STATE_READ_NAME
414 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100415 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100416 for line in data_f:
417 line = line.strip()
418 if len(line) and line[0] == '#': # Skip comments
419 continue
420
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100421 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100422 if len(line) == 0:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100423 if state == STATE_READ_ARGS:
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100424 raise GeneratorInputError("[%s:%d] Newline before arguments. " \
425 "Test function and arguments missing for %s" % \
426 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100427 continue
428
429 if state == STATE_READ_NAME:
430 # Read test name
431 name = line
432 state = STATE_READ_ARGS
433 elif state == STATE_READ_ARGS:
434 # Check dependencies
435 m = re.search('depends_on\:(.*)', line)
436 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100437 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100438 else:
439 # Read test vectors
440 parts = escaped_split(line, ':')
441 function = parts[0]
442 args = parts[1:]
443 yield name, function, deps, args
444 deps = []
445 state = STATE_READ_NAME
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100446 if state == STATE_READ_ARGS:
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100447 raise GeneratorInputError("[%s:%d] Newline before arguments. " \
448 "Test function and arguments missing for %s" % \
449 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100450
451
452def gen_dep_check(dep_id, dep):
453 """
454 Generate code for the dependency.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100455
Azim Khanf0e42fb2017-08-02 14:47:13 +0100456 :param dep_id: Dependency identifier
457 :param dep: Dependency macro
458 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100459 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100460 if dep_id < 0:
461 raise GeneratorInputError("Dependency Id should be a positive integer.")
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100462 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100463 if len(dep) == 0:
464 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100465 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100466 case {id}:
467 {{
Azim Khand61b8372017-07-10 11:54:01 +0100468#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100469 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100470#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100471 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100472#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100473 }}
474 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100475 return dep_check
476
477
478def gen_expression_check(exp_id, exp):
479 """
480 Generates code for expression check
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100481
Azim Khanf0e42fb2017-08-02 14:47:13 +0100482 :param exp_id: Expression Identifier
483 :param exp: Expression/Macro
484 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100485 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100486 if exp_id < 0:
487 raise GeneratorInputError("Expression Id should be a positive integer.")
488 if len(exp) == 0:
489 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100490 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100491 case {exp_id}:
492 {{
493 *out_value = {expression};
494 }}
495 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100496 return exp_code
497
498
Azim Khan599cd242017-07-06 17:34:27 +0100499def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100500 """
Azim Khan599cd242017-07-06 17:34:27 +0100501 Write dependencies to intermediate test data file.
502 It also returns dependency check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100503
Azim Khanf0e42fb2017-08-02 14:47:13 +0100504 :param out_data_f: Output intermediate data file
505 :param test_deps: Dependencies
506 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
507 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100508 """
Azim Khan599cd242017-07-06 17:34:27 +0100509 dep_check_code = ''
510 if len(test_deps):
511 out_data_f.write('depends_on')
512 for dep in test_deps:
513 if dep not in unique_deps:
514 unique_deps.append(dep)
515 dep_id = unique_deps.index(dep)
516 dep_check_code += gen_dep_check(dep_id, dep)
517 else:
518 dep_id = unique_deps.index(dep)
519 out_data_f.write(':' + str(dep_id))
520 out_data_f.write('\n')
521 return dep_check_code
522
523
524def write_parameters(out_data_f, test_args, func_args, unique_expressions):
525 """
526 Writes test parameters to the intermediate data file.
527 Also generates expression code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100528
Azim Khanf0e42fb2017-08-02 14:47:13 +0100529 :param out_data_f: Output intermediate data file
530 :param test_args: Test parameters
531 :param func_args: Function arguments
532 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
533 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100534 """
535 expression_code = ''
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100536 for i in range(len(test_args)):
Azim Khan599cd242017-07-06 17:34:27 +0100537 typ = func_args[i]
538 val = test_args[i]
539
540 # check if val is a non literal int val
541 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
542 typ = 'exp'
543 if val not in unique_expressions:
544 unique_expressions.append(val)
545 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
546 # use index().
547 exp_id = unique_expressions.index(val)
548 expression_code += gen_expression_check(exp_id, val)
549 val = exp_id
550 else:
551 val = unique_expressions.index(val)
552 out_data_f.write(':' + typ + ':' + str(val))
553 out_data_f.write('\n')
554 return expression_code
555
556
557def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
558 """
559 Adds preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100560
Azim Khanf0e42fb2017-08-02 14:47:13 +0100561 :param suite_deps: Test suite dependencies read from the .functions file.
562 :param dep_check_code: Dependency check code
563 :param expression_code: Expression check code
564 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100565 """
Azim Khan599cd242017-07-06 17:34:27 +0100566 if len(suite_deps):
567 ifdef = gen_deps_one_line(suite_deps)
568 dep_check_code = '''
569{ifdef}
570{code}
Azim Khan599cd242017-07-06 17:34:27 +0100571#endif
572'''.format(ifdef=ifdef, code=dep_check_code)
573 expression_code = '''
574{ifdef}
575{code}
Azim Khan599cd242017-07-06 17:34:27 +0100576#endif
577'''.format(ifdef=ifdef, code=expression_code)
578 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100579
580
Azim Khan13c6bfb2017-06-15 14:45:56 +0100581def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100582 """
583 Generates dependency checks, expression code and intermediate data file from test data file.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100584
Azim Khanf0e42fb2017-08-02 14:47:13 +0100585 :param data_f: Data file object
586 :param out_data_f:Output intermediate data file
587 :param func_info: Dict keyed by function and with function id and arguments info
588 :param suite_deps: Test suite deps
589 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100590 """
591 unique_deps = []
592 unique_expressions = []
593 dep_check_code = ''
594 expression_code = ''
595 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
596 out_data_f.write(test_name + '\n')
597
Azim Khan599cd242017-07-06 17:34:27 +0100598 # Write deps
599 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100600
Azim Khan599cd242017-07-06 17:34:27 +0100601 # Write test function name
602 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100603 if test_function_name not in func_info:
604 raise GeneratorInputError("Function %s not found!" % test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100605 func_id, func_args = func_info[test_function_name]
606 out_data_f.write(str(func_id))
607
608 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100609 if len(test_args) != len(func_args):
610 raise GeneratorInputError("Invalid number of arguments in test %s. See function %s signature." % (test_name,
611 function_name))
Azim Khan599cd242017-07-06 17:34:27 +0100612 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100613
Azim Khan599cd242017-07-06 17:34:27 +0100614 # Write a newline as test case separator
615 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100616
Azim Khan599cd242017-07-06 17:34:27 +0100617 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100618 return dep_check_code, expression_code
619
620
Azim Khan1de892b2017-06-09 15:02:36 +0100621def 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 +0100622 """
623 Generate mbed-os test code.
624
Azim Khanf0e42fb2017-08-02 14:47:13 +0100625 :param funcs_file: Functions file object
626 :param data_file: Data file object
627 :param template_file: Template file object
628 :param platform_file: Platform file object
629 :param help_file: Helper functions file object
630 :param suites_dir: Test suites dir
631 :param c_file: Output C file object
632 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100633 :return:
634 """
635 for name, path in [('Functions file', funcs_file),
636 ('Data file', data_file),
637 ('Template file', template_file),
638 ('Platform file', platform_file),
639 ('Help code file', help_file),
640 ('Suites dir', suites_dir)]:
641 if not os.path.exists(path):
642 raise IOError("ERROR: %s [%s] not found!" % (name, path))
643
644 snippets = {'generator_script' : os.path.basename(__file__)}
645
646 # Read helpers
647 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
648 snippets['test_common_helper_file'] = help_file
649 snippets['test_common_helpers'] = help_f.read()
650 snippets['test_platform_file'] = platform_file
651 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
652 out_data_file.replace('\\', '\\\\')) # escape '\'
653
654 # Function code
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100655 with FileWrapper(funcs_file) as funcs_f, FileWrapper(data_file) as data_f, open(out_data_file, 'w') as out_data_f:
Azim Khan13c6bfb2017-06-15 14:45:56 +0100656 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100657 snippets['functions_code'] = func_code
658 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100659 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 +0100660 snippets['dep_check_code'] = dep_check_code
661 snippets['expression_code'] = expression_code
662
663 snippets['test_file'] = c_file
664 snippets['test_main_file'] = template_file
665 snippets['test_case_file'] = funcs_file
666 snippets['test_case_data_file'] = data_file
667 # Read Template
668 # Add functions
669 #
670 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
671 line_no = 1
672 for line in template_f.readlines():
673 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
674 code = line.format(**snippets)
675 c_f.write(code)
676 line_no += 1
677
678
679def check_cmd():
680 """
681 Command line parser.
682
683 :return:
684 """
685 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
686
687 parser.add_argument("-f", "--functions-file",
688 dest="funcs_file",
689 help="Functions file",
690 metavar="FUNCTIONS",
691 required=True)
692
693 parser.add_argument("-d", "--data-file",
694 dest="data_file",
695 help="Data file",
696 metavar="DATA",
697 required=True)
698
699 parser.add_argument("-t", "--template-file",
700 dest="template_file",
701 help="Template file",
702 metavar="TEMPLATE",
703 required=True)
704
705 parser.add_argument("-s", "--suites-dir",
706 dest="suites_dir",
707 help="Suites dir",
708 metavar="SUITES",
709 required=True)
710
711 parser.add_argument("--help-file",
712 dest="help_file",
713 help="Help file",
714 metavar="HELPER",
715 required=True)
716
717 parser.add_argument("-p", "--platform-file",
718 dest="platform_file",
719 help="Platform code file",
720 metavar="PLATFORM_FILE",
721 required=True)
722
723 parser.add_argument("-o", "--out-dir",
724 dest="out_dir",
725 help="Dir where generated code and scripts are copied",
726 metavar="OUT_DIR",
727 required=True)
728
729 args = parser.parse_args()
730
731 data_file_name = os.path.basename(args.data_file)
732 data_name = os.path.splitext(data_file_name)[0]
733
734 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +0100735 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100736
737 out_c_file_dir = os.path.dirname(out_c_file)
738 out_data_file_dir = os.path.dirname(out_data_file)
739 for d in [out_c_file_dir, out_data_file_dir]:
740 if not os.path.exists(d):
741 os.makedirs(d)
742
Azim Khan1de892b2017-06-09 15:02:36 +0100743 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100744 args.help_file, args.suites_dir, out_c_file, out_data_file)
745
746
747if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100748 try:
749 check_cmd()
750 except GeneratorInputError as e:
751 script_name = os.path.basename(sys.argv[0])
752 print("%s: input error: %s" % (script_name, str(e)))