make_fint.c 39.1 KB
Newer Older
1
#define _XOPEN_SOURCE 700
2
#define _GNU_SOURCE // needed for getline(3) on some systems it seems
3
#include <ctype.h>
4
#include <errno.h>
5
#include <regex.h>
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
6
7
8
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
9
#include <sys/types.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
10
#include <time.h>
11
#include <unistd.h>
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
12

13
14
15
#ifndef HAVE_GETLINE
#include "getline.c"
#endif
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
16

17
//#include "config.h"
18
#define VERSION "1.7.2"
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
19
20
typedef struct
{
21
  size_t naline;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
22
23
24
25
26
27
  char *fname;
  char *aline[99];
  char *text;
}
Docu;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
28
// Example: ./make_fint -d ../doc/pio/ cdipio.h
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

static const char default_doc_root[] = "../doc";
static struct {
  const char *name;
  size_t len;
} fname_list[] = {
  { "c_quick_ref.txt", 0 },
  { "f_quick_ref.txt", 0 },
  { "tex/c_quick_ref.tex", 0 },
  { "tex/f_quick_ref.tex", 0 },
};
enum {
  NAME_C_QUICK_REF,
  NAME_F_QUICK_REF,
  NAME_C_QUICK_REF_TEX,
  NAME_F_QUICK_REF_TEX,
  fname_list_size = sizeof(fname_list)/sizeof(fname_list[0]),
};


49
50
static Docu cdoc[9999], fdoc[9999];
static size_t ncdoc = 0, nfdoc = 0;
51
static int debug = 0, verbose = 0;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
52

Thomas Jahns's avatar
Thomas Jahns committed
53
static int doccmp(const void *s1, const void *s2)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
54
55
56
57
58
59
60
{
  Docu *x = (Docu *) s1;
  Docu *y = (Docu *) s2;

  return (strcmp(x->fname, y->fname));
}

Thomas Jahns's avatar
Thomas Jahns committed
61
static void doctotex(FILE *fp, Docu *doc, size_t ndoc)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
62
{
63
  size_t i, k;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
64
65
66
67
68
69
70
71
72
73
74
75

  for ( i = 0; i < ndoc; i++ )
    {
      fprintf(fp, "\\section*{\\tt \\htmlref{%s}{%s}}\n\n", doc[i].fname, doc[i].fname);
      fprintf(fp, "\\begin{verbatim}\n");
      for ( k = 0; k < doc[i].naline; k++ )
	fprintf(fp, "    %s\n", doc[i].aline[k]);
      fprintf(fp, "\\end{verbatim}\n");
      fprintf(fp, "\n%s.\n\n\n", doc[i].text);
    }
}

Thomas Jahns's avatar
Thomas Jahns committed
76
static void doctotxt(FILE *fp, Docu *doc, size_t ndoc)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
77
{
78
  size_t i, k;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
79
80
81
82
83
84
85
86
87
88

  for ( i = 0; i < ndoc; i++ )
    {
      fprintf(fp, "%s\n\n", doc[i].fname);
      for ( k = 0; k < doc[i].naline; k++ )
	fprintf(fp, "    %s\n", doc[i].aline[k]);
      fprintf(fp, "\n  %s.\n\n", doc[i].text);
    }
}

89
enum cftype {ISVOID, ISCONSTSTRING, ISINT, ISREAL, ISDOUBLE, ISMPI_COMM,
90
91
             ISXT_IDXLIST, ISCHOICE, ISINTP, ISFLOATV, ISFLOATVV,
             ISDOUBLEV, ISDOUBLEVV, ISINTV, ISINTVV, ISREALP,
92
93
             ISDOUBLEP, ISCBUF, ISUUID, ISUCHAR, ISSTRING, ISSTRINGP,
             VOIDFUNCVOID,
94
95
             NUM_KNOWN_ARG_TYPES};

96
97
98
static inline int
isArrayArgType(int argType);

99
100
101
102
103
enum conversionType { CONV_ARG, CONV_RET };


typedef int (*cfConversionEmitter)(FILE *outfp, const char *argName,
                                   size_t argNameLen, enum conversionType part);
104
105
typedef int (*cfPrologueEmitter)(FILE *outfp, size_t argNum);

106
107
108

static int cfMPICommConvert(FILE *outfp, const char *argName,
                            size_t argNameLen, enum conversionType part);
109

110
111
112
static int cfXtIdxlistConvert(FILE *outfp, const char *argName,
                            size_t argNameLen, enum conversionType part);

113
114
static int cfVoidFuncPrologue(FILE *outfp, size_t argNum);

115
struct symbol {
116
117
  const char *f77name, *cfint, *cfmt, *parseRE;
  /* pair of parentheses which matches the argument name */
118
  size_t nameMatch;
119
  int needsExtraWrapper, needsPrologue;
120
  cfConversionEmitter convert;
121
  const char *convcfmt;
122
  cfPrologueEmitter prologue;
123
124
125
126
127
128
129
130
  regex_t preg;
};

/* C symbol names */
#define SYMRE "([A-Za-z_][A-Za-z_0-9]*)"
/* white-space */
#define WS "[[:blank:]\n]"
#define NWS "[^[:blank:]\n]"
131
/* Note: size of this table must match the cftype enum */
132
133
static struct symbol funArgSym[]
  = { { "",                "",        "void",
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        "^"WS"*void"WS"*)", 0, 0, 0 },
      { "CHARACTER(80)",    "STRING",  "char *%.*s",
        "^"WS"*const"WS"+char"WS"+\\*"SYMRE WS"*\\(", 1, 0, 0 },
      { "INTEGER",         "INT",     "int %.*s",
        "^"WS"*(const"WS"+)?int("WS"+"SYMRE")?"WS"*[,\\)]", 3, 0, 0 },
      { "REAL",            "FLOAT",   "float %.*s",
        "^"WS"*(const"WS"+)?float"WS"+"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
      { "DOUBLEPRECISION", "DOUBLE",  "double %.*s",
        "^"WS"*(const"WS"+)?double"WS"+"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
      { "INTEGER",         "INT", "MPI_Comm %.*s",
        "^"WS"*MPI_Comm"WS"+"SYMRE"?"WS"*[,\\)]", 1, 1, 0,
        cfMPICommConvert, "int %.*s" },
      { "TYPE(XT_IDXLIST)", "PVOID", "Xt_idxlist %.*s",
        "^"WS"*Xt_idxlist"WS"+"SYMRE"?"WS"*[,\\)]", 1, 1, 0,
        cfXtIdxlistConvert, "void *%.*s" },
      { "CHOICE", "PVOID", "const void *%.*s",
        "^"WS"*const"WS"+void"WS"*\\*"WS"*"SYMRE"?"WS"*[,\\)]", 1, 0, 0 },
      { "INTEGER",         "PINT",    "int *%.*s",
        "^"WS"*(const"WS"+)?int"WS"+\\*"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
153
154
155
156
157
158
159
160
161
162
163
164
      { "REAL",            "FLOATV",  "float %.*s[]",
        "^"WS"*(const"WS"+)?float("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
        WS"*[,\\)]", 3, 0, 0 },
      { "REAL",            "FLOATVV", "float %.*s[][]",
        "^"WS"*(const"WS"+)?float("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
        WS"*\\[[^]]*\\]"WS"*[,\\)]", 3, 0, 0 },
      { "DOUBLEPRECISION", "DOUBLEV",  "double %.*s[]",
        "^"WS"*(const"WS"+)?double("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
        WS"*[,\\)]", 3, 0, 0 },
      { "DOUBLEPRECISION", "DOUBLEVV", "double %.*s[][]",
        "^"WS"*(const"WS"+)?double("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
        WS"*\\[[^]]*\\]"WS"*[,\\)]", 3, 0, 0 },
165
      { "INTEGER",         "INTV",    "int  %.*s[]",
166
        "^"WS"*(const"WS"+)?int("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
167
168
        WS"*[,\\)]", 3, 0, 0 },
      { "INTEGER",         "INTVV",    "int %.*s[][]",
169
        "^"WS"*(const"WS"+)?int("WS"+"SYMRE")?"WS"*\\[[^]]*\\]"
170
171
172
173
174
        WS"*\\[[^]]*\\]"WS"*[,\\)]", 3, 0, 0 },
      { "REAL",            "PFLOAT",  "float *%.*s",
        "^"WS"*(const"WS"+)?float"WS"+\\*"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
      { "DOUBLEPRECISION", "PDOUBLE", "double *%.*s",
        "^"WS"*(const"WS"+)?double"WS"+\\*"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
175
      { "CHARACTER*(*)",   "PPSTRING",    "char *%.*s",
176
177
        "^"WS"*(const"WS"+)?char"WS"+\\*""([A-Za-z_][A-Za-z_0-9]*_cbuf)"
        WS"*[,\\)]", 2, 0, 0 },
178
179
180
181
      { "INTEGER*1(16)",   "PVOID",    "unsigned char %.*s[16]",
        "^"WS"*(const"WS"+)?unsigned"WS"+char"WS"+"SYMRE"?\\[(16|CDI_UUID_SIZE)\\]"WS"*[,\\)]", 2, 0, 0 },
      { "INTEGER*1(*)",   "PVOID",    "unsigned char *%.*s",
        "^"WS"*(const"WS"+)?unsigned"WS"+char"WS"+\\*"SYMRE"?"WS"*[,\\)]", 2, 0, 0 },
182
183
184
185
      { "CHARACTER*(*)",   "STRING",  "char *%.*s",
        "^"WS"*const"WS"+char"WS"+\\*"WS"*"SYMRE"?"WS"*[,\\)]", 1, 0, 0 },
      { "CHARACTER*(*)",   "PSTRING", "char *%.*s",
        "^"WS"*char"WS"+\\*"SYMRE"?"WS"*[,\\)]", 1, 0, 0 },
186
187
188
      { "PROCEDURE", "ROUTINE", "void (*%.*s)(void)",
        "^"WS"*void"WS"*\\("WS"*\\*"WS"*"SYMRE"?"WS"*\\)"
        WS"*\\("WS"*void"WS"*\\)"WS"*[,\\)]", 1, 0, 1,
189
        NULL, NULL, cfVoidFuncPrologue },
190
191
192
};

static struct symbol funRet[] = {
193
194
195
196
197
198
199
200
201
202
203
204
  { "",                "",        "void %.*s",
    "void"WS"+"SYMRE WS"*\\(", 1, 0, 0 },
  { "CHARACTER",       "STRING",  "char *%.*s",
    "char"WS"+\\*"WS"*"SYMRE WS"*\\(", 1, 0, 0 },
  { "INTEGER",         "INT",     "int %.*s",
    "(const"WS"+)?int"WS"+"SYMRE WS"*\\(", 2, 0, 0 },
  { "REAL",            "FLOAT",   "float %.*s",
    "(const"WS"+)?float"WS"+"SYMRE WS"*\\(", 2, 0, 0 },
  { "DOUBLEPRECISION", "DOUBLE",  "double %.*s",
    "(const"WS"+)?double"WS"+"SYMRE WS"*\\(", 2, 0, 0 },
  { "INTEGER",         "INT",     "MPI_Comm %.*s",
    "MPI_Comm"WS"+"SYMRE WS"*\\(", 1, 0, 0, cfMPICommConvert, "int %.*s" },
205
206
207
208
209
210
211
};

enum { NUM_RET_TYPES = sizeof (funRet) / sizeof (funRet[0]) };
enum decl { UNKNOWN_DECL, FUNC_DECL, PARAM_DECL };

enum {
  MAX_FUNC_ARGS = 200,
212
  MAX_FUNC_NAME_LEN = 127,
213
214
215
216
217
};

static inline size_t
compress_whitespace(size_t len, char str[]);

218
219
220
static int
reCompile(regex_t *restrict RE, const char *restrict REstring,
          char * restrict *restrict lineBuf, size_t * restrict lineBufSize);
Thomas Jahns's avatar
Thomas Jahns committed
221
222
223
224
static size_t
symRegexCompile(size_t numSyms, struct symbol symList[],
                char **line, size_t *lineBufSize);

225
226
static void
build_header_name(const char *fname, char *cppMacro);
Thomas Jahns's avatar
Thomas Jahns committed
227

228
229
230
231
232
233
234
235
static int detectComment(char **line_, ssize_t *lineLen, size_t *lineBufSize,
                         size_t maxMatch, regmatch_t reMatch[],
                         char *xname, size_t *xnameLen,
                         char *xdes,
                         FILE *fpin, FILE *fpinc, FILE *fpint);

static regex_t commentStartRE, commentEndRE, commentRE, docCommentRE;

236
237
static void fortran_interface(char *fname, char *fnameinc, char *fnameint,
                              const char *doc_root)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
238
239
240
{
  FILE *fpin, *fpinc, *fpint;
  FILE *fp;
241
242
243
  char *line = NULL, *pline;
  size_t lineBufSize = 0;
  char sname[128], *parname;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
244
  char xname[128], xdes[128];
245
  xname[0] = 0;
246
  size_t xnameLen = 0;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
247
  int parvalue;
248
  enum cftype functype;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
249
  int lineno = 0;
250

251
  char funcname[MAX_FUNC_NAME_LEN];
252
253
254
255
  regmatch_t funcargfull[MAX_FUNC_ARGS];
  regmatch_t funcargname[MAX_FUNC_ARGS];
  int  funcargtype[MAX_FUNC_ARGS];
  /* char *strsort[99999]; */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
256
257
258
  char timestr[30];
  time_t date_and_time_in_sec;
  struct tm *date_and_time;
259
260
  regmatch_t *reMatch = NULL;
  size_t maxMatch = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
261
262
263
264
265
266
267
268
269

  date_and_time_in_sec = time(NULL);
  timestr[0] = 0;

  if ( date_and_time_in_sec != -1 )
    {
      date_and_time = localtime(&date_and_time_in_sec);
      (void) strftime(timestr, sizeof(timestr), "%B %Y", date_and_time);
    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
270
271
272
273
274
275
276
277
278
279

  fpin = fopen(fname, "r");
  if ( fpin == NULL ) { perror(fname); return; }

  fpinc = fopen(fnameinc, "w");
  if ( fpinc == NULL ) { perror(fnameinc); return; }

  fpint = fopen(fnameint, "w");
  if ( fpint == NULL ) { perror(fnameint); return; }

280
  /* complete symbol table data */
Thomas Jahns's avatar
Thomas Jahns committed
281
282
283
284
285
286
287
288
  {
    maxMatch = symRegexCompile(NUM_KNOWN_ARG_TYPES, funArgSym,
                             &line, &lineBufSize);
    size_t maxFunMatch = symRegexCompile(NUM_RET_TYPES, funRet,
                                         &line, &lineBufSize);
    if (maxFunMatch > maxMatch)
      maxMatch = maxFunMatch;
  }
289
  ++maxMatch;
290
291
292
293
294
295
296
297
298
299
300
301
302
303
  reMatch = (regmatch_t *)malloc((size_t)maxMatch * sizeof (reMatch[0]));
  /* compile comment start regular expression */
  {
    static const char commentStartREString[] = "^"WS"*/\\*"WS"*(.*"NWS")"WS"*";
    if (reCompile(&commentStartRE, commentStartREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
  }
  /* compile comment end regular expression */
  {
    static const char commentEndREString[] = "\\*/";
    if (reCompile(&commentEndRE, commentEndREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
  }
  /* compile complete comment regular expression */
304
  {
305
306
307
    static const char commentREString[] = "^"WS"*/\\*"WS"*(.*"NWS")"WS"*\\*/";
    if (reCompile(&commentRE, commentREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
308
309
310
  }
  /* compile documentation comment regular expression */
  {
311
    static const char docCommentREString[] = "^"WS"*/\\*"WS"*"SYMRE":"
312
      WS"*("NWS".*"NWS")"WS"*\\*/";
313
314
    if (reCompile(&docCommentRE, docCommentREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
315
  }
316
317
318
  regex_t cppCondRE;
  {
    static const char cppCondREString[]
319
      = "^"WS"*#"WS"*((ifn?def)"WS"+\\(?"SYMRE"\\)?|endif)"WS"*(/\\*[^*]*\\*/|//.*)?";
320
321
322
    if (reCompile(&cppCondRE, cppCondREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
  }
323
324
325
326
327
328
329
  regex_t cppElseRE;
  {
    static const char cppElseREString[]
      = "^"WS"*#"WS"*else"WS"*(/\\*[^*]*\\*/|//.*)?";
    if (reCompile(&cppElseRE, cppElseREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
  }
330
331
332
333
334
335
  regex_t emptyStringRE;
  {
    static const char emptyStringREString[] = "^"WS"*";
    if (reCompile(&emptyStringRE, emptyStringREString, &line, &lineBufSize))
      exit(EXIT_FAILURE);
  }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
336
337
  /* fortran include */

338
  fprintf(fpinc, "! This file was automatically generated, don't edit!\n");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
339
  fprintf(fpinc, "!\n");
340
  fprintf(fpinc, "! Fortran interface for CDI library version %s\n", VERSION);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
341
342
343
344
  fprintf(fpinc, "!\n");
  fprintf(fpinc, "! Author:\n");
  fprintf(fpinc, "! -------\n");
  fprintf(fpinc, "! Uwe Schulzweida, MPI-MET, Hamburg,   %s\n", timestr);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
345
346
347
348
  fprintf(fpinc, "!\n\n");

  /* fortran interface */

349
  fprintf(fpint, "/* Automatically generated by make_fint.c, don't edit! */\n");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
350
351
352
353
354
  fprintf(fpint, "\n");
  fprintf(fpint, "#if defined (HAVE_CONFIG_H)\n");
  fprintf(fpint, "#  include \"config.h\"\n");
  fprintf(fpint, "#endif\n");
  fprintf(fpint, "\n");
355
  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
356
    char *cppMacro = (char*) malloc(strlen(fname) + 2);
357
358
359
360
361
362
    build_header_name(fname, cppMacro);
    fprintf(fpint, "#if ! defined (%s)\n"
            "#  include \"%s\"\n"
            "#endif\n"
            "\n", cppMacro, fname);
  }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
363
364
365
366
367
368
369
  fprintf(fpint, "#if defined (HAVE_CF_INTERFACE)\n");
  fprintf(fpint, "\n");
  fprintf(fpint, "#if ! defined (__CFORTRAN_LOADED)\n");
  fprintf(fpint, "#  include \"cfortran.h\"\n");
  fprintf(fpint, "#endif\n");
  fprintf(fpint, "\n");

370
371
  ssize_t lineLen;
  while ((lineLen = getline(&line, &lineBufSize, fpin)) >= 0)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
372
    {
373
      static const char cplusplus_macro[] = "__cplusplus";
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
374
375
      lineno++;
      functype = ISVOID;
376
377
      size_t funcargc = 0;
      pline = line;
378
      int needsExtraWrapper = 0, needsPrologue = 0;
379
      size_t funcnameLen;
380
381
382
383
384
385
386
      enum decl declType = UNKNOWN_DECL;
      do {
        for (int retType = 0; retType < NUM_RET_TYPES; ++retType)
          if (!regexec(&funRet[retType].preg, pline, maxMatch, reMatch, 0))
            {
              functype = retType;
              declType = FUNC_DECL;
387
388
              needsExtraWrapper
                = needsExtraWrapper || funRet[retType].needsExtraWrapper;
389
390
391
392
393
              break;
            }
        if (declType == UNKNOWN_DECL)
          break;
        regmatch_t *nameMatch = reMatch + funRet[functype].nameMatch;
394
395
        if (debug)
          printf("Found: %.*s\n",
396
                 (int) (nameMatch->rm_eo - nameMatch->rm_so),
397
                 pline + nameMatch->rm_so);
398
399
        ssize_t funNameLast = reMatch[0].rm_eo - 1;
        ssize_t nameLen = nameMatch->rm_eo - nameMatch->rm_so;
400
        funcnameLen = (size_t)nameLen;
401
402
403
404
405
        if ( pline[funNameLast] != '(' )
          {
            printf("%s\n>(< not found!", line);
            return;
          }
406
407
        memcpy(funcname, pline + nameMatch->rm_so, funcnameLen);
        funcname[funcnameLen] = 0;
408
409
        pline += reMatch[0].rm_eo;
      } while (0);
410
411
      int cppSwitchLen, cppSymLen;

412
413
414
415
416
      if (declType == FUNC_DECL)
        {
	  funcargname[funcargc].rm_so = (regoff_t)(pline - line);
          {
            ssize_t i = 0;
417
            size_t innerParens = 0;
418
419
420
421
            do {
              ssize_t restLen = lineLen - (ssize_t)(pline - line);
              for (; i < restLen; i++ )
                {
422
                  switch (pline[i])
423
                    {
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
                    case ',':
                      if (!innerParens)
                        {
                          funcargc++;
                          funcargname[funcargc].rm_so
                            = (regoff_t)(pline - line + i + 1);
                        }
                      break;
                    case '(':
                      ++innerParens;
                      break;
                    case ')':
                      if (!innerParens)
                        {
                          funcargc++;
                          funcargname[funcargc].rm_so
                            = (regoff_t)(pline - line + i + 1);
                          goto endOfArgSearch;
                        }
                      else
                        --innerParens;
445
446
447
                      break;
                    }
                }
448
              endOfArgSearch:
449
450
451
452
453
454
455
456
              if (i < restLen)
                break;
              char *lineExtension = NULL;
              size_t extSize = 0, plineOff = (size_t)(pline - line);
              ssize_t extLen;
              if ((extLen = getline(&lineExtension, &extSize, fpin)) <= 0)
                break;
              if ((size_t)(lineLen + extLen) >= lineBufSize)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
457
                if (!(line = (char*) realloc(line, (size_t)(lineLen + extLen + 1))))
458
459
460
461
462
463
                  exit(EXIT_FAILURE);
              memcpy(line + lineLen, lineExtension, (size_t)extLen + 1);
              lineLen += extLen;
              pline = line + plineOff;
            } while (1);
          }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
464
465

	  /*  printf("funcargc = %d\n", funcargc);*/
466
467
468
469
470
471
472
473
474
            /* test if argument list is actually empty */
          if (funcargc == 1
              && !regexec(&emptyStringRE, line + funcargname[0].rm_so, 1,
                          reMatch, 0)
              && (funcargname[0].rm_so + reMatch[0].rm_eo
                  == funcargname[funcargc].rm_so - 1))
            {
              funcargc = 0;
            }
475
476
          {
            size_t i;
477
            for (i = 0; i < funcargc; ++i )
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
              {
                pline = line + funcargname[i].rm_so;
                int argtype;
                regoff_t argStart = (regoff_t)(pline - line);
                for (argtype = ISVOID;
                     argtype < NUM_KNOWN_ARG_TYPES;
                     ++argtype)
                  if (!regexec(&funArgSym[argtype].preg, pline, maxMatch,
                               reMatch, 0))
                    {
                      funcargtype[i] = argtype;
                      funcargfull[i].rm_so = reMatch[0].rm_so + argStart;
                      funcargfull[i].rm_eo = reMatch[0].rm_eo + argStart;
                      regmatch_t *nameMatch = reMatch + funArgSym[argtype].nameMatch;
                      funcargname[i].rm_so = nameMatch->rm_so + argStart;
                      funcargname[i].rm_eo = nameMatch->rm_eo + argStart;
494
495
                      needsExtraWrapper
                        = needsExtraWrapper || funArgSym[argtype].needsExtraWrapper;
496
497
                      needsPrologue = needsPrologue
                        || funArgSym[argtype].needsPrologue;
498
499
500
501
502
503
504
505
506
507
508
509
510
511
                      break;
                    }
                if (argtype == NUM_KNOWN_ARG_TYPES)
                  {
                    printf("%s not implemented\n", line + funcargname[i].rm_so);
                    break;
                  }
              }
            if ( i != funcargc )
              {
                printf("problem parsing line: %s\n", line);
                continue;
              }
          }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
512
513

	  strcpy(sname, funcname);
514

Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
515
516
517
518
519
	  /* fortran include */

	  if ( functype == ISVOID )
	    fprintf(fpinc, "!     %-16s", "");
	  else
520
	    fprintf(fpinc, "      %-16s", funArgSym[functype].f77name);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
521
522
523
524

          fprintf(fpinc, "%s", sname);
	  fprintf(fpinc, "\n");
	  if ( (funcargc == 1 && funcargtype[0] == ISVOID) ) funcargc = 0;
525
	  for (size_t i = 0; i < funcargc; i++ )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
526
527
528
529
530
	    {
	      if ( i == 0 )
		fprintf(fpinc, "!%36s(", "");
	      else
		fprintf(fpinc, ",\n!%36s ", "");
531
              int argType = funcargtype[i];
532
              int isArray = isArrayArgType(argType);
533
	      fprintf(fpinc, "%-16s%.*s%s", funArgSym[argType].f77name,
534
                      (int)(funcargname[i].rm_eo - funcargname[i].rm_so),
535
536
                      line + funcargname[i].rm_so,
                      isArray ? "(*)" : "");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
537
538
539
540
541
542
	    }
	  if ( funcargc )
	    fprintf(fpinc, ")\n");
	  fprintf(fpinc, "      %-16s%s\n\n", "EXTERNAL", sname);

	  /* fortran interface */
543
544
          const char *delegateName;
          char delegateNameBuf[MAX_FUNC_NAME_LEN + 7];
545
          size_t delegateNameLen = funcnameLen;
546
547
548
549
550
551
552
553
554
555
556
          /* emit prologue if needed */
          if (needsPrologue)
            {
              if (funRet[functype].needsPrologue)
                funRet[functype].prologue(fpint, (size_t)-1);
              for (size_t i = 0; i < funcargc; i++ )
                {
                  if (funArgSym[funcargtype[i]].needsPrologue)
                    funArgSym[funcargtype[i]].prologue(fpint, i);
                }
            }
557
558
559
560
561
          /* emit wrapper for type conversions if needed */
          if (needsExtraWrapper)
            {
              strcpy(delegateNameBuf, funcname);
              strcat(delegateNameBuf, "_fwrap");
562
              delegateNameLen += 6;
563
              delegateName = delegateNameBuf;
564
565
566
567
568
              fputs("static ", fpint);
              fprintf(fpint, (funRet[functype].convert
                              ?funRet[functype].convcfmt:funRet[functype].cfmt),
                      (int)delegateNameLen, delegateName);
              fputs("(", fpint);
569
570
              for (size_t i = 0; i < funcargc; i++ )
                {
571
572
573
574
575
                  if (i > 0)
                    fputs(", ", fpint);
                  fprintf(fpint, (funArgSym[funcargtype[i]].convert
                                  ?funArgSym[funcargtype[i]].convcfmt
                                  :funArgSym[funcargtype[i]].cfmt),
576
577
578
579
580
                          (int)(funcargname[i].rm_eo - funcargname[i].rm_so),
                          line + funcargname[i].rm_so);
                }
              fputs(")\n{\n", fpint);
              if (functype != ISVOID)
581
582
583
584
585
586
                {
                  fputs("  ", fpint);
                  fprintf(fpint, funRet[functype].cfmt, 1, "v");
                  fprintf(fpint, ";\n"
                          "  v = %s(", funcname);
                }
587
588
589
590
              else
                fprintf(fpint, "  %s(", funcname);
              for (size_t i = 0; i < funcargc; i++ )
                {
591
592
                  if (i > 0)
                    fputs(", ", fpint);
593
594
595
596
597
598
599
600
601
                  if (funArgSym[funcargtype[i]].convert)
                    {
                      funArgSym[funcargtype[i]]
                        .convert(fpint,
                                 line + funcargname[i].rm_so,
                                 (size_t)(funcargname[i].rm_eo
                                          - funcargname[i].rm_so), CONV_ARG);
                    }
                  else
602
                    fprintf(fpint, "%.*s",
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
                            (int)(funcargname[i].rm_eo - funcargname[i].rm_so),
                            line + funcargname[i].rm_so);
                }
              fputs(");\n", fpint);
              if (functype != ISVOID)
                {
                  fputs("  return ", fpint);
                  if (funRet[functype].convert)
                    funRet[functype].convert(fpint, "v", 1, CONV_RET);
                  else
                    fputc('v', fpint);
                  fputs(";\n", fpint);
                }
              fputs("}\n", fpint);
            }
          else
            delegateName = funcname;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
620
621
622
623
	  if ( functype == ISVOID )
	    fprintf(fpint, "FCALLSCSUB");
	  else
	    fprintf(fpint, "FCALLSCFUN");
624
	  fprintf(fpint, "%zd ", funcargc);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
625
626
	  fprintf(fpint, "(");
	  if ( functype != ISVOID )
627
628
	    fprintf(fpint, "%s, ", funRet[functype].cfint);
	  fprintf(fpint, "%s, ", delegateName);
629
630
	  for (size_t i = 0; i < funcnameLen; ++i)
            sname[i] = (char)toupper((int) sname[i]);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
631
	  fprintf(fpint, "%s, ", sname);
632
633
	  for (size_t i = 0; i < funcnameLen; ++i)
            sname[i] = (char)tolower((int) sname[i]);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
634
	  fprintf(fpint, "%s", sname);
635
	  for (size_t i = 0; i < funcargc; i++ )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
636
	    {
637
638
	      fprintf(fpint, ", %s", funArgSym[funcargtype[i]].cfint);
	    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
639
640
641
	  fprintf(fpint, ")\n");


642
643
	  if ( funcnameLen == xnameLen
               && memcmp(funcname, xname, funcnameLen) == 0 )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
644
645
	    {
	      char xline[128];
646
              size_t xlineLen = 0;
647
648
	      int nch;

Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
649
650
651
652
653
654
	      /* C Quick Guide */

	      cdoc[ncdoc].naline = 0;
	      cdoc[ncdoc].text   = NULL;
	      cdoc[ncdoc].fname  = strdup(funcname);

655
656
657
658
659
660
	      nch = sprintf(xline, funRet[functype].cfmt,
                            (int)funcnameLen, funcname);
              xline[nch++] = ' ';
              xline[nch++] = '(';
              xline[nch] = '\0';
              xlineLen = (size_t)nch;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
661
662
663

	      if ( (funcargc == 1 && funcargtype[0] == ISVOID) ) funcargc = 0;

664
	      for (size_t i = 0; i < funcargc; i++ )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
665
		{
666
667
668
669
670
		  if (i)
                    {
                      strcat(xline, ", ");
                      xlineLen += 2;
                    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
671

672
673
674
675
676
677
678
679
680
681
682
                  /* extract full argument text from match */
                  char farg[128];
                  /* - 1 to omit closing paren ) or comma , */
                  int nchn = snprintf(farg, sizeof (farg), "%.*s",
                                      (int)(funcargfull[i].rm_eo
                                            - funcargfull[i].rm_so - 1),
                                      line + funcargfull[i].rm_so);
                  if (nchn < 0)
                    abort();
                  /* compress white-space */
                  nchn = (int)compress_whitespace((size_t)nchn, farg);
683
		  if ( (xlineLen + (size_t)nchn) > (size_t)80 )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
684
		    {
685
                      if (i) xline[--xlineLen] = 0;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
686
687
		      cdoc[ncdoc].aline[cdoc[ncdoc].naline++] = strdup(xline);
		      sprintf(xline, "%*s", nch, "");
688
                      xlineLen = (size_t)nch;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
689
690
		    }
		  strcat(xline, farg);
691
                  xlineLen += (size_t)nchn;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
692
		}
693
	      strcat(xline, ");");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
694
695
696
697
698
699
700
701
702
703
704
705
	      cdoc[ncdoc].aline[cdoc[ncdoc].naline++] = strdup(xline);
	      cdoc[ncdoc].text  = strdup(xdes);

	      ncdoc++;

	      /* Fortran Quick Guide */

	      fdoc[nfdoc].naline = 0;
	      fdoc[nfdoc].text   = NULL;
	      fdoc[nfdoc].fname  = strdup(funcname);

	      if ( functype == ISVOID )
706
		nch = sprintf(xline, "SUBROUTINE %s", xname);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
707
	      else
708
		nch = sprintf(xline, "%s FUNCTION %s", funArgSym[functype].f77name, xname);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
709
710

	      if ( (funcargc == 1 && funcargtype[0] == ISVOID) ) funcargc = 0;
711
              if (funcargc) strcat(xline, " ("), nch += 2;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
712

713
714
              xlineLen = (size_t)nch;

715
	      for (size_t i = 0; i < funcargc; i++ )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
716
		{
717
718
719
720
721
		  if (i)
                    {
                      strcat(xline, ", ");
                      xlineLen += 2U;
                    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
722

723
724
                  char farg[128];
                  /* FIXME: optional empty argument name unhandled */
725
726
                  int argType = funcargtype[i];
                  int isArray = isArrayArgType(argType);
727
		  int nchn
728
729
                    = snprintf(farg, sizeof (farg), "%s %.*s%s",
                               funArgSym[argType].f77name,
730
731
                               (int)(funcargname[i].rm_eo
                                     - funcargname[i].rm_so),
732
733
                               line + funcargname[i].rm_so,
                               isArray ? "(*)" : "");
734
735
                  if (nchn < 0)
                    abort();
736
		  if ( (xlineLen + (size_t)nchn) > 80 )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
737
		    {
738
                      if (i) xline[--xlineLen] = 0;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
739
740
		      fdoc[nfdoc].aline[fdoc[nfdoc].naline++] = strdup(xline);
		      sprintf(xline, "%*s", nch, "");
741
                      xlineLen = (size_t)nch;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
742
743
		    }
		  strcat(xline, farg);
744
                  xlineLen += (size_t)nchn;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
745
746
747
748
749
750
751
752
		}
	      if ( funcargc ) strcat(xline, ")");
	      fdoc[nfdoc].aline[fdoc[nfdoc].naline++] = strdup(xline);
	      fdoc[nfdoc].text  = strdup(xdes);

	      nfdoc++;
	    }
	}
753
      else if ( memcmp(line, "#define", 7) == 0 )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
754
755
756
757
758
	{
	  pline = line;
	  pline += 7;
	  while ( isspace((int) *pline) ) pline++;
	  parname = pline;
759
	  size_t len = strlen(pline);
760
761
          size_t i = 0;
	  for (; i < len; i++ )
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
762
763
764
765
766
767
768
769
770
771
772
	    {
	      if ( isspace((int) pline[i]) ) break;
	    }
	  if ( i == len ) continue;
	  parname[i] = 0;
	  pline += i+1;
	  while ( isspace((int) *pline) ) pline++;
	  if ( ! (isdigit((int) *pline) || *pline == '-') ) continue;
	  parvalue = atoi(pline);

	  /* fortran include */
773
774
775
	  fprintf(fpinc, "      INTEGER    %-22s\n"
                  "      PARAMETER (%-22s = %2d)\n", parname, parname,
                  parvalue);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
776
	}
777
778
779
780
781
782
      else if (!regexec(&cppCondRE, line, maxMatch, reMatch, 0)
               && ((cppSwitchLen = reMatch[2].rm_eo - reMatch[2].rm_so) == 5)
               && ((size_t)(cppSymLen = reMatch[3].rm_eo - reMatch[3].rm_so)
                   == sizeof (cplusplus_macro) - 1)
               && !memcmp(line + reMatch[3].rm_so, cplusplus_macro,
                          sizeof (cplusplus_macro) - 1))
783
	{
784
785
          fprintf(stderr, "Found conditional C++ block, skipping to #else\n");
          while ((lineLen = getline(&line, &lineBufSize, fpin)) >= 0)
786
787
            {
              ++lineno;
788
789
790
791
792
793
794
              static const char endif_str[] = "endif";
              if (!regexec(&cppElseRE, line, maxMatch, reMatch, 0)
                  || (!regexec(&cppCondRE, line, maxMatch, reMatch, 0)
                      && ((size_t)(cppSymLen = reMatch[1].rm_eo - reMatch[1].rm_so)
                          == sizeof (endif_str) - 1)
                      && !memcmp(line + reMatch[1].rm_so, endif_str,
                                 sizeof (endif_str) - 1)))
795
796
                break;
            }
797
        }
798
799
800
801
802
      else if (detectComment(&line, &lineLen, &lineBufSize,
                             maxMatch, reMatch,
                             xname, &xnameLen, xdes,
                             fpin, fpinc, fpint))
        ;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
803
804
      else
	{
805
806
807
	  if ( lineLen > 1 )
	    printf("skip: line %3d  size %3zd  %s%s", lineno, lineLen, line,
                   line[lineLen-1]=='\n'?"":"missing new-line\n");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
808
809
810
	}
    }

811
812
  fputs("\n"
        "#endif\n", fpint);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
813
814
815
816
817
818
819
820

  fclose(fpin);
  fclose(fpinc);
  fclose(fpint);

  qsort(cdoc, ncdoc, sizeof(Docu), doccmp);
  qsort(fdoc, nfdoc, sizeof(Docu), doccmp);

821
822
823
824
825
826
827
828
829
830
831
832
833
834

  char *filename;
  size_t doc_root_len = strlen(doc_root);
  {
    size_t max_len = 0;
    for (size_t i = 0; i < (size_t)fname_list_size; ++i)
      {
        size_t len = strlen(fname_list[i].name);
        fname_list[i].len = len;
        if (len > max_len)
          max_len = len;
      }
    /* path to document root, separating /, max of path within root,
     * terminating '\0'  */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
835
    filename = (char*) malloc(doc_root_len + 1 + max_len + 1);
836
837
838
839
840
841
842
843
  }

  memcpy(filename, doc_root, doc_root_len);
  filename[doc_root_len] = '/';
  memcpy(filename + doc_root_len + 1,
         fname_list[NAME_C_QUICK_REF].name,
         fname_list[NAME_C_QUICK_REF].len + 1);
  fp = fopen(filename, "w");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
844
845
  if ( fp )
    {
846
847
      fputs("C Quick Reference\n"
            "-----------------\n\n", fp);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
848
849
850
851

      doctotxt(fp, cdoc, ncdoc);
      fclose(fp);
    }
852
853
854
855
856
  else
    {
      fprintf(stderr, "warning: cannot open documentation output file %s, %s",
              filename, strerror(errno));
    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
857

858
859
860
861
  memcpy(filename + doc_root_len + 1,
         fname_list[NAME_F_QUICK_REF].name,
         fname_list[NAME_F_QUICK_REF].len + 1);
  fp = fopen(filename, "w");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
862
863
  if ( fp )
    {
864
865
      fputs("Fortran Quick Reference\n"
            "-----------------------\n\n", fp);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
866
867
868
869

      doctotxt(fp, fdoc, nfdoc);
      fclose(fp);
    }
870
871
872
873
874
  else
    {
      fprintf(stderr, "warning: cannot open documentation output file %s, %s",
              filename, strerror(errno));
    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
875

876
877
878
879
  memcpy(filename + doc_root_len + 1,
         fname_list[NAME_C_QUICK_REF_TEX].name,
         fname_list[NAME_C_QUICK_REF_TEX].len + 1);
  fp = fopen(filename, "w");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
880
881
  if ( fp )
    {
882
883
884
885
886
887
      fputs("\\chapter*{Quick Reference}\n"
            "\\addcontentsline{toc}{chapter}{Quick Reference}\n"
            "\n"
            "This appendix provide a brief listing of the C language bindings of the\n"
            "CDI library routines:\n"
            "\n", fp);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
888
889
890
891

      doctotex(fp, cdoc, ncdoc);
      fclose(fp);
    }
892
893
894
895
896
  else
    {
      fprintf(stderr, "warning: cannot open documentation output file %s, %s",
              filename, strerror(errno));
    }
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
897

898
899
900
901
  memcpy(filename + doc_root_len + 1,
         fname_list[NAME_F_QUICK_REF_TEX].name,
         fname_list[NAME_F_QUICK_REF_TEX].len + 1);
  fp = fopen(filename, "w");
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
902
903
  if ( fp )
    {
904
905
906
907
908
909
      fputs("\\chapter*{Quick Reference}\n"
            "\\addcontentsline{toc}{chapter}{Quick Reference}\n"
            "\n"
            "This appendix provide a brief listing of the Fortran language bindings of the\n"
            "CDI library routines:\n"
            "\n", fp);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
910
911
912
913

      doctotex(fp, fdoc, nfdoc);
      fclose(fp);
    }
914
915
916
917
918
  else
    {
      fprintf(stderr, "warning: cannot open documentation output file %s, %s",
              filename, strerror(errno));
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
919
  free(filename);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
920
921
}

922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
static void
build_header_name(const char *fname, char *cppMacro)
{
  size_t len = strlen(fname);
  for (size_t i = 0; i < len; ++i)
    switch (fname[i])
      {
      case '.':
        cppMacro[i] = '_';
        break;
      default:
        cppMacro[i] = (char)toupper((int)fname[i]);
      }
  cppMacro[len] = '_';
  cppMacro[len + 1] = '\0';
}

Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
939
940
941
942
int main(int argc, char *argv[])
{
  char *fname;
  char *cp;
943
  const char *doc_root = default_doc_root;
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
944
945
946
  char fnameinc[128], fnameint[128];
  size_t len;

947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
  int optargCount = 0;
  {
    int opt;
    while ((opt = getopt(argc, argv, "d:")) != -1)
      switch (opt) {
      case 'd':
        doc_root = optarg;
        optargCount = 2;
        break;
      default: /* '?' */
        fprintf(stderr, "Usage: %s [-d DOCROOT] includefile\n", argv[0]);
        return(EXIT_FAILURE);
      }
  }


  if ( argc != 2 + optargCount)
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
964
    {
965
      printf("Usage:  %s [-d DOCROOT] includefile\n", argv[0]);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
966
967
968
      return (1);
    }

969
  fname = argv[1 + optargCount];
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
970
971
972

  cp = strrchr(fname, '.');
  if ( cp == NULL ) len = strlen(fname);
973
  else              len = (size_t)(cp - fname);
974

975
976
  memcpy(fnameinc, fname, len);
  memcpy(fnameint, fname, len);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
977
978
979

  strcpy(fnameinc+len, ".inc");
  strcpy(fnameint+len, "Fortran.c");
980

981
  fortran_interface(fname, fnameinc, fnameint, doc_root);
Uwe Schulzweida's avatar
Cleanup    
Uwe Schulzweida committed
982
983
984

  return (0);
}
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013

static inline size_t
compress_whitespace(size_t len, char str[])
{
  size_t wpos = 0;
  size_t i = 0;
  /* skip leading white-space */
  while (i < len && (isblank(str[i]) || str[i] == '\n'))
    ++i;
  /* after the leading white-space the following is
   * an alternation of white- and non-white-space
   * characters, where sequences of the latter will
   * be compressed to a single space */
  while (i < len)
    {
      /* handle white-space */
      while (i < len && !(isblank(str[i]) || str[i] == '\n'))
        str[wpos++] = str[i++];
      /* skip non-white-space */
      size_t wscount = 0;
      while (i < len && (isblank(str[i]) || str[i] == '\n'))
        ++i, ++wscount;
      if (wscount)
        str[wpos++] = ' ';
    }
  str[wpos] = '\0';
  return wpos;
}

Thomas Jahns's avatar
Thomas Jahns committed
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
enum {
  REGEX_MAX_ERRSTRLEN = 1024,
};


static size_t
symRegexCompile(size_t numSyms, struct symbol symList[],
                char **line, size_t *lineBufSize)
{
  size_t maxMatch = 0;
  for (size_t sym = 0; sym < numSyms; ++sym)
    {
1026
1027
1028
      if (reCompile(&symList[sym].preg, symList[sym].parseRE,
                    line, lineBufSize))
        exit(EXIT_FAILURE);
Thomas Jahns's avatar
Thomas Jahns committed
1029
1030
1031
1032
1033
1034
      if (symList[sym].nameMatch > maxMatch)
        maxMatch = symList[sym].nameMatch;
    }
  return maxMatch;
}

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
static int
reCompile(regex_t *restrict RE, const char *restrict REstring,
          char * restrict *restrict lineBuf, size_t * restrict lineBufSize)
{
  int errcode;
  if ((errcode = regcomp(RE, REstring, REG_EXTENDED)))
    {
      char *restrict line;
      size_t resize;
      if (*lineBufSize < REGEX_MAX_ERRSTRLEN
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1045
          && (line = (char*) realloc(*lineBuf, resize = REGEX_MAX_ERRSTRLEN)))
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
        {
          *lineBuf = line;
          *lineBufSize = resize;
          regerror(errcode, RE, line, *lineBufSize);
          fprintf(stderr, "Error compiling regular expression: %s: %s\n",
                  REstring, *lineBuf);
        }
    }
  return errcode;
}

1057
1058
/* emit conversion code for MPI_Comm argument */
static int cfMPICommConvert(FILE *outfp, const char *argName,
1059
                            size_t argNameLen, enum conversionType part)
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
{
  int retval = 0;
  switch (part)
    {
    case CONV_ARG:
      retval
        = fprintf(outfp, "MPI_Comm_f2c(%.*s)", (int)argNameLen, argName);
      break;
    case CONV_RET:
      retval = fprintf(outfp, "MPI_Comm_c2f(%.*s)", (int)argNameLen, argName);
      break;
    }
  return retval;
}
1074

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
/* emit conversion code for Xt_idxlist argument */
static int cfXtIdxlistConvert(FILE *outfp, const char *argName,
                              size_t argNameLen, enum conversionType part)
{
  int retval = 0;
  switch (part)
    {
    case CONV_ARG:
      retval
        = fprintf(outfp, "(*(Xt_idxlist *)%.*s)", (int)argNameLen, argName);
      break;
    case CONV_RET:
      abort();
      break;
    }
  return retval;
}

1093
1094
1095
static int cfVoidFuncPrologue(FILE *outfp, size_t argNum)
{
  int retval
Thomas Jahns's avatar
Thomas Jahns committed
1096
1097
    = fprintf(outfp, "\n#undef ROUTINE_%zu\n#define ROUTINE_%zu %s\n",
              argNum+1, argNum+1, "(void (*)(void))");
1098
1099
1100
  return retval;
}

1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
enum {
  FOUND_NOTHING,
  FOUND_COMMENT,
  FOUND_DOCCOMMENT,
};

static int detectComment(char **line_, ssize_t *lineLen, size_t *lineBufSize,
                         size_t maxMatch, regmatch_t reMatch[],
                         char *xname, size_t *xnameLen,
                         char *xdes,
                         FILE *fpin, FILE *fpinc, FILE *fpint)
{
  char *restrict line = *line_;
  int matchType;
  do {
    if (!regexec(&docCommentRE, line, maxMatch, reMatch, 0))
      {
        /* found documentation comment */
        size_t nameMatchLen = (size_t)(reMatch[1].rm_eo - reMatch[1].rm_so),
          docMatchLen = (size_t)(reMatch[2].rm_eo - reMatch[2].rm_so);
        memcpy(xname, line + reMatch[1].rm_so, nameMatchLen);
        xname[nameMatchLen] = 0;
        *xnameLen = nameMatchLen;
        memcpy(xdes, line + reMatch[2].rm_so, docMatchLen);
        {
          char *eol = xdes;
          while ((eol = strchr(eol, '\n')))
            {
              ++eol;
              /* delete whitespace following newline */
              size_t squeezeLen = strspn(eol, " \t*");
              char *startoftext = eol + squeezeLen;
              memmove(eol, startoftext, docMatchLen - (size_t)(eol - xdes));
              docMatchLen -= squeezeLen;
            }
        }
        xdes[docMatchLen] = 0;
1138
1139
1140
        if (verbose || debug)
          printf("Found documentation for \"%s\": \"%s\"\n", xname,
                 xdes);
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
        matchType = FOUND_DOCCOMMENT;
        break;
      }
    else if (!regexec(&commentRE, line, maxMatch, reMatch, 0))
      {
        size_t commentLen = (size_t)(reMatch[1].rm_eo - reMatch[1].rm_so);
        char *comment = line + reMatch[1].rm_so;
        {
          char savedCommentEnd = comment[commentLen];
          comment[commentLen] = '\0';
          /* fortran include */
          fputs("!\n", fpinc);
          char *cline = comment;
          do {
            cline += strspn(cline, " \t*");
            char *eol = strchr(cline, '\n');
            if (!eol)
              eol = comment + commentLen;
            size_t lineLen = (size_t)(eol - cline);
            fprintf(fpinc, "!  %.*s\n", (int)lineLen, cline);
            cline = (eol != comment + commentLen) ? eol + 1: NULL;
          } while (cline);
          fputs("!\n", fpinc);
          comment[commentLen] = savedCommentEnd;
        }
        /* fortran interface */
        fprintf(fpint, "\n/*  %.*s  */\n\n", (int)commentLen, comment);
        matchType = FOUND_COMMENT;
        break;
      }
    /* found comment start, read further lines and retry */
    else if (!regexec(&commentStartRE, line, maxMatch, reMatch, 0))
      {
        int foundCommentEnd = 0;
        char *lineExtension = NULL;
        size_t extSize = 0;
        do {
          ssize_t extLen;
          if ((extLen = getline(&lineExtension, &extSize, fpin)) <= 0)
            break;
          if ((size_t)(*lineLen + extLen) >= *lineBufSize)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1182
            if (!(line = realloc(line, (size_t)(*lineLen + extLen + 1))))
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
              exit(EXIT_FAILURE);
          memcpy(line + *lineLen, lineExtension, (size_t)extLen + 1);
          *lineLen += extLen;
          foundCommentEnd
            = !regexec(&commentEndRE, lineExtension, maxMatch, reMatch, 0);
        } while (!foundCommentEnd);
      }
    else
      /* found no comment at all */
      break;
  } while (1);
  *line_ = line;
  return matchType;
}

1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
static inline int
isArrayArgType(int argType)
{
  return argType == ISFLOATV
    || argType == ISFLOATVV
    || argType == ISDOUBLEV
    || argType == ISDOUBLEVV
    || argType == ISINTV
    || argType == ISINTVV;
}
1208
1209


1210
1211
1212
1213
1214
1215
1216
1217
1218
/*
 * Local Variables:
 * c-file-style: "Java"
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * show-trailing-whitespace: t
 * require-trailing-newline: t
 * End:
 */
1219