sourcehook/generate/shworker/fd_hopter.cpp
author Pavol Marko <pavolmarko@gmail.com>
Thu Apr 14 16:17:40 2005 +0000 (2005-04-14)
changeset 3 5a9efd949f83
parent 1 586787053c73
child 195 5f80856d32d8
permissions -rw-r--r--
Fixed bugs with multiple and virtual inheritance
     1 // From fastdelegate
     2 // http://www.codeproject.com/cpp/FastDelegate.asp
     3 
     4 // Modified to be run from shworker by PM
     5 
     6 
     7 // HOPTER.EXE -- A simple header generator for vararg templates
     8 /*  MOTIVATION
     9  C++ doesn't have a vararg feature for templates. This can be a
    10  nuisance when writing class libraries. There are a few options:
    11  (a) manually repeat code. This is tedious and error prone.
    12  (b) Use macros. Messy, can't cope with template
    13    arguments, and users get hard-to-interpret error messages.
    14  (c) Use the boost preprocessor library. This slows compilation,
    15    and introduces a dependency on boost.
    16  (d) Write a program to automatically generate the code.
    17    I've never seen a general program to do this job, so this is 
    18    a very simple command-line program to do it.
    19 
    20  Why is it called Hopter?
    21  I wanted a word that started with h, to be reminiscent of header
    22  files. At the time, my 2yo son kept talking about 'Hopter Copters'
    23  (he couldn't pronounce 'helicopter').
    24  It also reflects the level of sophistication of this program --
    25  it was named by a two year old.
    26 
    27  IMPLEMENTATION
    28 
    29  When you analyze the problem, you find that the requirements
    30  are very simple.
    31  Varargs are needed in two places: templates and functions.
    32  You want to use them in two ways: when declaring the template
    33  or function, and when invoking the function / selecting the 
    34  template.
    35 
    36  It's a brain-dead implementation, which just does a search-and-replace
    37  of specific strings. It could be done with a few lines using sed on
    38  a *NIX platform. Because I use Windows, I've done a quick and dirty
    39  implementation using CString.
    40 
    41 In a file, @VARARGS at the start of a line indicates the start of the code
    42 to be expanded. @ENDVAR at the start of a line marks the end of the 
    43 expansion.
    44 
    45  declare template  --  template <@CLASSARGS> class SomeClass
    46  template<class Param1, class Param2>
    47  class SomeClass
    48 
    49  declare function  -- somefunc(@FUNCARGS)
    50  somefunc(Param1 p1, Param2 p2)
    51 
    52  select template -- SomeClass<@SELARGS>
    53  SomeClass<Param1, Param2>
    54 
    55  invoke function -- somefunc(@INVOKEARGS)
    56  somefunc(p1, p2)
    57 
    58  I also provide @NUM which is the number of arguments.
    59  The case where @NUM is zero is a special case: for template declarations,
    60  the entire template<> bit needs to disappear. When other arguments are 
    61  involved, either at the beginning or end of the list, there a commas 
    62  which might need to be removed.
    63 
    64  I've used .hxx as the extension for these files. This enables C++ 
    65  I wanted to use an unusual file extension (.HOH) for these files, because they
    66  aren't real header files. But I also like to use the C++ syntax highlighting 
    67  in Visual Studio. I chose .hxx because MSVC treats it as C++, but it 
    68  seems to very rarely used.
    69 
    70  Installation (for VC6, if you want to use .HOH as the extension instead):
    71  Go into the registry and change 
    72  HKEY_CURRENT_USER\Software\Microsoft\DevStudio\6.0\Text Editor\Tabs/Language Settings\C/C++\FileExtensions from cpp;cxx;c;h;hxx;hpp;inl;tlh;tli;rc;rc2 
    73  to cpp;cxx;c;h;hxx;hpp;inl;tlh;tli;rc;rc2;hoh by adding �;hoh� to the end.
    74  Then add this as a custom build step to the main file of your project:
    75  hopter $(InputDir)\*.hoh $(InputDir)\*.h
    76 
    77 */
    78 
    79 #include <string>
    80 #include <stdarg.h>
    81 #include <stdio.h>
    82 
    83 // This is a quick-n-dirty implementation of a CString replacement.
    84 // It promises nothing more than to provide enough functionality to get
    85 // this program to run.
    86 // Note that I have really never used CString, so the information to
    87 // implement the members that are used in this program come from
    88 // online documentation at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmfc98/html/_mfc_cstring.asp
    89 // Also, I have only used VC++ a few times, a long time ago, so
    90 // I really do not know what all their alphabet soup is suppoed to
    91 // mean, so I just made a guess...
    92 
    93 
    94 class CString
    95 {
    96 public:
    97   enum { MAX_FORMAT_STRING_SIZE = 8 * 1044 };
    98   CString()
    99     : str_()
   100   {
   101   }
   102 
   103   CString(
   104       CString const & rhs)
   105     : str_(rhs.str_)
   106   {
   107   }
   108 
   109   CString(
   110       char ch,
   111       int repeat = 1)
   112     : str_(repeat, ch)
   113   {
   114   }
   115 
   116   CString(
   117       char const * s)
   118     : str_(s)
   119   {
   120   }
   121 
   122   CString & operator=(
   123       CString const & rhs)
   124   {
   125     str_ = rhs.str_;
   126     return *this;
   127   }
   128 
   129   CString & operator=(
   130       char const * s)
   131   {
   132     str_ = s;
   133     return *this;
   134   }
   135 
   136   CString & operator=(
   137       char ch)
   138   {
   139     str_ = ch;
   140     return *this;
   141   }
   142 
   143   void Format(
   144       char const * fmt,
   145       ...)
   146   {
   147     char buffer[ MAX_FORMAT_STRING_SIZE ];
   148     va_list ap;
   149     va_start(ap, fmt);
   150     vsprintf(buffer, fmt, ap);
   151     va_end(ap);
   152     str_ = buffer;
   153   }
   154 
   155   char operator[](
   156       int x) const
   157   {
   158     return str_[x];
   159   }
   160   
   161   CString & operator+=(
   162       CString const & x)
   163   {
   164     str_ += x.str_; return *this;
   165   }
   166 
   167   int Replace(
   168       CString const & lhs,
   169       CString const & rhs)
   170   {
   171     int rval = 0;
   172     std::string::size_type pos = 0;
   173     while (pos < str_.length())
   174     {
   175       pos = str_.find(lhs.str_, pos);
   176       if (pos != std::string::npos)
   177       {
   178         str_.replace(pos, lhs.GetLength(), rhs.str_);
   179         pos += rhs.GetLength();
   180         ++rval;
   181       }
   182     }
   183     return rval;
   184   }
   185 
   186   int GetLength() const
   187   {
   188     return str_.length();
   189   }
   190 
   191   operator char const * () const
   192   {
   193     return str_.c_str();
   194   }
   195 
   196 private:
   197   std::string str_;
   198 };
   199 
   200 
   201 CString operator+(
   202     CString const & x,
   203     CString const & y)
   204 {
   205   CString result(x);
   206   result += y;
   207   return result;
   208 }
   209 
   210 
   211 /* Example: This is an excerpt from boost::function_template.hpp
   212 
   213 #define BOOST_FUNCTION_FUNCTION_INVOKER \
   214   BOOST_JOIN(function_invoker,BOOST_FUNCTION_NUM_ARGS)
   215 #define BOOST_FUNCTION_VOID_FUNCTION_INVOKER \
   216   BOOST_JOIN(void_function_invoker,BOOST_FUNCTION_NUM_ARGS)
   217 
   218       template<
   219         typename FunctionPtr,
   220         typename R BOOST_FUNCTION_COMMA
   221         BOOST_FUNCTION_TEMPLATE_PARMS
   222       >
   223       struct BOOST_FUNCTION_GET_FUNCTION_INVOKER
   224       {
   225         typedef typename ct_if<(is_void<R>::value),
   226                             BOOST_FUNCTION_VOID_FUNCTION_INVOKER<
   227                             FunctionPtr,
   228                             R BOOST_FUNCTION_COMMA
   229                             BOOST_FUNCTION_TEMPLATE_ARGS
   230                           >,
   231                           BOOST_FUNCTION_FUNCTION_INVOKER<
   232                             FunctionPtr,
   233                             R BOOST_FUNCTION_COMMA
   234                             BOOST_FUNCTION_TEMPLATE_ARGS
   235                           >
   236                        >::type type;
   237       };
   238 
   239 Using HOPTER, this can be written as:
   240 
   241     template< typename FunctionPtr, typename R, @CLASSARGS>
   242       struct get_function_invoker@NUM
   243 	  {
   244         typedef typename ct_if<(is_void<R>::value),
   245 					void_function_invoker@NUM<FunctionPtr, R, @SELARGS>,
   246 					function_invoker@NUM<FunctionPtr,R, @SELARGS>
   247                        >::type type;
   248       };
   249 */
   250 
   251 int MaxNumArgs;
   252 
   253 /// Makes the necessary subsititutions in 'bigblock', and writes to fout.
   254 void PrintVarArgs(FILE *fout, CString bigblock, int num) {
   255 	CString numstr;
   256 	CString invokelist;
   257 	CString funclist;
   258 	CString selectlist;
   259 	CString classlist;
   260 	CString commastr;
   261 	numstr.Format("%d", num);
   262 	if (num==0) {
   263 		invokelist="";
   264 		funclist="";
   265 		selectlist="";
   266 		commastr="";
   267 		classlist="";
   268 	}else {
   269 		invokelist="p1";
   270 		funclist="Param1 p1";
   271 		selectlist = "Param1";
   272 		classlist = "class Param1";
   273 		commastr=", ";
   274 		CString str;
   275 		for (int k=2; k<=num; k++) {
   276 			str.Format(", p%d", k);
   277 			invokelist+=str;
   278 			str.Format(", Param%d p%d", k, k);
   279 			funclist+=str;
   280 			str.Format(", Param%d", k);
   281 			selectlist += str;
   282 			str.Format(", class Param%d", k);
   283 			classlist += str;
   284 		}
   285 	}
   286 
   287 	// Simple replacement of number of arguments
   288 	bigblock.Replace("@NUM", numstr);
   289 
   290 	// Template declarations
   291 	if (num==0) bigblock.Replace("template<@CLASSARGS>", "");
   292 	else bigblock.Replace("template<@CLASSARGS>", 
   293 		(CString)"template<" + classlist+">");
   294 	if (num==0) bigblock.Replace("template <@CLASSARGS>", "");
   295 	else bigblock.Replace("template <@CLASSARGS>", 
   296 		(CString)"template<" + classlist+">");
   297 	bigblock.Replace(",@CLASSARGS", commastr + classlist);
   298 	bigblock.Replace(", @CLASSARGS", commastr + classlist);
   299 	bigblock.Replace("@CLASSARGS, ", classlist + commastr);
   300 	bigblock.Replace("@CLASSARGS,", classlist + commastr);
   301 	bigblock.Replace("@CLASSARGS", classlist);
   302 
   303 	// Template selections
   304 	CString selargstr;
   305 	if (num==0) selargstr = "";
   306 	else selargstr = (CString)"<"+selectlist+">";
   307 
   308 	bigblock.Replace("<@SELARGS>", selargstr);
   309 	bigblock.Replace("< @SELARGS >", selargstr);
   310 	bigblock.Replace(",@SELARGS", commastr + selectlist);
   311 	bigblock.Replace(", @SELARGS", commastr + selectlist);
   312 	bigblock.Replace("@SELARGS, ", selectlist + commastr);
   313 	bigblock.Replace("@SELARGS,", selectlist + commastr);
   314 	bigblock.Replace("@SELARGS", selectlist);
   315 
   316 	// Function declarations
   317 	bigblock.Replace(",@FUNCARGS", commastr + funclist);
   318 	bigblock.Replace(", @FUNCARGS", commastr + funclist);
   319 	bigblock.Replace("@FUNCARGS, ", funclist + commastr);
   320 	bigblock.Replace("@FUNCARGS,", funclist + commastr);
   321 	bigblock.Replace("@FUNCARGS", funclist);
   322 
   323 	// Function invocation
   324 	bigblock.Replace(",@INVOKEARGS", commastr + invokelist);
   325 	bigblock.Replace(", @INVOKEARGS", commastr + invokelist);
   326 	bigblock.Replace("@INVOKEARGS, ", invokelist + commastr);
   327 	bigblock.Replace("@INVOKEARGS,", invokelist + commastr);
   328 	bigblock.Replace("@INVOKEARGS", invokelist);
   329 
   330 	fprintf(fout, bigblock);				
   331 }
   332 
   333 int hopter(int numargs, const char *filenamein, const char *filenameout)
   334 {
   335 
   336 	MaxNumArgs = numargs;
   337 
   338 	FILE * fin;
   339 	FILE *fout;
   340 
   341 	fin =fopen(filenamein,"rt");
   342 	if (!fin) { printf("Error, can't open %s\n", filenamein); return 1; };
   343 	fout = fopen (filenameout, "wt");
   344 	if (!fout) { printf("Error, can't open %s\n", filenameout); return 1; };
   345 	char buf[5000];
   346 	for (;;) {
   347 	 if (!fgets(buf, 5000, fin)) break;
   348 		if (!strncmp(buf, "@VARARGS", 8)) {
   349 			// found a match...
   350 			CString bigblock;
   351 			for (;;) {
   352 				if (feof(fin)) { printf("No matching @ENDVAR !!??\n"); return 1; };
   353 				fgets(buf, 5000, fin);
   354 				if (!strncmp(buf, "@ENDVAR", 7)) break;
   355 				bigblock+=buf;
   356 			}
   357 //			fprintf(fout, "// Auto-generated code [[[\n");
   358 			for (int k=0; k<=MaxNumArgs; k++) {
   359 				fprintf(fout, "//N=%d\n", k);
   360 				PrintVarArgs(fout, bigblock, k);
   361 			}
   362 //			fprintf(fout, "// ]]] End auto-generated code\n");
   363 		} else {
   364 			fprintf(fout, "%s", buf);
   365 		}
   366 	}
   367 	fclose(fin);
   368 	fclose(fout);
   369 	return 0;
   370 }