blob: 78bbaa39999a9b9248edbca991d2cf542e02c4de [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
Gilles Peskine667f7f82018-06-18 17:51:56 +020079 # Override the generator function in a way that works in both Python 2
80 # and Python 3.
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010081 def __next__(self):
Azim Khan4b543232017-06-30 09:35:21 +010082 """
83 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010084 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010085 """
Gilles Peskine667f7f82018-06-18 17:51:56 +020086 parent = super(FileWrapper, self)
87 if hasattr(parent, '__next__'):
88 line = parent.__next__() # Python 3
89 else:
90 line = parent.next() # Python 2
Azim Khan4b543232017-06-30 09:35:21 +010091 if line:
92 self.line_no += 1
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010093 # Convert byte array to string with correct encoding
94 return line.decode(sys.getdefaultencoding())
95 return None
Gilles Peskine667f7f82018-06-18 17:51:56 +020096 next = __next__
Azim Khan4b543232017-06-30 09:35:21 +010097
98
99def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100100 """
101 Split NOT character '!' from dependency. Used by gen_deps()
102
103 :param dep: Dependency list
104 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
105 """
Azim Khan4b543232017-06-30 09:35:21 +0100106 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
107
108
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100109def gen_deps(deps):
110 """
111 Generates dependency i.e. if def and endif code
112
Azim Khanf0e42fb2017-08-02 14:47:13 +0100113 :param deps: List of dependencies.
114 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100115 """
Azim Khan4b543232017-06-30 09:35:21 +0100116 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
117 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
118
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100119 return dep_start, dep_end
120
121
122def gen_deps_one_line(deps):
123 """
124 Generates dependency checks in one line. Useful for writing code in #else case.
125
Azim Khanf0e42fb2017-08-02 14:47:13 +0100126 :param deps: List of dependencies.
127 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100128 """
Azim Khan4b543232017-06-30 09:35:21 +0100129 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
130 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100131
132
Azim Khan4b543232017-06-30 09:35:21 +0100133def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100134 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100135 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100136
Azim Khanf0e42fb2017-08-02 14:47:13 +0100137 :param name: Test function name
138 :param locals: Local variables declaration code
139 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
140 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100141 """
142 # Then create the wrapper
143 wrapper = '''
144void {name}_wrapper( void ** params )
145{{
Gilles Peskine77761412018-06-18 17:51:40 +0200146{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100147 {name}( {args} );
148}}
Gilles Peskine77761412018-06-18 17:51:40 +0200149'''.format(name=name,
150 unused_params='' if args_dispatch else ' (void) params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100151 args=', '.join(args_dispatch),
152 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100153 return wrapper
154
155
156def gen_dispatch(name, deps):
157 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100158 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100159
Azim Khanf0e42fb2017-08-02 14:47:13 +0100160 :param name: Test function name
161 :param deps: List of dependencies
162 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100163 """
164 if len(deps):
165 ifdef = gen_deps_one_line(deps)
166 dispatch_code = '''
167{ifdef}
168 {name}_wrapper,
169#else
170 NULL,
171#endif
172'''.format(ifdef=ifdef, name=name)
173 else:
174 dispatch_code = '''
175 {name}_wrapper,
176'''.format(name=name)
177
178 return dispatch_code
179
180
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000181def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100182 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000183 Parses function headers or helper code until end pattern.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100184
Azim Khanf0e42fb2017-08-02 14:47:13 +0100185 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000186 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100187 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100188 """
Azim Khan4b543232017-06-30 09:35:21 +0100189 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100190 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000191 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100192 break
193 headers += line
194 else:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000195 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100196
Azim Khan4b543232017-06-30 09:35:21 +0100197 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100198
199
Azim Khan4b543232017-06-30 09:35:21 +0100200def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100201 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100202 Parses test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100203
Azim Khanf0e42fb2017-08-02 14:47:13 +0100204 :param funcs_f: file object for .functions file
205 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100206 """
207 deps = []
208 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100209 m = re.search('depends_on\:(.*)', line.strip())
210 if m:
211 deps += [x.strip() for x in m.group(1).split(':')]
212 if re.search(END_DEP_REGEX, line):
213 break
214 else:
215 raise InvalidFileFormat("file: %s - end dependency pattern [%s] not found!" % (funcs_f.name, END_DEP_REGEX))
216
Azim Khan4b543232017-06-30 09:35:21 +0100217 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100218
219
220def parse_function_deps(line):
221 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100222 Parses function dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100223
Azim Khanf0e42fb2017-08-02 14:47:13 +0100224 :param line: Line from .functions file that has dependencies.
225 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100226 """
227 deps = []
228 m = re.search(BEGIN_CASE_REGEX, line)
229 dep_str = m.group(1)
230 if len(dep_str):
231 m = re.search('depends_on:(.*)', dep_str)
232 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100233 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100234 return deps
235
236
237def parse_function_signature(line):
238 """
239 Parsing function signature
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100240
Azim Khanf0e42fb2017-08-02 14:47:13 +0100241 :param line: Line from .functions file that has a function signature.
242 :return: function name, argument list, local variables for wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100243 """
244 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100245 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100246 args_dispatch = []
247 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
248 if not m:
249 raise ValueError("Test function should return 'void'\n%s" % line)
250 name = m.group(1)
251 line = line[len(m.group(0)):]
252 arg_idx = 0
253 for arg in line[:line.find(')')].split(','):
254 arg = arg.strip()
255 if arg == '':
256 continue
257 if re.search('int\s+.*', arg.strip()):
258 args.append('int')
259 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
260 elif re.search('char\s*\*\s*.*', arg.strip()):
261 args.append('char*')
262 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100263 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100264 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100265 # create a structure
266 locals += """ HexParam_t hex%d = {%s, %s};
267""" % (arg_idx, '(uint8_t *) params[%d]' % arg_idx, '*( (uint32_t *) params[%d] )' % (arg_idx + 1))
268
269 args_dispatch.append('&hex%d' % arg_idx)
270 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100271 else:
Azim Khan4b543232017-06-30 09:35:21 +0100272 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100273 arg_idx += 1
274
Azim Khan4b543232017-06-30 09:35:21 +0100275 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100276
277
Azim Khan4b543232017-06-30 09:35:21 +0100278def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100279 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100280 Parses out a function from function file object and generates function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100281
Azim Khanf0e42fb2017-08-02 14:47:13 +0100282 :param funcs_f: file object of the functions file.
283 :param deps: List of dependencies
284 :param suite_deps: List of test suite dependencies
285 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100286 """
Azim Khan4b543232017-06-30 09:35:21 +0100287 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100288 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100289 # Check function signature
290 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
291 if m:
292 # check if we have full signature i.e. split in more lines
293 if not re.match('.*\)', line):
294 for lin in funcs_f:
295 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100296 if re.search('.*?\)', line):
297 break
Azim Khan4b543232017-06-30 09:35:21 +0100298 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100299 code += line.replace(name, 'test_' + name)
300 name = 'test_' + name
301 break
302 else:
303 raise InvalidFileFormat("file: %s - Test functions not found!" % funcs_f.name)
304
305 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100306 if re.search(END_CASE_REGEX, line):
307 break
308 code += line
309 else:
310 raise InvalidFileFormat("file: %s - end case pattern [%s] not found!" % (funcs_f.name, END_CASE_REGEX))
311
312 # Add exit label if not present
313 if code.find('exit:') == -1:
314 s = code.rsplit('}', 1)
315 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100316 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100317 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100318}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100319
Azim Khan4b543232017-06-30 09:35:21 +0100320 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100321 ifdef, endif = gen_deps(deps)
322 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100323 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100324
325
326def parse_functions(funcs_f):
327 """
328 Returns functions code pieces
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100329
Azim Khanf0e42fb2017-08-02 14:47:13 +0100330 :param funcs_f: file object of the functions file.
331 :return: List of test suite dependencies, test function dispatch code, function code and
332 a dict with function identifiers and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100333 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100334 suite_headers = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000335 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100336 suite_deps = []
337 suite_functions = ''
338 func_info = {}
339 function_idx = 0
340 dispatch_code = ''
341 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100342 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000343 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100344 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000345 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
346 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
347 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100348 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100349 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100350 suite_deps += deps
351 elif re.search(BEGIN_CASE_REGEX, line):
352 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100353 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100354 suite_functions += func_code
355 # Generate dispatch code and enumeration info
356 assert func_name not in func_info, "file: %s - function %s re-declared at line %d" % \
Azim Khan4b543232017-06-30 09:35:21 +0100357 (funcs_f.name, func_name, funcs_f.line_no)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100358 func_info[func_name] = (function_idx, args)
359 dispatch_code += '/* Function Id: %d */\n' % function_idx
360 dispatch_code += func_dispatch
361 function_idx += 1
362
363 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000364 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100365 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100366
367
368def escaped_split(str, ch):
369 """
370 Split str on character ch but ignore escaped \{ch}
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100371 Since return value is used to write back to the intermediate data file.
Azim Khan599cd242017-07-06 17:34:27 +0100372 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100373
Azim Khanf0e42fb2017-08-02 14:47:13 +0100374 :param str: String to split
375 :param ch: split character
376 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100377 """
378 if len(ch) > 1:
379 raise ValueError('Expected split character. Found string!')
380 out = []
381 part = ''
382 escape = False
383 for i in range(len(str)):
384 if not escape and str[i] == ch:
385 out.append(part)
386 part = ''
387 else:
Azim Khanacc54732017-07-03 14:06:45 +0100388 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100389 escape = not escape and str[i] == '\\'
390 if len(part):
391 out.append(part)
392 return out
393
394
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100395def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100396 """
397 Parses .data file
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100398
Azim Khanf0e42fb2017-08-02 14:47:13 +0100399 :param data_f: file object of the data file.
400 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100401 """
402 STATE_READ_NAME = 0
403 STATE_READ_ARGS = 1
404 state = STATE_READ_NAME
405 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100406 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100407 for line in data_f:
408 line = line.strip()
409 if len(line) and line[0] == '#': # Skip comments
410 continue
411
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100412 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100413 if len(line) == 0:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100414 assert state != STATE_READ_ARGS, "Newline before arguments. " \
415 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100416 continue
417
418 if state == STATE_READ_NAME:
419 # Read test name
420 name = line
421 state = STATE_READ_ARGS
422 elif state == STATE_READ_ARGS:
423 # Check dependencies
424 m = re.search('depends_on\:(.*)', line)
425 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100426 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100427 else:
428 # Read test vectors
429 parts = escaped_split(line, ':')
430 function = parts[0]
431 args = parts[1:]
432 yield name, function, deps, args
433 deps = []
434 state = STATE_READ_NAME
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100435 assert state != STATE_READ_ARGS, "Newline before arguments. " \
436 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100437
438
439def gen_dep_check(dep_id, dep):
440 """
441 Generate code for the dependency.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100442
Azim Khanf0e42fb2017-08-02 14:47:13 +0100443 :param dep_id: Dependency identifier
444 :param dep: Dependency macro
445 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100446 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100447 assert dep_id > -1, "Dependency Id should be a positive integer."
448 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
449 assert len(dep) > 0, "Dependency should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100450 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100451 case {id}:
452 {{
Azim Khand61b8372017-07-10 11:54:01 +0100453#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100454 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100455#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100456 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100457#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100458 }}
459 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100460 return dep_check
461
462
463def gen_expression_check(exp_id, exp):
464 """
465 Generates code for expression check
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100466
Azim Khanf0e42fb2017-08-02 14:47:13 +0100467 :param exp_id: Expression Identifier
468 :param exp: Expression/Macro
469 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100470 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100471 assert exp_id > -1, "Expression Id should be a positive integer."
472 assert len(exp) > 0, "Expression should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100473 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100474 case {exp_id}:
475 {{
476 *out_value = {expression};
477 }}
478 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100479 return exp_code
480
481
Azim Khan599cd242017-07-06 17:34:27 +0100482def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100483 """
Azim Khan599cd242017-07-06 17:34:27 +0100484 Write dependencies to intermediate test data file.
485 It also returns dependency check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100486
Azim Khanf0e42fb2017-08-02 14:47:13 +0100487 :param out_data_f: Output intermediate data file
488 :param test_deps: Dependencies
489 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
490 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100491 """
Azim Khan599cd242017-07-06 17:34:27 +0100492 dep_check_code = ''
493 if len(test_deps):
494 out_data_f.write('depends_on')
495 for dep in test_deps:
496 if dep not in unique_deps:
497 unique_deps.append(dep)
498 dep_id = unique_deps.index(dep)
499 dep_check_code += gen_dep_check(dep_id, dep)
500 else:
501 dep_id = unique_deps.index(dep)
502 out_data_f.write(':' + str(dep_id))
503 out_data_f.write('\n')
504 return dep_check_code
505
506
507def write_parameters(out_data_f, test_args, func_args, unique_expressions):
508 """
509 Writes test parameters to the intermediate data file.
510 Also generates expression code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100511
Azim Khanf0e42fb2017-08-02 14:47:13 +0100512 :param out_data_f: Output intermediate data file
513 :param test_args: Test parameters
514 :param func_args: Function arguments
515 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
516 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100517 """
518 expression_code = ''
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100519 for i in range(len(test_args)):
Azim Khan599cd242017-07-06 17:34:27 +0100520 typ = func_args[i]
521 val = test_args[i]
522
523 # check if val is a non literal int val
524 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
525 typ = 'exp'
526 if val not in unique_expressions:
527 unique_expressions.append(val)
528 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
529 # use index().
530 exp_id = unique_expressions.index(val)
531 expression_code += gen_expression_check(exp_id, val)
532 val = exp_id
533 else:
534 val = unique_expressions.index(val)
535 out_data_f.write(':' + typ + ':' + str(val))
536 out_data_f.write('\n')
537 return expression_code
538
539
540def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
541 """
542 Adds preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100543
Azim Khanf0e42fb2017-08-02 14:47:13 +0100544 :param suite_deps: Test suite dependencies read from the .functions file.
545 :param dep_check_code: Dependency check code
546 :param expression_code: Expression check code
547 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100548 """
Azim Khan599cd242017-07-06 17:34:27 +0100549 if len(suite_deps):
550 ifdef = gen_deps_one_line(suite_deps)
551 dep_check_code = '''
552{ifdef}
553{code}
Azim Khan599cd242017-07-06 17:34:27 +0100554#endif
555'''.format(ifdef=ifdef, code=dep_check_code)
556 expression_code = '''
557{ifdef}
558{code}
Azim Khan599cd242017-07-06 17:34:27 +0100559#endif
560'''.format(ifdef=ifdef, code=expression_code)
561 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100562
563
Azim Khan13c6bfb2017-06-15 14:45:56 +0100564def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100565 """
566 Generates dependency checks, expression code and intermediate data file from test data file.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100567
Azim Khanf0e42fb2017-08-02 14:47:13 +0100568 :param data_f: Data file object
569 :param out_data_f:Output intermediate data file
570 :param func_info: Dict keyed by function and with function id and arguments info
571 :param suite_deps: Test suite deps
572 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100573 """
574 unique_deps = []
575 unique_expressions = []
576 dep_check_code = ''
577 expression_code = ''
578 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
579 out_data_f.write(test_name + '\n')
580
Azim Khan599cd242017-07-06 17:34:27 +0100581 # Write deps
582 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100583
Azim Khan599cd242017-07-06 17:34:27 +0100584 # Write test function name
585 test_function_name = 'test_' + function_name
586 assert test_function_name in func_info, "Function %s not found!" % test_function_name
587 func_id, func_args = func_info[test_function_name]
588 out_data_f.write(str(func_id))
589
590 # Write parameters
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100591 assert len(test_args) == len(func_args), \
592 "Invalid number of arguments in test %s. See function %s signature." % (test_name, function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100593 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100594
Azim Khan599cd242017-07-06 17:34:27 +0100595 # Write a newline as test case separator
596 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100597
Azim Khan599cd242017-07-06 17:34:27 +0100598 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100599 return dep_check_code, expression_code
600
601
Azim Khan1de892b2017-06-09 15:02:36 +0100602def 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 +0100603 """
604 Generate mbed-os test code.
605
Azim Khanf0e42fb2017-08-02 14:47:13 +0100606 :param funcs_file: Functions file object
607 :param data_file: Data file object
608 :param template_file: Template file object
609 :param platform_file: Platform file object
610 :param help_file: Helper functions file object
611 :param suites_dir: Test suites dir
612 :param c_file: Output C file object
613 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100614 :return:
615 """
616 for name, path in [('Functions file', funcs_file),
617 ('Data file', data_file),
618 ('Template file', template_file),
619 ('Platform file', platform_file),
620 ('Help code file', help_file),
621 ('Suites dir', suites_dir)]:
622 if not os.path.exists(path):
623 raise IOError("ERROR: %s [%s] not found!" % (name, path))
624
625 snippets = {'generator_script' : os.path.basename(__file__)}
626
627 # Read helpers
628 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
629 snippets['test_common_helper_file'] = help_file
630 snippets['test_common_helpers'] = help_f.read()
631 snippets['test_platform_file'] = platform_file
632 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
633 out_data_file.replace('\\', '\\\\')) # escape '\'
634
635 # Function code
Azim Khanacc54732017-07-03 14:06:45 +0100636 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 +0100637 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100638 snippets['functions_code'] = func_code
639 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100640 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 +0100641 snippets['dep_check_code'] = dep_check_code
642 snippets['expression_code'] = expression_code
643
644 snippets['test_file'] = c_file
645 snippets['test_main_file'] = template_file
646 snippets['test_case_file'] = funcs_file
647 snippets['test_case_data_file'] = data_file
648 # Read Template
649 # Add functions
650 #
651 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
652 line_no = 1
653 for line in template_f.readlines():
654 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
655 code = line.format(**snippets)
656 c_f.write(code)
657 line_no += 1
658
659
660def check_cmd():
661 """
662 Command line parser.
663
664 :return:
665 """
666 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
667
668 parser.add_argument("-f", "--functions-file",
669 dest="funcs_file",
670 help="Functions file",
671 metavar="FUNCTIONS",
672 required=True)
673
674 parser.add_argument("-d", "--data-file",
675 dest="data_file",
676 help="Data file",
677 metavar="DATA",
678 required=True)
679
680 parser.add_argument("-t", "--template-file",
681 dest="template_file",
682 help="Template file",
683 metavar="TEMPLATE",
684 required=True)
685
686 parser.add_argument("-s", "--suites-dir",
687 dest="suites_dir",
688 help="Suites dir",
689 metavar="SUITES",
690 required=True)
691
692 parser.add_argument("--help-file",
693 dest="help_file",
694 help="Help file",
695 metavar="HELPER",
696 required=True)
697
698 parser.add_argument("-p", "--platform-file",
699 dest="platform_file",
700 help="Platform code file",
701 metavar="PLATFORM_FILE",
702 required=True)
703
704 parser.add_argument("-o", "--out-dir",
705 dest="out_dir",
706 help="Dir where generated code and scripts are copied",
707 metavar="OUT_DIR",
708 required=True)
709
710 args = parser.parse_args()
711
712 data_file_name = os.path.basename(args.data_file)
713 data_name = os.path.splitext(data_file_name)[0]
714
715 out_c_file = os.path.join(args.out_dir, data_name + '.c')
716 out_data_file = os.path.join(args.out_dir, data_file_name)
717
718 out_c_file_dir = os.path.dirname(out_c_file)
719 out_data_file_dir = os.path.dirname(out_data_file)
720 for d in [out_c_file_dir, out_data_file_dir]:
721 if not os.path.exists(d):
722 os.makedirs(d)
723
Azim Khan1de892b2017-06-09 15:02:36 +0100724 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100725 args.help_file, args.suites_dir, out_c_file, out_data_file)
726
727
728if __name__ == "__main__":
729 check_cmd()