blob: 38b0d75478a00b467d3af5d45e4e59260213df76 [file] [log] [blame]
Azim Khanf0e42fb2017-08-02 14:47:13 +01001# Test suites code generator.
2#
Mohammad Azim Khan78befd92018-03-06 11:49:41 +00003# Copyright (C) 2018, ARM Limited, All Rights Reserved
Azim Khanf0e42fb2017-08-02 14:47:13 +01004# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18# This file is part of mbed TLS (https://tls.mbed.org)
19
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010020"""
Azim Khanf0e42fb2017-08-02 14:47:13 +010021Test Suite code generator.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010022
Azim Khanf0e42fb2017-08-02 14:47:13 +010023Generates a test source file using following input files:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010024
Azim Khanf0e42fb2017-08-02 14:47:13 +010025test_suite_xyz.function - Read test functions from test suite functions file.
26test_suite_xyz.data - Read test functions and their dependencies to generate
27 dispatch and dependency check code.
28main template - Substitute generated test function dispatch code, dependency
29 checking code.
30platform .function - Read host or target platform implementation for
31 dispatching test cases from .data file.
32helper .function - Read common reusable functions.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010033"""
34
Azim Khanf0e42fb2017-08-02 14:47:13 +010035
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010036import os
37import re
38import argparse
39import shutil
40
41
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010042BEGIN_HEADER_REGEX = '/\*\s*BEGIN_HEADER\s*\*/'
43END_HEADER_REGEX = '/\*\s*END_HEADER\s*\*/'
44
Mohammad Azim Khanb5229292018-02-06 13:08:01 +000045BEGIN_SUITE_HELPERS_REGEX = '/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
46END_SUITE_HELPERS_REGEX = '/\*\s*END_SUITE_HELPERS\s*\*/'
47
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010048BEGIN_DEP_REGEX = 'BEGIN_DEPENDENCIES'
49END_DEP_REGEX = 'END_DEPENDENCIES'
50
51BEGIN_CASE_REGEX = '/\*\s*BEGIN_CASE\s*(.*?)\s*\*/'
52END_CASE_REGEX = '/\*\s*END_CASE\s*\*/'
53
54
55class InvalidFileFormat(Exception):
56 """
57 Exception to indicate invalid file format.
58 """
59 pass
60
61
Azim Khan4b543232017-06-30 09:35:21 +010062class FileWrapper(file):
63 """
64 File wrapper class. Provides reading with line no. tracking.
65 """
66
67 def __init__(self, file_name):
68 """
69 Init file handle.
70
Azim Khanf0e42fb2017-08-02 14:47:13 +010071 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +010072 """
73 super(FileWrapper, self).__init__(file_name, 'r')
74 self.line_no = 0
75
76 def next(self):
77 """
78 Iterator return impl.
Azim Khanf0e42fb2017-08-02 14:47:13 +010079 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010080 """
81 line = super(FileWrapper, self).next()
82 if line:
83 self.line_no += 1
84 return line
85
86 def readline(self, limit=0):
87 """
88 Wrap the base class readline.
89
Azim Khanf0e42fb2017-08-02 14:47:13 +010090 :param limit: limit to match file.readline([limit])
91 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +010092 """
93 return self.next()
94
95
96def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +010097 """
98 Split NOT character '!' from dependency. Used by gen_deps()
99
100 :param dep: Dependency list
101 :return: list of tuples where index 0 has '!' if there was a '!' before the dependency string
102 """
Azim Khan4b543232017-06-30 09:35:21 +0100103 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
104
105
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100106def gen_deps(deps):
107 """
108 Generates dependency i.e. if def and endif code
109
Azim Khanf0e42fb2017-08-02 14:47:13 +0100110 :param deps: List of dependencies.
111 :return: if defined and endif code with macro annotations for readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100112 """
Azim Khan4b543232017-06-30 09:35:21 +0100113 dep_start = ''.join(['#if %sdefined(%s)\n' % split_dep(x) for x in deps])
114 dep_end = ''.join(['#endif /* %s */\n' % x for x in reversed(deps)])
115
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100116 return dep_start, dep_end
117
118
119def gen_deps_one_line(deps):
120 """
121 Generates dependency checks in one line. Useful for writing code in #else case.
122
Azim Khanf0e42fb2017-08-02 14:47:13 +0100123 :param deps: List of dependencies.
124 :return: ifdef code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100125 """
Azim Khan4b543232017-06-30 09:35:21 +0100126 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
127 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100128
129
Azim Khan4b543232017-06-30 09:35:21 +0100130def gen_function_wrapper(name, locals, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100131 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100132 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100133
Azim Khanf0e42fb2017-08-02 14:47:13 +0100134 :param name: Test function name
135 :param locals: Local variables declaration code
136 :param args_dispatch: List of dispatch arguments. Ex: ['(char *)params[0]', '*((int *)params[1])']
137 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100138 """
139 # Then create the wrapper
140 wrapper = '''
141void {name}_wrapper( void ** params )
142{{
143 {unused_params}
Azim Khan2397bba2017-06-09 04:35:03 +0100144{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100145 {name}( {args} );
146}}
Azim Khan4b543232017-06-30 09:35:21 +0100147'''.format(name=name, unused_params='(void)params;' if len(args_dispatch) == 0 else '',
148 args=', '.join(args_dispatch),
149 locals=locals)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100150 return wrapper
151
152
153def gen_dispatch(name, deps):
154 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100155 Generates dispatch code for the test function table.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100156
Azim Khanf0e42fb2017-08-02 14:47:13 +0100157 :param name: Test function name
158 :param deps: List of dependencies
159 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100160 """
161 if len(deps):
162 ifdef = gen_deps_one_line(deps)
163 dispatch_code = '''
164{ifdef}
165 {name}_wrapper,
166#else
167 NULL,
168#endif
169'''.format(ifdef=ifdef, name=name)
170 else:
171 dispatch_code = '''
172 {name}_wrapper,
173'''.format(name=name)
174
175 return dispatch_code
176
177
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000178def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100179 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000180 Parses function headers or helper code until end pattern.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100181
Azim Khanf0e42fb2017-08-02 14:47:13 +0100182 :param funcs_f: file object for .functions file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000183 :param end_regex: Pattern to stop parsing
Azim Khanf0e42fb2017-08-02 14:47:13 +0100184 :return: Test suite headers code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100185 """
Azim Khan4b543232017-06-30 09:35:21 +0100186 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100187 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000188 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100189 break
190 headers += line
191 else:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000192 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100193
Azim Khan4b543232017-06-30 09:35:21 +0100194 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100195
196
Azim Khan4b543232017-06-30 09:35:21 +0100197def parse_suite_deps(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100198 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100199 Parses test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100200
Azim Khanf0e42fb2017-08-02 14:47:13 +0100201 :param funcs_f: file object for .functions file
202 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100203 """
204 deps = []
205 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100206 m = re.search('depends_on\:(.*)', line.strip())
207 if m:
208 deps += [x.strip() for x in m.group(1).split(':')]
209 if re.search(END_DEP_REGEX, line):
210 break
211 else:
212 raise InvalidFileFormat("file: %s - end dependency pattern [%s] not found!" % (funcs_f.name, END_DEP_REGEX))
213
Azim Khan4b543232017-06-30 09:35:21 +0100214 return deps
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100215
216
217def parse_function_deps(line):
218 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100219 Parses function dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100220
Azim Khanf0e42fb2017-08-02 14:47:13 +0100221 :param line: Line from .functions file that has dependencies.
222 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100223 """
224 deps = []
225 m = re.search(BEGIN_CASE_REGEX, line)
226 dep_str = m.group(1)
227 if len(dep_str):
228 m = re.search('depends_on:(.*)', dep_str)
229 if m:
Azim Khan4b543232017-06-30 09:35:21 +0100230 deps = [x.strip() for x in m.group(1).strip().split(':')]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100231 return deps
232
233
234def parse_function_signature(line):
235 """
236 Parsing function signature
237
Azim Khanf0e42fb2017-08-02 14:47:13 +0100238 :param line: Line from .functions file that has a function signature.
239 :return: function name, argument list, local variables for wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100240 """
241 args = []
Azim Khan2397bba2017-06-09 04:35:03 +0100242 locals = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100243 args_dispatch = []
244 m = re.search('\s*void\s+(\w+)\s*\(', line, re.I)
245 if not m:
246 raise ValueError("Test function should return 'void'\n%s" % line)
247 name = m.group(1)
248 line = line[len(m.group(0)):]
249 arg_idx = 0
250 for arg in line[:line.find(')')].split(','):
251 arg = arg.strip()
252 if arg == '':
253 continue
254 if re.search('int\s+.*', arg.strip()):
255 args.append('int')
256 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
257 elif re.search('char\s*\*\s*.*', arg.strip()):
258 args.append('char*')
259 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100260 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100261 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100262 # create a structure
263 locals += """ HexParam_t hex%d = {%s, %s};
264""" % (arg_idx, '(uint8_t *) params[%d]' % arg_idx, '*( (uint32_t *) params[%d] )' % (arg_idx + 1))
265
266 args_dispatch.append('&hex%d' % arg_idx)
267 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100268 else:
Azim Khan4b543232017-06-30 09:35:21 +0100269 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100270 arg_idx += 1
271
Azim Khan4b543232017-06-30 09:35:21 +0100272 return name, args, locals, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100273
274
Azim Khan4b543232017-06-30 09:35:21 +0100275def parse_function_code(funcs_f, deps, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100276 """
Azim Khanf0e42fb2017-08-02 14:47:13 +0100277 Parses out a function from function file object and generates function and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100278
Azim Khanf0e42fb2017-08-02 14:47:13 +0100279 :param funcs_f: file object of the functions file.
280 :param deps: List of dependencies
281 :param suite_deps: List of test suite dependencies
282 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100283 """
Azim Khan4b543232017-06-30 09:35:21 +0100284 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100285 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100286 # Check function signature
287 m = re.match('.*?\s+(\w+)\s*\(', line, re.I)
288 if m:
289 # check if we have full signature i.e. split in more lines
290 if not re.match('.*\)', line):
291 for lin in funcs_f:
292 line += lin
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100293 if re.search('.*?\)', line):
294 break
Azim Khan4b543232017-06-30 09:35:21 +0100295 name, args, locals, args_dispatch = parse_function_signature(line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100296 code += line.replace(name, 'test_' + name)
297 name = 'test_' + name
298 break
299 else:
300 raise InvalidFileFormat("file: %s - Test functions not found!" % funcs_f.name)
301
302 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100303 if re.search(END_CASE_REGEX, line):
304 break
305 code += line
306 else:
307 raise InvalidFileFormat("file: %s - end case pattern [%s] not found!" % (funcs_f.name, END_CASE_REGEX))
308
309 # Add exit label if not present
310 if code.find('exit:') == -1:
311 s = code.rsplit('}', 1)
312 if len(s) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100313 code = """exit:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100314 ;;
Azim Khan4b543232017-06-30 09:35:21 +0100315}""".join(s)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100316
Azim Khan4b543232017-06-30 09:35:21 +0100317 code += gen_function_wrapper(name, locals, args_dispatch)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100318 ifdef, endif = gen_deps(deps)
319 dispatch_code = gen_dispatch(name, suite_deps + deps)
Azim Khan4b543232017-06-30 09:35:21 +0100320 return name, args, ifdef + code + endif, dispatch_code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100321
322
323def parse_functions(funcs_f):
324 """
325 Returns functions code pieces
326
Azim Khanf0e42fb2017-08-02 14:47:13 +0100327 :param funcs_f: file object of the functions file.
328 :return: List of test suite dependencies, test function dispatch code, function code and
329 a dict with function identifiers and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100330 """
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100331 suite_headers = ''
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000332 suite_helpers = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100333 suite_deps = []
334 suite_functions = ''
335 func_info = {}
336 function_idx = 0
337 dispatch_code = ''
338 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100339 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000340 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100341 suite_headers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000342 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
343 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
344 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100345 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khan4b543232017-06-30 09:35:21 +0100346 deps = parse_suite_deps(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100347 suite_deps += deps
348 elif re.search(BEGIN_CASE_REGEX, line):
349 deps = parse_function_deps(line)
Azim Khan4b543232017-06-30 09:35:21 +0100350 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100351 suite_functions += func_code
352 # Generate dispatch code and enumeration info
353 assert func_name not in func_info, "file: %s - function %s re-declared at line %d" % \
Azim Khan4b543232017-06-30 09:35:21 +0100354 (funcs_f.name, func_name, funcs_f.line_no)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100355 func_info[func_name] = (function_idx, args)
356 dispatch_code += '/* Function Id: %d */\n' % function_idx
357 dispatch_code += func_dispatch
358 function_idx += 1
359
360 ifdef, endif = gen_deps(suite_deps)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000361 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
Azim Khan13c6bfb2017-06-15 14:45:56 +0100362 return suite_deps, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100363
364
365def escaped_split(str, ch):
366 """
367 Split str on character ch but ignore escaped \{ch}
Azim Khan599cd242017-07-06 17:34:27 +0100368 Since return value is used to write back to the intermediate data file.
369 Any escape characters in the input are retained in the output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100370
Azim Khanf0e42fb2017-08-02 14:47:13 +0100371 :param str: String to split
372 :param ch: split character
373 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100374 """
375 if len(ch) > 1:
376 raise ValueError('Expected split character. Found string!')
377 out = []
378 part = ''
379 escape = False
380 for i in range(len(str)):
381 if not escape and str[i] == ch:
382 out.append(part)
383 part = ''
384 else:
Azim Khanacc54732017-07-03 14:06:45 +0100385 part += str[i]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100386 escape = not escape and str[i] == '\\'
387 if len(part):
388 out.append(part)
389 return out
390
391
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100392def parse_test_data(data_f, debug=False):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100393 """
394 Parses .data file
395
Azim Khanf0e42fb2017-08-02 14:47:13 +0100396 :param data_f: file object of the data file.
397 :return: Generator that yields test name, function name, dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100398 """
399 STATE_READ_NAME = 0
400 STATE_READ_ARGS = 1
401 state = STATE_READ_NAME
402 deps = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100403 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100404 for line in data_f:
405 line = line.strip()
406 if len(line) and line[0] == '#': # Skip comments
407 continue
408
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100409 # Blank line indicates end of test
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100410 if len(line) == 0:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100411 assert state != STATE_READ_ARGS, "Newline before arguments. " \
412 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100413 continue
414
415 if state == STATE_READ_NAME:
416 # Read test name
417 name = line
418 state = STATE_READ_ARGS
419 elif state == STATE_READ_ARGS:
420 # Check dependencies
421 m = re.search('depends_on\:(.*)', line)
422 if m:
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100423 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100424 else:
425 # Read test vectors
426 parts = escaped_split(line, ':')
427 function = parts[0]
428 args = parts[1:]
429 yield name, function, deps, args
430 deps = []
431 state = STATE_READ_NAME
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100432 assert state != STATE_READ_ARGS, "Newline before arguments. " \
433 "Test function and arguments missing for %s" % name
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100434
435
436def gen_dep_check(dep_id, dep):
437 """
438 Generate code for the dependency.
439
Azim Khanf0e42fb2017-08-02 14:47:13 +0100440 :param dep_id: Dependency identifier
441 :param dep: Dependency macro
442 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100443 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100444 assert dep_id > -1, "Dependency Id should be a positive integer."
445 noT, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
446 assert len(dep) > 0, "Dependency should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100447 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100448 case {id}:
449 {{
Azim Khand61b8372017-07-10 11:54:01 +0100450#if {noT}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100451 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100452#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100453 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100454#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100455 }}
456 break;'''.format(noT=noT, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100457 return dep_check
458
459
460def gen_expression_check(exp_id, exp):
461 """
462 Generates code for expression check
463
Azim Khanf0e42fb2017-08-02 14:47:13 +0100464 :param exp_id: Expression Identifier
465 :param exp: Expression/Macro
466 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100467 """
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100468 assert exp_id > -1, "Expression Id should be a positive integer."
469 assert len(exp) > 0, "Expression should not be an empty string."
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100470 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100471 case {exp_id}:
472 {{
473 *out_value = {expression};
474 }}
475 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100476 return exp_code
477
478
Azim Khan599cd242017-07-06 17:34:27 +0100479def write_deps(out_data_f, test_deps, unique_deps):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100480 """
Azim Khan599cd242017-07-06 17:34:27 +0100481 Write dependencies to intermediate test data file.
482 It also returns dependency check code.
483
Azim Khanf0e42fb2017-08-02 14:47:13 +0100484 :param out_data_f: Output intermediate data file
485 :param test_deps: Dependencies
486 :param unique_deps: Mutable list to track unique dependencies that are global to this re-entrant function.
487 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100488 """
Azim Khan599cd242017-07-06 17:34:27 +0100489 dep_check_code = ''
490 if len(test_deps):
491 out_data_f.write('depends_on')
492 for dep in test_deps:
493 if dep not in unique_deps:
494 unique_deps.append(dep)
495 dep_id = unique_deps.index(dep)
496 dep_check_code += gen_dep_check(dep_id, dep)
497 else:
498 dep_id = unique_deps.index(dep)
499 out_data_f.write(':' + str(dep_id))
500 out_data_f.write('\n')
501 return dep_check_code
502
503
504def write_parameters(out_data_f, test_args, func_args, unique_expressions):
505 """
506 Writes test parameters to the intermediate data file.
507 Also generates expression code.
508
Azim Khanf0e42fb2017-08-02 14:47:13 +0100509 :param out_data_f: Output intermediate data file
510 :param test_args: Test parameters
511 :param func_args: Function arguments
512 :param unique_expressions: Mutable list to track unique expressions that are global to this re-entrant function.
513 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100514 """
515 expression_code = ''
516 for i in xrange(len(test_args)):
517 typ = func_args[i]
518 val = test_args[i]
519
520 # check if val is a non literal int val
521 if typ == 'int' and not re.match('(\d+$)|((0x)?[0-9a-fA-F]+$)', val): # its an expression
522 typ = 'exp'
523 if val not in unique_expressions:
524 unique_expressions.append(val)
525 # exp_id can be derived from len(). But for readability and consistency with case of existing let's
526 # use index().
527 exp_id = unique_expressions.index(val)
528 expression_code += gen_expression_check(exp_id, val)
529 val = exp_id
530 else:
531 val = unique_expressions.index(val)
532 out_data_f.write(':' + typ + ':' + str(val))
533 out_data_f.write('\n')
534 return expression_code
535
536
537def gen_suite_deps_checks(suite_deps, dep_check_code, expression_code):
538 """
539 Adds preprocessor checks for test suite dependencies.
540
Azim Khanf0e42fb2017-08-02 14:47:13 +0100541 :param suite_deps: Test suite dependencies read from the .functions file.
542 :param dep_check_code: Dependency check code
543 :param expression_code: Expression check code
544 :return: Dependency and expression code guarded by test suite dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100545 """
Azim Khan599cd242017-07-06 17:34:27 +0100546 if len(suite_deps):
547 ifdef = gen_deps_one_line(suite_deps)
548 dep_check_code = '''
549{ifdef}
550{code}
Azim Khan599cd242017-07-06 17:34:27 +0100551#endif
552'''.format(ifdef=ifdef, code=dep_check_code)
553 expression_code = '''
554{ifdef}
555{code}
Azim Khan599cd242017-07-06 17:34:27 +0100556#endif
557'''.format(ifdef=ifdef, code=expression_code)
558 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100559
560
Azim Khan13c6bfb2017-06-15 14:45:56 +0100561def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100562 """
563 Generates dependency checks, expression code and intermediate data file from test data file.
564
Azim Khanf0e42fb2017-08-02 14:47:13 +0100565 :param data_f: Data file object
566 :param out_data_f:Output intermediate data file
567 :param func_info: Dict keyed by function and with function id and arguments info
568 :param suite_deps: Test suite deps
569 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100570 """
571 unique_deps = []
572 unique_expressions = []
573 dep_check_code = ''
574 expression_code = ''
575 for test_name, function_name, test_deps, test_args in parse_test_data(data_f):
576 out_data_f.write(test_name + '\n')
577
Azim Khan599cd242017-07-06 17:34:27 +0100578 # Write deps
579 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100580
Azim Khan599cd242017-07-06 17:34:27 +0100581 # Write test function name
582 test_function_name = 'test_' + function_name
583 assert test_function_name in func_info, "Function %s not found!" % test_function_name
584 func_id, func_args = func_info[test_function_name]
585 out_data_f.write(str(func_id))
586
587 # Write parameters
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100588 assert len(test_args) == len(func_args), \
589 "Invalid number of arguments in test %s. See function %s signature." % (test_name, function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100590 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100591
Azim Khan599cd242017-07-06 17:34:27 +0100592 # Write a newline as test case separator
593 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100594
Azim Khan599cd242017-07-06 17:34:27 +0100595 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100596 return dep_check_code, expression_code
597
598
Azim Khan1de892b2017-06-09 15:02:36 +0100599def 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 +0100600 """
601 Generate mbed-os test code.
602
Azim Khanf0e42fb2017-08-02 14:47:13 +0100603 :param funcs_file: Functions file object
604 :param data_file: Data file object
605 :param template_file: Template file object
606 :param platform_file: Platform file object
607 :param help_file: Helper functions file object
608 :param suites_dir: Test suites dir
609 :param c_file: Output C file object
610 :param out_data_file: Output intermediate data file object
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100611 :return:
612 """
613 for name, path in [('Functions file', funcs_file),
614 ('Data file', data_file),
615 ('Template file', template_file),
616 ('Platform file', platform_file),
617 ('Help code file', help_file),
618 ('Suites dir', suites_dir)]:
619 if not os.path.exists(path):
620 raise IOError("ERROR: %s [%s] not found!" % (name, path))
621
622 snippets = {'generator_script' : os.path.basename(__file__)}
623
624 # Read helpers
625 with open(help_file, 'r') as help_f, open(platform_file, 'r') as platform_f:
626 snippets['test_common_helper_file'] = help_file
627 snippets['test_common_helpers'] = help_f.read()
628 snippets['test_platform_file'] = platform_file
629 snippets['platform_code'] = platform_f.read().replace('DATA_FILE',
630 out_data_file.replace('\\', '\\\\')) # escape '\'
631
632 # Function code
Azim Khanacc54732017-07-03 14:06:45 +0100633 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 +0100634 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100635 snippets['functions_code'] = func_code
636 snippets['dispatch_code'] = dispatch_code
Azim Khan13c6bfb2017-06-15 14:45:56 +0100637 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 +0100638 snippets['dep_check_code'] = dep_check_code
639 snippets['expression_code'] = expression_code
640
641 snippets['test_file'] = c_file
642 snippets['test_main_file'] = template_file
643 snippets['test_case_file'] = funcs_file
644 snippets['test_case_data_file'] = data_file
645 # Read Template
646 # Add functions
647 #
648 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
649 line_no = 1
650 for line in template_f.readlines():
651 snippets['line_no'] = line_no + 1 # Increment as it sets next line number
652 code = line.format(**snippets)
653 c_f.write(code)
654 line_no += 1
655
656
657def check_cmd():
658 """
659 Command line parser.
660
661 :return:
662 """
663 parser = argparse.ArgumentParser(description='Generate code for mbed-os tests.')
664
665 parser.add_argument("-f", "--functions-file",
666 dest="funcs_file",
667 help="Functions file",
668 metavar="FUNCTIONS",
669 required=True)
670
671 parser.add_argument("-d", "--data-file",
672 dest="data_file",
673 help="Data file",
674 metavar="DATA",
675 required=True)
676
677 parser.add_argument("-t", "--template-file",
678 dest="template_file",
679 help="Template file",
680 metavar="TEMPLATE",
681 required=True)
682
683 parser.add_argument("-s", "--suites-dir",
684 dest="suites_dir",
685 help="Suites dir",
686 metavar="SUITES",
687 required=True)
688
689 parser.add_argument("--help-file",
690 dest="help_file",
691 help="Help file",
692 metavar="HELPER",
693 required=True)
694
695 parser.add_argument("-p", "--platform-file",
696 dest="platform_file",
697 help="Platform code file",
698 metavar="PLATFORM_FILE",
699 required=True)
700
701 parser.add_argument("-o", "--out-dir",
702 dest="out_dir",
703 help="Dir where generated code and scripts are copied",
704 metavar="OUT_DIR",
705 required=True)
706
707 args = parser.parse_args()
708
709 data_file_name = os.path.basename(args.data_file)
710 data_name = os.path.splitext(data_file_name)[0]
711
712 out_c_file = os.path.join(args.out_dir, data_name + '.c')
713 out_data_file = os.path.join(args.out_dir, data_file_name)
714
715 out_c_file_dir = os.path.dirname(out_c_file)
716 out_data_file_dir = os.path.dirname(out_data_file)
717 for d in [out_c_file_dir, out_data_file_dir]:
718 if not os.path.exists(d):
719 os.makedirs(d)
720
Azim Khan1de892b2017-06-09 15:02:36 +0100721 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100722 args.help_file, args.suites_dir, out_c_file, out_data_file)
723
724
725if __name__ == "__main__":
726 check_cmd()