params.c 26.9 KB
Newer Older
Emmanuel Thomé's avatar
Emmanuel Thomé committed
1
#include "cado.h"
2 3 4 5
#include <stdlib.h>
#include <string.h>
#include <ctype.h>              /* isdigit isspace */
#include <limits.h>             /* INT_MIN INT_MAX */
6
#include <errno.h>
7
#include <stdarg.h>
8
#include <inttypes.h>
9 10 11

#include "params.h"
#include "macros.h"
12
#include "misc.h"
13
#include "portability.h"
14 15 16

void param_list_init(param_list pl)
{
17
    memset(pl, 0, sizeof(param_list));
18 19 20 21
    pl->ndocs_alloc = 16;
    pl->ndocs = 0;
    pl->docs = (param_list_doc *) malloc(pl->ndocs_alloc *
            sizeof(param_list_doc));
22 23 24
    pl->alloc = 16;
    pl->p = (parameter *) malloc(pl->alloc * sizeof(parameter));
    pl->consolidated = 1;
25
    pl->size = 0;
26 27 28
    pl->aliases = NULL;
    pl->naliases = 0;
    pl->naliases_alloc = 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
29 30 31
    pl->switches = NULL;
    pl->nswitches = 0;
    pl->nswitches_alloc = 0;
32
    ASSERT_ALWAYS(pl->docs != NULL && pl->p != NULL);
33 34 35 36
}

void param_list_clear(param_list pl)
{
37 38 39 40 41
    for(int i = 0 ; i < pl->ndocs ; i++) {
        free(pl->docs[i]->key);
        free(pl->docs[i]->doc);
    }
    free(pl->docs);
42
    for(unsigned int i = 0 ; i < pl->size ; i++) {
43
        if (pl->p[i]->key) free(pl->p[i]->key);
44 45 46
        free(pl->p[i]->value);
    }
    free(pl->p);
47 48 49
    for(int i = 0 ; i < pl->naliases ; i++) {
        if (pl->aliases[i]->alias) free(pl->aliases[i]->alias);
    }
50
    free(pl->aliases);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
51 52
    for(int i = 0 ; i < pl->nswitches ; i++) {
        free(pl->switches[i]->switchname);
53
    }
Emmanuel Thomé's avatar
Emmanuel Thomé committed
54
    free(pl->switches);
55
    memset(pl, 0, sizeof(pl[0]));
56 57
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
void param_list_decl_usage(param_list pl, const char * key, const char * doc)
{
    if (pl->ndocs == pl->ndocs_alloc) {
        pl->ndocs_alloc += 16;
        pl->docs = (param_list_doc *) realloc(pl->docs,
                pl->ndocs_alloc * sizeof(param_list_doc));
        ASSERT_ALWAYS(pl->docs != NULL);
    }
    int i = pl->ndocs;
    pl->ndocs++;
    pl->docs[i]->key = strdup(key);
    pl->docs[i]->doc = strdup(doc);
    ASSERT_ALWAYS(pl->docs[i]->key != NULL && pl->docs[i]->doc != NULL);
    pl->use_doc = 1;
}

74 75 76 77 78 79 80 81
static int is_documented_key(param_list pl, const char *key) {
    for (int i = 0; i < pl->ndocs; ++i) {
        if (strcmp(key, pl->docs[i]->key) == 0)
            return 1;
    }
    return 0;
}

82 83
void param_list_print_usage(param_list pl, const char * argv0, FILE *f)
{
84 85
    if (argv0 != NULL)
        fprintf(f, "Usage: %s <parameters>\n", argv0);
86 87 88 89 90 91 92 93 94 95 96 97 98
    fprintf(f, "The available parameters are the following:\n");
    char whites[20];
    for (int i = 0; i < 20; ++i)
        whites[i] = ' ';
    for (int i = 0; i < pl->ndocs; ++i) {
        int l = strlen(pl->docs[i]->key);
        l = MAX(1, 10-l);
        whites[l] ='\0';
        fprintf(f, "    -%s%s%s\n", pl->docs[i]->key, whites, pl->docs[i]->doc);
        whites[l] =' ';
    }
}

99 100 101 102 103 104 105
static void make_room(param_list pl, unsigned int more)
{
    if (pl->size + more <= pl->alloc) {
        return;
    }

    for( ; pl->size + more > pl->alloc ; ) {
Paul Zimmermann's avatar
Paul Zimmermann committed
106
      pl->alloc += 8 + (pl->alloc >> 1);
107 108 109 110 111
    }

    pl->p = (parameter *) realloc(pl->p, pl->alloc * sizeof(parameter));
}

Emmanuel Thomé's avatar
Emmanuel Thomé committed
112
static int param_list_add_key_nostrdup(param_list pl,
113 114 115
        char * key, char * value, enum parameter_origin o)
{
    make_room(pl, 1);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
116
    int r = pl->size;
117 118 119
    pl->p[pl->size]->key = key;
    pl->p[pl->size]->value = value;
    pl->p[pl->size]->origin = o;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
120
    // switches always count as parsed, of course. Hence the (value==NULL) thing
121 122
    pl->p[pl->size]->parsed = (value == NULL);
    // values above 1 are built within the sorting step.
123
    pl->p[pl->size]->seen = 1;
124 125
    pl->size++;
    pl->consolidated = 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
126
    return r;
127 128
}

Emmanuel Thomé's avatar
Emmanuel Thomé committed
129
int param_list_add_key(param_list pl,
130 131
        const char * key, const char * value, enum parameter_origin o)
{
Emmanuel Thomé's avatar
Emmanuel Thomé committed
132
    int r = param_list_add_key_nostrdup(pl,
133
            key ? strdup(key) : NULL, value ? strdup(value) : NULL, o);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
134
    return r;
135 136 137 138 139 140 141 142 143
}

struct sorting_data {
    parameter_srcptr s;
    int p;
};

typedef int (*sortfunc_t) (const void *, const void *);

144 145 146 147 148 149 150
int strcmp_or_null(const char * a, const char * b)
{
    if (a == NULL) { return b ? -1 : 0; }
    if (b == NULL) { return a ? 1 : 0; }
    return strcmp(a, b);
}

151 152 153
int paramcmp(const struct sorting_data * a, const struct sorting_data * b)
{
    int r;
154
    r = strcmp_or_null(a->s->key, b->s->key);
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    if (r) return r;
    r = a->s->origin - b->s->origin;
    if (r) return r;
    /* Compare by pointer position so that the sort is stable */
    return a->p - b->p;
}

/* Sort (for searching), and remove duplicates. */
void param_list_consolidate(param_list pl)
{
    if (pl->consolidated) {
        return;
    }
    struct sorting_data * intermediate;
    intermediate = malloc(pl->size * sizeof(struct sorting_data));
    for(unsigned int i = 0 ; i < pl->size ; i++) {
        intermediate[i].p = i;
        intermediate[i].s = pl->p[i];
    }
    qsort(intermediate, pl->size, sizeof(struct sorting_data),
            (sortfunc_t) &paramcmp);

    parameter * np = (parameter *) malloc(pl->alloc * sizeof(parameter));
    for(unsigned int i = 0 ; i < pl->size ; i++) {
        memcpy(np[i], pl->p[intermediate[i].p], sizeof(parameter));
    }
    free(pl->p);
    pl->p = np;
    free(intermediate);

    // now remove duplicates. The sorting has priorities right.
186
    unsigned int j = 0;
187
    for(unsigned int i = 0 ; i < pl->size ; i++) {
188
        if (pl->p[i]->key != NULL && i + 1 < pl->size && strcmp(pl->p[i]->key, pl->p[i+1]->key) == 0) {
189
            /* The latest pair in the list is the one having highest
190
             * priority. So we don't do the copy at this moment.
191
             */
192 193
            free(pl->p[i]->key);
            free(pl->p[i]->value);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
194
            // this value is useful for switches
195
            pl->p[i+1]->seen += pl->p[i]->seen;
196
        } else {
197
            // in theory memcpy does not allow overlaps, even trivial ones.
198 199 200
            if (i != j) {
                memcpy(pl->p[j], pl->p[i], sizeof(parameter));
            }
201 202 203 204 205 206 207 208
            j++;
        }
    }
    pl->size = j;

    pl->consolidated = 1;
}

209 210 211 212
void param_list_remove_key(param_list pl, const char * key)
{
    unsigned int j = 0;
    for(unsigned int i = 0 ; i < pl->size ; i++) {
213 214
        if (strcmp_or_null(pl->p[i]->key, key) == 0) {
            if (pl->p[i]->key) free(pl->p[i]->key);
215 216 217 218 219 220 221 222 223 224 225 226 227 228
            free(pl->p[i]->value);
        } else {
            if (i != j) {
                memcpy(pl->p[j], pl->p[i], sizeof(parameter));
            }
            j++;
        }
    }
    pl->size = j;

    pl->consolidated = 1;
}


229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
int param_list_read_stream(param_list pl, FILE *f)
{
    int all_ok=1;
    const int linelen = 512;
    char line[linelen];
    char * newkey;
    char * newvalue;
    while (!feof(f)) {
        if (fgets(line, linelen, f) == NULL)
            break;
        if (line[0] == '#')
            continue;
        // remove possible comment at end of line.
        char * hash;
        if ((hash = strchr(line, '#')) != NULL) {
            *hash = '\0';
        }

        char * p = line;

        // trailing space
        int l = strlen(p);
251
        for( ; l && isspace((int)(unsigned char)p[l-1]) ; l--);
252 253 254
        p[l] = '\0';

        // leading space.
255
        for( ; *p && isspace((int)(unsigned char)*p) ; p++, l--);
256 257 258 259 260 261 262

        // empty ps are ignored.
        if (l == 0)
            continue;

        // look for a left-hand-side.
        l = 0;
263
        if (!(isalpha((int)(unsigned char)p[l]) || p[l] == '_' || p[l] == '-')) {
264 265 266
            param_list_add_key(pl, NULL, line, PARAMETER_FROM_FILE);
            continue;
        }
267
        for( ; p[l] && (isalnum((int)(unsigned char)p[l]) || p[l] == '_' || p[l] == '-') ; l++);
268 269 270 271 272 273 274 275 276 277 278 279 280

        int lhs_length = l;

        if (lhs_length == 0) {
            fprintf(stderr, "Parse error, no usable key for config line:\n%s\n",
                    line);
            all_ok=0;
            continue;
        }

        /* Now we can match (whitespace*)(separator)(whitespace*)(data)
         */
        char * q = p + lhs_length;
281
        for( ; *q && isspace((int)(unsigned char)*q) ; q++);
282 283 284 285 286 287 288 289

        /* match separator, which is one of : = := */
        if (*q == '=') {
            q++;
        } else if (*q == ':') {
            q++;
            if (*q == '=')
                q++;
290
        } else if (q == p + lhs_length) {
291 292 293 294 295
            fprintf(stderr, "Parse error, no separator for config line:\n%s\n",
                    line);
            all_ok=0;
            continue;
        }
296
        for( ; *q && isspace((int)(unsigned char)*q) ; q++);
297 298 299 300 301 302 303

        newkey = malloc(lhs_length + 1);
        memcpy(newkey, p, lhs_length);
        newkey[lhs_length]='\0';

        newvalue = strdup(q);

304
        param_list_add_key_nostrdup(pl, newkey, newvalue, PARAMETER_FROM_FILE);
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    }
    param_list_consolidate(pl);

    return all_ok;
}

int param_list_read_file(param_list pl, const char * name)
{
    FILE * f;
    f = fopen(name, "r");
    if (f == NULL) {
        fprintf(stderr, "Cannot read %s\n", name);
        exit(1);
    }
    int r = param_list_read_stream(pl, f);
    fclose(f);
    return r;
}

324
int param_list_configure_alias(param_list pl, const char * key, const char * alias)
325
{
326 327 328 329 330
    if (pl->use_doc) {
        const char *k = key;
        if (k[0] == '-')
            k++;
        if (!is_documented_key(pl, k))
331
            fprintf(stderr, "# Warning: an alias %s is declared to the key %s that is undocumented\n", alias, key);
332
    }
333

334 335
    size_t len = strlen(alias);

336 337
    ASSERT_ALWAYS(alias != NULL);
    ASSERT_ALWAYS(key != NULL);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
338
    /* A switch may be aliases, but only as another switch !!! */
339 340 341 342 343 344 345
    ASSERT_ALWAYS(key[0] != '-' || (alias[0] == '-' && alias[len-1] != '='));

    if (alias[0] != '-' && alias[len-1] != '=') {
        /* Then, accept both the --xxx and xxx= forms */
        char * tmp;
        tmp = malloc(len + 4);
        snprintf(tmp, len+4, "--%s", alias);
346
        param_list_configure_alias(pl, key, tmp);
347
        snprintf(tmp, len+4, "%s=", alias);
348
        param_list_configure_alias(pl, key, tmp);
349 350 351
        free(tmp);
        return 0;
    }
352 353 354 355 356

    if (pl->naliases == pl->naliases_alloc) {
        pl->naliases_alloc += 1;
        pl->naliases_alloc <<= 1;
        pl->aliases = realloc(pl->aliases, pl->naliases_alloc * sizeof(param_list_alias));
357
    }
358
    pl->aliases[pl->naliases]->alias = strdup(alias);
359
    pl->aliases[pl->naliases]->key = key;
360 361 362
    pl->naliases++;
    return 0;
}
363

Emmanuel Thomé's avatar
Emmanuel Thomé committed
364
int param_list_configure_switch(param_list pl, const char * switchname, int * ptr)
365
{
366 367 368
    /* Some switches are passed as switchname = "switch", some as "-switch",
       and some as "--switch" ... */
    int offset = (switchname[0] == '-') ? (switchname[1] == '-' ? 2 : 1) : 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
369
    ASSERT_ALWAYS(switchname != NULL);
370
    if (pl->use_doc)
371
        if (!is_documented_key(pl, offset+switchname))
372 373
            fprintf(stderr, "# Warning: a switch %s is declared but is undocumented\n", switchname);

Emmanuel Thomé's avatar
Emmanuel Thomé committed
374 375 376 377
    if ((pl->nswitches + 1) >= pl->nswitches_alloc) {
        pl->nswitches_alloc += 2;
        pl->nswitches_alloc <<= 1;
        pl->switches = realloc(pl->switches, pl->nswitches_alloc * sizeof(param_list_switch));
378
    }
Emmanuel Thomé's avatar
Emmanuel Thomé committed
379
    char * tmp = (char *) malloc(strlen(switchname)+2);
380
    tmp[0]='-';
Emmanuel Thomé's avatar
Emmanuel Thomé committed
381 382
    if (switchname[1] == '-') { // have -- in the switch
        strncpy(tmp, switchname, strlen(switchname) + 1);
383
    } else {
Emmanuel Thomé's avatar
Emmanuel Thomé committed
384
        strncpy(tmp+1, switchname, strlen(switchname) + 1);
385 386
    }
    // put the -- version
Emmanuel Thomé's avatar
Emmanuel Thomé committed
387 388
    pl->switches[pl->nswitches]->switchname = strdup(tmp);
    pl->switches[pl->nswitches]->ptr = ptr;
389
    if (ptr) *ptr = 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
390
    pl->nswitches++;
391
    // put the - version
Emmanuel Thomé's avatar
Emmanuel Thomé committed
392 393
    pl->switches[pl->nswitches]->switchname = strdup(tmp+1);
    pl->switches[pl->nswitches]->ptr = ptr;
394
    if (ptr) *ptr = 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
395
    pl->nswitches++;
396 397
    free(tmp);

398 399 400
    return 0;
}

401 402 403

static int param_list_update_cmdline_alias(param_list pl,
        param_list_alias al,
404
        int * p_argc, char *** p_argv)
405
{
406 407 408 409
    if (!pl->cmdline_argv0) {
        pl->cmdline_argv0 = *p_argv;
        pl->cmdline_argc0 = *p_argc;
    }
410
    const char * a = (*p_argv[0]);
411
    if (al->alias[strlen(al->alias)-1] == '=') {
Emmanuel Thomé's avatar
Emmanuel Thomé committed
412
        // since switches are aliased only by switches, we know we have a plain
413 414
        // option here.
        if (strncmp(a, al->alias, strlen(al->alias)) != 0)
415
            return 0;
416
        a += strlen(al->alias);
417 418
        if (a[1] == '\0')
            return 0;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
419 420
        // no +1 , since the alias contains the = sign already.
        param_list_add_key(pl, al->key, a, PARAMETER_FROM_CMDLINE);
421 422 423 424
        (*p_argv)+=1;
        (*p_argc)-=1;
        return 1;
    }
425
    if (strcmp(a, al->alias) == 0) {
426
        if (al->key[0] == '-') {
Emmanuel Thomé's avatar
Emmanuel Thomé committed
427
            /* This is a switch ; we have to treat it accordingly. The
428
             * difficult part is to properly land on
Emmanuel Thomé's avatar
Emmanuel Thomé committed
429
             * param_list_update_cmdline_switch at the proper time. This
430 431
             * means in particular not necessarily there. It's
             * considerably easier to simply change the value in the
432 433
             * command line. Except that it's a const cast, it's ugly.
             * Okay, my apologies, blah blah.
434
             */
435
            (*p_argv)[0] = (char*) al->key;
436 437 438 439 440 441 442 443 444 445 446 447 448
            /* leave argv and argc unchanged. */
            return 0;
        }
        (*p_argv)+=1;
        (*p_argc)-=1;
        if (*p_argc == 0) {
            fprintf(stderr, "Option %s requires an argument\n", a);
            exit(1);
        }
        param_list_add_key(pl, al->key, (*p_argv[0]), PARAMETER_FROM_CMDLINE);
        (*p_argv)+=1;
        (*p_argc)-=1;
        return 1;
449 450 451 452
    }
    return 0;
}

Emmanuel Thomé's avatar
Emmanuel Thomé committed
453 454
static int param_list_update_cmdline_switch(param_list pl,
        param_list_switch switchpar,
455
        int * p_argc, char *** p_argv)
456
{
457 458 459 460
    if (!pl->cmdline_argv0) {
        pl->cmdline_argv0 = *p_argv;
        pl->cmdline_argc0 = *p_argc;
    }
461
    const char * a = (*p_argv[0]);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
462 463
    if (strcmp(a, switchpar->switchname) == 0) {
        param_list_add_key(pl, switchpar->switchname, NULL, PARAMETER_FROM_CMDLINE);
464 465
        (*p_argv)+=1;
        (*p_argc)-=1;
Emmanuel Thomé's avatar
Emmanuel Thomé committed
466
        if (switchpar->ptr) (*(switchpar->ptr))++;
467 468
        return 1;
    }
469 470 471 472 473 474 475 476 477 478 479 480 481 482
    if (strncmp(switchpar->switchname, "--", 2) != 0)
        return 0;
    char * inv_switch;
    int rc = asprintf(&inv_switch, "--no-%s", switchpar->switchname+2);
    ASSERT_ALWAYS(rc>=0);
    int match = strcmp(inv_switch, a) == 0;
    free(inv_switch);
    if (match) {
        param_list_add_key(pl, a, NULL, PARAMETER_FROM_CMDLINE);
        (*p_argv)+=1;
        (*p_argc)-=1;
        if (switchpar->ptr) (*(switchpar->ptr))=0;
        return 1;
    }
483 484 485
    return 0;
}

486
int param_list_update_cmdline(param_list pl,
487
        int * p_argc, char *** p_argv)
488
{
489 490 491 492
    if (!pl->cmdline_argv0) {
        pl->cmdline_argv0 = *p_argv;
        pl->cmdline_argc0 = *p_argc;
    }
493 494 495 496 497 498 499
    if (*p_argc == 0)
        return 0;

    int i;

    /* We rely on having alias scanning first, because this incurs a
     * command line changed (could get along without except in the case
Emmanuel Thomé's avatar
Emmanuel Thomé committed
500
     * of switches where it's particularly handy).
501 502 503 504 505 506
     */
    for(i = 0 ; i < pl->naliases ; i++) {
        if (param_list_update_cmdline_alias(pl, pl->aliases[i], p_argc, p_argv))
            return 1;
    }

Emmanuel Thomé's avatar
Emmanuel Thomé committed
507 508
    for(i = 0 ; i < pl->nswitches ; i++) {
        if (param_list_update_cmdline_switch(pl, pl->switches[i], p_argc, p_argv))
509 510 511 512 513 514 515 516 517 518 519 520
            return 1;
    }

    const char * a = (*p_argv[0]);
    if (*p_argc >= 2 && a[0] == '-') {
        a++;
        a+= *a == '-';
        int x=0;
        /* parameters _must_ begin by alphabetic characters, or
         * otherwise we suffer to distinguish immediate numerical
         * entries.
         */
521
        if (!isalpha((int)(unsigned char)a[x]))
522
            return 0;
523
        for( ; a[x] && (isalnum((int)(unsigned char)a[x]) || a[x] == '_' || a[x] == '-') ; x++);
524 525 526 527 528 529 530 531 532
        if (a[x] == '\0') {
            param_list_add_key(pl, a, (*p_argv)[1], PARAMETER_FROM_CMDLINE);
            (*p_argv)+=2;
            (*p_argc)-=2;
            return 1;
        }
    } else {
        /* Check for <key>=<value> syntax */
        int x=0;
533
        for( ; a[x] && (isalnum((int)(unsigned char)a[x]) || a[x] == '_' || a[x] == '-') ; x++);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        if (a[x] == '=' && a[x+1]) {
            char * newkey = malloc(x+1);
            memcpy(newkey, a, x);
            newkey[x]='\0';
            char * newvalue = strdup(a+x+1);
            param_list_add_key_nostrdup(pl,
                    newkey, newvalue, PARAMETER_FROM_CMDLINE);
            (*p_argv)+=1;
            (*p_argc)-=1;
            return 1;
        }
    }
    return 0;
}

549 550
int param_strcmp(const char * a, parameter_srcptr b)
{
551
    return strcmp_or_null(a, b->key);
552 553 554 555
}

static int assoc(param_list pl, const char * key)
{
556
    if (pl->use_doc) {
557 558 559 560 561
        const char *k = (key[0] == '-') ? (1+key) : key;
        if (!is_documented_key(pl, k)) 
            fprintf(stderr, "# Warning: parameter %s is checked by this program but is undocumented.\n", k);
    }

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    void * found;

    param_list_consolidate(pl);
    found = bsearch(key, pl->p, pl->size,
            sizeof(parameter), (sortfunc_t) param_strcmp);
    if (found == NULL)
        return -1;
    parameter * c = (parameter *) found;
    return c-pl->p;
}

int param_list_parse_long(param_list pl, const char * key, long * r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    long res;
    res = strtol(value, &end, 0);
    if (*end != '\0') {
        fprintf(stderr, "Parse error: parameter for key %s is not a long: %s\n",
                key, value);
        exit(1);
    }
    if (r)
        *r = res;
590
    return pl->p[v]->seen;
591 592 593 594 595
}

int param_list_parse_int(param_list pl, const char * key, int * r)
{
    long res;
596 597 598
    int rc;
    rc = param_list_parse_long(pl, key, &res);
    if (rc == 0)
599 600 601 602 603 604 605 606 607
        return 0;
    if (res > INT_MAX || res < INT_MIN) {
        fprintf(stderr, "Parse error:"
                " parameter for key %s does not fit within an int: %ld\n",
                key, res);
        exit(1);
    }
    if (r)
        *r  = res;
608
    return rc;
609 610
}

611
int param_list_parse_int_and_int(param_list pl, const char * key, int * r, const char * sep)
612 613 614 615 616 617 618 619 620
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    long res[2];
    res[0] = strtol(value, &end, 0);
621
    if (strncmp(end, sep, strlen(sep)) != 0) {
622
        fprintf(stderr, "Parse error: parameter for key %s"
623 624
                " must match %%d%s%%d; got %s\n",
                key, sep, pl->p[v]->value);
625 626
        exit(1);
    }
627
    value = end + strlen(sep);
628 629 630
    res[1] = strtol(value, &end, 0);
    if (*end != '\0') {
        fprintf(stderr, "Parse error: parameter for key %s"
Emmanuel Thomé's avatar
Emmanuel Thomé committed
631 632
                " must match %%d%s%%d; got %s\n",
                key, sep, pl->p[v]->value);
633 634 635 636 637 638
        exit(1);
    }
    if (r) {
        r[0] = res[0];
        r[1] = res[1];
    }
639
    return pl->p[v]->seen;
640 641
}

642 643 644 645 646
int param_list_parse_intxint(param_list pl, const char * key, int * r)
{
    return param_list_parse_int_and_int(pl, key, r, "x");
}

647

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
int param_list_parse_ulong(param_list pl, const char * key, unsigned long * r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    unsigned long res;
    res = strtoul(value, &end, 0);
    if (*end != '\0') {
        fprintf(stderr, "Parse error:"
                " parameter for key %s is not an ulong: %s\n",
                key, value);
        exit(1);
    }
    if (r)
        *r = res;
666
    return pl->p[v]->seen;
667 668
}

669 670 671 672 673 674 675 676 677 678
int param_list_parse_size_t(param_list pl, const char * key, size_t * r)
{
    unsigned long t;
    int res;
    res = param_list_parse_ulong(pl, key, &t);
    if (res && r) { *r = t; }
    return res;
}


679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
int param_list_parse_int64(param_list pl, const char * key, int64_t * r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    int64_t res;
    res = strtoimax(value, &end, 0);
    if (*end != '\0') {
        fprintf(stderr, "Parse error:"
                " parameter for key %s is not an int64_t: %s\n",
                key, value);
        exit(1);
    }
    if (r)
        *r = res;
    return pl->p[v]->seen;
}

700 701 702 703 704 705 706 707 708 709 710 711
int param_list_parse_uint64(param_list pl, const char * key, uint64_t * r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    uint64_t res;
    res = strtoumax(value, &end, 0);
    if (*end != '\0') {
        fprintf(stderr, "Parse error:"
712
                " parameter for key %s is not an uint64_t: %s\n",
713 714 715 716 717 718 719 720
                key, value);
        exit(1);
    }
    if (r)
        *r = res;
    return pl->p[v]->seen;
}

721 722 723
int param_list_parse_uint(param_list pl, const char * key, unsigned int * r)
{
    unsigned long res;
724 725
    int rc = param_list_parse_ulong(pl, key, &res);
    if (rc == 0)
726 727 728
        return 0;
    if (res > UINT_MAX) {
        fprintf(stderr, "Parse error:"
ZIMMERMANN Paul's avatar
ZIMMERMANN Paul committed
729
                " parameter for key %s does not fit within an unsigned int: %ld\n",
730 731 732 733 734
                key, res);
        exit(1);
    }
    if (r)
        *r  = res;
735
    return rc;
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
}


int param_list_parse_double(param_list pl, const char * key, double * r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    double res;
    res = strtod(value, &end);
    if (*end != '\0') {
        fprintf(stderr, "Parse error: parameter for key %s is not an int: %s\n",
                key, value);
        exit(1);
    }
    if (r)
        *r = res;
756
    return pl->p[v]->seen;
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
}

int param_list_parse_string(param_list pl, const char * key, char * r, size_t n)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    pl->p[v]->parsed=1;
    char * value = pl->p[v]->value;
    if (r && strlen(value) > n-1) {
        fprintf(stderr, "Parse error:"
                " parameter for key %s does not fit within string buffer"
                " of length %lu\n", key, (unsigned long) n);
        exit(1);
    }
    if (r)
        strncpy(r, value, n);
774 775 776
    return pl->p[v]->seen;
}

Emmanuel Thomé's avatar
Emmanuel Thomé committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
int param_list_parse_int_list(param_list pl, const char * key, int * r, size_t n, const char * sep)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    char * value = pl->p[v]->value;
    pl->p[v]->parsed=1;
    char * end;
    int * res = malloc(n * sizeof(int));
    memset(res, 0, n * sizeof(int));
    size_t parsed = 0;
    for( ;; ) {
        res[parsed] = strtol(value, &end, 0);
        if (parsed++ == n)
            break;
        if (parsed && *end == '\0')
            break;
        if (strncmp(end, sep, strlen(sep)) != 0) {
            fprintf(stderr, "Parse error: parameter for key %s"
                    " must match %%d(%s%%d)*; got %s\n",
                    key, sep, pl->p[v]->value);
            exit(1);
        }
        value = end + strlen(sep);
    }
    if (*end != '\0') {
        fprintf(stderr, "Parse error: parameter for key %s"
804
                " must match %%d(%s%%d){0,%zu}; got %s\n",
Emmanuel Thomé's avatar
Emmanuel Thomé committed
805
                key, sep, n-1, pl->p[v]->value);
Emmanuel Thomé's avatar
Emmanuel Thomé committed
806 807 808 809 810 811 812 813 814
        exit(1);
    }
    if (r) {
        memcpy(r, res, n * sizeof(int));
    }
    free(res);
    return parsed;
}

815 816 817 818 819 820 821 822
const char * param_list_lookup_string(param_list pl, const char * key)
{
    int v = assoc(pl, key);
    if (v < 0)
        return NULL;
    pl->p[v]->parsed=1;
    const char * value = pl->p[v]->value;
    return value;
823 824 825 826 827 828 829 830 831 832 833 834
}

int param_list_parse_mpz(param_list pl, const char * key, mpz_ptr r)
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    pl->p[v]->parsed=1;
    unsigned int nread;
    int rc;
    char * value = pl->p[v]->value;
    if (r) {
835
        rc = gmp_sscanf(value, "%Zi%n", r, &nread);
836 837
    } else {
        /* scan even when the result is not wanted */
838
        rc = gmp_sscanf(value, "%*Zi%n", &nread);
839 840 841 842 843 844
    }
    if (rc != 1 || value[nread] != '\0') {
        fprintf(stderr, "Parse error: parameter for key %s is not an mpz: %s\n",
                key, value);
        exit(1);
    }
845 846 847
    return pl->p[v]->seen;
}

Emmanuel Thomé's avatar
Emmanuel Thomé committed
848
int param_list_parse_switch(param_list pl, const char * key)
849 850 851 852 853 854 855 856 857 858
{
    int v = assoc(pl, key);
    if (v < 0)
        return 0;
    pl->p[v]->parsed=1;
    if (pl->p[v]->value != NULL) {
        fprintf(stderr, "Parse error: option %s accepts no argument\n", key);
        exit(1);
    }
    return pl->p[v]->seen;
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
}

int param_list_all_consumed(param_list pl, char ** extraneous)
{
    for(unsigned int i = 0 ; i < pl->size ; i++) {
        if (!pl->p[i]->parsed) {
            pl->p[i]->parsed = 1;
            if (extraneous) {
                *extraneous = pl->p[i]->key;
            }
            return 0;
        }
    }
    return 1;
}

int param_list_warn_unused(param_list pl)
{
    int u = 0;
    for(unsigned int i = 0 ; i < pl->size ; i++) {
        if (pl->p[i]->origin != PARAMETER_FROM_FILE && !pl->p[i]->parsed) {
            fprintf(stderr, "Warning: unused command-line parameter %s\n",
                    pl->p[i]->key);
            u++;
        }
    }
    return u;
}

void param_list_display(param_list pl, FILE *f)
{
    param_list_consolidate(pl);
    for(unsigned int i = 0 ; i < pl->size ; i++) {
        fprintf(f,"%s=%s\n", pl->p[i]->key, pl->p[i]->value);
    }
}
895 896 897 898 899 900 901 902 903 904 905 906

void param_list_save(param_list pl, const char * filename)
{
    FILE * f = fopen(filename, "w");
    if (f == NULL) {
        fprintf(stderr, "fopen(%s): %s\n", filename, strerror(errno));
        exit(1);
    }

    param_list_display(pl, f);
    fclose(f);
}
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

int param_list_save_parameter(param_list pl, enum parameter_origin o, 
        const char * key, const char * format, ...)
{
    va_list ap;
    va_start(ap, format);

    char * tmp;
    int rc;
    rc = vasprintf(&tmp, format, ap);
    param_list_add_key(pl, key, tmp, o);
    free(tmp);

    return rc;
}
922 923 924 925 926 927 928 929 930

void print_command_line(FILE * stream, int argc, char * argv[])
{
    /* print command line */
    fprintf (stream, "# (%s) %s", CADO_REV, argv[0]);
    for (int i = 1; i < argc; i++)
        fprintf (stream, " %s", argv[i]);
    fprintf (stream, "\n");
#ifdef  __GNUC__
931
    fprintf (stream, "# Compiled with gcc " __VERSION__ "\n");
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

    /* Apple Clang (based on llvm) identifies itself as a flavour of GNUC 4.2.1
       but seems to compile CADO-NFS properly 
       $ echo | clang -dD -E -pipe -
       # 1 "<stdin>"
       # 1 "<stdin>" 1
       # 1 "<built-in>" 1
       # 1 "<built-in>" 3
       #define __llvm__ 1
       #define __clang__ 1
       #define __clang_major__ 4
       #define __clang_minor__ 1
       #define __clang_patchlevel__ 0
       #define __clang_version__ "4.1 ((tags/Apple/clang-421.11.66))"
       #define __GNUC_MINOR__ 2
       #define __GNUC_PATCHLEVEL__ 1
       #define __GNUC__ 4
       ...
    */
    
#if (GNUC_VERSION(4,1,2) || GNUC_VERSION(4,2,0) || GNUC_VERSION(4,2,1) || GNUC_VERSION(4,2,2)) \
  && ! (__llvm__ || __clang__)
954
    fprintf (stream, "# WARNING: this version of GCC is known to miscompile CADO-NFS. See https://gforge.inria.fr/tracker/index.php?func=detail&aid=14490\n");
955
#endif
956 957 958 959 960 961 962 963
#endif
    fprintf(stream, "# Compilation flags " CFLAGS "\n");
}

void param_list_print_command_line(FILE * stream, param_list pl)
{
    /* remember that the API for calling param_list functions mandates
     * that the binary name $0 is stripped from the provided lists */
964 965
    if (pl->cmdline_argv0 != NULL)
        print_command_line(stream, pl->cmdline_argc0+1, pl->cmdline_argv0-1);
966
}