blob: 345df533dcbb51fe16ba8a6fe4175a41da35acf1 [file] [log] [blame]
Jaeden Ameroe54e6932018-08-06 16:19:58 +01001#!/usr/bin/env python3
2# Test suites code generator.
3#
4# Copyright (C) 2018, ARM Limited, All Rights Reserved
5# 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 Crypto (https://tls.mbed.org)
20
21"""
22Test Suite code generator.
23
24Generates a test source file using following input files:
25
26test_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.
34"""
35
36
37import io
38import os
39import re
40import sys
41import argparse
42import shutil
43
44
45BEGIN_HEADER_REGEX = '/\*\s*BEGIN_HEADER\s*\*/'
46END_HEADER_REGEX = '/\*\s*END_HEADER\s*\*/'
47
48BEGIN_SUITE_HELPERS_REGEX = '/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
49END_SUITE_HELPERS_REGEX = '/\*\s*END_SUITE_HELPERS\s*\*/'
50
51BEGIN_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 """
60 Exception to indicate invalid file format.
61 """
62 pass
63
64
65class FileWrapper(io.FileIO):
66 """
67 File wrapper class. Provides reading with line no. tracking.
68 """
69
70 def __init__(self, file_name):
71 """
72 Init file handle.
73
74 :param file_name: File path to open.
75 """
76 super(FileWrapper, self).__init__(file_name, 'r')
77 self.line_no = 0
78
79 # Override the generator function in a way that works in both Python 2
80 # and Python 3.
81 def __next__(self):
82 """
83 Iterator return impl.
84 :return: Line read from file.
85 """
86 parent = super(FileWrapper, self)
87 if hasattr(parent, '__next__'):
88 line = parent.__next__() # Python 3
89 else:
90 line = parent.next() # Python 2
91 if line:
92 self.line_no += 1
93 # Convert byte array to string with correct encoding
94 return line.decode(sys.getdefaultencoding())
95 return None
96 next = __next__
97
98
99def split_dep(dep):
100 """
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 """
106 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
107
108
109def gen_deps(deps):
110 """
111 Generates dependency i.e. if def and endif code
112
113 :param deps: List of dependencies.
114 :return: if defined and endif code with macro annotations for readability.
115 """
116 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
119 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
126 :param deps: List of dependencies.
127 :return: ifdef code
128 """
129 defines = ('#if ' if len(deps) else '') + ' && '.join(['%sdefined(%s)' % split_dep(x) for x in deps])
130 return defines
131
132
133def gen_function_wrapper(name, locals, args_dispatch):
134 """
135 Creates test function wrapper code. A wrapper has the code to unpack parameters from parameters[] array.
136
137 :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.
141 """
142 # Then create the wrapper
143 wrapper = '''
144void {name}_wrapper( void ** params )
145{{
146{unused_params}{locals}
147 {name}( {args} );
148}}
149'''.format(name=name,
150 unused_params='' if args_dispatch else ' (void) params;\n',
151 args=', '.join(args_dispatch),
152 locals=locals)
153 return wrapper
154
155
156def gen_dispatch(name, deps):
157 """
158 Generates dispatch code for the test function table.
159
160 :param name: Test function name
161 :param deps: List of dependencies
162 :return: Dispatch code.
163 """
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
181def parse_until_pattern(funcs_f, end_regex):
182 """
183 Parses function headers or helper code until end pattern.
184
185 :param funcs_f: file object for .functions file
186 :param end_regex: Pattern to stop parsing
187 :return: Test suite headers code
188 """
189 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
190 for line in funcs_f:
191 if re.search(end_regex, line):
192 break
193 headers += line
194 else:
195 raise InvalidFileFormat("file: %s - end pattern [%s] not found!" % (funcs_f.name, end_regex))
196
197 return headers
198
199
200def parse_suite_deps(funcs_f):
201 """
202 Parses test suite dependencies.
203
204 :param funcs_f: file object for .functions file
205 :return: List of test suite dependencies.
206 """
207 deps = []
208 for line in funcs_f:
209 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
217 return deps
218
219
220def parse_function_deps(line):
221 """
222 Parses function dependencies.
223
224 :param line: Line from .functions file that has dependencies.
225 :return: List of dependencies.
226 """
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:
233 deps = [x.strip() for x in m.group(1).strip().split(':')]
234 return deps
235
236
237def parse_function_signature(line):
238 """
239 Parsing function signature
240
241 :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.
243 """
244 args = []
245 locals = ''
246 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)
263 elif re.search('HexParam_t\s*\*\s*.*', arg.strip()):
264 args.append('hex')
265 # 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
271 else:
272 raise ValueError("Test function arguments can only be 'int', 'char *' or 'HexParam_t'\n%s" % line)
273 arg_idx += 1
274
275 return name, args, locals, args_dispatch
276
277
278def parse_function_code(funcs_f, deps, suite_deps):
279 """
280 Parses out a function from function file object and generates function and dispatch code.
281
282 :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.
286 """
287 code = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
288 for line in funcs_f:
289 # 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
296 if re.search('.*?\)', line):
297 break
298 name, args, locals, args_dispatch = parse_function_signature(line)
299 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:
306 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:
316 code = """exit:
317 ;;
318}""".join(s)
319
320 code += gen_function_wrapper(name, locals, args_dispatch)
321 ifdef, endif = gen_deps(deps)
322 dispatch_code = gen_dispatch(name, suite_deps + deps)
323 return name, args, ifdef + code + endif, dispatch_code
324
325
326def parse_functions(funcs_f):
327 """
328 Returns functions code pieces
329
330 :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.
333 """
334 suite_headers = ''
335 suite_helpers = ''
336 suite_deps = []
337 suite_functions = ''
338 func_info = {}
339 function_idx = 0
340 dispatch_code = ''
341 for line in funcs_f:
342 if re.search(BEGIN_HEADER_REGEX, line):
343 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
344 suite_headers += headers
345 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
346 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
347 suite_helpers += helpers
348 elif re.search(BEGIN_DEP_REGEX, line):
349 deps = parse_suite_deps(funcs_f)
350 suite_deps += deps
351 elif re.search(BEGIN_CASE_REGEX, line):
352 deps = parse_function_deps(line)
353 func_name, args, func_code, func_dispatch = parse_function_code(funcs_f, deps, suite_deps)
354 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" % \
357 (funcs_f.name, func_name, funcs_f.line_no)
358 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)
364 func_code = ifdef + suite_headers + suite_helpers + suite_functions + endif
365 return suite_deps, dispatch_code, func_code, func_info
366
367
368def escaped_split(str, ch):
369 """
370 Split str on character ch but ignore escaped \{ch}
371 Since return value is used to write back to the intermediate data file.
372 Any escape characters in the input are retained in the output.
373
374 :param str: String to split
375 :param ch: split character
376 :return: List of splits
377 """
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:
388 part += str[i]
389 escape = not escape and str[i] == '\\'
390 if len(part):
391 out.append(part)
392 return out
393
394
395def parse_test_data(data_f, debug=False):
396 """
397 Parses .data file
398
399 :param data_f: file object of the data file.
400 :return: Generator that yields test name, function name, dependency list and function argument list.
401 """
402 STATE_READ_NAME = 0
403 STATE_READ_ARGS = 1
404 state = STATE_READ_NAME
405 deps = []
406 name = ''
407 for line in data_f:
408 line = line.strip()
409 if len(line) and line[0] == '#': # Skip comments
410 continue
411
412 # Blank line indicates end of test
413 if len(line) == 0:
414 assert state != STATE_READ_ARGS, "Newline before arguments. " \
415 "Test function and arguments missing for %s" % name
416 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:
426 deps = [x.strip() for x in m.group(1).split(':') if len(x.strip())]
427 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
435 assert state != STATE_READ_ARGS, "Newline before arguments. " \
436 "Test function and arguments missing for %s" % name
437
438
439def gen_dep_check(dep_id, dep):
440 """
441 Generate code for the dependency.
442
443 :param dep_id: Dependency identifier
444 :param dep: Dependency macro
445 :return: Dependency check code
446 """
447 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."
450 dep_check = '''
451 case {id}:
452 {{
453#if {noT}defined({macro})
454 ret = DEPENDENCY_SUPPORTED;
455#else
456 ret = DEPENDENCY_NOT_SUPPORTED;
457#endif
458 }}
459 break;'''.format(noT=noT, macro=dep, id=dep_id)
460 return dep_check
461
462
463def gen_expression_check(exp_id, exp):
464 """
465 Generates code for expression check
466
467 :param exp_id: Expression Identifier
468 :param exp: Expression/Macro
469 :return: Expression check code
470 """
471 assert exp_id > -1, "Expression Id should be a positive integer."
472 assert len(exp) > 0, "Expression should not be an empty string."
473 exp_code = '''
474 case {exp_id}:
475 {{
476 *out_value = {expression};
477 }}
478 break;'''.format(exp_id=exp_id, expression=exp)
479 return exp_code
480
481
482def write_deps(out_data_f, test_deps, unique_deps):
483 """
484 Write dependencies to intermediate test data file.
485 It also returns dependency check code.
486
487 :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.
491 """
492 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.
511
512 :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.
517 """
518 expression_code = ''
519 for i in range(len(test_args)):
520 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.
543
544 :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.
548 """
549 if len(suite_deps):
550 ifdef = gen_deps_one_line(suite_deps)
551 dep_check_code = '''
552{ifdef}
553{code}
554#endif
555'''.format(ifdef=ifdef, code=dep_check_code)
556 expression_code = '''
557{ifdef}
558{code}
559#endif
560'''.format(ifdef=ifdef, code=expression_code)
561 return dep_check_code, expression_code
562
563
564def gen_from_test_data(data_f, out_data_f, func_info, suite_deps):
565 """
566 Generates dependency checks, expression code and intermediate data file from test data file.
567
568 :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
573 """
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
581 # Write deps
582 dep_check_code += write_deps(out_data_f, test_deps, unique_deps)
583
584 # 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
591 assert len(test_args) == len(func_args), \
592 "Invalid number of arguments in test %s. See function %s signature." % (test_name, function_name)
593 expression_code += write_parameters(out_data_f, test_args, func_args, unique_expressions)
594
595 # Write a newline as test case separator
596 out_data_f.write('\n')
597
598 dep_check_code, expression_code = gen_suite_deps_checks(suite_deps, dep_check_code, expression_code)
599 return dep_check_code, expression_code
600
601
602def generate_code(funcs_file, data_file, template_file, platform_file, help_file, suites_dir, c_file, out_data_file):
603 """
604 Generate mbed-os test code.
605
606 :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
614 :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
636 with FileWrapper(funcs_file) as funcs_f, open(data_file, 'r') as data_f, open(out_data_file, 'w') as out_data_f:
637 suite_deps, dispatch_code, func_code, func_info = parse_functions(funcs_f)
638 snippets['functions_code'] = func_code
639 snippets['dispatch_code'] = dispatch_code
640 dep_check_code, expression_code = gen_from_test_data(data_f, out_data_f, func_info, suite_deps)
641 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
724 generate_code(args.funcs_file, args.data_file, args.template_file, args.platform_file,
725 args.help_file, args.suites_dir, out_c_file, out_data_file)
726
727
728if __name__ == "__main__":
729 check_cmd()