[BACK]Return to util.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / texi2mdoc

Annotation of texi2mdoc/util.c, Revision 1.26

1.26    ! kristaps    1: /*     $Id: util.c,v 1.25 2015/03/03 22:37:24 kristaps Exp $ */
1.1       kristaps    2: /*
                      3:  * Copyright (c) 2015 Kristaps Dzonsons <kristaps@bsd.lv>
                      4:  *
                      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
                      8:  *
                      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     16:  */
                     17: #include <sys/mman.h>
                     18: #include <sys/stat.h>
                     19:
                     20: #include <assert.h>
                     21: #include <ctype.h>
                     22: #include <fcntl.h>
                     23: #include <limits.h>
                     24: #include <stdarg.h>
                     25: #include <stdio.h>
                     26: #include <stdlib.h>
                     27: #include <string.h>
                     28: #include <time.h>
                     29: #include <unistd.h>
                     30:
                     31: #include "extern.h"
                     32:
                     33: /*
                     34:  * Unmap the top-most file in the stack of files currently opened (that
                     35:  * is, nested calls to parsefile()).
                     36:  */
                     37: void
                     38: texifilepop(struct texi *p)
                     39: {
                     40:        struct texifile *f;
                     41:
                     42:        assert(p->filepos > 0);
                     43:        f = &p->files[--p->filepos];
1.14      kristaps   44:        free(f->map);
1.1       kristaps   45: }
                     46:
1.7       kristaps   47: static void
                     48: teximacrofree(struct teximacro *p)
                     49: {
                     50:        size_t   i;
                     51:
                     52:        for (i = 0; i < p->argsz; i++)
                     53:                free(p->args[i]);
                     54:
                     55:        free(p->args);
                     56:        free(p->key);
                     57:        free(p->value);
                     58: }
                     59:
                     60: static void
                     61: texivaluefree(struct texivalue *p)
                     62: {
                     63:
                     64:        free(p->key);
                     65:        free(p->value);
                     66: }
                     67:
1.1       kristaps   68: /*
                     69:  * Unmap all files that we're currently using and free all resources
                     70:  * that we've allocated during the parse.
                     71:  * The utility should exit(...) after this is called.
                     72:  */
                     73: void
                     74: texiexit(struct texi *p)
                     75: {
                     76:        size_t   i;
                     77:
                     78:        /* Make sure we're newline-terminated. */
                     79:        if (p->outcol)
1.20      kristaps   80:                fputc('\n', p->outfile);
                     81:        if (NULL != p->chapters)
                     82:                teximdocclose(p, 1);
1.1       kristaps   83:
                     84:        /* Unmap all files. */
                     85:        while (p->filepos > 0)
                     86:                texifilepop(p);
                     87:
1.7       kristaps   88:        for (i = 0; i < p->macrosz; i++)
                     89:                teximacrofree(&p->macros[i]);
1.1       kristaps   90:        for (i = 0; i < p->dirsz; i++)
                     91:                free(p->dirs[i]);
1.4       kristaps   92:        for (i = 0; i < p->indexsz; i++)
                     93:                free(p->indexs[i]);
1.7       kristaps   94:        for (i = 0; i < p->valsz; i++)
                     95:                texivaluefree(&p->vals[i]);
1.4       kristaps   96:
1.7       kristaps   97:        free(p->macros);
1.1       kristaps   98:        free(p->vals);
1.4       kristaps   99:        free(p->indexs);
1.1       kristaps  100:        free(p->dirs);
                    101:        free(p->subtitle);
                    102:        free(p->title);
1.26    ! kristaps  103:        free(p->copying);
1.1       kristaps  104: }
                    105:
                    106: /*
                    107:  * Fatal error: unmap all files and exit.
                    108:  * The "errstring" is passed to perror(3).
                    109:  */
                    110: void
                    111: texiabort(struct texi *p, const char *errstring)
                    112: {
                    113:
                    114:        perror(errstring);
                    115:        texiexit(p);
                    116:        exit(EXIT_FAILURE);
                    117: }
                    118:
                    119: /*
                    120:  * Print a generic warning message (to stderr) tied to our current
                    121:  * location in the parse sequence.
                    122:  */
                    123: void
                    124: texiwarn(const struct texi *p, const char *fmt, ...)
                    125: {
1.15      kristaps  126:        va_list                  ap;
                    127:        const struct texifile   *f;
                    128:
                    129:        f = &p->files[p->filepos - 1];
                    130:
                    131:        if (f->insplice)
                    132:                fprintf(stderr, "%s:%zu:%zu (%zuB left in splice): "
                    133:                        "warning: ", f->name, f->line + 1,
                    134:                        f->col + 1, f->insplice);
                    135:        else
                    136:                fprintf(stderr, "%s:%zu:%zu: warning: ",
                    137:                        f->name, f->line + 1, f->col + 1);
1.1       kristaps  138:
                    139:        va_start(ap, fmt);
                    140:        vfprintf(stderr, fmt, ap);
                    141:        va_end(ap);
                    142:        fputc('\n', stderr);
                    143: }
                    144:
                    145: /*
                    146:  * Print an error message (to stderr) tied to our current location in
                    147:  * the parse sequence, invoke texiexit(), then die.
                    148:  */
                    149: void
                    150: texierr(struct texi *p, const char *fmt, ...)
                    151: {
1.15      kristaps  152:        va_list          ap;
                    153:        struct texifile *f;
                    154:
                    155:        f = &p->files[p->filepos - 1];
                    156:
                    157:        if (f->insplice)
                    158:                fprintf(stderr, "%s:%zu:%zu: (%zuB left in splice): "
                    159:                        "error: ", f->name, f->line + 1,
                    160:                        f->col + 1, f->insplice);
                    161:        else
                    162:                fprintf(stderr, "%s:%zu:%zu: error: ",
                    163:                        f->name, f->line + 1, f->col + 1);
1.1       kristaps  164:
                    165:        va_start(ap, fmt);
                    166:        vfprintf(stderr, fmt, ap);
                    167:        va_end(ap);
                    168:        fputc('\n', stderr);
                    169:        texiexit(p);
                    170:        exit(EXIT_FAILURE);
                    171: }
                    172:
                    173: /*
                    174:  * Put a single data character to the output if we're not ignoring.
1.13      kristaps  175:  * Escape starting a line with a control character and slashes.
1.1       kristaps  176:  */
                    177: void
                    178: texiputchar(struct texi *p, char c)
                    179: {
                    180:
                    181:        if (p->ign)
                    182:                return;
                    183:        if ('.' == c && 0 == p->outcol)
1.20      kristaps  184:                fputs("\\&", p->outfile);
1.10      kristaps  185:        if ('\'' == c && 0 == p->outcol)
1.20      kristaps  186:                fputs("\\&", p->outfile);
1.1       kristaps  187:
1.23      kristaps  188:        if (p->uppercase)
                    189:                fputc(toupper((unsigned int)c), p->outfile);
                    190:        else
                    191:                fputc(c, p->outfile);
1.13      kristaps  192:        if ('\\' == c)
1.20      kristaps  193:                fputc('e', p->outfile);
1.1       kristaps  194:        p->seenvs = 0;
                    195:        if ('\n' == c) {
                    196:                p->outcol = 0;
                    197:                p->seenws = 0;
                    198:        } else
                    199:                p->outcol++;
                    200: }
                    201:
                    202: /*
1.13      kristaps  203:  * Put an opaque series of characters.
                    204:  * Characters starting a line with a control character are escaped, but
                    205:  * that's it, so don't use this for non-controlled sequences of text.
1.1       kristaps  206:  */
                    207: void
                    208: texiputchars(struct texi *p, const char *s)
                    209: {
                    210:
1.13      kristaps  211:        if (p->ign)
                    212:                return;
                    213:        if ('.' == *s && 0 == p->outcol)
1.20      kristaps  214:                fputs("\\&", p->outfile);
1.13      kristaps  215:        if ('\'' == *s && 0 == p->outcol)
1.20      kristaps  216:                fputs("\\&", p->outfile);
1.23      kristaps  217:        if (p->uppercase)
                    218:                for ( ; '\0' != *s; s++)
                    219:                        p->outcol += fputc(toupper
                    220:                                ((unsigned int)*s), p->outfile);
                    221:        else
                    222:                p->outcol += fputs(s, p->outfile);
1.13      kristaps  223:        p->seenvs = 0;
1.9       kristaps  224: }
                    225:
                    226: /*
                    227:  * This puts all characters onto the output stream but makes sure to
                    228:  * escape mdoc(7) slashes.
1.14      kristaps  229:  * FIXME: useless.
1.9       kristaps  230:  */
                    231: void
1.14      kristaps  232: texiputbuf(struct texi *p, size_t start, size_t end)
1.9       kristaps  233: {
                    234:
1.14      kristaps  235:        for ( ; start < end; start++)
                    236:                texiputchar(p, BUF(p)[start]);
1.1       kristaps  237: }
                    238:
                    239: /*
                    240:  * Close an mdoc(7) macro opened with teximacroopen().
                    241:  * If there are no more macros on the line, prints a newline.
                    242:  */
                    243: void
                    244: teximacroclose(struct texi *p)
                    245: {
                    246:
                    247:        if (p->ign)
                    248:                return;
                    249:
                    250:        if (0 == --p->outmacro) {
1.20      kristaps  251:                fputc('\n', p->outfile);
1.1       kristaps  252:                p->outcol = p->seenws = 0;
                    253:        }
                    254: }
                    255:
                    256: /*
                    257:  * Open a mdoc(7) macro.
                    258:  * This is used for line macros, e.g., Qq [foo bar baz].
                    259:  * It can be invoked for nested macros, e.g., Qq Li foo .
                    260:  * TODO: flush-right punctuation (e.g., parenthesis).
                    261:  */
                    262: void
                    263: teximacroopen(struct texi *p, const char *s)
                    264: {
                    265:        int      rc;
                    266:
                    267:        if (p->ign)
                    268:                return;
                    269:
                    270:        if (p->outcol && 0 == p->outmacro) {
1.20      kristaps  271:                fputc('\n', p->outfile);
1.1       kristaps  272:                p->outcol = 0;
                    273:        }
                    274:
                    275:        if (0 == p->outmacro)
1.20      kristaps  276:                fputc('.', p->outfile);
1.1       kristaps  277:        else
1.20      kristaps  278:                fputc(' ', p->outfile);
1.1       kristaps  279:
1.20      kristaps  280:        if (EOF != (rc = fputs(s, p->outfile)))
1.1       kristaps  281:                p->outcol += rc;
                    282:
1.20      kristaps  283:        fputc(' ', p->outfile);
1.1       kristaps  284:        p->outcol++;
                    285:        p->outmacro++;
                    286:        p->seenws = 0;
                    287: }
                    288:
                    289: /*
                    290:  * Put a stadnalone mdoc(7) command with the trailing newline.
                    291:  */
                    292: void
                    293: teximacro(struct texi *p, const char *s)
                    294: {
                    295:
                    296:        if (p->ign)
                    297:                return;
                    298:
                    299:        if (p->outmacro)
                    300:                texierr(p, "\"%s\" in open line scope!?", s);
                    301:        if (p->literal)
                    302:                texierr(p, "\"%s\" in a literal scope!?", s);
                    303:
                    304:        if (p->outcol)
1.20      kristaps  305:                fputc('\n', p->outfile);
1.1       kristaps  306:
1.20      kristaps  307:        fputc('.', p->outfile);
                    308:        fputs(s, p->outfile);
                    309:        fputc('\n', p->outfile);
1.1       kristaps  310:        p->outcol = p->seenws = 0;
                    311: }
                    312:
                    313: /*
                    314:  * Introduce vertical space during normal (non-macro) input.
                    315:  */
                    316: void
                    317: texivspace(struct texi *p)
                    318: {
                    319:
1.5       kristaps  320:        if (p->seenvs || TEXILIST_TABLE == p->list)
1.1       kristaps  321:                return;
                    322:        teximacro(p, "Pp");
                    323:        p->seenvs = 1;
                    324: }
                    325:
                    326: /*
                    327:  * Advance by a single byte in the input stream, adjusting our location
                    328:  * in the current input file.
                    329:  */
                    330: void
1.14      kristaps  331: advance(struct texi *p, size_t *pos)
1.1       kristaps  332: {
1.15      kristaps  333:        struct texifile *f;
1.1       kristaps  334:
1.15      kristaps  335:        f = &p->files[p->filepos - 1];
                    336:
                    337:        if (0 == f->insplice) {
                    338:                if ('\n' == BUF(p)[*pos]) {
                    339:                        f->line++;
                    340:                        f->col = 0;
                    341:                } else
                    342:                        f->col++;
1.17      kristaps  343:        } else {
1.15      kristaps  344:                --f->insplice;
1.17      kristaps  345:                if (0 == f->insplice)
                    346:                        f->depth = 0;
                    347:        }
1.1       kristaps  348:
                    349:        (*pos)++;
                    350: }
                    351:
                    352: /*
                    353:  * It's common to wait punctuation to float on the right side of macro
                    354:  * lines in mdoc(7), e.g., ".Em hello ) ."
                    355:  * This function does so, and should be called before teximacroclose().
                    356:  * It will detect that it's the last in the nested macros and
                    357:  * appropriately flush-left punctuation alongside the macro.
                    358:  */
                    359: void
1.14      kristaps  360: texipunctuate(struct texi *p, size_t *pos)
1.1       kristaps  361: {
                    362:        size_t   start, end;
                    363:
                    364:        if (1 != p->outmacro)
                    365:                return;
                    366:
1.14      kristaps  367:        for (start = end = *pos; end < BUFSZ(p); end++) {
                    368:                switch (BUF(p)[end]) {
1.1       kristaps  369:                case (','):
                    370:                case (')'):
                    371:                case ('.'):
                    372:                case ('"'):
                    373:                case (':'):
1.22      kristaps  374:                case (';'):
1.1       kristaps  375:                case ('!'):
                    376:                case ('?'):
                    377:                        continue;
                    378:                default:
                    379:                        break;
                    380:                }
                    381:                break;
                    382:        }
                    383:        if (end == *pos)
                    384:                return;
1.14      kristaps  385:        if (end + 1 == BUFSZ(p) || ' ' == BUF(p)[end] ||
                    386:                '\n' == BUF(p)[end]) {
1.1       kristaps  387:                for ( ; start < end; start++) {
                    388:                        texiputchar(p, ' ');
1.14      kristaps  389:                        texiputchar(p, BUF(p)[start]);
                    390:                        advance(p, pos);
1.1       kristaps  391:                }
                    392:        }
                    393: }
                    394:
                    395: /*
                    396:  * Advance to the next non-whitespace word in the input stream.
                    397:  * If we're in literal mode, then print all of the whitespace as we're
                    398:  * doing so.
                    399:  */
                    400: static size_t
1.14      kristaps  401: advancenext(struct texi *p, size_t *pos)
1.1       kristaps  402: {
                    403:
                    404:        if (p->literal) {
1.14      kristaps  405:                while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos])) {
                    406:                        texiputchar(p, BUF(p)[*pos]);
                    407:                        advance(p, pos);
1.1       kristaps  408:                }
                    409:                return(*pos);
                    410:        }
                    411:
1.14      kristaps  412:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos])) {
1.1       kristaps  413:                p->seenws = 1;
                    414:                /*
                    415:                 * If it looks like we've printed a double-line, then
                    416:                 * output a paragraph.
                    417:                 * FIXME: this is stupid.
                    418:                 */
1.14      kristaps  419:                if (*pos && '\n' == BUF(p)[*pos] && '\n' == BUF(p)[*pos - 1])
1.1       kristaps  420:                        texivspace(p);
1.14      kristaps  421:                advance(p, pos);
1.1       kristaps  422:        }
                    423:        return(*pos);
                    424: }
                    425:
                    426: /*
                    427:  * Advance to the EOLN in the input stream.
1.22      kristaps  428:  * This will skip over '@' markers in an effort to ignore escaped
                    429:  * newlines.
1.1       kristaps  430:  */
                    431: size_t
1.14      kristaps  432: advanceeoln(struct texi *p, size_t *pos, int consumenl)
1.1       kristaps  433: {
                    434:
1.22      kristaps  435:        while (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos]) {
                    436:                if ('@' == BUF(p)[*pos])
                    437:                        advance(p, pos);
1.14      kristaps  438:                advance(p, pos);
1.22      kristaps  439:        }
1.14      kristaps  440:        if (*pos < BUFSZ(p) && consumenl)
                    441:                advance(p, pos);
1.1       kristaps  442:        return(*pos);
                    443: }
                    444:
                    445: /*
                    446:  * Advance to position "end", which is an absolute position in the
                    447:  * current buffer greater than or equal to the current position.
                    448:  */
                    449: void
1.14      kristaps  450: advanceto(struct texi *p, size_t *pos, size_t end)
1.1       kristaps  451: {
                    452:
                    453:        assert(*pos <= end);
                    454:        while (*pos < end)
1.14      kristaps  455:                advance(p, pos);
1.1       kristaps  456: }
                    457:
1.7       kristaps  458: static void
1.17      kristaps  459: texiexecmacro(struct texi *p, struct teximacro *m, size_t sv, size_t *pos)
1.7       kristaps  460: {
1.11      kristaps  461:        size_t            valsz, realsz, aasz, asz,
                    462:                           ssz, i, j, k, start, end;
                    463:        char             *val;
                    464:        char            **args;
                    465:        const char       *cp;
1.7       kristaps  466:
1.17      kristaps  467:        /* Disregard empty macros. */
1.22      kristaps  468:        if (0 == (valsz = realsz = strlen(m->value))) {
                    469:                args = argparse(p, pos, &asz, m->argsz);
                    470:                for (i = 0; i < asz; i++)
                    471:                        free(args[i]);
                    472:                free(args);
1.17      kristaps  473:                return;
1.22      kristaps  474:        }
1.17      kristaps  475:
                    476:        /*
                    477:         * This is important: it protect us from macros that invoke more
                    478:         * macros, possibly going on infinitely.
                    479:         * We use "sv" instead of the current position because we might
                    480:         * be invoked at the end of the macro (i.e., insplice == 0).
                    481:         * The "sv" value was initialised at the start of the macro.
                    482:         */
                    483:        if (sv > 0)
1.24      kristaps  484:                if (++p->files[p->filepos - 1].depth > 64)
1.17      kristaps  485:                        texierr(p, "maximium recursive depth");
                    486:
1.14      kristaps  487:        args = argparse(p, pos, &asz, m->argsz);
1.7       kristaps  488:        if (asz != m->argsz)
                    489:                texiwarn(p, "invalid macro argument length");
                    490:        aasz = asz < m->argsz ? asz : m->argsz;
                    491:
                    492:        if (0 == aasz) {
1.21      kristaps  493:                texisplice(p, m->value, valsz, *pos);
1.7       kristaps  494:                return;
                    495:        }
                    496:
                    497:        val = strdup(m->value);
                    498:
                    499:        for (i = j = 0; i < realsz; i++) {
                    500:                /* Parse blindly til the backslash delimiter. */
                    501:                if ('\\' != m->value[i]) {
                    502:                        val[j++] = m->value[i];
                    503:                        val[j] = '\0';
                    504:                        continue;
                    505:                } else if (i == realsz - 1)
                    506:                        texierr(p, "trailing argument name delimiter");
                    507:
                    508:                /* Double-backslash is escaped. */
                    509:                if ('\\' == m->value[i + 1]) {
                    510:                        val[j++] = m->value[i++];
                    511:                        val[j] = '\0';
                    512:                        continue;
                    513:                }
                    514:
                    515:                assert('\\' == m->value[i] && i < realsz - 1);
                    516:
                    517:                /* Parse to terminating delimiter. */
                    518:                /* FIXME: embedded, escaped delimiters? */
                    519:                for (start = end = i + 1; end < realsz; end++)
                    520:                        if ('\\' == m->value[end])
                    521:                                break;
                    522:                if (end == realsz)
                    523:                        texierr(p, "unterminated argument name");
                    524:
                    525:                for (k = 0; k < aasz; k++) {
                    526:                        if ((ssz = strlen(m->args[k])) != (end - start))
                    527:                                continue;
                    528:                        if (strncmp(&m->value[start], m->args[k], ssz))
                    529:                                continue;
                    530:                        break;
                    531:                }
                    532:
                    533:                /*
                    534:                 * Argument didn't exist in argument table.
1.14      kristaps  535:                 * Just ignore it.
1.7       kristaps  536:                 */
                    537:                if (k == aasz) {
1.14      kristaps  538:                        i = end;
1.7       kristaps  539:                        continue;
                    540:                }
                    541:
                    542:                if (strlen(args[k]) > ssz) {
                    543:                        valsz += strlen(args[k]);
                    544:                        val = realloc(val, valsz + 1);
                    545:                        if (NULL == val)
                    546:                                texiabort(p, NULL);
                    547:                }
                    548:
1.11      kristaps  549:                for (cp = args[k]; '\0' != *cp; cp++)
                    550:                        val[j++] = *cp;
                    551:
                    552:                val[j] = '\0';
1.7       kristaps  553:                i = end;
                    554:        }
                    555:
1.21      kristaps  556:        texisplice(p, val, strlen(val), *pos);
1.7       kristaps  557:
                    558:        for (i = 0; i < asz; i++)
                    559:                free(args[i]);
                    560:        free(args);
                    561:        free(val);
                    562: }
                    563:
1.1       kristaps  564: /*
                    565:  * Output a free-form word in the input stream, progressing to the next
                    566:  * command or white-space.
                    567:  * This also will advance the input stream.
                    568:  */
                    569: static void
1.14      kristaps  570: parseword(struct texi *p, size_t *pos, char extra)
1.1       kristaps  571: {
                    572:
1.25      kristaps  573:        /*
                    574:         * Some line control: if we (non-macro, non-literal) already
                    575:         * have more than 72 characters written to the screen, then
                    576:         * output a newline before getting started.
                    577:         */
1.1       kristaps  578:        if (p->seenws && 0 == p->outmacro &&
                    579:                 p->outcol > 72 && 0 == p->literal)
                    580:                texiputchar(p, '\n');
1.25      kristaps  581:
                    582:        /* Usual padding in the case of seen whitespace. */
1.1       kristaps  583:        if (p->seenws && p->outcol && 0 == p->literal)
                    584:                texiputchar(p, ' ');
                    585:
                    586:        p->seenws = 0;
                    587:
1.14      kristaps  588:        while (*pos < BUFSZ(p) && ! ismspace(BUF(p)[*pos])) {
                    589:                switch (BUF(p)[*pos]) {
1.1       kristaps  590:                case ('@'):
                    591:                case ('}'):
                    592:                case ('{'):
                    593:                        return;
                    594:                }
1.14      kristaps  595:                if ('\0' != extra && BUF(p)[*pos] == extra)
1.1       kristaps  596:                        return;
1.14      kristaps  597:                if (*pos < BUFSZ(p) - 1 &&
                    598:                         '`' == BUF(p)[*pos] &&
                    599:                         '`' == BUF(p)[*pos + 1]) {
1.1       kristaps  600:                        texiputchars(p, "\\(lq");
1.14      kristaps  601:                        advance(p, pos);
                    602:                } else if (*pos < BUFSZ(p) - 1 &&
                    603:                         '\'' == BUF(p)[*pos] &&
                    604:                         '\'' == BUF(p)[*pos + 1]) {
1.1       kristaps  605:                        texiputchars(p, "\\(rq");
1.14      kristaps  606:                        advance(p, pos);
1.1       kristaps  607:                } else
1.14      kristaps  608:                        texiputchar(p, BUF(p)[*pos]);
                    609:                advance(p, pos);
1.1       kristaps  610:        }
1.25      kristaps  611:
                    612:        /*
                    613:         * New sentence, new line:if we (non-macro, non-literal) see a
                    614:         * period at the end of the last printed word, then open a
                    615:         * newline.
                    616:         */
                    617:        if (0 == p->literal && 0 == p->outmacro &&
                    618:                *pos < BUFSZ(p) && '.' == BUF(p)[*pos - 1])
                    619:                texiputchar(p, '\n');
1.1       kristaps  620: }
                    621:
                    622: /*
                    623:  * Look up the command at position "pos" in the buffer, returning it (or
                    624:  * TEXICMD__MAX if none found) and setting "end" to be the absolute
                    625:  * index after the command name.
                    626:  */
                    627: enum texicmd
1.19      kristaps  628: texicmd(const struct texi *p, size_t pos, size_t *end, struct teximacro **macro)
1.1       kristaps  629: {
1.4       kristaps  630:        size_t   i, len, toksz;
1.1       kristaps  631:
1.14      kristaps  632:        assert('@' == BUF(p)[pos]);
1.1       kristaps  633:
1.7       kristaps  634:        if (NULL != macro)
                    635:                *macro = NULL;
                    636:
1.14      kristaps  637:        if ((*end = pos) == BUFSZ(p))
1.1       kristaps  638:                return(TEXICMD__MAX);
1.14      kristaps  639:        else if ((*end = ++pos) == BUFSZ(p))
1.1       kristaps  640:                return(TEXICMD__MAX);
                    641:
                    642:        /* Alphabetic commands are special. */
1.23      kristaps  643:        if ( ! isalpha((unsigned int)BUF(p)[pos])) {
1.14      kristaps  644:                if ((*end = pos + 1) == BUFSZ(p))
1.1       kristaps  645:                        return(TEXICMD__MAX);
                    646:                for (i = 0; i < TEXICMD__MAX; i++) {
                    647:                        if (1 != texitoks[i].len)
                    648:                                continue;
1.14      kristaps  649:                        if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], 1))
1.1       kristaps  650:                                return(i);
                    651:                }
1.14      kristaps  652:                texiwarn(p, "bad command: @%c", BUF(p)[pos]);
1.1       kristaps  653:                return(TEXICMD__MAX);
                    654:        }
                    655:
1.4       kristaps  656:        /* Scan to the end of the possible command name. */
1.14      kristaps  657:        for (*end = pos; *end < BUFSZ(p) && ! ismspace(BUF(p)[*end]); (*end)++)
                    658:                if ((*end > pos && ('@' == BUF(p)[*end] ||
                    659:                          '{' == BUF(p)[*end] || '}' == BUF(p)[*end])))
1.1       kristaps  660:                        break;
                    661:
1.4       kristaps  662:        /* Look for the command. */
1.1       kristaps  663:        len = *end - pos;
                    664:        for (i = 0; i < TEXICMD__MAX; i++) {
                    665:                if (len != texitoks[i].len)
                    666:                        continue;
1.14      kristaps  667:                if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], len))
1.1       kristaps  668:                        return(i);
                    669:        }
                    670:
1.4       kristaps  671:        /* Look for it in our indices. */
                    672:        for (i = 0; i < p->indexsz; i++) {
                    673:                toksz = strlen(p->indexs[i]);
                    674:                if (len != 5 + toksz)
                    675:                        continue;
1.14      kristaps  676:                if (strncmp(&BUF(p)[pos], p->indexs[i], toksz))
1.4       kristaps  677:                        continue;
1.14      kristaps  678:                if (0 == strncmp(&BUF(p)[pos + toksz], "index", 5))
1.7       kristaps  679:                        return(TEXICMD_USER_INDEX);
                    680:        }
                    681:
                    682:        for (i = 0; i < p->macrosz; i++) {
                    683:                if (len != strlen(p->macros[i].key))
                    684:                        continue;
1.14      kristaps  685:                if (strncmp(&BUF(p)[pos], p->macros[i].key, len))
1.7       kristaps  686:                        continue;
                    687:                if (NULL != macro)
                    688:                        *macro = &p->macros[i];
                    689:                return(TEXICMD__MAX);
1.4       kristaps  690:        }
                    691:
1.14      kristaps  692:        texiwarn(p, "bad command: @%.*s", (int)len, &BUF(p)[pos]);
1.1       kristaps  693:        return(TEXICMD__MAX);
                    694: }
                    695:
                    696: /*
                    697:  * Parse an argument from a bracketed command, e.g., @url{foo, baz}.
                    698:  * Num should be set to the argument we're currently parsing, although
                    699:  * it suffixes for it to be zero or non-zero.
                    700:  * This will return 1 if there are more arguments, 0 otherwise.
                    701:  * This will stop (returning 0) in the event of EOF or if we're not at a
                    702:  * bracket for the zeroth parse.
                    703:  */
                    704: int
1.14      kristaps  705: parsearg(struct texi *p, size_t *pos, size_t num)
1.1       kristaps  706: {
1.17      kristaps  707:        size_t            end, sv;
1.7       kristaps  708:        enum texicmd      cmd;
                    709:        struct teximacro *macro;
1.1       kristaps  710:
1.14      kristaps  711:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    712:                advance(p, pos);
                    713:        if (*pos == BUFSZ(p) || (0 == num && '{' != BUF(p)[*pos]))
1.1       kristaps  714:                return(0);
                    715:        if (0 == num)
1.14      kristaps  716:                advance(p, pos);
1.1       kristaps  717:
1.14      kristaps  718:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    719:                switch (BUF(p)[*pos]) {
1.1       kristaps  720:                case (','):
1.14      kristaps  721:                        advance(p, pos);
1.1       kristaps  722:                        return(1);
                    723:                case ('}'):
1.14      kristaps  724:                        advance(p, pos);
1.1       kristaps  725:                        return(0);
                    726:                case ('{'):
                    727:                        if (0 == p->ign)
                    728:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  729:                        advance(p, pos);
1.1       kristaps  730:                        continue;
                    731:                case ('@'):
                    732:                        break;
                    733:                default:
1.14      kristaps  734:                        parseword(p, pos, ',');
1.1       kristaps  735:                        continue;
                    736:                }
                    737:
1.17      kristaps  738:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  739:                cmd = texicmd(p, *pos, &end, &macro);
                    740:                advanceto(p, pos, end);
1.7       kristaps  741:                if (NULL != macro)
1.17      kristaps  742:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  743:                if (TEXICMD__MAX == cmd)
                    744:                        continue;
                    745:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  746:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  747:        }
                    748:        return(0);
                    749: }
                    750:
                    751: /*
                    752:  * Parse until the end of a bracketed statement, e.g., @foo{bar baz}.
                    753:  * This will stop in the event of EOF or if we're not at a bracket.
                    754:  */
                    755: void
1.18      kristaps  756: parsebracket(struct texi *p, size_t *pos, int dostack)
1.1       kristaps  757: {
1.18      kristaps  758:        size_t            end, sv, stack;
1.7       kristaps  759:        enum texicmd      cmd;
                    760:        struct teximacro *macro;
1.1       kristaps  761:
1.14      kristaps  762:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    763:                advance(p, pos);
1.1       kristaps  764:
1.14      kristaps  765:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.1       kristaps  766:                return;
1.14      kristaps  767:        advance(p, pos);
1.1       kristaps  768:
1.18      kristaps  769:        stack = 0;
1.14      kristaps  770:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    771:                switch (BUF(p)[*pos]) {
1.1       kristaps  772:                case ('}'):
1.18      kristaps  773:                        if (stack > 0) {
                    774:                                stack--;
                    775:                                advance(p, pos);
                    776:                                texiputchar(p, '}');
                    777:                                continue;
                    778:                        }
1.14      kristaps  779:                        advance(p, pos);
1.1       kristaps  780:                        return;
                    781:                case ('{'):
1.18      kristaps  782:                        if (dostack) {
                    783:                                stack++;
                    784:                                advance(p, pos);
                    785:                                texiputchar(p, '{');
                    786:                                continue;
                    787:                        }
1.1       kristaps  788:                        if (0 == p->ign)
                    789:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  790:                        advance(p, pos);
1.1       kristaps  791:                        continue;
                    792:                case ('@'):
                    793:                        break;
                    794:                default:
1.14      kristaps  795:                        parseword(p, pos, '\0');
1.1       kristaps  796:                        continue;
                    797:                }
                    798:
1.17      kristaps  799:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  800:                cmd = texicmd(p, *pos, &end, &macro);
                    801:                advanceto(p, pos, end);
1.7       kristaps  802:                if (NULL != macro)
1.17      kristaps  803:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  804:                if (TEXICMD__MAX == cmd)
                    805:                        continue;
                    806:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  807:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  808:        }
                    809: }
                    810:
                    811: /*
                    812:  * This should be invoked when we're on a macro line and want to process
                    813:  * to the end of the current input line, doing all of our macros along
                    814:  * the way.
                    815:  */
                    816: void
1.14      kristaps  817: parseeoln(struct texi *p, size_t *pos)
1.1       kristaps  818: {
1.17      kristaps  819:        size_t            end, sv;
1.7       kristaps  820:        enum texicmd      cmd;
                    821:        struct teximacro *macro;
1.1       kristaps  822:
1.14      kristaps  823:        while (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos]) {
                    824:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  825:                        p->seenws = 1;
                    826:                        if (p->literal)
1.14      kristaps  827:                                texiputchar(p, BUF(p)[*pos]);
                    828:                        advance(p, pos);
1.1       kristaps  829:                }
1.14      kristaps  830:                switch (BUF(p)[*pos]) {
1.1       kristaps  831:                case ('}'):
                    832:                        if (0 == p->ign)
                    833:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps  834:                        advance(p, pos);
1.1       kristaps  835:                        continue;
                    836:                case ('{'):
                    837:                        if (0 == p->ign)
                    838:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  839:                        advance(p, pos);
1.1       kristaps  840:                        continue;
                    841:                case ('@'):
                    842:                        break;
                    843:                default:
1.14      kristaps  844:                        parseword(p, pos, '\0');
1.1       kristaps  845:                        continue;
                    846:                }
                    847:
1.17      kristaps  848:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  849:                cmd = texicmd(p, *pos, &end, &macro);
                    850:                advanceto(p, pos, end);
1.7       kristaps  851:                if (NULL != macro)
1.17      kristaps  852:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  853:                if (TEXICMD__MAX == cmd)
                    854:                        continue;
                    855:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  856:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  857:        }
1.14      kristaps  858:
                    859:        if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                    860:                advance(p, pos);
1.19      kristaps  861: }
                    862:
                    863: /*
                    864:  * Peek to see if there's a command after subsequent whitespace.
                    865:  * If so, return the macro identifier.
                    866:  * This DOES NOT work with user-defined macros.
                    867:  */
                    868: enum texicmd
                    869: peekcmd(const struct texi *p, size_t pos)
                    870: {
                    871:        size_t          end;
                    872:
                    873:        while (pos < BUFSZ(p) && ismspace(BUF(p)[pos]))
                    874:                pos++;
                    875:        if (pos == BUFSZ(p) || '@' != BUF(p)[pos])
                    876:                return(TEXICMD__MAX);
                    877:        return(texicmd(p, pos, &end, NULL));
1.1       kristaps  878: }
                    879:
                    880: /*
                    881:  * Parse a single word or command.
                    882:  * This will return immediately at the EOF.
                    883:  */
1.14      kristaps  884: static void
                    885: parsesingle(struct texi *p, size_t *pos)
1.1       kristaps  886: {
1.17      kristaps  887:        size_t            end, sv;
1.7       kristaps  888:        enum texicmd      cmd;
                    889:        struct teximacro *macro;
1.1       kristaps  890:
1.14      kristaps  891:        if ((*pos = advancenext(p, pos)) >= BUFSZ(p))
1.1       kristaps  892:                return;
                    893:
1.14      kristaps  894:        switch (BUF(p)[*pos]) {
1.1       kristaps  895:        case ('}'):
                    896:                if (0 == p->ign)
                    897:                        texiwarn(p, "unexpected \"}\"");
1.14      kristaps  898:                advance(p, pos);
1.1       kristaps  899:                return;
                    900:        case ('{'):
                    901:                if (0 == p->ign)
                    902:                        texiwarn(p, "unexpected \"{\"");
1.14      kristaps  903:                advance(p, pos);
1.1       kristaps  904:                return;
                    905:        case ('@'):
                    906:                break;
                    907:        default:
1.14      kristaps  908:                parseword(p, pos, '\0');
1.1       kristaps  909:                return;
                    910:        }
                    911:
1.17      kristaps  912:        sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  913:        cmd = texicmd(p, *pos, &end, &macro);
                    914:        advanceto(p, pos, end);
1.7       kristaps  915:        if (NULL != macro)
1.17      kristaps  916:                texiexecmacro(p, macro, sv, pos);
1.1       kristaps  917:        if (TEXICMD__MAX == cmd)
                    918:                return;
                    919:        if (NULL != texitoks[cmd].fp)
1.14      kristaps  920:                (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  921: }
                    922:
                    923: /*
                    924:  * This is used in the @deffn type of command.
                    925:  * These have an arbitrary number of line arguments; however, these
                    926:  * arguments may or may not be surrounded by brackets.
                    927:  * In this function, we parse each one as either a bracketed or
                    928:  * non-bracketed argument, returning 0 when we've reached the end of
                    929:  * line or 1 otherwise.
                    930:  */
                    931: int
1.14      kristaps  932: parselinearg(struct texi *p, size_t *pos)
1.1       kristaps  933: {
                    934:
1.14      kristaps  935:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  936:                p->seenws = 1;
1.14      kristaps  937:                advance(p, pos);
1.1       kristaps  938:        }
                    939:
1.14      kristaps  940:        if (*pos < BUFSZ(p) && '{' == BUF(p)[*pos])
1.18      kristaps  941:                parsebracket(p, pos, 0);
1.14      kristaps  942:        else if (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos])
                    943:                parsesingle(p, pos);
1.1       kristaps  944:        else
                    945:                return(0);
                    946:
                    947:        return(1);
                    948: }
                    949:
                    950: /*
                    951:  * Parse til the end of the buffer.
                    952:  */
1.14      kristaps  953: static void
                    954: parseeof(struct texi *p)
1.1       kristaps  955: {
                    956:        size_t   pos;
                    957:
1.14      kristaps  958:        for (pos = 0; pos < BUFSZ(p); )
                    959:                parsesingle(p, &pos);
1.1       kristaps  960: }
                    961:
1.8       kristaps  962: void
1.21      kristaps  963: texisplice(struct texi *p, const char *buf, size_t sz, size_t pos)
1.8       kristaps  964: {
1.14      kristaps  965:        char            *cp;
                    966:        struct texifile *f;
1.8       kristaps  967:
1.14      kristaps  968:        assert(p->filepos > 0);
                    969:        f = &p->files[p->filepos - 1];
1.8       kristaps  970:
1.14      kristaps  971:        if (f->mapsz + sz > f->mapmaxsz) {
                    972:                f->mapmaxsz = f->mapsz + sz + 1024;
                    973:                cp = realloc(f->map, f->mapmaxsz);
                    974:                if (NULL == cp)
                    975:                        texiabort(p, NULL);
                    976:                f->map = cp;
                    977:        }
1.8       kristaps  978:
1.15      kristaps  979:        f->insplice += sz;
1.21      kristaps  980:        memmove(f->map + pos + sz, f->map + pos, f->mapsz - pos);
                    981:        memcpy(f->map + pos, buf, sz);
1.14      kristaps  982:        f->mapsz += sz;
1.8       kristaps  983: }
                    984:
                    985: /*
1.1       kristaps  986:  * Parse a block sequence until we have the "@end endtoken" command
                    987:  * invocation.
                    988:  * This will return immediately at EOF.
                    989:  */
                    990: void
1.14      kristaps  991: parseto(struct texi *p, size_t *pos, const char *endtoken)
1.1       kristaps  992: {
1.17      kristaps  993:        size_t            end, sv;
1.7       kristaps  994:        enum texicmd      cmd;
                    995:        size_t            endtoksz;
                    996:        struct teximacro *macro;
1.1       kristaps  997:
                    998:        endtoksz = strlen(endtoken);
                    999:        assert(endtoksz > 0);
                   1000:
1.14      kristaps 1001:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                   1002:                switch (BUF(p)[*pos]) {
1.1       kristaps 1003:                case ('}'):
                   1004:                        if (0 == p->ign)
                   1005:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps 1006:                        advance(p, pos);
1.1       kristaps 1007:                        continue;
                   1008:                case ('{'):
                   1009:                        if (0 == p->ign)
                   1010:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps 1011:                        advance(p, pos);
1.1       kristaps 1012:                        continue;
                   1013:                case ('@'):
                   1014:                        break;
                   1015:                default:
1.14      kristaps 1016:                        parseword(p, pos, '\0');
1.1       kristaps 1017:                        continue;
                   1018:                }
                   1019:
1.17      kristaps 1020:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps 1021:                cmd = texicmd(p, *pos, &end, &macro);
                   1022:                advanceto(p, pos, end);
1.1       kristaps 1023:                if (TEXICMD_END == cmd) {
1.14      kristaps 1024:                        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1025:                                advance(p, pos);
1.1       kristaps 1026:                        /*
                   1027:                         * FIXME: check the full word, not just its
                   1028:                         * initial substring!
                   1029:                         */
1.14      kristaps 1030:                        if (BUFSZ(p) - *pos >= endtoksz && 0 == strncmp
                   1031:                                 (&BUF(p)[*pos], endtoken, endtoksz)) {
                   1032:                                advanceeoln(p, pos, 0);
1.1       kristaps 1033:                                break;
                   1034:                        }
                   1035:                        if (0 == p->ign)
                   1036:                                texiwarn(p, "unexpected \"end\"");
1.14      kristaps 1037:                        advanceeoln(p, pos, 0);
1.1       kristaps 1038:                        continue;
1.7       kristaps 1039:                }
                   1040:                if (NULL != macro)
1.17      kristaps 1041:                        texiexecmacro(p, macro, sv, pos);
1.7       kristaps 1042:                if (TEXICMD__MAX == cmd)
                   1043:                        continue;
                   1044:                if (NULL != texitoks[cmd].fp)
1.14      kristaps 1045:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps 1046:        }
                   1047: }
                   1048:
                   1049: /*
1.12      kristaps 1050:  * Like parsefile() but used for reading from stdandard input.
                   1051:  * This can only be called for the first file!
                   1052:  */
                   1053: void
                   1054: parsestdin(struct texi *p)
                   1055: {
                   1056:        struct texifile *f;
                   1057:        ssize_t          ssz;
                   1058:
                   1059:        assert(0 == p->filepos);
                   1060:        f = &p->files[p->filepos];
                   1061:        memset(f, 0, sizeof(struct texifile));
                   1062:
                   1063:        f->type = TEXISRC_STDIN;
                   1064:        f->name = "<stdin>";
                   1065:
1.14      kristaps 1066:        for (f->mapsz = 0; ; f->mapsz += (size_t)ssz) {
                   1067:                if (f->mapsz == f->mapmaxsz) {
                   1068:                        if (f->mapmaxsz == (1U << 31))
1.12      kristaps 1069:                                texierr(p, "stdin buffer too long");
1.14      kristaps 1070:                        f->mapmaxsz = f->mapmaxsz > 65536 / 2 ?
                   1071:                                2 * f->mapmaxsz : 65536;
                   1072:                        f->map = realloc(f->map, f->mapmaxsz);
1.12      kristaps 1073:                        if (NULL == f->map)
                   1074:                                texiabort(p, NULL);
                   1075:                }
1.14      kristaps 1076:                ssz = read(STDIN_FILENO, f->map +
                   1077:                        (int)f->mapsz, f->mapmaxsz - f->mapsz);
1.12      kristaps 1078:                if (0 == ssz)
                   1079:                        break;
                   1080:                else if (-1 == ssz)
                   1081:                        texiabort(p, NULL);
                   1082:        }
                   1083:
                   1084:        p->filepos++;
1.14      kristaps 1085:        parseeof(p);
1.12      kristaps 1086:        texifilepop(p);
                   1087: }
                   1088:
                   1089: /*
1.1       kristaps 1090:  * Memory-map the file "fname" and begin parsing it unless "parse" is
                   1091:  * zero, in which case we just dump the file to stdout (making sure it
                   1092:  * doesn't trip up mdoc(7) along the way).
                   1093:  * This can be called in a nested context.
                   1094:  */
                   1095: void
                   1096: parsefile(struct texi *p, const char *fname, int parse)
                   1097: {
                   1098:        struct texifile *f;
                   1099:        int              fd;
                   1100:        struct stat      st;
                   1101:        size_t           i;
1.14      kristaps 1102:        char            *map;
1.1       kristaps 1103:
1.5       kristaps 1104:        if (64 == p->filepos)
1.6       kristaps 1105:                texierr(p, "too many open files");
1.1       kristaps 1106:        f = &p->files[p->filepos];
                   1107:        memset(f, 0, sizeof(struct texifile));
                   1108:
1.12      kristaps 1109:        f->type = TEXISRC_FILE;
1.1       kristaps 1110:        f->name = fname;
                   1111:        if (-1 == (fd = open(fname, O_RDONLY, 0))) {
                   1112:                texiabort(p, fname);
                   1113:        } else if (-1 == fstat(fd, &st)) {
                   1114:                close(fd);
                   1115:                texiabort(p, fname);
                   1116:        }
                   1117:
1.14      kristaps 1118:        f->mapsz = f->mapmaxsz = st.st_size;
                   1119:        map = mmap(NULL, f->mapsz,
1.1       kristaps 1120:                PROT_READ, MAP_SHARED, fd, 0);
                   1121:        close(fd);
                   1122:
1.14      kristaps 1123:        if (MAP_FAILED == map)
1.1       kristaps 1124:                texiabort(p, fname);
                   1125:
                   1126:        if ( ! parse) {
1.13      kristaps 1127:                for (i = 0; i < f->mapsz; i++)
1.14      kristaps 1128:                        texiputchar(p, map[i]);
1.13      kristaps 1129:                if (p->outcol)
                   1130:                        texiputchar(p, '\n');
1.14      kristaps 1131:                munmap(map, f->mapsz);
                   1132:                return;
                   1133:        }
                   1134:
                   1135:        p->filepos++;
                   1136:        f->map = malloc(f->mapsz);
                   1137:        memcpy(f->map, map, f->mapsz);
                   1138:        munmap(map, f->mapsz);
                   1139:        parseeof(p);
1.1       kristaps 1140:        texifilepop(p);
                   1141: }
                   1142:
1.2       kristaps 1143: /*
                   1144:  * Look up the value to a stored pair's value starting in "buf" from
                   1145:  * start to end.
                   1146:  * Return the pointer to the value memory, which can be NULL if the
                   1147:  * pointer key does not exist.
                   1148:  * The pointer can point to NULL if the value has been unset.
                   1149:  */
                   1150: static char **
1.14      kristaps 1151: valuequery(const struct texi *p, size_t start, size_t end)
1.2       kristaps 1152: {
                   1153:        size_t   i, sz, len;
                   1154:
                   1155:        assert(end >= start);
                   1156:        /* Ignore zero-length. */
                   1157:        if (0 == (len = (end - start)))
                   1158:                return(NULL);
                   1159:        for (i = 0; i < p->valsz; i++) {
                   1160:                sz = strlen(p->vals[i].key);
                   1161:                if (sz != len)
                   1162:                        continue;
1.14      kristaps 1163:                if (0 == strncmp(p->vals[i].key, &BUF(p)[start], len))
1.2       kristaps 1164:                        return(&p->vals[i].value);
                   1165:        }
                   1166:        return(NULL);
                   1167: }
                   1168:
                   1169: /*
                   1170:  * Parse a key until the end of line, e.g., @clear foo\n, and return the
                   1171:  * pointer to its value via valuequery().
                   1172:  */
                   1173: static char **
1.14      kristaps 1174: valuelquery(struct texi *p, size_t *pos)
1.2       kristaps 1175: {
                   1176:        size_t    start, end;
                   1177:        char    **ret;
                   1178:
1.14      kristaps 1179:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1180:                advance(p, pos);
                   1181:        if (*pos == BUFSZ(p))
1.2       kristaps 1182:                return(NULL);
1.14      kristaps 1183:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1184:                if ('\n' == BUF(p)[end])
1.2       kristaps 1185:                        break;
1.14      kristaps 1186:        advanceto(p, pos, end);
                   1187:        if (*pos < BUFSZ(p)) {
                   1188:                assert('\n' == BUF(p)[*pos]);
                   1189:                advance(p, pos);
1.2       kristaps 1190:        }
1.14      kristaps 1191:        if (NULL == (ret = valuequery(p, start, end)))
1.2       kristaps 1192:                return(NULL);
                   1193:        return(ret);
                   1194: }
                   1195:
                   1196: void
1.14      kristaps 1197: valuelclear(struct texi *p, size_t *pos)
1.2       kristaps 1198: {
                   1199:        char    **ret;
                   1200:
1.14      kristaps 1201:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1202:                return;
                   1203:        free(*ret);
                   1204:        *ret = NULL;
                   1205: }
                   1206:
                   1207: const char *
1.14      kristaps 1208: valuellookup(struct texi *p, size_t *pos)
1.2       kristaps 1209: {
                   1210:        char    **ret;
                   1211:
1.14      kristaps 1212:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1213:                return(NULL);
                   1214:        return(*ret);
                   1215: }
                   1216:
                   1217: /*
                   1218:  * Parse a key from a bracketed string, e.g., @value{foo}, and return
                   1219:  * the pointer to its value.
                   1220:  * If the returned pointer is NULL, either there was no string within
                   1221:  * the brackets (or no brackets), or the value was not found, or the
                   1222:  * value had previously been unset.
                   1223:  */
                   1224: const char *
1.14      kristaps 1225: valueblookup(struct texi *p, size_t *pos)
1.2       kristaps 1226: {
                   1227:        size_t    start, end;
                   1228:        char    **ret;
                   1229:
1.14      kristaps 1230:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1231:                advance(p, pos);
                   1232:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.2       kristaps 1233:                return(NULL);
1.14      kristaps 1234:        advance(p, pos);
                   1235:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1236:                if ('}' == BUF(p)[end])
1.2       kristaps 1237:                        break;
1.14      kristaps 1238:        advanceto(p, pos, end);
                   1239:        if (*pos < BUFSZ(p)) {
                   1240:                assert('}' == BUF(p)[*pos]);
                   1241:                advance(p, pos);
1.2       kristaps 1242:        }
1.14      kristaps 1243:        if (NULL == (ret = valuequery(p, start, end)))
1.2       kristaps 1244:                return(NULL);
                   1245:        return(*ret);
                   1246: }
                   1247:
                   1248: void
                   1249: valueadd(struct texi *p, char *key, char *val)
                   1250: {
                   1251:        size_t   i;
                   1252:
                   1253:        assert(NULL != key);
                   1254:        assert(NULL != val);
                   1255:
                   1256:        for (i = 0; i < p->valsz; i++)
                   1257:                if (0 == strcmp(p->vals[i].key, key))
                   1258:                        break;
                   1259:
                   1260:        if (i < p->valsz) {
                   1261:                free(key);
                   1262:                free(p->vals[i].value);
                   1263:                p->vals[i].value = val;
                   1264:        } else {
1.4       kristaps 1265:                /* FIXME: reallocarray() */
1.2       kristaps 1266:                p->vals = realloc(p->vals,
                   1267:                        (p->valsz + 1) *
                   1268:                         sizeof(struct texivalue));
1.4       kristaps 1269:                if (NULL == p->vals)
                   1270:                        texiabort(p, NULL);
1.2       kristaps 1271:                p->vals[p->valsz].key = key;
                   1272:                p->vals[p->valsz].value = val;
                   1273:                p->valsz++;
                   1274:        }
1.7       kristaps 1275: }
                   1276:
                   1277: /*
                   1278:  * Take the arguments to a macro, e.g., @foo{bar, baz, xyzzy} (or the
                   1279:  * declaration form, @macro foo {arg1, ...}) and textually convert it to
                   1280:  * an array of arguments of size "argsz".
                   1281:  * These need to be freed individually and as a whole.
                   1282:  * NOTE: this will puke on @, or @} macros, which can trick it into
                   1283:  * stopping argument parsing earlier.
                   1284:  * Ergo, textual: this doesn't interpret the arguments in any way.
                   1285:  */
                   1286: char **
1.14      kristaps 1287: argparse(struct texi *p, size_t *pos, size_t *argsz, size_t hint)
1.7       kristaps 1288: {
                   1289:        char    **args;
                   1290:        size_t    start, end, stack;
                   1291:
1.14      kristaps 1292:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1293:                advance(p, pos);
1.7       kristaps 1294:
                   1295:        args = NULL;
                   1296:        *argsz = 0;
                   1297:
1.17      kristaps 1298:        if (*pos == BUFSZ(p))
                   1299:                return(args);
                   1300:
1.14      kristaps 1301:        if ('{' != BUF(p)[*pos] && hint) {
1.10      kristaps 1302:                /*
                   1303:                 * Special case: if we encounter an unbracketed argument
                   1304:                 * and we're being invoked with non-zero arguments
                   1305:                 * (versus being set, i.e., hint>0), then parse until
                   1306:                 * the end of line.
                   1307:                 */
                   1308:                *argsz = 1;
                   1309:                args = calloc(1, sizeof(char *));
                   1310:                if (NULL == args)
                   1311:                        texiabort(p, NULL);
                   1312:                start = *pos;
1.14      kristaps 1313:                while (*pos < BUFSZ(p)) {
                   1314:                        if ('\n' == BUF(p)[*pos])
1.10      kristaps 1315:                                break;
1.14      kristaps 1316:                        advance(p, pos);
1.10      kristaps 1317:                }
                   1318:                args[0] = malloc(*pos - start + 1);
1.14      kristaps 1319:                memcpy(args[0], &BUF(p)[start], *pos - start);
1.10      kristaps 1320:                args[0][*pos - start] = '\0';
1.14      kristaps 1321:                if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                   1322:                        advance(p, pos);
1.10      kristaps 1323:                return(args);
1.14      kristaps 1324:        } else if ('{' != BUF(p)[*pos])
1.7       kristaps 1325:                return(args);
1.17      kristaps 1326:
                   1327:        assert('{' == BUF(p)[*pos]);
1.7       kristaps 1328:
                   1329:        /* Parse til the closing '}', putting into the array. */
1.14      kristaps 1330:        advance(p, pos);
                   1331:        while (*pos < BUFSZ(p)) {
                   1332:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1333:                        advance(p, pos);
1.7       kristaps 1334:                start = *pos;
                   1335:                stack = 0;
1.14      kristaps 1336:                while (*pos < BUFSZ(p)) {
1.7       kristaps 1337:                        /*
                   1338:                         * According to the manual, commas within
                   1339:                         * embedded commands are escaped.
                   1340:                         * We keep track of embedded-ness in the "stack"
                   1341:                         * state anyway, so this is free.
                   1342:                         */
1.14      kristaps 1343:                        if (',' == BUF(p)[*pos] && 0 == stack && 1 != hint)
1.7       kristaps 1344:                                break;
1.14      kristaps 1345:                        else if (0 == stack && '}' == BUF(p)[*pos])
1.7       kristaps 1346:                                break;
1.14      kristaps 1347:                        else if (0 != stack && '}' == BUF(p)[*pos])
1.7       kristaps 1348:                                stack--;
1.14      kristaps 1349:                        else if ('{' == BUF(p)[*pos])
1.7       kristaps 1350:                                stack++;
1.14      kristaps 1351:                        advance(p, pos);
1.7       kristaps 1352:                }
                   1353:                if (stack)
                   1354:                        texiwarn(p, "unterminated macro "
                   1355:                                "in macro arguments");
1.14      kristaps 1356:                if ((end = *pos) == BUFSZ(p))
1.7       kristaps 1357:                        break;
                   1358:                /* Test for zero-length '{  }'. */
1.14      kristaps 1359:                if (start == end && '}' == BUF(p)[*pos] && 0 == *argsz)
1.7       kristaps 1360:                        break;
                   1361:                /* FIXME: use reallocarray. */
                   1362:                args = realloc
                   1363:                        (args, sizeof(char *) *
                   1364:                         (*argsz + 1));
                   1365:                if (NULL == args)
                   1366:                        texiabort(p, NULL);
                   1367:                args[*argsz] = malloc(end - start + 1);
                   1368:                if (NULL == args[*argsz])
                   1369:                        texiabort(p, NULL);
                   1370:                memcpy(args[*argsz],
1.14      kristaps 1371:                        &BUF(p)[start], end - start);
1.7       kristaps 1372:                args[*argsz][end - start] = '\0';
                   1373:                (*argsz)++;
1.14      kristaps 1374:                if ('}' == BUF(p)[*pos])
1.7       kristaps 1375:                        break;
1.14      kristaps 1376:                advance(p, pos);
1.7       kristaps 1377:        }
                   1378:
1.14      kristaps 1379:        if (*pos == BUFSZ(p))
1.7       kristaps 1380:                texierr(p, "unterminated arguments");
1.14      kristaps 1381:        assert('}' == BUF(p)[*pos]);
                   1382:        advance(p, pos);
1.7       kristaps 1383:        return(args);
1.2       kristaps 1384: }
1.20      kristaps 1385:
                   1386: /*
                   1387:  * If we're printing chapters, then do some naviation here and then
                   1388:  * close our outfile.
                   1389:  * I want to call this the SEE ALSO section, but that's not really what
                   1390:  * it is: we'll refer to the "initial" (top) node and the next and
                   1391:  * previous chapters.
                   1392:  */
                   1393: void
                   1394: teximdocclose(struct texi *p, int last)
                   1395: {
                   1396:        char     buf[PATH_MAX];
                   1397:
                   1398:        if (NULL == p->chapters || 0 == p->chapnum)
                   1399:                return;
                   1400:
                   1401:        teximacro(p, "Sh INFO NAVIGATION");
                   1402:
                   1403:        /* Print a reference to the "top" node. */
                   1404:        if (p->chapnum > 1) {
1.22      kristaps 1405:                texiputchars(p, "Top node,");
1.20      kristaps 1406:                snprintf(buf, sizeof(buf), "node1 7");
                   1407:                teximacroopen(p, "Xr ");
                   1408:                texiputchars(p, buf);
1.22      kristaps 1409:                texiputchars(p, " ;");
1.20      kristaps 1410:                teximacroclose(p);
                   1411:        }
                   1412:
                   1413:        /* Print a reference to the previous node. */
                   1414:        if (p->chapnum > 2) {
1.22      kristaps 1415:                texiputchars(p, "previous node,");
1.20      kristaps 1416:                snprintf(buf, sizeof(buf),
                   1417:                        "node%zu 7", p->chapnum - 1);
                   1418:                teximacroopen(p, "Xr ");
                   1419:                texiputchars(p, buf);
                   1420:                if ( ! last)
1.22      kristaps 1421:                        texiputchars(p, " ;");
1.20      kristaps 1422:                teximacroclose(p);
                   1423:        }
                   1424:
                   1425:        /* Print a reference to the next node. */
                   1426:        if ( ! last) {
1.22      kristaps 1427:                if (1 == p->chapnum)
                   1428:                        texiputchars(p, "Next node,");
                   1429:                else
                   1430:                        texiputchars(p, "next node,");
1.20      kristaps 1431:                snprintf(buf, sizeof(buf),
                   1432:                        "node%zu 7", p->chapnum + 1);
                   1433:                teximacroopen(p, "Xr ");
                   1434:                texiputchars(p, buf);
                   1435:                teximacroclose(p);
                   1436:        }
                   1437:
                   1438:        fclose(p->outfile);
                   1439: }
                   1440:
                   1441: /*
                   1442:  * Open a mdoc(7) context.
                   1443:  * If we're printing chapters, then open the outfile here, too.
                   1444:  * Otherwise just print the mdoc(7) prologue.
                   1445:  */
                   1446: void
1.21      kristaps 1447: teximdocopen(struct texi *p, size_t *pos)
1.20      kristaps 1448: {
                   1449:        const char      *cp;
                   1450:        time_t           t;
                   1451:        char             date[32];
                   1452:        char             fname[PATH_MAX];
                   1453:
                   1454:        if (NULL != p->chapters) {
                   1455:                snprintf(fname, sizeof(fname), "%s/node%zu.7",
                   1456:                        p->chapters, ++p->chapnum);
                   1457:                p->outfile = fopen(fname, "w");
                   1458:                if (NULL == p->outfile)
                   1459:                        texiabort(p, fname);
                   1460:        }
                   1461:
                   1462:        /*
                   1463:         * Here we print our standard mdoc(7) prologue.
                   1464:         * We use the title set with @settitle for the `Nd' description
                   1465:         * and the source document filename (the first one as invoked on
                   1466:         * the command line) for the title.
                   1467:         * The date is set to the current date.
                   1468:         */
                   1469:        t = time(NULL);
                   1470:        strftime(date, sizeof(date), "%F", localtime(&t));
                   1471:
                   1472:        teximacroopen(p, "Dd");
                   1473:        texiputchars(p, date);
                   1474:        teximacroclose(p);
                   1475:        teximacroopen(p, "Dt");
                   1476:        for (cp = p->title; '\0' != *cp; cp++)
                   1477:                texiputchar(p, toupper((unsigned int)*cp));
                   1478:        texiputchars(p, " 7");
                   1479:        teximacroclose(p);
                   1480:        teximacro(p, "Os");
                   1481:        teximacro(p, "Sh NAME");
                   1482:        teximacroopen(p, "Nm");
                   1483:        for (cp = p->title; '\0' != *cp; cp++)
                   1484:                texiputchar(p, *cp);
                   1485:        teximacroclose(p);
                   1486:        teximacroopen(p, "Nd");
1.21      kristaps 1487:        /*
                   1488:         * The subtitle `Nd' can consist of arbitrary macros, so paste
                   1489:         * it and parse to the end of the line.
                   1490:         */
                   1491:        if (NULL != p->subtitle) {
                   1492:                texisplice(p, p->subtitle, strlen(p->subtitle), *pos);
                   1493:                parseeoln(p, pos);
                   1494:        } else
1.20      kristaps 1495:                texiputchars(p, "Unknown description");
                   1496:        teximacroclose(p);
                   1497:        p->seenvs = 1;
                   1498: }
                   1499:

CVSweb