blob: 33da990df6352afdb81d86286b66af6109342cea [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
Azim Khan936ea932018-06-28 16:47:12 +0100100 # Convert byte array to string with correct encoding and
101 # strip any whitespaces added in the decoding process.
102 return line.decode(sys.getdefaultencoding()).strip() + "\n"
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100103 return None
Gilles Peskine667f7f82018-06-18 17:51:56 +0200104 next = __next__
Azim Khan4b543232017-06-30 09:35:21 +0100105
106
107def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100108 """
109 Split NOT character '!' from dependency. Used by gen_deps()
110
111 :param dep: Dependency list
112 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
113 """
Azim Khan4b543232017-06-30 09:35:21 +0100114 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
115
116
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100117def gen_deps(deps):
118 """
119 Generates dependency i.e. if def and endif code
120
Azim Khanf0e42fb2017-08-02 14:47:13 +0100121 :param deps: List of dependencies.
122 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100123 """
Azim Khan4b543232017-06-30 09:35:21 +0100124 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
125 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
126
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100127 return dep_start, dep_end
128
129
130def gen_deps_one_line(deps):
131 """
132 Generates dependency checks in one line. Useful for writing code in #else case.
133
Azim Khanf0e42fb2017-08-02 14:47:13 +0100134 :param deps: List of dependencies.
135 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100136 """
Azim Khan4b543232017-06-30 09:35:21 +0100137 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
138 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100139
140
Azim Khan4b543232017-06-30 09:35:21 +0100141def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100142 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100143 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100144
Azim Khanf0e42fb2017-08-02 14:47:13 +0100145 :param name: Test function name
146 :param locals: Local variables declaration code
147 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
148 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100149 """
150 # Then create the wrapper
151 wrapper = '''
152void {name}_wrapper( void ** params )
153{{
Gilles Peskine77761412018-06-18 17:51:40 +0200154{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100155 {name}( {args} );
156}}
Gilles Peskine77761412018-06-18 17:51:40 +0200157'''.format(name=name,
Mohammad Azim Khanc3521df2018-06-26 14:06:52 +0100158 unused_params='' if args_dispatch else ' (void)params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100159 args=', '.join(args_dispatch),
160 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100161 return wrapper
162
163
164def gen_dispatch(name, deps):
165 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100166 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100167
Azim Khanf0e42fb2017-08-02 14:47:13 +0100168 :param name: Test function name
169 :param deps: List of dependencies
170 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100171 """
172 if len(deps):
173 ifdef = gen_deps_one_line(deps)
174 dispatch_code = '''
175{ifdef}
176 {name}_wrapper,
177#else
178 NULL,
179#endif
180'''.format(ifdef=ifdef, name=name)
181 else:
182 dispatch_code = '''
183 {name}_wrapper,
184'''.format(name=name)
185
186 return dispatch_code
187
188
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000189def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100190 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000191 Parses function headers or helper code until end pattern.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100192
Azim Khanf0e42fb2017-08-02 14:47:13 +0100193 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000194 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100195 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100196 """
Azim Khan4b543232017-06-30 09:35:21 +0100197 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100198 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000199 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100200 break
201 headers += line
202 else:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000203 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100204
Azim Khan4b543232017-06-30 09:35:21 +0100205 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100206
207
Azim Khan4b543232017-06-30 09:35:21 +0100208def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100209 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100210 Parses test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100211
Azim Khanf0e42fb2017-08-02 14:47:13 +0100212 :param funcs_f: file object for .functions file
213 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100214 """
215 deps = []
216 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100217 m = re.search('depends_on\:(.*)', line.strip())
218 if m:
219 deps += [x.strip() for x in m.group(1).split(':')]
220 if re.search(END_DEP_REGEX, line):
221 break
222 else:
223 raise InvalidFileFormat("file: %s - end dependency pattern [%s] not found!" % (funcs_f.name, END_DEP_REGEX))
224
Azim Khan4b543232017-06-30 09:35:21 +0100225 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100226
227
228def parse_function_deps(line):
229 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100230 Parses function dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100231
Azim Khanf0e42fb2017-08-02 14:47:13 +0100232 :param line: Line from .functions file that has dependencies.
233 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100234 """
235 deps = []
236 m = re.search(BEGIN_CASE_REGEX, line)
237 dep_str = m.group(1)
238 if len(dep_str):
239 m = re.search('depends_on:(.*)', dep_str)
240 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100241 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100242 return deps
243
244
245def parse_function_signature(line):
246 """
247 Parsing function signature
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100248
Azim Khanf0e42fb2017-08-02 14:47:13 +0100249 :param line: Line from .functions file that has a function signature.
250 :return: function name, argument list, local variables for wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100251 """
252 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100253 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100254 args_dispatch = []
255 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
256 if not m:
257 raise ValueError("Test function should return 'void'\n%s" % line)
258 name = m.group(1)
259 line = line[len(m.group(0)):]
260 arg_idx = 0
261 for arg in line[:line.find(')')].split(','):
262 arg = arg.strip()
263 if arg == '':
264 continue
265 if re.search('int\s+.*', arg.strip()):
266 args.append('int')
267 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
268 elif re.search('char\s*\*\s*.*', arg.strip()):
269 args.append('char*')
270 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100271 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100272 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100273 # create a structure
274 locals += """ HexParam_t hex%d = {%s, %s};
275""" % (arg_idx, '(uint8_t *) params[%d]' % arg_idx, '*( (uint32_t *) params[%d] )' % (arg_idx + 1))
276
277 args_dispatch.append('&hex%d' % arg_idx)
278 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100279 else:
Azim Khan4b543232017-06-30 09:35:21 +0100280 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100281 arg_idx += 1
282
Azim Khan4b543232017-06-30 09:35:21 +0100283 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100284
285
Azim Khan4b543232017-06-30 09:35:21 +0100286def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100287 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100288 Parses out a function from function file object and generates function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100289
Azim Khanf0e42fb2017-08-02 14:47:13 +0100290 :param funcs_f: file object of the functions file.
291 :param deps: List of dependencies
292 :param suite_deps: List of test suite dependencies
293 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100294 """
Azim Khan4b543232017-06-30 09:35:21 +0100295 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100296 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100297 # Check function signature
298 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
299 if m:
300 # check if we have full signature i.e. split in more lines
301 if not re.match('.*\)', line):
302 for lin in funcs_f:
303 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100304 if re.search('.*?\)', line):
305 break
Azim Khan4b543232017-06-30 09:35:21 +0100306 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100307 code += line.replace(name, 'test_' + name)
308 name = 'test_' + name
309 break
310 else:
311 raise InvalidFileFormat("file: %s - Test functions not found!" % funcs_f.name)
312
313 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100314 if re.search(END_CASE_REGEX, line):
315 break
316 code += line
317 else:
318 raise InvalidFileFormat("file: %s - end case pattern [%s] not found!" % (funcs_f.name, END_CASE_REGEX))
319
320 # Add exit label if not present
321 if code.find('exit:') == -1:
322 s = code.rsplit('}', 1)
323 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100324 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100325 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100326}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100327
Azim Khan4b543232017-06-30 09:35:21 +0100328 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100329 ifdef, endif = gen_deps(deps)
330 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100331 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100332
333
334def parse_functions(funcs_f):
335 """
336 Returns functions code pieces
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100337
Azim Khanf0e42fb2017-08-02 14:47:13 +0100338 :param funcs_f: file object of the functions file.
339 :return: List of test suite dependencies, test function dispatch code, function code and
340 a dict with function identifiers and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100341 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100342 suite_headers = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000343 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100344 suite_deps = []
345 suite_functions = ''
346 func_info = {}
347 function_idx = 0
348 dispatch_code = ''
349 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100350 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000351 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100352 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000353 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
354 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
355 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100356 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100357 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100358 suite_deps += deps
359 elif re.search(BEGIN_CASE_REGEX, line):
360 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100361 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100362 suite_functions += func_code
363 # Generate dispatch code and enumeration info
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100364 if func_name in func_info:
365 raise GeneratorInputError(
366 "file: %s - function %s re-declared at line %d" % \
367 (funcs_f.name, func_name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100368 func_info[func_name] = (function_idx, args)
369 dispatch_code += '/* Function Id: %d */\n' % function_idx
370 dispatch_code += func_dispatch
371 function_idx += 1
372
373 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000374 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100375 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100376
377
378def escaped_split(str, ch):
379 """
380 Split str on character ch but ignore escaped \{ch}
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100381 Since return value is used to write back to the intermediate data file.
Azim Khan599cd242017-07-06 17:34:27 +0100382 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100383
Azim Khanf0e42fb2017-08-02 14:47:13 +0100384 :param str: String to split
385 :param ch: split character
386 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100387 """
388 if len(ch) > 1:
389 raise ValueError('Expected split character. Found string!')
390 out = []
391 part = ''
392 escape = False
393 for i in range(len(str)):
394 if not escape and str[i] == ch:
395 out.append(part)
396 part = ''
397 else:
Azim Khanacc54732017-07-03 14:06:45 +0100398 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100399 escape = not escape and str[i] == '\\'
400 if len(part):
401 out.append(part)
402 return out
403
404
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100405def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100406 """
407 Parses .data file
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100408
Azim Khanf0e42fb2017-08-02 14:47:13 +0100409 :param data_f: file object of the data file.
410 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100411 """
412 STATE_READ_NAME = 0
413 STATE_READ_ARGS = 1
414 state = STATE_READ_NAME
415 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100416 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100417 for line in data_f:
418 line = line.strip()
419 if len(line) and line[0] == '#': # Skip comments
420 continue
421
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100422 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100423 if len(line) == 0:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100424 if state == STATE_READ_ARGS:
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100425 raise GeneratorInputError("[%s:%d] Newline before arguments. " \
426 "Test function and arguments missing for %s" % \
427 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100428 continue
429
430 if state == STATE_READ_NAME:
431 # Read test name
432 name = line
433 state = STATE_READ_ARGS
434 elif state == STATE_READ_ARGS:
435 # Check dependencies
436 m = re.search('depends_on\:(.*)', line)
437 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100438 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100439 else:
440 # Read test vectors
441 parts = escaped_split(line, ':')
442 function = parts[0]
443 args = parts[1:]
444 yield name, function, deps, args
445 deps = []
446 state = STATE_READ_NAME
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100447 if state == STATE_READ_ARGS:
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100448 raise GeneratorInputError("[%s:%d] Newline before arguments. " \
449 "Test function and arguments missing for %s" % \
450 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100451
452
453def gen_dep_check(dep_id, dep):
454 """
455 Generate code for the dependency.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100456
Azim Khanf0e42fb2017-08-02 14:47:13 +0100457 :param dep_id: Dependency identifier
458 :param dep: Dependency macro
459 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100460 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100461 if dep_id < 0:
462 raise GeneratorInputError("Dependency Id should be a positive integer.")
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100463 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100464 if len(dep) == 0:
465 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100466 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100467 case {id}:
468 {{
Azim Khand61b8372017-07-10 11:54:01 +0100469#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100470 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100471#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100472 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100473#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100474 }}
475 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100476 return dep_check
477
478
479def gen_expression_check(exp_id, exp):
480 """
481 Generates code for expression check
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100482
Azim Khanf0e42fb2017-08-02 14:47:13 +0100483 :param exp_id: Expression Identifier
484 :param exp: Expression/Macro
485 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100486 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100487 if exp_id < 0:
488 raise GeneratorInputError("Expression Id should be a positive integer.")
489 if len(exp) == 0:
490 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100491 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100492 case {exp_id}:
493 {{
494 *out_value = {expression};
495 }}
496 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100497 return exp_code
498
499
Azim Khan599cd242017-07-06 17:34:27 +0100500def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100501 """
Azim Khan599cd242017-07-06 17:34:27 +0100502 Write dependencies to intermediate test data file.
503 It also returns dependency check 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_deps: Dependencies
507 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
508 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100509 """
Azim Khan599cd242017-07-06 17:34:27 +0100510 dep_check_code = ''
511 if len(test_deps):
512 out_data_f.write('depends_on')
513 for dep in test_deps:
514 if dep not in unique_deps:
515 unique_deps.append(dep)
516 dep_id = unique_deps.index(dep)
517 dep_check_code += gen_dep_check(dep_id, dep)
518 else:
519 dep_id = unique_deps.index(dep)
520 out_data_f.write(':' + str(dep_id))
521 out_data_f.write('\n')
522 return dep_check_code
523
524
525def write_parameters(out_data_f, test_args, func_args, unique_expressions):
526 """
527 Writes test parameters to the intermediate data file.
528 Also generates expression code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100529
Azim Khanf0e42fb2017-08-02 14:47:13 +0100530 :param out_data_f: Output intermediate data file
531 :param test_args: Test parameters
532 :param func_args: Function arguments
533 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
534 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100535 """
536 expression_code = ''
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100537 for i in range(len(test_args)):
Azim Khan599cd242017-07-06 17:34:27 +0100538 typ = func_args[i]
539 val = test_args[i]
540
541 # check if val is a non literal int val
542 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
543 typ = 'exp'
544 if val not in unique_expressions:
545 unique_expressions.append(val)
546 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
547 # use index().
548 exp_id = unique_expressions.index(val)
549 expression_code += gen_expression_check(exp_id, val)
550 val = exp_id
551 else:
552 val = unique_expressions.index(val)
553 out_data_f.write(':' + typ + ':' + str(val))
554 out_data_f.write('\n')
555 return expression_code
556
557
558def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
559 """
560 Adds preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100561
Azim Khanf0e42fb2017-08-02 14:47:13 +0100562 :param suite_deps: Test suite dependencies read from the .functions file.
563 :param dep_check_code: Dependency check code
564 :param expression_code: Expression check code
565 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100566 """
Azim Khan599cd242017-07-06 17:34:27 +0100567 if len(suite_deps):
568 ifdef = gen_deps_one_line(suite_deps)
569 dep_check_code = '''
570{ifdef}
571{code}
Azim Khan599cd242017-07-06 17:34:27 +0100572#endif
573'''.format(ifdef=ifdef, code=dep_check_code)
574 expression_code = '''
575{ifdef}
576{code}
Azim Khan599cd242017-07-06 17:34:27 +0100577#endif
578'''.format(ifdef=ifdef, code=expression_code)
579 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100580
581
Azim Khan13c6bfb2017-06-15 14:45:56 +0100582def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100583 """
584 Generates dependency checks, expression code and intermediate data file from test data file.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100585
Azim Khanf0e42fb2017-08-02 14:47:13 +0100586 :param data_f: Data file object
587 :param out_data_f:Output intermediate data file
588 :param func_info: Dict keyed by function and with function id and arguments info
589 :param suite_deps: Test suite deps
590 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100591 """
592 unique_deps = []
593 unique_expressions = []
594 dep_check_code = ''
595 expression_code = ''
596 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
597 out_data_f.write(test_name + '\n')
598
Azim Khan599cd242017-07-06 17:34:27 +0100599 # Write deps
600 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100601
Azim Khan599cd242017-07-06 17:34:27 +0100602 # Write test function name
603 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100604 if test_function_name not in func_info:
605 raise GeneratorInputError("Function %s not found!" % test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100606 func_id, func_args = func_info[test_function_name]
607 out_data_f.write(str(func_id))
608
609 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100610 if len(test_args) != len(func_args):
611 raise GeneratorInputError("Invalid number of arguments in test %s. See function %s signature." % (test_name,
612 function_name))
Azim Khan599cd242017-07-06 17:34:27 +0100613 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100614
Azim Khan599cd242017-07-06 17:34:27 +0100615 # Write a newline as test case separator
616 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100617
Azim Khan599cd242017-07-06 17:34:27 +0100618 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100619 return dep_check_code, expression_code
620
621
Azim Khan1de892b2017-06-09 15:02:36 +0100622def 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 +0100623 """
624 Generate mbed-os test code.
625
Azim Khanf0e42fb2017-08-02 14:47:13 +0100626 :param funcs_file: Functions file object
627 :param data_file: Data file object
628 :param template_file: Template file object
629 :param platform_file: Platform file object
630 :param help_file: Helper functions file object
631 :param suites_dir: Test suites dir
632 :param c_file: Output C file object
633 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100634 :return:
635 """
636 for name, path in [('Functions file', funcs_file),
637 ('Data file', data_file),
638 ('Template file', template_file),
639 ('Platform file', platform_file),
640 ('Help code file', help_file),
641 ('Suites dir', suites_dir)]:
642 if not os.path.exists(path):
643 raise IOError("ERROR: %s [%s] not found!" % (name, path))
644
645 snippets = {'generator_script' : os.path.basename(__file__)}
646
647 # Read helpers
648 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
649 snippets['test_common_helper_file'] = help_file
650 snippets['test_common_helpers'] = help_f.read()
651 snippets['test_platform_file'] = platform_file
652 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
653 out_data_file.replace('\\', '\\\\')) # escape '\'
654
655 # Function code
Mohammad Azim Khan8f6e8cf2018-06-26 16:57:37 +0100656 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 +0100657 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100658 snippets['functions_code'] = func_code
659 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100660 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 +0100661 snippets['dep_check_code'] = dep_check_code
662 snippets['expression_code'] = expression_code
663
664 snippets['test_file'] = c_file
665 snippets['test_main_file'] = template_file
666 snippets['test_case_file'] = funcs_file
667 snippets['test_case_data_file'] = data_file
668 # Read Template
669 # Add functions
670 #
671 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
672 line_no = 1
673 for line in template_f.readlines():
674 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
675 code = line.format(**snippets)
676 c_f.write(code)
677 line_no += 1
678
679
680def check_cmd():
681 """
682 Command line parser.
683
684 :return:
685 """
686 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
687
688 parser.add_argument("-f", "--functions-file",
689 dest="funcs_file",
690 help="Functions file",
691 metavar="FUNCTIONS",
692 required=True)
693
694 parser.add_argument("-d", "--data-file",
695 dest="data_file",
696 help="Data file",
697 metavar="DATA",
698 required=True)
699
700 parser.add_argument("-t", "--template-file",
701 dest="template_file",
702 help="Template file",
703 metavar="TEMPLATE",
704 required=True)
705
706 parser.add_argument("-s", "--suites-dir",
707 dest="suites_dir",
708 help="Suites dir",
709 metavar="SUITES",
710 required=True)
711
712 parser.add_argument("--help-file",
713 dest="help_file",
714 help="Help file",
715 metavar="HELPER",
716 required=True)
717
718 parser.add_argument("-p", "--platform-file",
719 dest="platform_file",
720 help="Platform code file",
721 metavar="PLATFORM_FILE",
722 required=True)
723
724 parser.add_argument("-o", "--out-dir",
725 dest="out_dir",
726 help="Dir where generated code and scripts are copied",
727 metavar="OUT_DIR",
728 required=True)
729
730 args = parser.parse_args()
731
732 data_file_name = os.path.basename(args.data_file)
733 data_name = os.path.splitext(data_file_name)[0]
734
735 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +0100736 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100737
738 out_c_file_dir = os.path.dirname(out_c_file)
739 out_data_file_dir = os.path.dirname(out_data_file)
740 for d in [out_c_file_dir, out_data_file_dir]:
741 if not os.path.exists(d):
742 os.makedirs(d)
743
Azim Khan1de892b2017-06-09 15:02:36 +0100744 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100745 args.help_file, args.suites_dir, out_c_file, out_data_file)
746
747
748if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100749 try:
750 check_cmd()
751 except GeneratorInputError as e:
752 script_name = os.path.basename(sys.argv[0])
753 print("%s: input error: %s" % (script_name, str(e)))