blob: b2d49129eb21b1bd552ef3f2a28601125ce25c81 [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 Khan040b6a22018-06-28 16:49:13 +010026test_suite_xyz.function - Read test functions from test suite
27 functions file.
28test_suite_xyz.data - Read test functions and their
29 dependencies to generate dispatch and
30 dependency check code.
31main_test.function - Template to substitute generated test
32 function dispatch code, dependency
33 checking code.
34platform .function - Read host or target platform
35 implementation for dispatching test
36 cases from .data file.
37helpers.function - Read common reusable functions.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010038"""
39
Azim Khanf0e42fb2017-08-02 14:47:13 +010040
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010041import io
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010042import os
43import re
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010044import sys
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010045import argparse
46import shutil
47
48
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010049BEGIN_HEADER_REGEX = '/\*\s*BEGIN_HEADER\s*\*/'
50END_HEADER_REGEX = '/\*\s*END_HEADER\s*\*/'
51
Mohammad Azim Khanb5229292018-02-06 13:08:01 +000052BEGIN_SUITE_HELPERS_REGEX = '/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
53END_SUITE_HELPERS_REGEX = '/\*\s*END_SUITE_HELPERS\s*\*/'
54
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010055BEGIN_DEP_REGEX = 'BEGIN_DEPENDENCIES'
56END_DEP_REGEX = 'END_DEPENDENCIES'
57
58BEGIN_CASE_REGEX = '/\*\s*BEGIN_CASE\s*(.*?)\s*\*/'
59END_CASE_REGEX = '/\*\s*END_CASE\s*\*/'
60
61
62class InvalidFileFormat(Exception):
63 """
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010064 Exception to indicate invalid file format.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010065 """
66 pass
67
68
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +010069class GeneratorInputError(Exception):
70 """
71 Exception to indicate error in the input to the generator.
72 """
73 pass
74
75
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010076class FileWrapper(io.FileIO):
Azim Khan4b543232017-06-30 09:35:21 +010077 """
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010078 File wrapper class. Provides reading with line no. tracking.
Azim Khan4b543232017-06-30 09:35:21 +010079 """
80
81 def __init__(self, file_name):
82 """
83 Init file handle.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +010084
Azim Khanf0e42fb2017-08-02 14:47:13 +010085 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +010086 """
87 super(FileWrapper, self).__init__(file_name, 'r')
88 self.line_no = 0
89
Azim Khan040b6a22018-06-28 16:49:13 +010090 # Override the generator function in a way that works in both
91 # Python 2 and Python 3.
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +010092 def __next__(self):
Azim Khan4b543232017-06-30 09:35:21 +010093 """
94 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010095 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010096 """
Gilles Peskine667f7f82018-06-18 17:51:56 +020097 parent = super(FileWrapper, self)
98 if hasattr(parent, '__next__'):
99 line = parent.__next__() # Python 3
100 else:
101 line = parent.next() # Python 2
Azim Khan4b543232017-06-30 09:35:21 +0100102 if line:
103 self.line_no += 1
Azim Khan936ea932018-06-28 16:47:12 +0100104 # Convert byte array to string with correct encoding and
105 # strip any whitespaces added in the decoding process.
106 return line.decode(sys.getdefaultencoding()).strip() + "\n"
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100107 return None
Gilles Peskine667f7f82018-06-18 17:51:56 +0200108 next = __next__
Azim Khan4b543232017-06-30 09:35:21 +0100109
110
111def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100112 """
113 Split NOT character '!' from dependency. Used by gen_deps()
114
115 :param dep: Dependency list
Azim Khan040b6a22018-06-28 16:49:13 +0100116 :return: list of tuples where index 0 has '!' if there was a '!'
117 before the dependency string
Azim Khanf0e42fb2017-08-02 14:47:13 +0100118 """
Azim Khan4b543232017-06-30 09:35:21 +0100119 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
120
121
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100122def gen_deps(deps):
123 """
124 Generates dependency i.e. if def and endif code
125
Azim Khanf0e42fb2017-08-02 14:47:13 +0100126 :param deps: List of dependencies.
Azim Khan040b6a22018-06-28 16:49:13 +0100127 :return: if defined and endif code with macro annotations for
128 readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100129 """
Azim Khan4b543232017-06-30 09:35:21 +0100130 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
131 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
132
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100133 return dep_start, dep_end
134
135
136def gen_deps_one_line(deps):
137 """
Azim Khan040b6a22018-06-28 16:49:13 +0100138 Generates dependency checks in one line. Useful for writing code
139 in #else case.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100140
Azim Khanf0e42fb2017-08-02 14:47:13 +0100141 :param deps: List of dependencies.
142 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100143 """
Azim Khan040b6a22018-06-28 16:49:13 +0100144 defines = '#if ' if len(deps) else ''
145 defines += ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
Azim Khan4b543232017-06-30 09:35:21 +0100146 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100147
148
Azim Khan4b543232017-06-30 09:35:21 +0100149def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100150 """
Azim Khan040b6a22018-06-28 16:49:13 +0100151 Creates test function wrapper code. A wrapper has the code to
152 unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100153
Azim Khanf0e42fb2017-08-02 14:47:13 +0100154 :param name: Test function name
155 :param locals: Local variables declaration code
Azim Khan040b6a22018-06-28 16:49:13 +0100156 :param args_dispatch: List of dispatch arguments.
157 Ex: ['(char *)params[0]', '*((int *)params[1])']
Azim Khanf0e42fb2017-08-02 14:47:13 +0100158 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100159 """
160 # Then create the wrapper
161 wrapper = '''
162void {name}_wrapper( void ** params )
163{{
Gilles Peskine77761412018-06-18 17:51:40 +0200164{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100165 {name}( {args} );
166}}
Gilles Peskine77761412018-06-18 17:51:40 +0200167'''.format(name=name,
Mohammad Azim Khanc3521df2018-06-26 14:06:52 +0100168 unused_params='' if args_dispatch else ' (void)params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100169 args=', '.join(args_dispatch),
170 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100171 return wrapper
172
173
174def gen_dispatch(name, deps):
175 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100176 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100177
Azim Khanf0e42fb2017-08-02 14:47:13 +0100178 :param name: Test function name
179 :param deps: List of dependencies
180 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100181 """
182 if len(deps):
183 ifdef = gen_deps_one_line(deps)
184 dispatch_code = '''
185{ifdef}
186 {name}_wrapper,
187#else
188 NULL,
189#endif
190'''.format(ifdef=ifdef, name=name)
191 else:
192 dispatch_code = '''
193 {name}_wrapper,
194'''.format(name=name)
195
196 return dispatch_code
197
198
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000199def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100200 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000201 Parses function headers or helper code until end pattern.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100202
Azim Khanf0e42fb2017-08-02 14:47:13 +0100203 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000204 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100205 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100206 """
Azim Khan4b543232017-06-30 09:35:21 +0100207 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100208 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000209 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100210 break
211 headers += line
212 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100213 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" %
214 (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100215
Azim Khan4b543232017-06-30 09:35:21 +0100216 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100217
218
Azim Khan4b543232017-06-30 09:35:21 +0100219def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100220 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100221 Parses test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100222
Azim Khanf0e42fb2017-08-02 14:47:13 +0100223 :param funcs_f: file object for .functions file
224 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100225 """
226 deps = []
227 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100228 m = re.search('depends_on\:(.*)', line.strip())
229 if m:
230 deps += [x.strip() for x in m.group(1).split(':')]
231 if re.search(END_DEP_REGEX, line):
232 break
233 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100234 raise InvalidFileFormat("file: %s - end dependency pattern [%s]"
235 " not found!" % (funcs_f.name, END_DEP_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100236
Azim Khan4b543232017-06-30 09:35:21 +0100237 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100238
239
240def parse_function_deps(line):
241 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100242 Parses function dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100243
Azim Khanf0e42fb2017-08-02 14:47:13 +0100244 :param line: Line from .functions file that has dependencies.
245 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100246 """
247 deps = []
248 m = re.search(BEGIN_CASE_REGEX, line)
249 dep_str = m.group(1)
250 if len(dep_str):
251 m = re.search('depends_on:(.*)', dep_str)
252 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100253 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100254 return deps
255
256
257def parse_function_signature(line):
258 """
259 Parsing function signature
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100260
Azim Khan040b6a22018-06-28 16:49:13 +0100261 :param line: Line from .functions file that has a function
262 signature.
263 :return: function name, argument list, local variables for
264 wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100265 """
266 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100267 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100268 args_dispatch = []
269 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
270 if not m:
271 raise ValueError("Test function should return 'void'\n%s" % line)
272 name = m.group(1)
273 line = line[len(m.group(0)):]
274 arg_idx = 0
275 for arg in line[:line.find(')')].split(','):
276 arg = arg.strip()
277 if arg == '':
278 continue
279 if re.search('int\s+.*', arg.strip()):
280 args.append('int')
281 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
282 elif re.search('char\s*\*\s*.*', arg.strip()):
283 args.append('char*')
284 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100285 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100286 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100287 # create a structure
Azim Khan040b6a22018-06-28 16:49:13 +0100288 pointer_initializer = '(uint8_t *) params[%d]' % arg_idx
289 len_initializer = '*( (uint32_t *) params[%d] )' % (arg_idx+1)
Azim Khan2397bba2017-06-09 04:35:03 +0100290 locals += """ HexParam_t hex%d = {%s, %s};
Azim Khan040b6a22018-06-28 16:49:13 +0100291""" % (arg_idx, pointer_initializer, len_initializer)
Azim Khan2397bba2017-06-09 04:35:03 +0100292
293 args_dispatch.append('&hex%d' % arg_idx)
294 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100295 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100296 raise ValueError("Test function arguments can only be 'int', "
297 "'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100298 arg_idx += 1
299
Azim Khan4b543232017-06-30 09:35:21 +0100300 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100301
302
Azim Khan4b543232017-06-30 09:35:21 +0100303def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100304 """
Azim Khan040b6a22018-06-28 16:49:13 +0100305 Parses out a function from function file object and generates
306 function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100307
Azim Khanf0e42fb2017-08-02 14:47:13 +0100308 :param funcs_f: file object of the functions file.
309 :param deps: List of dependencies
310 :param suite_deps: List of test suite dependencies
311 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100312 """
Azim Khan4b543232017-06-30 09:35:21 +0100313 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100314 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100315 # Check function signature
316 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
317 if m:
318 # check if we have full signature i.e. split in more lines
319 if not re.match('.*\)', line):
320 for lin in funcs_f:
321 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100322 if re.search('.*?\)', line):
323 break
Azim Khan4b543232017-06-30 09:35:21 +0100324 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100325 code += line.replace(name, 'test_' + name)
326 name = 'test_' + name
327 break
328 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100329 raise InvalidFileFormat("file: %s - Test functions not found!" %
330 funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100331
332 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100333 if re.search(END_CASE_REGEX, line):
334 break
335 code += line
336 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100337 raise InvalidFileFormat("file: %s - end case pattern [%s] not "
338 "found!" % (funcs_f.name, END_CASE_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100339
340 # Add exit label if not present
341 if code.find('exit:') == -1:
342 s = code.rsplit('}', 1)
343 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100344 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100345 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100346}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100347
Azim Khan4b543232017-06-30 09:35:21 +0100348 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100349 ifdef, endif = gen_deps(deps)
350 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100351 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100352
353
354def parse_functions(funcs_f):
355 """
356 Returns functions code pieces
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100357
Azim Khanf0e42fb2017-08-02 14:47:13 +0100358 :param funcs_f: file object of the functions file.
Azim Khan040b6a22018-06-28 16:49:13 +0100359 :return: List of test suite dependencies, test function dispatch
360 code, function code and a dict with function identifiers
361 and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100362 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100363 suite_headers = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000364 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100365 suite_deps = []
366 suite_functions = ''
367 func_info = {}
368 function_idx = 0
369 dispatch_code = ''
370 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100371 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000372 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100373 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000374 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
375 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
376 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100377 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100378 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100379 suite_deps += deps
380 elif re.search(BEGIN_CASE_REGEX, line):
381 deps = parse_function_deps(line)
Azim Khan040b6a22018-06-28 16:49:13 +0100382 func_name, args, func_code, func_dispatch =\
383 parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100384 suite_functions += func_code
385 # Generate dispatch code and enumeration info
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100386 if func_name in func_info:
387 raise GeneratorInputError(
388 "file: %s - function %s re-declared at line %d" % \
389 (funcs_f.name, func_name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100390 func_info[func_name] = (function_idx, args)
391 dispatch_code += '/* Function Id: %d */\n' % function_idx
392 dispatch_code += func_dispatch
393 function_idx += 1
394
395 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000396 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100397 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100398
399
400def escaped_split(str, ch):
401 """
402 Split str on character ch but ignore escaped \{ch}
Azim Khan040b6a22018-06-28 16:49:13 +0100403 Since, return value is used to write back to the intermediate
404 data file, any escape characters in the input are retained in the
405 output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100406
Azim Khanf0e42fb2017-08-02 14:47:13 +0100407 :param str: String to split
408 :param ch: split character
409 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100410 """
411 if len(ch) > 1:
412 raise ValueError('Expected split character. Found string!')
413 out = []
414 part = ''
415 escape = False
416 for i in range(len(str)):
417 if not escape and str[i] == ch:
418 out.append(part)
419 part = ''
420 else:
Azim Khanacc54732017-07-03 14:06:45 +0100421 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100422 escape = not escape and str[i] == '\\'
423 if len(part):
424 out.append(part)
425 return out
426
427
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100428def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100429 """
430 Parses .data file
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100431
Azim Khanf0e42fb2017-08-02 14:47:13 +0100432 :param data_f: file object of the data file.
Azim Khan040b6a22018-06-28 16:49:13 +0100433 :return: Generator that yields test name, function name,
434 dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100435 """
436 STATE_READ_NAME = 0
437 STATE_READ_ARGS = 1
438 state = STATE_READ_NAME
439 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100440 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100441 for line in data_f:
442 line = line.strip()
443 if len(line) and line[0] == '#': # Skip comments
444 continue
445
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100446 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100447 if len(line) == 0:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100448 if state == STATE_READ_ARGS:
Azim Khan040b6a22018-06-28 16:49:13 +0100449 raise GeneratorInputError("[%s:%d] Newline before arguments. "
450 "Test function and arguments "
451 "missing for %s" %
452 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100453 continue
454
455 if state == STATE_READ_NAME:
456 # Read test name
457 name = line
458 state = STATE_READ_ARGS
459 elif state == STATE_READ_ARGS:
460 # Check dependencies
461 m = re.search('depends_on\:(.*)', line)
462 if m:
Azim Khan040b6a22018-06-28 16:49:13 +0100463 deps = [x.strip() for x in m.group(1).split(':') if len(
464 x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100465 else:
466 # Read test vectors
467 parts = escaped_split(line, ':')
468 function = parts[0]
469 args = parts[1:]
470 yield name, function, deps, args
471 deps = []
472 state = STATE_READ_NAME
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100473 if state == STATE_READ_ARGS:
Azim Khan040b6a22018-06-28 16:49:13 +0100474 raise GeneratorInputError("[%s:%d] Newline before arguments. "
475 "Test function and arguments missing for "
476 "%s" % (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100477
478
479def gen_dep_check(dep_id, dep):
480 """
481 Generate code for the dependency.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100482
Azim Khanf0e42fb2017-08-02 14:47:13 +0100483 :param dep_id: Dependency identifier
484 :param dep: Dependency macro
485 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100486 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100487 if dep_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100488 raise GeneratorInputError("Dependency Id should be a positive "
489 "integer.")
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100490 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100491 if len(dep) == 0:
492 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100493 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100494 case {id}:
495 {{
Azim Khand61b8372017-07-10 11:54:01 +0100496#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100497 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100498#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100499 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100500#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100501 }}
502 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100503 return dep_check
504
505
506def gen_expression_check(exp_id, exp):
507 """
508 Generates code for expression check
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100509
Azim Khanf0e42fb2017-08-02 14:47:13 +0100510 :param exp_id: Expression Identifier
511 :param exp: Expression/Macro
512 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100513 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100514 if exp_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100515 raise GeneratorInputError("Expression Id should be a positive "
516 "integer.")
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100517 if len(exp) == 0:
518 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100519 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100520 case {exp_id}:
521 {{
522 *out_value = {expression};
523 }}
524 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100525 return exp_code
526
527
Azim Khan599cd242017-07-06 17:34:27 +0100528def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100529 """
Azim Khan599cd242017-07-06 17:34:27 +0100530 Write dependencies to intermediate test data file.
531 It also returns dependency check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100532
Azim Khanf0e42fb2017-08-02 14:47:13 +0100533 :param out_data_f: Output intermediate data file
534 :param test_deps: Dependencies
Azim Khan040b6a22018-06-28 16:49:13 +0100535 :param unique_deps: Mutable list to track unique dependencies
536 that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100537 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100538 """
Azim Khan599cd242017-07-06 17:34:27 +0100539 dep_check_code = ''
540 if len(test_deps):
541 out_data_f.write('depends_on')
542 for dep in test_deps:
543 if dep not in unique_deps:
544 unique_deps.append(dep)
545 dep_id = unique_deps.index(dep)
546 dep_check_code += gen_dep_check(dep_id, dep)
547 else:
548 dep_id = unique_deps.index(dep)
549 out_data_f.write(':' + str(dep_id))
550 out_data_f.write('\n')
551 return dep_check_code
552
553
554def write_parameters(out_data_f, test_args, func_args, unique_expressions):
555 """
556 Writes test parameters to the intermediate data file.
557 Also generates expression code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100558
Azim Khanf0e42fb2017-08-02 14:47:13 +0100559 :param out_data_f: Output intermediate data file
560 :param test_args: Test parameters
561 :param func_args: Function arguments
Azim Khan040b6a22018-06-28 16:49:13 +0100562 :param unique_expressions: Mutable list to track unique
563 expressions that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100564 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100565 """
566 expression_code = ''
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100567 for i in range(len(test_args)):
Azim Khan599cd242017-07-06 17:34:27 +0100568 typ = func_args[i]
569 val = test_args[i]
570
Azim Khan040b6a22018-06-28 16:49:13 +0100571 # check if val is a non literal int val (i.e. an expression)
572 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val):
Azim Khan599cd242017-07-06 17:34:27 +0100573 typ = 'exp'
574 if val not in unique_expressions:
575 unique_expressions.append(val)
Azim Khan040b6a22018-06-28 16:49:13 +0100576 # exp_id can be derived from len(). But for
577 # readability and consistency with case of existing
578 # let's use index().
Azim Khan599cd242017-07-06 17:34:27 +0100579 exp_id = unique_expressions.index(val)
580 expression_code += gen_expression_check(exp_id, val)
581 val = exp_id
582 else:
583 val = unique_expressions.index(val)
584 out_data_f.write(':' + typ + ':' + str(val))
585 out_data_f.write('\n')
586 return expression_code
587
588
589def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
590 """
591 Adds preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100592
Azim Khan040b6a22018-06-28 16:49:13 +0100593 :param suite_deps: Test suite dependencies read from the
594 .functions file.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100595 :param dep_check_code: Dependency check code
596 :param expression_code: Expression check code
Azim Khan040b6a22018-06-28 16:49:13 +0100597 :return: Dependency and expression code guarded by test suite
598 dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100599 """
Azim Khan599cd242017-07-06 17:34:27 +0100600 if len(suite_deps):
601 ifdef = gen_deps_one_line(suite_deps)
602 dep_check_code = '''
603{ifdef}
604{code}
Azim Khan599cd242017-07-06 17:34:27 +0100605#endif
606'''.format(ifdef=ifdef, code=dep_check_code)
607 expression_code = '''
608{ifdef}
609{code}
Azim Khan599cd242017-07-06 17:34:27 +0100610#endif
611'''.format(ifdef=ifdef, code=expression_code)
612 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100613
614
Azim Khan13c6bfb2017-06-15 14:45:56 +0100615def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100616 """
Azim Khan040b6a22018-06-28 16:49:13 +0100617 Generates dependency checks, expression code and intermediate
618 data file from test data file.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100619
Azim Khanf0e42fb2017-08-02 14:47:13 +0100620 :param data_f: Data file object
621 :param out_data_f:Output intermediate data file
Azim Khan040b6a22018-06-28 16:49:13 +0100622 :param func_info: Dict keyed by function and with function id
623 and arguments info
Azim Khanf0e42fb2017-08-02 14:47:13 +0100624 :param suite_deps: Test suite deps
625 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100626 """
627 unique_deps = []
628 unique_expressions = []
629 dep_check_code = ''
630 expression_code = ''
Azim Khan040b6a22018-06-28 16:49:13 +0100631 for test_name, function_name, test_deps, test_args in parse_test_data(
632 data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100633 out_data_f.write(test_name + '\n')
634
Azim Khan599cd242017-07-06 17:34:27 +0100635 # Write deps
636 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100637
Azim Khan599cd242017-07-06 17:34:27 +0100638 # Write test function name
639 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100640 if test_function_name not in func_info:
Azim Khan040b6a22018-06-28 16:49:13 +0100641 raise GeneratorInputError("Function %s not found!" %
642 test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100643 func_id, func_args = func_info[test_function_name]
644 out_data_f.write(str(func_id))
645
646 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100647 if len(test_args) != len(func_args):
Azim Khan040b6a22018-06-28 16:49:13 +0100648 raise GeneratorInputError("Invalid number of arguments in test "
649 "%s. See function %s signature." % (
650 test_name, function_name))
651 expression_code += write_parameters(out_data_f, test_args, func_args,
652 unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100653
Azim Khan599cd242017-07-06 17:34:27 +0100654 # Write a newline as test case separator
655 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100656
Azim Khan040b6a22018-06-28 16:49:13 +0100657 dep_check_code, expression_code = gen_suite_deps_checks(
658 suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100659 return dep_check_code, expression_code
660
661
Azim Khan040b6a22018-06-28 16:49:13 +0100662def generate_code(funcs_file, data_file, template_file, platform_file,
663 help_file, suites_dir, c_file, out_data_file):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100664 """
665 Generate mbed-os test code.
666
Azim Khanf0e42fb2017-08-02 14:47:13 +0100667 :param funcs_file: Functions file object
668 :param data_file: Data file object
669 :param template_file: Template file object
670 :param platform_file: Platform file object
671 :param help_file: Helper functions file object
672 :param suites_dir: Test suites dir
673 :param c_file: Output C file object
674 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100675 :return:
676 """
677 for name, path in [('Functions file', funcs_file),
678 ('Data file', data_file),
679 ('Template file', template_file),
680 ('Platform file', platform_file),
681 ('Help code file', help_file),
682 ('Suites dir', suites_dir)]:
683 if not os.path.exists(path):
684 raise IOError("ERROR: %s [%s] not found!" % (name, path))
685
686 snippets = {'generator_script' : os.path.basename(__file__)}
687
688 # Read helpers
Azim Khan040b6a22018-06-28 16:49:13 +0100689 with open(help_file, 'r') as help_f, open(platform_file, 'r') as \
690 platform_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100691 snippets['test_common_helper_file'] = help_file
692 snippets['test_common_helpers'] = help_f.read()
693 snippets['test_platform_file'] = platform_file
Azim Khan040b6a22018-06-28 16:49:13 +0100694 snippets['platform_code'] = platform_f.read().replace(
695 'DATA_FILE', out_data_file.replace('\\', '\\\\')) # escape '\'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100696
697 # Function code
Azim Khan040b6a22018-06-28 16:49:13 +0100698 with FileWrapper(funcs_file) as funcs_f, FileWrapper(data_file) as \
699 data_f, open(out_data_file, 'w') as out_data_f:
700 suite_deps, dispatch_code, func_code, func_info = parse_functions(
701 funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100702 snippets['functions_code'] = func_code
703 snippets['dispatch_code'] = dispatch_code
Azim Khan040b6a22018-06-28 16:49:13 +0100704 dep_check_code, expression_code = gen_from_test_data(
705 data_f, out_data_f, func_info, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100706 snippets['dep_check_code'] = dep_check_code
707 snippets['expression_code'] = expression_code
708
709 snippets['test_file'] = c_file
710 snippets['test_main_file'] = template_file
711 snippets['test_case_file'] = funcs_file
712 snippets['test_case_data_file'] = data_file
713 # Read Template
714 # Add functions
715 #
716 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
717 line_no = 1
718 for line in template_f.readlines():
Azim Khan040b6a22018-06-28 16:49:13 +0100719 # Update line number. +1 as #line directive sets next line number
720 snippets['line_no'] = line_no + 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100721 code = line.format(**snippets)
722 c_f.write(code)
723 line_no += 1
724
725
726def check_cmd():
727 """
728 Command line parser.
729
730 :return:
731 """
Azim Khan040b6a22018-06-28 16:49:13 +0100732 parser = argparse.ArgumentParser(
733 description='Generate code for mbed-os tests.')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100734
735 parser.add_argument("-f", "--functions-file",
736 dest="funcs_file",
737 help="Functions file",
738 metavar="FUNCTIONS",
739 required=True)
740
741 parser.add_argument("-d", "--data-file",
742 dest="data_file",
743 help="Data file",
744 metavar="DATA",
745 required=True)
746
747 parser.add_argument("-t", "--template-file",
748 dest="template_file",
749 help="Template file",
750 metavar="TEMPLATE",
751 required=True)
752
753 parser.add_argument("-s", "--suites-dir",
754 dest="suites_dir",
755 help="Suites dir",
756 metavar="SUITES",
757 required=True)
758
759 parser.add_argument("--help-file",
760 dest="help_file",
761 help="Help file",
762 metavar="HELPER",
763 required=True)
764
765 parser.add_argument("-p", "--platform-file",
766 dest="platform_file",
767 help="Platform code file",
768 metavar="PLATFORM_FILE",
769 required=True)
770
771 parser.add_argument("-o", "--out-dir",
772 dest="out_dir",
773 help="Dir where generated code and scripts are copied",
774 metavar="OUT_DIR",
775 required=True)
776
777 args = parser.parse_args()
778
779 data_file_name = os.path.basename(args.data_file)
780 data_name = os.path.splitext(data_file_name)[0]
781
782 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +0100783 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100784
785 out_c_file_dir = os.path.dirname(out_c_file)
786 out_data_file_dir = os.path.dirname(out_data_file)
787 for d in [out_c_file_dir, out_data_file_dir]:
788 if not os.path.exists(d):
789 os.makedirs(d)
790
Azim Khan040b6a22018-06-28 16:49:13 +0100791 generate_code(args.funcs_file, args.data_file, args.template_file,
792 args.platform_file, args.help_file, args.suites_dir,
793 out_c_file, out_data_file)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100794
795
796if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100797 try:
798 check_cmd()
799 except GeneratorInputError as e:
800 script_name = os.path.basename(sys.argv[0])
801 print("%s: input error: %s" % (script_name, str(e)))