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

Annotation of docbook2mdoc/parse.c, Revision 1.15

1.15    ! schwarze    1: /* $Id: parse.c,v 1.14 2019/04/05 14:37:36 schwarze Exp $ */
1.1       schwarze    2: /*
                      3:  * Copyright (c) 2014 Kristaps Dzonsons <kristaps@bsd.lv>
                      4:  * Copyright (c) 2019 Ingo Schwarze <schwarze@openbsd.org>
                      5:  *
                      6:  * Permission to use, copy, modify, and distribute this software for any
                      7:  * purpose with or without fee is hereby granted, provided that the above
                      8:  * copyright notice and this permission notice appear in all copies.
                      9:  *
                     10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
                     11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
                     13:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     15:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     16:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17:  */
                     18: #include <assert.h>
                     19: #include <ctype.h>
1.6       schwarze   20: #include <stdarg.h>
1.1       schwarze   21: #include <stdio.h>
1.5       schwarze   22: #include <stdlib.h>
1.1       schwarze   23: #include <string.h>
                     24: #include <unistd.h>
                     25:
                     26: #include "node.h"
                     27: #include "parse.h"
                     28:
                     29: /*
                     30:  * The implementation of the DocBook parser.
                     31:  */
                     32:
1.14      schwarze   33: enum   pstate {
                     34:        PARSE_ELEM,
                     35:        PARSE_TAG,
                     36:        PARSE_ARG,
                     37:        PARSE_SQ,
                     38:        PARSE_DQ
                     39: };
                     40:
1.1       schwarze   41: /*
                     42:  * Global parse state.
                     43:  * Keep this as simple and small as possible.
                     44:  */
                     45: struct parse {
                     46:        const char      *fname;  /* Name of the input file. */
                     47:        struct ptree    *tree;   /* Complete parse result. */
                     48:        struct pnode    *cur;    /* Current node in the tree. */
1.5       schwarze   49:        enum nodeid      ncur;   /* Type of the current node. */
                     50:        int              line;   /* Line number in the input file. */
                     51:        int              col;    /* Column number in the input file. */
                     52:        int              nline;  /* Line number of next token. */
                     53:        int              ncol;   /* Column number of next token. */
1.4       schwarze   54:        int              del;    /* Levels of nested nodes being deleted. */
1.5       schwarze   55:        int              attr;   /* The most recent attribute is valid. */
1.1       schwarze   56:        int              warn;
                     57: };
                     58:
                     59: struct element {
                     60:        const char      *name;   /* DocBook element name. */
                     61:        enum nodeid      node;   /* Node type to generate. */
                     62: };
                     63:
                     64: static const struct element elements[] = {
1.3       schwarze   65:        { "acronym",            NODE_IGNORE },
1.1       schwarze   66:        { "affiliation",        NODE_AFFILIATION },
1.4       schwarze   67:        { "anchor",             NODE_DELETE },
1.1       schwarze   68:        { "application",        NODE_APPLICATION },
                     69:        { "arg",                NODE_ARG },
                     70:        { "author",             NODE_AUTHOR },
                     71:        { "authorgroup",        NODE_AUTHORGROUP },
                     72:        { "blockquote",         NODE_BLOCKQUOTE },
                     73:        { "book",               NODE_BOOK },
                     74:        { "bookinfo",           NODE_BOOKINFO },
                     75:        { "caution",            NODE_CAUTION },
                     76:        { "chapter",            NODE_SECTION },
                     77:        { "citerefentry",       NODE_CITEREFENTRY },
                     78:        { "citetitle",          NODE_CITETITLE },
                     79:        { "cmdsynopsis",        NODE_CMDSYNOPSIS },
1.13      schwarze   80:        { "code",               NODE_LITERAL },
1.1       schwarze   81:        { "colspec",            NODE_COLSPEC },
                     82:        { "command",            NODE_COMMAND },
                     83:        { "constant",           NODE_CONSTANT },
1.7       schwarze   84:        { "contrib",            NODE_CONTRIB },
1.1       schwarze   85:        { "copyright",          NODE_COPYRIGHT },
                     86:        { "date",               NODE_DATE },
                     87:        { "editor",             NODE_EDITOR },
                     88:        { "email",              NODE_EMAIL },
                     89:        { "emphasis",           NODE_EMPHASIS },
                     90:        { "entry",              NODE_ENTRY },
                     91:        { "envar",              NODE_ENVAR },
1.13      schwarze   92:        { "errorname",          NODE_ERRORNAME },
1.1       schwarze   93:        { "fieldsynopsis",      NODE_FIELDSYNOPSIS },
                     94:        { "filename",           NODE_FILENAME },
1.7       schwarze   95:        { "firstname",          NODE_PERSONNAME },
1.1       schwarze   96:        { "firstterm",          NODE_FIRSTTERM },
                     97:        { "footnote",           NODE_FOOTNOTE },
                     98:        { "funcdef",            NODE_FUNCDEF },
                     99:        { "funcprototype",      NODE_FUNCPROTOTYPE },
                    100:        { "funcsynopsis",       NODE_FUNCSYNOPSIS },
                    101:        { "funcsynopsisinfo",   NODE_FUNCSYNOPSISINFO },
                    102:        { "function",           NODE_FUNCTION },
                    103:        { "glossterm",          NODE_GLOSSTERM },
                    104:        { "group",              NODE_GROUP },
                    105:        { "holder",             NODE_HOLDER },
                    106:        { "index",              NODE_INDEX },
1.4       schwarze  107:        { "indexterm",          NODE_DELETE },
1.1       schwarze  108:        { "info",               NODE_INFO },
                    109:        { "informalequation",   NODE_INFORMALEQUATION },
1.11      schwarze  110:        { "informaltable",      NODE_TABLE },
1.1       schwarze  111:        { "inlineequation",     NODE_INLINEEQUATION },
                    112:        { "itemizedlist",       NODE_ITEMIZEDLIST },
                    113:        { "keysym",             NODE_KEYSYM },
                    114:        { "legalnotice",        NODE_LEGALNOTICE },
                    115:        { "link",               NODE_LINK },
                    116:        { "listitem",           NODE_LISTITEM },
                    117:        { "literal",            NODE_LITERAL },
                    118:        { "literallayout",      NODE_LITERALLAYOUT },
                    119:        { "manvolnum",          NODE_MANVOLNUM },
                    120:        { "member",             NODE_MEMBER },
                    121:        { "mml:math",           NODE_MML_MATH },
                    122:        { "mml:mfenced",        NODE_MML_MFENCED },
                    123:        { "mml:mfrac",          NODE_MML_MFRAC },
                    124:        { "mml:mi",             NODE_MML_MI },
                    125:        { "mml:mn",             NODE_MML_MN },
                    126:        { "mml:mo",             NODE_MML_MO },
                    127:        { "mml:mrow",           NODE_MML_MROW },
                    128:        { "mml:msub",           NODE_MML_MSUB },
                    129:        { "mml:msup",           NODE_MML_MSUP },
                    130:        { "modifier",           NODE_MODIFIER },
                    131:        { "note",               NODE_NOTE },
                    132:        { "option",             NODE_OPTION },
                    133:        { "orderedlist",        NODE_ORDEREDLIST },
                    134:        { "orgname",            NODE_ORGNAME },
1.7       schwarze  135:        { "othername",          NODE_PERSONNAME },
1.1       schwarze  136:        { "para",               NODE_PARA },
                    137:        { "paramdef",           NODE_PARAMDEF },
                    138:        { "parameter",          NODE_PARAMETER },
                    139:        { "part",               NODE_SECTION },
                    140:        { "personname",         NODE_PERSONNAME },
1.3       schwarze  141:        { "phrase",             NODE_IGNORE },
1.1       schwarze  142:        { "preface",            NODE_PREFACE },
1.4       schwarze  143:        { "primary",            NODE_DELETE },
1.1       schwarze  144:        { "programlisting",     NODE_PROGRAMLISTING },
                    145:        { "prompt",             NODE_PROMPT },
                    146:        { "quote",              NODE_QUOTE },
                    147:        { "refclass",           NODE_REFCLASS },
                    148:        { "refdescriptor",      NODE_REFDESCRIPTOR },
                    149:        { "refentry",           NODE_REFENTRY },
                    150:        { "refentryinfo",       NODE_REFENTRYINFO },
                    151:        { "refentrytitle",      NODE_REFENTRYTITLE },
                    152:        { "refmeta",            NODE_REFMETA },
                    153:        { "refmetainfo",        NODE_REFMETAINFO },
                    154:        { "refmiscinfo",        NODE_REFMISCINFO },
                    155:        { "refname",            NODE_REFNAME },
                    156:        { "refnamediv",         NODE_REFNAMEDIV },
                    157:        { "refpurpose",         NODE_REFPURPOSE },
                    158:        { "refsect1",           NODE_SECTION },
                    159:        { "refsect2",           NODE_SECTION },
                    160:        { "refsect3",           NODE_SECTION },
                    161:        { "refsection",         NODE_SECTION },
                    162:        { "refsynopsisdiv",     NODE_REFSYNOPSISDIV },
                    163:        { "releaseinfo",        NODE_RELEASEINFO },
                    164:        { "replaceable",        NODE_REPLACEABLE },
                    165:        { "row",                NODE_ROW },
                    166:        { "sbr",                NODE_SBR },
                    167:        { "screen",             NODE_SCREEN },
1.4       schwarze  168:        { "secondary",          NODE_DELETE },
1.1       schwarze  169:        { "sect1",              NODE_SECTION },
                    170:        { "sect2",              NODE_SECTION },
                    171:        { "section",            NODE_SECTION },
                    172:        { "sgmltag",            NODE_SGMLTAG },
1.15    ! schwarze  173:        { "simpara",            NODE_PARA },
1.1       schwarze  174:        { "simplelist",         NODE_SIMPLELIST },
                    175:        { "spanspec",           NODE_SPANSPEC },
1.13      schwarze  176:        { "structfield",        NODE_PARAMETER },
                    177:        { "structname",         NODE_TYPE },
1.1       schwarze  178:        { "subtitle",           NODE_SUBTITLE },
1.7       schwarze  179:        { "surname",            NODE_PERSONNAME },
1.12      schwarze  180:        { "symbol",             NODE_CONSTANT },
1.1       schwarze  181:        { "synopsis",           NODE_SYNOPSIS },
                    182:        { "table",              NODE_TABLE },
                    183:        { "tbody",              NODE_TBODY },
                    184:        { "term",               NODE_TERM },
                    185:        { "tfoot",              NODE_TFOOT },
                    186:        { "tgroup",             NODE_TGROUP },
                    187:        { "thead",              NODE_THEAD },
                    188:        { "tip",                NODE_TIP },
                    189:        { "title",              NODE_TITLE },
1.3       schwarze  190:        { "trademark",          NODE_IGNORE },
1.1       schwarze  191:        { "type",               NODE_TYPE },
                    192:        { "ulink",              NODE_ULINK },
1.13      schwarze  193:        { "userinput",          NODE_LITERAL },
1.1       schwarze  194:        { "variablelist",       NODE_VARIABLELIST },
                    195:        { "varlistentry",       NODE_VARLISTENTRY },
                    196:        { "varname",            NODE_VARNAME },
                    197:        { "warning",            NODE_WARNING },
                    198:        { "wordasword",         NODE_WORDASWORD },
1.4       schwarze  199:        { "xi:include",         NODE_DELETE_WARN },
1.1       schwarze  200:        { "year",               NODE_YEAR },
1.5       schwarze  201:        { NULL,                 NODE_IGNORE }
1.1       schwarze  202: };
                    203:
1.9       schwarze  204: struct entity {
                    205:        const char      *name;
                    206:        const char      *roff;
                    207: };
                    208:
                    209: /*
                    210:  * XML character entity references found in the wild.
                    211:  * Those that don't have an exact mandoc_char(7) representation
                    212:  * are approximated, and the desired codepoint is given as a comment.
                    213:  * Encoding them as \\[u...] would leave -Tascii out in the cold.
                    214:  */
                    215: static const struct entity entities[] = {
                    216:        { "alpha",      "\\(*a" },
                    217:        { "amp",        "&" },
                    218:        { "apos",       "'" },
                    219:        { "auml",       "\\(:a" },
                    220:        { "beta",       "\\(*b" },
                    221:        { "circ",       "^" },      /* U+02C6 */
                    222:        { "copy",       "\\(co" },
                    223:        { "dagger",     "\\(dg" },
                    224:        { "Delta",      "\\(*D" },
                    225:        { "eacute",     "\\('e" },
                    226:        { "emsp",       "\\ " },    /* U+2003 */
                    227:        { "gt",         ">" },
                    228:        { "hairsp",     "\\^" },
                    229:        { "kappa",      "\\(*k" },
                    230:        { "larr",       "\\(<-" },
                    231:        { "ldquo",      "\\(lq" },
                    232:        { "le",         "\\(<=" },
                    233:        { "lowbar",     "_" },
                    234:        { "lsqb",       "[" },
                    235:        { "lt",         "<" },
                    236:        { "mdash",      "\\(em" },
                    237:        { "minus",      "\\-" },
                    238:        { "ndash",      "\\(en" },
                    239:        { "nbsp",       "\\ " },
                    240:        { "num",        "#" },
                    241:        { "oslash",     "\\(/o" },
                    242:        { "ouml",       "\\(:o" },
                    243:        { "percnt",     "%" },
                    244:        { "quot",       "\\(dq" },
                    245:        { "rarr",       "\\(->" },
                    246:        { "rArr",       "\\(rA" },
                    247:        { "rdquo",      "\\(rq" },
                    248:        { "reg",        "\\(rg" },
                    249:        { "rho",        "\\(*r" },
                    250:        { "rsqb",       "]" },
                    251:        { "sigma",      "\\(*s" },
                    252:        { "shy",        "\\&" },     /* U+00AD */
                    253:        { "tau",        "\\(*t" },
                    254:        { "tilde",      "\\[u02DC]" },
                    255:        { "times",      "\\[tmu]" },
                    256:        { "uuml",       "\\(:u" },
                    257:        { NULL,         NULL }
                    258: };
                    259:
1.6       schwarze  260: static void
                    261: error_msg(struct parse *p, const char *fmt, ...)
                    262: {
                    263:        va_list          ap;
                    264:
                    265:        fprintf(stderr, "%s:%d:%d: ", p->fname, p->line, p->col);
                    266:        va_start(ap, fmt);
                    267:        vfprintf(stderr, fmt, ap);
                    268:        va_end(ap);
                    269:        fputc('\n', stderr);
                    270:        p->tree->flags |= TREE_FAIL;
                    271: }
                    272:
                    273: static void
                    274: warn_msg(struct parse *p, const char *fmt, ...)
                    275: {
                    276:        va_list          ap;
                    277:
                    278:        if (p->warn == 0)
                    279:                return;
                    280:
                    281:        fprintf(stderr, "%s:%d:%d: warning: ", p->fname, p->line, p->col);
                    282:        va_start(ap, fmt);
                    283:        vfprintf(stderr, fmt, ap);
                    284:        va_end(ap);
                    285:        fputc('\n', stderr);
                    286: }
                    287:
1.1       schwarze  288: /*
                    289:  * Process a string of characters.
                    290:  * If a text node is already open, append to it.
                    291:  * Otherwise, create a new one as a child of the current node.
                    292:  */
                    293: static void
1.5       schwarze  294: xml_char(struct parse *ps, const char *p, int sz)
1.1       schwarze  295: {
                    296:        struct pnode    *dat;
                    297:
1.5       schwarze  298:        if (ps->del > 0)
1.1       schwarze  299:                return;
                    300:
1.5       schwarze  301:        if (ps->cur == NULL) {
1.6       schwarze  302:                error_msg(ps, "discarding text before document: %.*s", sz, p);
1.5       schwarze  303:                return;
                    304:        }
                    305:
1.1       schwarze  306:        if (ps->cur->node != NODE_TEXT) {
                    307:                if ((dat = calloc(1, sizeof(*dat))) == NULL) {
                    308:                        perror(NULL);
                    309:                        exit(1);
                    310:                }
                    311:                dat->node = NODE_TEXT;
                    312:                dat->parent = ps->cur;
                    313:                TAILQ_INIT(&dat->childq);
                    314:                TAILQ_INIT(&dat->attrq);
                    315:                TAILQ_INSERT_TAIL(&ps->cur->childq, dat, child);
                    316:                ps->cur = dat;
                    317:        }
                    318:
1.5       schwarze  319:        if (ps->tree->flags & TREE_CLOSED &&
1.6       schwarze  320:            ps->cur->parent == ps->tree->root)
                    321:                warn_msg(ps, "text after end of document: %.*s", sz, p);
1.5       schwarze  322:
1.1       schwarze  323:        /* Append to the current text node. */
                    324:
                    325:        assert(sz >= 0);
                    326:        ps->cur->b = realloc(ps->cur->b, ps->cur->bsz + sz + 1);
                    327:        if (ps->cur->b == NULL) {
                    328:                perror(NULL);
                    329:                exit(1);
                    330:        }
                    331:        memcpy(ps->cur->b + ps->cur->bsz, p, sz);
                    332:        ps->cur->bsz += sz;
                    333:        ps->cur->b[ps->cur->bsz] = '\0';
                    334:        ps->cur->real = ps->cur->b;
                    335: }
                    336:
                    337: static void
                    338: pnode_trim(struct pnode *pn)
                    339: {
                    340:        assert(pn->node == NODE_TEXT);
                    341:        for (; pn->bsz > 0; pn->b[--pn->bsz] = '\0')
                    342:                if (isspace((unsigned char)pn->b[pn->bsz - 1]) == 0)
                    343:                        break;
                    344: }
                    345:
1.9       schwarze  346: static void
                    347: xml_entity(struct parse *p, const char *name)
                    348: {
                    349:        const struct entity     *entity;
                    350:        struct pnode            *dat;
                    351:
                    352:        if (p->del > 0)
                    353:                return;
                    354:
                    355:        if (p->cur == NULL) {
                    356:                error_msg(p, "discarding entity before document: &%s;", name);
                    357:                return;
                    358:        }
                    359:
                    360:        /* Close out the text node, if there is one. */
                    361:        if (p->cur->node == NODE_TEXT) {
                    362:                pnode_trim(p->cur);
                    363:                p->cur = p->cur->parent;
                    364:        }
                    365:
                    366:        if (p->tree->flags & TREE_CLOSED && p->cur == p->tree->root)
                    367:                warn_msg(p, "entity after end of document: &%s;", name);
                    368:
                    369:        for (entity = entities; entity->name != NULL; entity++)
                    370:                if (strcmp(name, entity->name) == 0)
                    371:                        break;
                    372:
                    373:        if (entity->roff == NULL) {
                    374:                error_msg(p, "unknown entity &%s;", name);
                    375:                return;
                    376:        }
                    377:
                    378:        /* Create, append, and close out an entity node. */
                    379:        if ((dat = calloc(1, sizeof(*dat))) == NULL ||
                    380:            (dat->b = dat->real = strdup(entity->roff)) == NULL) {
                    381:                perror(NULL);
                    382:                exit(1);
                    383:        }
                    384:        dat->node = NODE_ESCAPE;
                    385:        dat->bsz = strlen(dat->b);
                    386:        dat->parent = p->cur;
                    387:        TAILQ_INIT(&dat->childq);
                    388:        TAILQ_INIT(&dat->attrq);
                    389:        TAILQ_INSERT_TAIL(&p->cur->childq, dat, child);
                    390: }
                    391:
1.1       schwarze  392: /*
                    393:  * Begin an element.
                    394:  */
                    395: static void
1.5       schwarze  396: xml_elem_start(struct parse *ps, const char *name)
1.1       schwarze  397: {
1.5       schwarze  398:        const struct element    *elem;
                    399:        struct pnode            *dat;
1.1       schwarze  400:
1.5       schwarze  401:        if (*name == '!' || *name == '?')
1.1       schwarze  402:                return;
                    403:
1.4       schwarze  404:        /*
                    405:         * An ancestor is excluded from the tree;
                    406:         * keep track of the number of levels excluded.
                    407:         */
                    408:        if (ps->del > 0) {
                    409:                ps->del++;
                    410:                return;
                    411:        }
                    412:
1.1       schwarze  413:        /* Close out the text node, if there is one. */
                    414:        if (ps->cur != NULL && ps->cur->node == NODE_TEXT) {
                    415:                pnode_trim(ps->cur);
                    416:                ps->cur = ps->cur->parent;
                    417:        }
                    418:
                    419:        for (elem = elements; elem->name != NULL; elem++)
                    420:                if (strcmp(elem->name, name) == 0)
                    421:                        break;
                    422:
1.6       schwarze  423:        if (elem->name == NULL)
                    424:                error_msg(ps, "unknown element <%s>", name);
                    425:
1.5       schwarze  426:        ps->ncur = elem->node;
1.1       schwarze  427:
1.5       schwarze  428:        switch (ps->ncur) {
1.4       schwarze  429:        case NODE_DELETE_WARN:
1.6       schwarze  430:                warn_msg(ps, "skipping element <%s>", name);
1.2       schwarze  431:                /* FALLTHROUGH */
1.4       schwarze  432:        case NODE_DELETE:
                    433:                ps->del = 1;
                    434:                /* FALLTHROUGH */
1.2       schwarze  435:        case NODE_IGNORE:
                    436:                return;
                    437:        case NODE_INLINEEQUATION:
1.1       schwarze  438:                ps->tree->flags |= TREE_EQN;
1.2       schwarze  439:                break;
                    440:        default:
                    441:                break;
                    442:        }
1.1       schwarze  443:
1.6       schwarze  444:        if (ps->tree->flags & TREE_CLOSED && ps->cur->parent == NULL)
                    445:                warn_msg(ps, "element after end of document: <%s>", name);
1.5       schwarze  446:
1.1       schwarze  447:        if ((dat = calloc(1, sizeof(*dat))) == NULL) {
                    448:                perror(NULL);
                    449:                exit(1);
                    450:        }
                    451:        dat->node = elem->node;
                    452:        dat->parent = ps->cur;
                    453:        TAILQ_INIT(&dat->childq);
                    454:        TAILQ_INIT(&dat->attrq);
                    455:
                    456:        if (ps->cur != NULL)
                    457:                TAILQ_INSERT_TAIL(&ps->cur->childq, dat, child);
                    458:
                    459:        ps->cur = dat;
                    460:        if (ps->tree->root == NULL)
                    461:                ps->tree->root = dat;
1.5       schwarze  462: }
                    463:
                    464: static void
                    465: xml_attrkey(struct parse *ps, const char *name)
                    466: {
                    467:        struct pattr    *attr;
                    468:        enum attrkey     key;
1.1       schwarze  469:
1.5       schwarze  470:        if (ps->del > 0 || *name == '\0')
                    471:                return;
                    472:        if ((key = attrkey_parse(name)) == ATTRKEY__MAX) {
                    473:                ps->attr = 0;
                    474:                return;
                    475:        }
                    476:        if ((attr = calloc(1, sizeof(*attr))) == NULL) {
                    477:                perror(NULL);
                    478:                exit(1);
                    479:        }
                    480:        attr->key = key;
                    481:        attr->val = ATTRVAL__MAX;
                    482:        attr->rawval = NULL;
                    483:        TAILQ_INSERT_TAIL(&ps->cur->attrq, attr, child);
                    484:        ps->attr = 1;
                    485: }
                    486:
                    487: static void
                    488: xml_attrval(struct parse *ps, const char *name)
                    489: {
                    490:        struct pattr    *attr;
                    491:
                    492:        if (ps->del > 0 || ps->attr == 0)
                    493:                return;
                    494:        if ((attr = TAILQ_LAST(&ps->cur->attrq, pattrq)) == NULL)
                    495:                return;
                    496:        if ((attr->val = attrval_parse(name)) == ATTRVAL__MAX &&
                    497:            (attr->rawval = strdup(name)) == NULL) {
                    498:                perror(NULL);
                    499:                exit(1);
1.1       schwarze  500:        }
                    501: }
                    502:
                    503: /*
                    504:  * Roll up the parse tree.
                    505:  * If we're at a text node, roll that one up first.
                    506:  */
                    507: static void
1.5       schwarze  508: xml_elem_end(struct parse *ps, const char *name)
1.1       schwarze  509: {
1.5       schwarze  510:        const struct element    *elem;
                    511:        enum nodeid              node;
1.1       schwarze  512:
1.4       schwarze  513:        /*
                    514:         * An ancestor is excluded from the tree;
                    515:         * keep track of the number of levels excluded.
                    516:         */
                    517:        if (ps->del > 1) {
                    518:                ps->del--;
                    519:                return;
                    520:        }
                    521:
1.1       schwarze  522:        /* Close out the text node, if there is one. */
1.5       schwarze  523:        if (ps->del == 0 && ps->cur != NULL && ps->cur->node == NODE_TEXT) {
1.1       schwarze  524:                pnode_trim(ps->cur);
                    525:                ps->cur = ps->cur->parent;
                    526:        }
1.2       schwarze  527:
1.5       schwarze  528:        if (name != NULL) {
                    529:                for (elem = elements; elem->name != NULL; elem++)
                    530:                        if (strcmp(elem->name, name) == 0)
                    531:                                break;
                    532:                node = elem->node;
                    533:        } else
                    534:                node = ps->ncur;
1.2       schwarze  535:
1.5       schwarze  536:        switch (node) {
1.4       schwarze  537:        case NODE_DELETE_WARN:
                    538:        case NODE_DELETE:
1.5       schwarze  539:                if (ps->del > 0)
                    540:                        ps->del--;
1.4       schwarze  541:                break;
1.2       schwarze  542:        case NODE_IGNORE:
                    543:                break;
                    544:        default:
1.5       schwarze  545:                if (ps->cur == NULL || node != ps->cur->node) {
1.6       schwarze  546:                        warn_msg(ps, "element not open: </%s>", name);
1.5       schwarze  547:                        break;
                    548:                }
                    549:
                    550:                /*
                    551:                 * Refrain from actually closing the document element.
                    552:                 * If no more content follows, no harm is done, but if
                    553:                 * some content still follows, simply processing it is
                    554:                 * obviously better than discarding it or crashing.
                    555:                 */
                    556:
                    557:                if (ps->cur->parent == NULL)
                    558:                        ps->tree->flags |= TREE_CLOSED;
                    559:                else
                    560:                        ps->cur = ps->cur->parent;
1.4       schwarze  561:                break;
1.2       schwarze  562:        }
1.4       schwarze  563:        assert(ps->del == 0);
1.1       schwarze  564: }
                    565:
                    566: struct parse *
                    567: parse_alloc(int warn)
                    568: {
                    569:        struct parse    *p;
                    570:
                    571:        if ((p = calloc(1, sizeof(*p))) == NULL)
                    572:                return NULL;
                    573:
                    574:        if ((p->tree = calloc(1, sizeof(*p->tree))) == NULL) {
                    575:                free(p);
                    576:                return NULL;
                    577:        }
                    578:        p->warn = warn;
                    579:        return p;
                    580: }
                    581:
                    582: void
                    583: parse_free(struct parse *p)
                    584: {
                    585:        if (p == NULL)
                    586:                return;
                    587:        if (p->tree != NULL) {
                    588:                pnode_unlink(p->tree->root);
                    589:                free(p->tree);
                    590:        }
                    591:        free(p);
                    592: }
                    593:
1.14      schwarze  594: static void
                    595: increment(struct parse *p, char *b, size_t *pend, int refill)
                    596: {
                    597:        if (refill) {
                    598:                if (b[*pend] == '\n') {
                    599:                        p->nline++;
                    600:                        p->ncol = 1;
                    601:                } else
                    602:                        p->ncol++;
                    603:        }
                    604:        ++*pend;
                    605: }
                    606:
1.5       schwarze  607: /*
                    608:  * Advance the pend pointer to the next character in the charset.
                    609:  * If the charset starts with a space, it stands for any whitespace.
                    610:  * Update the new input file position, used for messages.
                    611:  * Do not overrun the buffer b of length rlen.
                    612:  * When reaching the end, NUL-terminate the buffer and return 1;
                    613:  * otherwise, return 0.
                    614:  */
                    615: static int
                    616: advance(struct parse *p, char *b, size_t rlen, size_t *pend,
1.14      schwarze  617:     const char *charset, int refill)
1.5       schwarze  618: {
                    619:        int              space;
                    620:
                    621:        if (*charset == ' ') {
                    622:                space = 1;
                    623:                charset++;
                    624:        } else
                    625:                space = 0;
                    626:
1.14      schwarze  627:        if (refill) {
                    628:                p->nline = p->line;
                    629:                p->ncol = p->col;
                    630:        }
1.5       schwarze  631:        while (*pend < rlen) {
                    632:                if (space && isspace((unsigned char)b[*pend]))
                    633:                        break;
                    634:                if (strchr(charset, b[*pend]) != NULL)
                    635:                        break;
1.14      schwarze  636:                increment(p, b, pend, refill);
1.5       schwarze  637:        }
                    638:        if (*pend == rlen) {
                    639:                b[rlen] = '\0';
1.14      schwarze  640:                return refill;
1.5       schwarze  641:        } else
                    642:                return 0;
                    643: }
                    644:
1.14      schwarze  645: size_t
                    646: parse_string(struct parse *p, char *b, size_t rlen,
                    647:     enum pstate *pstate, int refill)
                    648: {
                    649:        char            *cp;
                    650:        size_t           poff;  /* Parse offset in b[]. */
                    651:        size_t           pend;  /* Offset of the end of the current word. */
                    652:        int              elem_end;
                    653:
                    654:        pend = 0;
                    655:        for (;;) {
                    656:
                    657:                /* Proceed to the next token, skipping whitespace. */
                    658:
                    659:                if (refill) {
                    660:                        p->line = p->nline;
                    661:                        p->col = p->ncol;
                    662:                }
                    663:                if ((poff = pend) == rlen)
                    664:                        break;
                    665:                if (isspace((unsigned char)b[pend])) {
                    666:                        increment(p, b, &pend, refill);
                    667:                        continue;
                    668:                }
                    669:
                    670:                /*
                    671:                 * The following four cases (ARG, TAG, and starting an
                    672:                 * entity or a tag) all parse a word or quoted string.
                    673:                 * If that extends beyond the read buffer and the last
                    674:                 * read(2) still got data, they all break out of the
                    675:                 * token loop to request more data from the read loop.
                    676:                 *
                    677:                 * Also, three of them detect self-closing tags, those
                    678:                 * ending with "/>", setting the flag elem_end and
                    679:                 * calling xml_elem_end() at the very end, after
                    680:                 * handling the attribute value, attribute name, or
                    681:                 * tag name, respectively.
                    682:                 */
                    683:
                    684:                /* Parse an attribute value. */
                    685:
                    686:                if (*pstate >= PARSE_ARG) {
                    687:                        if (*pstate == PARSE_ARG &&
                    688:                            (b[pend] == '\'' || b[pend] == '"')) {
                    689:                                *pstate = b[pend] == '"' ?
                    690:                                    PARSE_DQ : PARSE_SQ;
                    691:                                increment(p, b, &pend, refill);
                    692:                                continue;
                    693:                        }
                    694:                        if (advance(p, b, rlen, &pend,
                    695:                            *pstate == PARSE_DQ ? "\"" :
                    696:                            *pstate == PARSE_SQ ? "'" : " >", refill))
                    697:                                break;
                    698:                        *pstate = PARSE_TAG;
                    699:                        elem_end = 0;
                    700:                        if (b[pend] == '>') {
                    701:                                *pstate = PARSE_ELEM;
                    702:                                if (pend > 0 && b[pend - 1] == '/') {
                    703:                                        b[pend - 1] = '\0';
                    704:                                        elem_end = 1;
                    705:                                }
                    706:                        }
                    707:                        b[pend] = '\0';
                    708:                        if (pend < rlen)
                    709:                                increment(p, b, &pend, refill);
                    710:                        xml_attrval(p, b + poff);
                    711:                        if (elem_end)
                    712:                                xml_elem_end(p, NULL);
                    713:
                    714:                /* Look for an attribute name. */
                    715:
                    716:                } else if (*pstate == PARSE_TAG) {
                    717:                        if (advance(p, b, rlen, &pend, " =>", refill))
                    718:                                break;
                    719:                        elem_end = 0;
                    720:                        switch (b[pend]) {
                    721:                        case '>':
                    722:                                *pstate = PARSE_ELEM;
                    723:                                if (pend > 0 && b[pend - 1] == '/') {
                    724:                                        b[pend - 1] = '\0';
                    725:                                        elem_end = 1;
                    726:                                }
                    727:                                break;
                    728:                        case '=':
                    729:                                *pstate = PARSE_ARG;
                    730:                                break;
                    731:                        default:
                    732:                                break;
                    733:                        }
                    734:                        b[pend] = '\0';
                    735:                        if (pend < rlen)
                    736:                                increment(p, b, &pend, refill);
                    737:                        xml_attrkey(p, b + poff);
                    738:                        if (elem_end)
                    739:                                xml_elem_end(p, NULL);
                    740:
                    741:                /* Begin an opening or closing tag. */
                    742:
                    743:                } else if (b[poff] == '<') {
                    744:                        if (advance(p, b, rlen, &pend, " >", refill))
                    745:                                break;
                    746:                        if (pend > poff + 3 &&
                    747:                            strncmp(b + poff, "<!--", 4) == 0) {
                    748:
                    749:                                /* Skip a comment. */
                    750:
                    751:                                cp = strstr(b + pend - 2, "-->");
                    752:                                if (cp == NULL) {
                    753:                                        if (refill)
                    754:                                                break;
                    755:                                        cp = b + rlen;
                    756:                                } else
                    757:                                        cp += 3;
                    758:                                while (b + pend < cp)
                    759:                                        increment(p, b, &pend, refill);
                    760:                                continue;
                    761:                        }
                    762:                        elem_end = 0;
                    763:                        if (b[pend] != '>')
                    764:                                *pstate = PARSE_TAG;
                    765:                        else if (pend > 0 && b[pend - 1] == '/') {
                    766:                                b[pend - 1] = '\0';
                    767:                                elem_end = 1;
                    768:                        }
                    769:                        b[pend] = '\0';
                    770:                        if (pend < rlen)
                    771:                                increment(p, b, &pend, refill);
                    772:                        if (b[++poff] == '/') {
                    773:                                elem_end = 1;
                    774:                                poff++;
                    775:                        } else
                    776:                                xml_elem_start(p, b + poff);
                    777:                        if (elem_end)
                    778:                                xml_elem_end(p, b + poff);
                    779:
                    780:                /* Process an entity. */
                    781:
                    782:                } else if (b[poff] == '&') {
                    783:                        if (advance(p, b, rlen, &pend, ";", refill))
                    784:                                break;
                    785:                        b[pend] = '\0';
                    786:                        if (pend < rlen)
                    787:                                increment(p, b, &pend, refill);
                    788:                        xml_entity(p, b + poff + 1);
                    789:
                    790:                /* Process text up to the next tag, entity, or EOL. */
                    791:
                    792:                } else {
                    793:                        advance(p, b, rlen, &pend, "<&", refill);
                    794:                        xml_char(p, b + poff, pend - poff);
                    795:                }
                    796:        }
                    797:        return poff;
                    798: }
                    799:
1.1       schwarze  800: struct ptree *
                    801: parse_file(struct parse *p, int fd, const char *fname)
                    802: {
                    803:        char             b[4096];
1.5       schwarze  804:        ssize_t          rsz;   /* Return value from read(2). */
1.14      schwarze  805:        size_t           rlen;  /* Number of bytes in b[]. */
1.5       schwarze  806:        size_t           poff;  /* Parse offset in b[]. */
1.14      schwarze  807:        enum pstate      pstate;
1.1       schwarze  808:
                    809:        p->fname = fname;
1.5       schwarze  810:        p->nline = 1;
                    811:        p->ncol = 1;
1.14      schwarze  812:        pstate = PARSE_ELEM;
1.5       schwarze  813:        rlen = 0;
                    814:
                    815:        /*
                    816:         * Read loop.
                    817:         *
1.14      schwarze  818:          * If the previous token was incomplete and asked for more
                    819:          * input, we have to enter the read loop once more even on EOF.
1.5       schwarze  820:         * Once rsz is 0, incomplete tokens will no longer ask
                    821:         * for more input but instead use whatever there is,
                    822:         * and then exit the read loop.
                    823:         * The minus one on the size limit for read(2) is needed
                    824:         * such that advance() can set b[rlen] to NUL when needed.
                    825:         */
                    826:
1.14      schwarze  827:        while ((rsz = read(fd, b + rlen, sizeof(b) - rlen - 1)) >= 0 &&
                    828:            (rlen += rsz) > 0) {
                    829:                poff = parse_string(p, b, rlen, &pstate, rsz > 0);
1.5       schwarze  830:                /* Buffer exhausted; shift left and re-fill. */
                    831:                assert(poff > 0);
                    832:                rlen -= poff;
1.14      schwarze  833:                memmove(b, b + poff, rlen);
1.5       schwarze  834:        }
                    835:        if (rsz < 0) {
                    836:                perror(fname);
                    837:                p->tree->flags |= TREE_FAIL;
                    838:        }
                    839:        if (p->cur != NULL && p->cur->node == NODE_TEXT) {
                    840:                pnode_trim(p->cur);
                    841:                p->cur = p->cur->parent;
                    842:        }
1.6       schwarze  843:        if ((p->tree->flags & TREE_CLOSED) == 0)
                    844:                warn_msg(p, "document not closed");
1.1       schwarze  845:        return p->tree;
                    846: }

CVSweb