#!/usr/bin/env python

#  Copyright (c) 2016, College of William & Mary
#  All rights reserved.
#  
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#      * Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#      * Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#      * Neither the name of the College of William & Mary nor the
#        names of its contributors may be used to endorse or promote products
#        derived from this software without specific prior written permission.
#  
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COLLEGE OF WILLIAM & MARY BE LIABLE FOR ANY
#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#  
#  PRIMME: https://github.com/primme/primme
#  Contact: Andreas Stathopoulos, a n d r e a s _at_ c s . w m . e d u

import re
import sys

"""
This module extracts function declarations from function implementations preceded by
APPEND_FUNC and allows to change the name of the final symbol.

It is expected the next pattern for the function to process:

   APPEND_FUNC(OLD_SUFFIX, NEW_SUFFIX_SYMBOL) [ USE(NEW_SUFFIX, "MACRO") ]+ 
   type fun_attribute+ fun_name (...) {

First for every tag USE(NEW_SUFFIX, MACRO) it is printed out:

   #if !defined(CHECK_TEMPLATE) && !defined(fun_name_alias)
   #   define fun_name_alias CONCAT(fun_name_stem, MACRO)
   #endif

where fun_name_alias is generated by replacing OLD_SUFFIX by NEW_SUFFIX in fun_name,
and fun_name_stem is fun_name without OLD_SUFFIX. And after that it is
printed out:

   type fun_attribute+ new_fun_name (...) ;

where new_fun_name is generated by replacing OLD_SUFFIX by NEW_SUFFIX_SYMBOL in
fun_name.

Examples
--------
The most direct use is to automatically change the function name (the symbol
name) and the header files when the function prototype depends on macros.
For instance, we have this function in f.c:

   TYPE sum_x(TYPE a, TYPE b) { return a+b; }

If we build f.c with different values for TYPE, all symbols will have the
name sum_x, then they cannot be included together in the same executable
or library. A possible alternative is to use a macro to change the
function name depending of TYPE, for instance:
 
   #define sum_x CONCAT(sum_, TYPE)
   TYPE sum_x(TYPE a, TYPE b) { return a+b; }

where CONCAT can be a macro that just appends the two arguments.
Still it is needed to manually declare all the possible prototypes in
a header file. This tool automatizes this task.

Let the content of f.c be:

   #define sum_x CONCAT(sum_, SUF)
   #define CONCAT(a, b) CONCATX(a, b)
   #define CONCATX(a, b) a ## b
   APPEND_FUNC(,)
   TYPE sum_x(TYPE a, TYPE b) { return a+b; }

The content of f.h can be generated invoking the preprocessor and passing the
output to this module. For instance the next commands:

   gcc -E f.c -DSUF=f -DTYPE=float | ctemplate > f.h
   gcc -E f.c -DSUF=d -DTYPE=double | ctemplate >> f.h

generated the next content in f.h:

   float sum_f(float a, float b);
   double sum_d(double a, double b);
 
Now f.h can be include in other source file that calls some of sum_x variants.

With a little more of effort, ctemplate can generate also the define that
replaces sum_x with the corresponding variant. Let update the content of f.c:

   #include "f.h"
   #define CONCAT(a, b) CONCATX(a, b)
   #define CONCATX(a, b) a ## b
   APPEND_FUNC(x,SUF) USE(x,"SUF")
   TYPE sum_x(TYPE a, TYPE b) { return a+b; }

First generate f.h executing:

   cat < /dev/null > f.h
   gcc -E f.c -DCHECK_TEMPLATE -DSUF=f -DTYPE=float | ctemplate > f.h
   gcc -E f.c -DCHECK_TEMPLATE -DSUF=d -DTYPE=double | ctemplate >> f.h

After that the content of f.h should be:

   #if !defined(CHECK_TEMPLATE) && !defined(sum_x)
   #  define sum_x CONCAT(sum_,SUF)
   #endif
   float sum_f(float a, float b);
   #if !defined(CHECK_TEMPLATE) && !defined(sum_x)
   #  define sum_x CONCAT(sum_,SUF)
   #endif
   double sum_d(double a, double b);

Now sum_x calls sum_f or sum_d depending of the value of the macro SUF.
"""

def generate_definitions(s):
	r = []
	defined_macros = set()
	p = r'\s*'.join(r'APPEND_FUNC \( (?P<SUF>\w*) , (?P<NEW>\w*) \) (?P<USE>(USE \( \w* , "[^"]*" \) )*) (?P<D>[^{(;]+ (?P<F>\b\w+\b) \([^{;]*) \{'.split())
	for m in re.finditer(p, s):
		# Replace SUF by NEW in the function name F
		Fnew = re.sub(m.group('SUF')+'$', m.group('NEW'), m.group('F'))
		Fstem = re.sub(m.group('SUF')+'$', '', m.group('F'))
		D = re.sub(r'\b{0}\b'.format(m.group('F')), Fnew, m.group('D'))
		if m.group('USE'):
			for useNEW, useMACRO in re.findall(r'\s*'.join(r'USE \( (\w*) , "([^"]*)" \)'.split()), m.group('USE')):
				if Fstem+useNEW not in defined_macros:
					defined_macros.add(Fstem+useNEW)
					r.append("""\
#if !defined(CHECK_TEMPLATE) && !defined({alias})
#  define {alias} CONCAT({stem},{macro})
#endif\
""".format(alias=Fstem+useNEW, stem=Fstem, macro=useMACRO))
		r.append(D.strip() + ";")
	r.append("")
	return "\n".join(r)

def test_generate_definitions():
	s = "APPEND_FUNC(,d) int f0(int a, int b) {return f1(a);}"
	r = generate_definitions(s)
	assert("int f0d(int a, int b)" in r)
	assert("{" not in r)
	assert("}" not in r)
	assert(";" in r)

	s = 'APPEND_FUNC(x,d) USE(r,"R_PREFIX") int f0x(int a, int b) {return f1(a);}'
	r = generate_definitions(s)
	assert("int f0d(int a, int b)" in r)
	assert("{" not in r)
	assert("}" not in r)
	assert(";" in r)


if __name__ == "__main__":
	if "-t" in sys.argv:
		test_generate_definitions()
	else:
		# Filter out lines starting with '#', they are preprocessor notes
		s = "".join([l for l in sys.stdin.readlines() if not l.startswith("#")])
		sys.stdout.write(generate_definitions(s))
