]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/parse_entry.c
ncurses 6.3 - patch 20220507
[ncurses.git] / ncurses / tinfo / parse_entry.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  ****************************************************************************/
35
36 /*
37  *      parse_entry.c -- compile one terminfo or termcap entry
38  *
39  *      Get an exact in-core representation of an entry.  Don't
40  *      try to resolve use or tc capabilities, that is someone
41  *      else's job.  Depends on the lexical analyzer to get tokens
42  *      from the input stream.
43  */
44
45 #define __INTERNAL_CAPS_VISIBLE
46 #include <curses.priv.h>
47
48 #include <ctype.h>
49 #include <tic.h>
50
51 MODULE_ID("$Id: parse_entry.c,v 1.107 2022/05/08 00:11:44 tom Exp $")
52
53 #ifdef LINT
54 static short const parametrized[] =
55 {0};
56 #else
57 #include <parametrized.h>
58 #endif
59
60 static void postprocess_termcap(TERMTYPE2 *, bool);
61 static void postprocess_terminfo(TERMTYPE2 *);
62 static struct name_table_entry const *lookup_fullname(const char *name);
63
64 #if NCURSES_XNAMES
65
66 static struct name_table_entry const *
67 _nc_extend_names(ENTRY * entryp, const char *name, int token_type)
68 {
69     static struct name_table_entry temp;
70     TERMTYPE2 *tp = &(entryp->tterm);
71     unsigned offset = 0;
72     unsigned actual;
73     unsigned tindex;
74     unsigned first, last, n;
75     bool found;
76
77     switch (token_type) {
78     case BOOLEAN:
79         first = 0;
80         last = tp->ext_Booleans;
81         offset = tp->ext_Booleans;
82         tindex = tp->num_Booleans;
83         break;
84     case NUMBER:
85         first = tp->ext_Booleans;
86         last = tp->ext_Numbers + first;
87         offset = (unsigned) (tp->ext_Booleans + tp->ext_Numbers);
88         tindex = tp->num_Numbers;
89         break;
90     case STRING:
91         first = (unsigned) (tp->ext_Booleans + tp->ext_Numbers);
92         last = tp->ext_Strings + first;
93         offset = (unsigned) (tp->ext_Booleans + tp->ext_Numbers + tp->ext_Strings);
94         tindex = tp->num_Strings;
95         break;
96     case CANCEL:
97         actual = NUM_EXT_NAMES(tp);
98         for (n = 0; n < actual; n++) {
99             if (!strcmp(name, tp->ext_Names[n])) {
100                 if (n > (unsigned) (tp->ext_Booleans + tp->ext_Numbers)) {
101                     token_type = STRING;
102                 } else if (n > tp->ext_Booleans) {
103                     token_type = NUMBER;
104                 } else {
105                     token_type = BOOLEAN;
106                 }
107                 return _nc_extend_names(entryp, name, token_type);
108             }
109         }
110         /* Well, we are given a cancel for a name that we don't recognize */
111         return _nc_extend_names(entryp, name, STRING);
112     default:
113         return 0;
114     }
115
116     /* Adjust the 'offset' (insertion-point) to keep the lists of extended
117      * names sorted.
118      */
119     for (n = first, found = FALSE; n < last; n++) {
120         int cmp = strcmp(tp->ext_Names[n], name);
121         if (cmp == 0)
122             found = TRUE;
123         if (cmp >= 0) {
124             offset = n;
125             tindex = n - first;
126             switch (token_type) {
127             case BOOLEAN:
128                 tindex += BOOLCOUNT;
129                 break;
130             case NUMBER:
131                 tindex += NUMCOUNT;
132                 break;
133             case STRING:
134                 tindex += STRCOUNT;
135                 break;
136             }
137             break;
138         }
139     }
140
141 #define for_each_value(max) \
142         for (last = (unsigned) (max - 1); last > tindex; last--)
143
144     if (!found) {
145         switch (token_type) {
146         case BOOLEAN:
147             tp->ext_Booleans++;
148             tp->num_Booleans++;
149             TYPE_REALLOC(NCURSES_SBOOL, tp->num_Booleans, tp->Booleans);
150             for_each_value(tp->num_Booleans)
151                 tp->Booleans[last] = tp->Booleans[last - 1];
152             break;
153         case NUMBER:
154             tp->ext_Numbers++;
155             tp->num_Numbers++;
156             TYPE_REALLOC(NCURSES_INT2, tp->num_Numbers, tp->Numbers);
157             for_each_value(tp->num_Numbers)
158                 tp->Numbers[last] = tp->Numbers[last - 1];
159             break;
160         case STRING:
161             tp->ext_Strings++;
162             tp->num_Strings++;
163             TYPE_REALLOC(char *, tp->num_Strings, tp->Strings);
164             for_each_value(tp->num_Strings)
165                 tp->Strings[last] = tp->Strings[last - 1];
166             break;
167         }
168         actual = NUM_EXT_NAMES(tp);
169         TYPE_REALLOC(char *, actual, tp->ext_Names);
170         while (--actual > offset)
171             tp->ext_Names[actual] = tp->ext_Names[actual - 1];
172         tp->ext_Names[offset] = _nc_save_str(name);
173     }
174
175     temp.nte_name = tp->ext_Names[offset];
176     temp.nte_type = token_type;
177     temp.nte_index = (short) tindex;
178     temp.nte_link = -1;
179
180     return &temp;
181 }
182
183 static const char *
184 usertype2s(int mask)
185 {
186     const char *result = "unknown";
187     if (mask & (1 << BOOLEAN)) {
188         result = "boolean";
189     } else if (mask & (1 << NUMBER)) {
190         result = "number";
191     } else if (mask & (1 << STRING)) {
192         result = "string";
193     }
194     return result;
195 }
196
197 static bool
198 expected_type(const char *name, int token_type, bool silent)
199 {
200     struct user_table_entry const *entry = _nc_find_user_entry(name);
201     bool result = TRUE;
202     if ((entry != 0) && (token_type != CANCEL)) {
203         int have_type = (1 << token_type);
204         if (!(entry->ute_type & have_type)) {
205             if (!silent)
206                 _nc_warning("expected %s-type for %s, have %s",
207                             usertype2s(entry->ute_type),
208                             name,
209                             usertype2s(have_type));
210             result = FALSE;
211         }
212     }
213     return result;
214 }
215 #endif /* NCURSES_XNAMES */
216
217 /*
218  * A valid entry name uses characters from the "portable character set"
219  * (more commonly referred to as US-ASCII), and disallows some of the
220  * punctuation characters:
221  *
222  * '/' is a pathname separator
223  * '\' may be a pathname separator, but more important, is an escape
224  * '|' delimits names and description
225  * '#' denotes a numeric value
226  * '=' denotes a string value
227  * '@' denotes a cancelled symbol
228  * ',' separates terminfo capabilities
229  * ':' separates termcap capabilities
230  *
231  * Termcap capability names may begin with a '#' or '@' (since they have
232  * exactly two characters).
233  */
234 static bool
235 valid_entryname(const char *name)
236 {
237     bool result = TRUE;
238     bool first = TRUE;
239     int ch;
240     while ((ch = UChar(*name++)) != '\0') {
241         if (ch <= ' ' || ch > '~' || strchr("/\\|=,:", ch) != NULL) {
242             result = FALSE;
243             break;
244         }
245         if (!first && strchr("#@", ch) != NULL) {
246             result = FALSE;
247             break;
248         }
249         first = FALSE;
250     }
251     return result;
252 }
253
254 /*
255  *      int
256  *      _nc_parse_entry(entry, literal, silent)
257  *
258  *      Compile one entry.  Doesn't try to resolve use or tc capabilities.
259  *
260  *      found-forward-use = FALSE
261  *      re-initialise internal arrays
262  *      get_token();
263  *      if the token was not a name in column 1, complain and die
264  *      save names in entry's string table
265  *      while (get_token() is not EOF and not NAMES)
266  *              check for existence and type-correctness
267  *              enter cap into structure
268  *              if STRING
269  *                  save string in entry's string table
270  *      push back token
271  */
272
273 #define BAD_TC_USAGE if (!bad_tc_usage) \
274         { bad_tc_usage = TRUE; \
275          _nc_warning("Legacy termcap allows only a trailing tc= clause"); }
276
277 #define MAX_NUMBER MAX_OF_TYPE(NCURSES_INT2)
278
279 NCURSES_EXPORT(int)
280 _nc_parse_entry(ENTRY * entryp, int literal, bool silent)
281 {
282     int token_type;
283     struct name_table_entry const *entry_ptr;
284     char *ptr, *base;
285     const char *name;
286     bool bad_tc_usage = FALSE;
287
288     TR(TRACE_DATABASE,
289        (T_CALLED("_nc_parse_entry(entry=%p, literal=%d, silent=%d)"),
290         (void *) entryp, literal, silent));
291
292     token_type = _nc_get_token(silent);
293
294     if (token_type == EOF)
295         returnDB(EOF);
296     if (token_type != NAMES)
297         _nc_err_abort("Entry does not start with terminal names in column one");
298
299     _nc_init_entry(entryp);
300
301     entryp->cstart = _nc_comment_start;
302     entryp->cend = _nc_comment_end;
303     entryp->startline = _nc_start_line;
304     DEBUG(2, ("Comment range is %ld to %ld", entryp->cstart, entryp->cend));
305
306     /*
307      * Strip off the 2-character termcap name, if present.  Originally termcap
308      * used that as an indexing aid.  We can retain 2-character terminfo names,
309      * but note that they would be lost if we translate to/from termcap.  This
310      * feature is supposedly obsolete since "newer" BSD implementations do not
311      * use it; however our reference for this feature is SunOS 4.x, which
312      * implemented it.  Note that the resulting terminal type was never the
313      * 2-character name, but was instead the first alias after that.
314      */
315 #define ok_TC2(s) (isgraph(UChar(s)) && (s) != '|')
316     ptr = _nc_curr_token.tk_name;
317     if (_nc_syntax == SYN_TERMCAP
318 #if NCURSES_XNAMES
319         && !_nc_user_definable
320 #endif
321         ) {
322         if (ok_TC2(ptr[0]) && ok_TC2(ptr[1]) && (ptr[2] == '|')) {
323             ptr += 3;
324             _nc_curr_token.tk_name[2] = '\0';
325         }
326     }
327
328     entryp->tterm.str_table = entryp->tterm.term_names = _nc_save_str(ptr);
329
330     if (entryp->tterm.str_table == 0)
331         returnDB(ERR);
332
333     DEBUG(2, ("Starting '%s'", ptr));
334
335     /*
336      * We do this because the one-token lookahead in the parse loop
337      * results in the terminal type getting prematurely set to correspond
338      * to that of the next entry.
339      */
340     name = _nc_first_name(entryp->tterm.term_names);
341     if (!valid_entryname(name)) {
342         _nc_warning("invalid entry name \"%s\"", name);
343         name = "invalid";
344     }
345     _nc_set_type(name);
346
347     /* check for overly-long names and aliases */
348     for (base = entryp->tterm.term_names; (ptr = strchr(base, '|')) != 0;
349          base = ptr + 1) {
350         if (ptr - base > MAX_ALIAS) {
351             _nc_warning("%s `%.*s' may be too long",
352                         (base == entryp->tterm.term_names)
353                         ? "primary name"
354                         : "alias",
355                         (int) (ptr - base), base);
356         }
357     }
358
359     entryp->nuses = 0;
360
361     for (token_type = _nc_get_token(silent);
362          token_type != EOF && token_type != NAMES;
363          token_type = _nc_get_token(silent)) {
364         bool is_use = (strcmp(_nc_curr_token.tk_name, "use") == 0);
365         bool is_tc = !is_use && (strcmp(_nc_curr_token.tk_name, "tc") == 0);
366         if (is_use || is_tc) {
367             if (!VALID_STRING(_nc_curr_token.tk_valstring)
368                 || _nc_curr_token.tk_valstring[0] == '\0') {
369                 _nc_warning("missing name for use-clause");
370                 continue;
371             } else if (!valid_entryname(_nc_curr_token.tk_valstring)) {
372                 _nc_warning("invalid name for use-clause \"%s\"",
373                             _nc_curr_token.tk_valstring);
374                 continue;
375             } else if (entryp->nuses >= MAX_USES) {
376                 _nc_warning("too many use-clauses, ignored \"%s\"",
377                             _nc_curr_token.tk_valstring);
378                 continue;
379             }
380             entryp->uses[entryp->nuses].name = _nc_save_str(_nc_curr_token.tk_valstring);
381             entryp->uses[entryp->nuses].line = _nc_curr_line;
382             entryp->nuses++;
383             if (entryp->nuses > 1 && is_tc) {
384                 BAD_TC_USAGE
385             }
386         } else {
387             /* normal token lookup */
388             entry_ptr = _nc_find_entry(_nc_curr_token.tk_name,
389                                        _nc_get_hash_table(_nc_syntax));
390
391             /*
392              * Our kluge to handle aliasing.  The reason it is done
393              * this ugly way, with a linear search, is so the hashing
394              * machinery doesn't have to be made really complicated
395              * (also we get better warnings this way).  No point in
396              * making this case fast, aliased caps aren't common now
397              * and will get rarer.
398              */
399             if (entry_ptr == NOTFOUND) {
400                 const struct alias *ap;
401
402                 if (_nc_syntax == SYN_TERMCAP) {
403                     if (entryp->nuses != 0) {
404                         BAD_TC_USAGE
405                     }
406                     for (ap = _nc_get_alias_table(TRUE); ap->from; ap++)
407                         if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
408                             if (ap->to == (char *) 0) {
409                                 _nc_warning("%s (%s termcap extension) ignored",
410                                             ap->from, ap->source);
411                                 goto nexttok;
412                             }
413
414                             entry_ptr = _nc_find_entry(ap->to,
415                                                        _nc_get_hash_table(TRUE));
416                             if (entry_ptr && !silent)
417                                 _nc_warning("%s (%s termcap extension) aliased to %s",
418                                             ap->from, ap->source, ap->to);
419                             break;
420                         }
421                 } else {        /* if (_nc_syntax == SYN_TERMINFO) */
422                     for (ap = _nc_get_alias_table(FALSE); ap->from; ap++)
423                         if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
424                             if (ap->to == (char *) 0) {
425                                 _nc_warning("%s (%s terminfo extension) ignored",
426                                             ap->from, ap->source);
427                                 goto nexttok;
428                             }
429
430                             entry_ptr = _nc_find_entry(ap->to,
431                                                        _nc_get_hash_table(FALSE));
432                             if (entry_ptr && !silent)
433                                 _nc_warning("%s (%s terminfo extension) aliased to %s",
434                                             ap->from, ap->source, ap->to);
435                             break;
436                         }
437
438                     if (entry_ptr == NOTFOUND) {
439                         entry_ptr = lookup_fullname(_nc_curr_token.tk_name);
440                     }
441                 }
442             }
443 #if NCURSES_XNAMES
444             /*
445              * If we have extended-names active, we will automatically
446              * define a name based on its context.
447              */
448             if (entry_ptr == NOTFOUND
449                 && _nc_user_definable) {
450                 if (expected_type(_nc_curr_token.tk_name, token_type, silent)) {
451                     if ((entry_ptr = _nc_extend_names(entryp,
452                                                       _nc_curr_token.tk_name,
453                                                       token_type)) != 0) {
454                         if (_nc_tracing >= DEBUG_LEVEL(1)) {
455                             _nc_warning("extended capability '%s'",
456                                         _nc_curr_token.tk_name);
457                         }
458                     }
459                 } else {
460                     /* ignore it: we have already printed error message */
461                     continue;
462                 }
463             }
464 #endif /* NCURSES_XNAMES */
465
466             /* can't find this cap name, not even as an alias */
467             if (entry_ptr == NOTFOUND) {
468                 if (!silent)
469                     _nc_warning("unknown capability '%s'",
470                                 _nc_curr_token.tk_name);
471                 continue;
472             }
473
474             /* deal with bad type/value combinations. */
475             if (token_type == CANCEL) {
476                 /*
477                  * Prefer terminfo in this (long-obsolete) ambiguity:
478                  */
479                 if (!strcmp("ma", _nc_curr_token.tk_name)) {
480                     entry_ptr = _nc_find_type_entry("ma", NUMBER,
481                                                     _nc_syntax != 0);
482                     assert(entry_ptr != 0);
483                 }
484             } else if (entry_ptr->nte_type != token_type) {
485                 /*
486                  * Nasty special cases here handle situations in which type
487                  * information can resolve name clashes.  Normal lookup
488                  * finds the last instance in the capability table of a
489                  * given name, regardless of type.  find_type_entry looks
490                  * for a first matching instance with given type.  So as
491                  * long as all ambiguous names occur in pairs of distinct
492                  * type, this will do the job.
493                  */
494
495                 if (token_type == NUMBER
496                     && !strcmp("ma", _nc_curr_token.tk_name)) {
497                     /* tell max_attributes from arrow_key_map */
498                     entry_ptr = _nc_find_type_entry("ma", NUMBER,
499                                                     _nc_syntax != 0);
500                     assert(entry_ptr != 0);
501
502                 } else if (token_type == STRING
503                            && !strcmp("MT", _nc_curr_token.tk_name)) {
504                     /* map terminfo's string MT to MT */
505                     entry_ptr = _nc_find_type_entry("MT", STRING,
506                                                     _nc_syntax != 0);
507                     assert(entry_ptr != 0);
508
509                 } else if (token_type == BOOLEAN
510                            && entry_ptr->nte_type == STRING) {
511                     /* treat strings without following "=" as empty strings */
512                     token_type = STRING;
513                 } else {
514                     /* we couldn't recover; skip this token */
515                     if (!silent) {
516                         const char *type_name;
517                         switch (entry_ptr->nte_type) {
518                         case BOOLEAN:
519                             type_name = "boolean";
520                             break;
521                         case STRING:
522                             type_name = "string";
523                             break;
524                         case NUMBER:
525                             type_name = "numeric";
526                             break;
527                         default:
528                             type_name = "unknown";
529                             break;
530                         }
531                         _nc_warning("wrong type used for %s capability '%s'",
532                                     type_name, _nc_curr_token.tk_name);
533                     }
534                     continue;
535                 }
536             }
537
538             /* now we know that the type/value combination is OK */
539             switch (token_type) {
540             case CANCEL:
541                 switch (entry_ptr->nte_type) {
542                 case BOOLEAN:
543                     entryp->tterm.Booleans[entry_ptr->nte_index] = CANCELLED_BOOLEAN;
544                     break;
545
546                 case NUMBER:
547                     entryp->tterm.Numbers[entry_ptr->nte_index] = CANCELLED_NUMERIC;
548                     break;
549
550                 case STRING:
551                     entryp->tterm.Strings[entry_ptr->nte_index] = CANCELLED_STRING;
552                     break;
553                 }
554                 break;
555
556             case BOOLEAN:
557                 entryp->tterm.Booleans[entry_ptr->nte_index] = TRUE;
558                 break;
559
560             case NUMBER:
561 #if !NCURSES_EXT_NUMBERS
562                 if (_nc_curr_token.tk_valnumber > MAX_NUMBER) {
563                     entryp->tterm.Numbers[entry_ptr->nte_index] = MAX_NUMBER;
564                 } else
565 #endif
566                 {
567                     entryp->tterm.Numbers[entry_ptr->nte_index] =
568                         (NCURSES_INT2) _nc_curr_token.tk_valnumber;
569                 }
570                 break;
571
572             case STRING:
573                 ptr = _nc_curr_token.tk_valstring;
574                 if (_nc_syntax == SYN_TERMCAP) {
575                     int n = entry_ptr->nte_index;
576                     ptr = _nc_captoinfo(_nc_curr_token.tk_name,
577                                         ptr,
578                                         (n < (int) SIZEOF(parametrized))
579                                         ? parametrized[n]
580                                         : 0);
581                 }
582                 entryp->tterm.Strings[entry_ptr->nte_index] = _nc_save_str(ptr);
583                 break;
584
585             default:
586                 if (!silent)
587                     _nc_warning("unknown token type");
588                 _nc_panic_mode((char) ((_nc_syntax == SYN_TERMCAP) ? ':' : ','));
589                 continue;
590             }
591         }                       /* end else cur_token.name != "use" */
592       nexttok:
593         continue;               /* cannot have a label w/o statement */
594     }                           /* endwhile (not EOF and not NAMES) */
595
596     _nc_push_token(token_type);
597     _nc_set_type(_nc_first_name(entryp->tterm.term_names));
598
599     /*
600      * Try to deduce as much as possible from extension capabilities
601      * (this includes obsolete BSD capabilities).  Sigh...it would be more
602      * space-efficient to call this after use resolution, but it has
603      * to be done before entry allocation is wrapped up.
604      */
605     if (!literal) {
606         if (_nc_syntax == SYN_TERMCAP) {
607             bool has_base_entry = FALSE;
608
609             /*
610              * Don't insert defaults if this is a `+' entry meant only
611              * for inclusion in other entries (not sure termcap ever
612              * had these, actually).
613              */
614             if (strchr(entryp->tterm.term_names, '+')) {
615                 has_base_entry = TRUE;
616             } else {
617                 unsigned i;
618                 /*
619                  * Otherwise, look for a base entry that will already
620                  * have picked up defaults via translation.
621                  */
622                 for (i = 0; i < entryp->nuses; i++) {
623                     if (entryp->uses[i].name != 0
624                         && !strchr(entryp->uses[i].name, '+'))
625                         has_base_entry = TRUE;
626                 }
627             }
628
629             postprocess_termcap(&entryp->tterm, has_base_entry);
630         } else
631             postprocess_terminfo(&entryp->tterm);
632     }
633     _nc_wrap_entry(entryp, FALSE);
634
635     returnDB(OK);
636 }
637
638 NCURSES_EXPORT(int)
639 _nc_capcmp(const char *s, const char *t)
640 /* compare two string capabilities, stripping out padding */
641 {
642     bool ok_s = VALID_STRING(s);
643     bool ok_t = VALID_STRING(t);
644
645     if (ok_s && ok_t) {
646         for (;;) {
647             if (s[0] == '$' && s[1] == '<') {
648                 for (s += 2;; s++) {
649                     if (!(isdigit(UChar(*s))
650                           || *s == '.'
651                           || *s == '*'
652                           || *s == '/'
653                           || *s == '>')) {
654                         break;
655                     }
656                 }
657             }
658
659             if (t[0] == '$' && t[1] == '<') {
660                 for (t += 2;; t++) {
661                     if (!(isdigit(UChar(*t))
662                           || *t == '.'
663                           || *t == '*'
664                           || *t == '/'
665                           || *t == '>')) {
666                         break;
667                     }
668                 }
669             }
670
671             /* we've now pushed s and t past any padding they pointed at */
672
673             if (*s == '\0' && *t == '\0')
674                 return (0);
675
676             if (*s != *t)
677                 return (*t - *s);
678
679             /* else *s == *t but one is not NUL, so continue */
680             s++, t++;
681         }
682     } else if (ok_s || ok_t) {
683         return 1;
684     }
685     return 0;
686 }
687
688 static void
689 append_acs0(string_desc * dst, int code, char *src, size_t off)
690 {
691     if (src != 0 && off < strlen(src)) {
692         char temp[3];
693         temp[0] = (char) code;
694         temp[1] = src[off];
695         temp[2] = 0;
696         _nc_safe_strcat(dst, temp);
697     }
698 }
699
700 static void
701 append_acs(string_desc * dst, int code, char *src)
702 {
703     if (VALID_STRING(src) && strlen(src) == 1) {
704         append_acs0(dst, code, src, 0);
705     }
706 }
707
708 /*
709  * The ko capability, if present, consists of a comma-separated capability
710  * list.  For each capability, we may assume there is a keycap that sends the
711  * string which is the value of that capability.
712  */
713 #define DATA(from, to) { { from }, { to } }
714 typedef struct {
715     const char from[3];
716     const char to[6];
717 } assoc;
718 static assoc const ko_xlate[] =
719 {
720     DATA("al", "kil1"),         /* insert line key  -> KEY_IL    */
721     DATA("bt", "kcbt"),         /* back tab         -> KEY_BTAB  */
722     DATA("cd", "ked"),          /* clear-to-eos key -> KEY_EOL   */
723     DATA("ce", "kel"),          /* clear-to-eol key -> KEY_EOS   */
724     DATA("cl", "kclr"),         /* clear key        -> KEY_CLEAR */
725     DATA("ct", "tbc"),          /* clear all tabs   -> KEY_CATAB */
726     DATA("dc", "kdch1"),        /* delete char      -> KEY_DC    */
727     DATA("dl", "kdl1"),         /* delete line      -> KEY_DL    */
728     DATA("do", "kcud1"),        /* down key         -> KEY_DOWN  */
729     DATA("ei", "krmir"),        /* exit insert key  -> KEY_EIC   */
730     DATA("ho", "khome"),        /* home key         -> KEY_HOME  */
731     DATA("ic", "kich1"),        /* insert char key  -> KEY_IC    */
732     DATA("im", "kIC"),          /* insert-mode key  -> KEY_SIC   */
733     DATA("le", "kcub1"),        /* le key           -> KEY_LEFT  */
734     DATA("nd", "kcuf1"),        /* nd key           -> KEY_RIGHT */
735     DATA("nl", "kent"),         /* new line key     -> KEY_ENTER */
736     DATA("st", "khts"),         /* set-tab key      -> KEY_STAB  */
737     DATA("ta", ""),
738     DATA("up", "kcuu1"),        /* up-arrow key     -> KEY_UP    */
739 };
740
741 /*
742  * This routine fills in string caps that either had defaults under
743  * termcap or can be manufactured from obsolete termcap capabilities.
744  * It was lifted from Ross Ridge's mytinfo package.
745  */
746
747 static const char C_CR[] = "\r";
748 static const char C_LF[] = "\n";
749 static const char C_BS[] = "\b";
750 static const char C_HT[] = "\t";
751
752 /*
753  * This bit of legerdemain turns all the terminfo variable names into
754  * references to locations in the arrays Booleans, Numbers, and Strings ---
755  * precisely what's needed.
756  */
757
758 #undef CUR
759 #define CUR tp->
760
761 static void
762 postprocess_termcap(TERMTYPE2 *tp, bool has_base)
763 {
764     char buf[MAX_LINE * 2 + 2];
765     string_desc result;
766
767     TR(TRACE_DATABASE,
768        (T_CALLED("postprocess_termcap(tp=%p, has_base=%d)"),
769         (void *) tp, has_base));
770
771     /*
772      * TERMCAP DEFAULTS AND OBSOLETE-CAPABILITY TRANSLATIONS
773      *
774      * This first part of the code is the functional inverse of the
775      * fragment in capdefaults.c.
776      * ----------------------------------------------------------------------
777      */
778
779     /* if there was a tc entry, assume we picked up defaults via that */
780     if (!has_base) {
781         if (WANTED(init_3string) && PRESENT(termcap_init2))
782             init_3string = _nc_save_str(termcap_init2);
783
784         if (WANTED(reset_2string) && PRESENT(termcap_reset))
785             reset_2string = _nc_save_str(termcap_reset);
786
787         if (WANTED(carriage_return)) {
788             if (carriage_return_delay > 0) {
789                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
790                             "%s$<%d>", C_CR, carriage_return_delay);
791                 carriage_return = _nc_save_str(buf);
792             } else
793                 carriage_return = _nc_save_str(C_CR);
794         }
795         if (WANTED(cursor_left)) {
796             if (backspace_delay > 0) {
797                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
798                             "%s$<%d>", C_BS, backspace_delay);
799                 cursor_left = _nc_save_str(buf);
800             } else if (backspaces_with_bs == 1)
801                 cursor_left = _nc_save_str(C_BS);
802             else if (PRESENT(backspace_if_not_bs))
803                 cursor_left = backspace_if_not_bs;
804         }
805         /* vi doesn't use "do", but it does seem to use nl (or '\n') instead */
806         if (WANTED(cursor_down)) {
807             if (PRESENT(linefeed_if_not_lf))
808                 cursor_down = linefeed_if_not_lf;
809             else if (linefeed_is_newline != 1) {
810                 if (new_line_delay > 0) {
811                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
812                                 "%s$<%d>", C_LF, new_line_delay);
813                     cursor_down = _nc_save_str(buf);
814                 } else
815                     cursor_down = _nc_save_str(C_LF);
816             }
817         }
818         if (WANTED(scroll_forward) && crt_no_scrolling != 1) {
819             if (PRESENT(linefeed_if_not_lf))
820                 cursor_down = linefeed_if_not_lf;
821             else if (linefeed_is_newline != 1) {
822                 if (new_line_delay > 0) {
823                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
824                                 "%s$<%d>", C_LF, new_line_delay);
825                     scroll_forward = _nc_save_str(buf);
826                 } else
827                     scroll_forward = _nc_save_str(C_LF);
828             }
829         }
830         if (WANTED(newline)) {
831             if (linefeed_is_newline == 1) {
832                 if (new_line_delay > 0) {
833                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
834                                 "%s$<%d>", C_LF, new_line_delay);
835                     newline = _nc_save_str(buf);
836                 } else
837                     newline = _nc_save_str(C_LF);
838             } else if (PRESENT(carriage_return) && PRESENT(scroll_forward)) {
839                 _nc_str_init(&result, buf, sizeof(buf));
840                 if (_nc_safe_strcat(&result, carriage_return)
841                     && _nc_safe_strcat(&result, scroll_forward))
842                     newline = _nc_save_str(buf);
843             } else if (PRESENT(carriage_return) && PRESENT(cursor_down)) {
844                 _nc_str_init(&result, buf, sizeof(buf));
845                 if (_nc_safe_strcat(&result, carriage_return)
846                     && _nc_safe_strcat(&result, cursor_down))
847                     newline = _nc_save_str(buf);
848             }
849         }
850     }
851
852     /*
853      * Inverse of capdefaults.c code ends here.
854      * ----------------------------------------------------------------------
855      *
856      * TERMCAP-TO TERMINFO MAPPINGS FOR SOURCE TRANSLATION
857      *
858      * These translations will *not* be inverted by tgetent().
859      */
860
861     if (!has_base) {
862         /*
863          * We wait until now to decide if we've got a working cr because even
864          * one that doesn't work can be used for newline. Unfortunately the
865          * space allocated for it is wasted.
866          */
867         if (return_does_clr_eol == 1 || no_correctly_working_cr == 1)
868             carriage_return = ABSENT_STRING;
869
870         /*
871          * Supposedly most termcap entries have ta now and '\t' is no longer a
872          * default, but it doesn't seem to be true...
873          */
874         if (WANTED(tab)) {
875             if (horizontal_tab_delay > 0) {
876                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
877                             "%s$<%d>", C_HT, horizontal_tab_delay);
878                 tab = _nc_save_str(buf);
879             } else
880                 tab = _nc_save_str(C_HT);
881         }
882         if (init_tabs == ABSENT_NUMERIC && has_hardware_tabs == TRUE)
883             init_tabs = 8;
884
885         /*
886          * Assume we can beep with ^G unless we're given bl@.
887          */
888         if (WANTED(bell))
889             bell = _nc_save_str("\007");
890     }
891
892     /*
893      * Translate the old termcap :pt: capability to it#8 + ht=\t
894      */
895     if (has_hardware_tabs == TRUE) {
896         if (init_tabs != 8 && init_tabs != ABSENT_NUMERIC)
897             _nc_warning("hardware tabs with a width other than 8: %d", init_tabs);
898         else {
899             if (PRESENT(tab) && _nc_capcmp(tab, C_HT))
900                 _nc_warning("hardware tabs with a non-^I tab string %s",
901                             _nc_visbuf(tab));
902             else {
903                 if (WANTED(tab))
904                     tab = _nc_save_str(C_HT);
905                 init_tabs = 8;
906             }
907         }
908     }
909     /*
910      * Now translate the ko capability, if there is one.  This
911      * isn't from mytinfo...
912      */
913     if (PRESENT(other_non_function_keys)) {
914         char *base;
915         char *bp, *cp, *dp;
916         struct name_table_entry const *from_ptr;
917         struct name_table_entry const *to_ptr;
918         char buf2[MAX_TERMINFO_LENGTH];
919         bool foundim;
920
921         /* we're going to use this for a special case later */
922         dp = strchr(other_non_function_keys, 'i');
923         foundim = (dp != 0) && (dp[1] == 'm');
924
925         /* look at each comma-separated capability in the ko string... */
926         for (base = other_non_function_keys;
927              (cp = strchr(base, ',')) != 0;
928              base = cp + 1) {
929             size_t len = (unsigned) (cp - base);
930             size_t n;
931             assoc const *ap = 0;
932
933             for (n = 0; n < SIZEOF(ko_xlate); ++n) {
934                 if (len == strlen(ko_xlate[n].from)
935                     && strncmp(ko_xlate[n].from, base, len) == 0) {
936                     ap = ko_xlate + n;
937                     break;
938                 }
939             }
940             if (ap == 0) {
941                 _nc_warning("unknown capability `%.*s' in ko string",
942                             (int) len, base);
943                 continue;
944             } else if (ap->to[0] == '\0')       /* ignore it */
945                 continue;
946
947             /* now we know we found a match in ko_table, so... */
948
949             from_ptr = _nc_find_entry(ap->from, _nc_get_hash_table(TRUE));
950             to_ptr = _nc_find_entry(ap->to, _nc_get_hash_table(FALSE));
951
952             if (!from_ptr || !to_ptr)   /* should never happen! */
953                 _nc_err_abort("ko translation table is invalid, I give up");
954
955             if (WANTED(tp->Strings[from_ptr->nte_index])) {
956                 _nc_warning("no value for ko capability %s", ap->from);
957                 continue;
958             }
959
960             if (tp->Strings[to_ptr->nte_index]) {
961                 const char *s = tp->Strings[from_ptr->nte_index];
962                 const char *t = tp->Strings[to_ptr->nte_index];
963                 /* There's no point in warning about it if it is the same
964                  * string; that's just an inefficiency.
965                  */
966                 if (VALID_STRING(s) && VALID_STRING(t) && strcmp(s, t) != 0)
967                     _nc_warning("%s (%s) already has an explicit value %s, ignoring ko",
968                                 ap->to, ap->from, t);
969                 continue;
970             }
971
972             /*
973              * The magic moment -- copy the mapped key string over,
974              * stripping out padding.
975              */
976             bp = tp->Strings[from_ptr->nte_index];
977             if (VALID_STRING(bp)) {
978                 for (dp = buf2; *bp; bp++) {
979                     if (bp[0] == '$' && bp[1] == '<') {
980                         while (*bp && *bp != '>') {
981                             ++bp;
982                         }
983                     } else
984                         *dp++ = *bp;
985                 }
986                 *dp = '\0';
987
988                 tp->Strings[to_ptr->nte_index] = _nc_save_str(buf2);
989             } else {
990                 tp->Strings[to_ptr->nte_index] = bp;
991             }
992         }
993
994         /*
995          * Note: ko=im and ko=ic both want to grab the `Insert'
996          * keycap.  There's a kich1 but no ksmir, so the ic capability
997          * got mapped to kich1 and im to kIC to avoid a collision.
998          * If the description has im but not ic, hack kIC back to kich1.
999          */
1000         if (foundim && WANTED(key_ic) && PRESENT(key_sic)) {
1001             key_ic = key_sic;
1002             key_sic = ABSENT_STRING;
1003         }
1004     }
1005
1006     if (!has_base) {
1007         if (!hard_copy) {
1008             if (WANTED(key_backspace))
1009                 key_backspace = _nc_save_str(C_BS);
1010             if (WANTED(key_left))
1011                 key_left = _nc_save_str(C_BS);
1012             if (WANTED(key_down))
1013                 key_down = _nc_save_str(C_LF);
1014         }
1015     }
1016
1017     /*
1018      * Translate XENIX forms characters.
1019      */
1020     if (PRESENT(acs_ulcorner) ||
1021         PRESENT(acs_llcorner) ||
1022         PRESENT(acs_urcorner) ||
1023         PRESENT(acs_lrcorner) ||
1024         PRESENT(acs_ltee) ||
1025         PRESENT(acs_rtee) ||
1026         PRESENT(acs_btee) ||
1027         PRESENT(acs_ttee) ||
1028         PRESENT(acs_hline) ||
1029         PRESENT(acs_vline) ||
1030         PRESENT(acs_plus)) {
1031         char buf2[MAX_TERMCAP_LENGTH];
1032
1033         _nc_str_init(&result, buf2, sizeof(buf2));
1034         _nc_safe_strcat(&result, acs_chars);
1035
1036         append_acs(&result, 'j', acs_lrcorner);
1037         append_acs(&result, 'k', acs_urcorner);
1038         append_acs(&result, 'l', acs_ulcorner);
1039         append_acs(&result, 'm', acs_llcorner);
1040         append_acs(&result, 'n', acs_plus);
1041         append_acs(&result, 'q', acs_hline);
1042         append_acs(&result, 't', acs_ltee);
1043         append_acs(&result, 'u', acs_rtee);
1044         append_acs(&result, 'v', acs_btee);
1045         append_acs(&result, 'w', acs_ttee);
1046         append_acs(&result, 'x', acs_vline);
1047
1048         if (buf2[0]) {
1049             acs_chars = _nc_save_str(buf2);
1050             _nc_warning("acsc string synthesized from XENIX capabilities");
1051         }
1052     } else if (acs_chars == ABSENT_STRING
1053                && PRESENT(enter_alt_charset_mode)
1054                && PRESENT(exit_alt_charset_mode)) {
1055         acs_chars = _nc_save_str(VT_ACSC);
1056     }
1057     returnVoidDB;
1058 }
1059
1060 static void
1061 postprocess_terminfo(TERMTYPE2 *tp)
1062 {
1063     TR(TRACE_DATABASE,
1064        (T_CALLED("postprocess_terminfo(tp=%p)"),
1065         (void *) tp));
1066
1067     /*
1068      * TERMINFO-TO-TERMINFO MAPPINGS FOR SOURCE TRANSLATION
1069      * ----------------------------------------------------------------------
1070      */
1071
1072     /*
1073      * Translate AIX forms characters.
1074      */
1075     if (PRESENT(box_chars_1)) {
1076         char buf2[MAX_TERMCAP_LENGTH];
1077         string_desc result;
1078
1079         _nc_str_init(&result, buf2, sizeof(buf2));
1080         _nc_safe_strcat(&result, acs_chars);
1081
1082         append_acs0(&result, 'l', box_chars_1, 0);      /* ACS_ULCORNER */
1083         append_acs0(&result, 'q', box_chars_1, 1);      /* ACS_HLINE */
1084         append_acs0(&result, 'k', box_chars_1, 2);      /* ACS_URCORNER */
1085         append_acs0(&result, 'x', box_chars_1, 3);      /* ACS_VLINE */
1086         append_acs0(&result, 'j', box_chars_1, 4);      /* ACS_LRCORNER */
1087         append_acs0(&result, 'm', box_chars_1, 5);      /* ACS_LLCORNER */
1088         append_acs0(&result, 'w', box_chars_1, 6);      /* ACS_TTEE */
1089         append_acs0(&result, 'u', box_chars_1, 7);      /* ACS_RTEE */
1090         append_acs0(&result, 'v', box_chars_1, 8);      /* ACS_BTEE */
1091         append_acs0(&result, 't', box_chars_1, 9);      /* ACS_LTEE */
1092         append_acs0(&result, 'n', box_chars_1, 10);     /* ACS_PLUS */
1093
1094         if (buf2[0]) {
1095             acs_chars = _nc_save_str(buf2);
1096             _nc_warning("acsc string synthesized from AIX capabilities");
1097             box_chars_1 = ABSENT_STRING;
1098         }
1099     }
1100     /*
1101      * ----------------------------------------------------------------------
1102      */
1103     returnVoidDB;
1104 }
1105
1106 /*
1107  * Do a linear search through the terminfo tables to find a given full-name.
1108  * We don't expect to do this often, so there's no hashing function.
1109  *
1110  * In effect, this scans through the 3 lists of full-names, and looks them
1111  * up in _nc_info_table, which is organized so that the nte_index fields are
1112  * sorted, but the nte_type fields are not necessarily grouped together.
1113  */
1114 static struct name_table_entry const *
1115 lookup_fullname(const char *find)
1116 {
1117     int state = -1;
1118
1119     for (;;) {
1120         int count = 0;
1121         NCURSES_CONST char *const *names;
1122
1123         switch (++state) {
1124         case BOOLEAN:
1125             names = boolfnames;
1126             break;
1127         case STRING:
1128             names = strfnames;
1129             break;
1130         case NUMBER:
1131             names = numfnames;
1132             break;
1133         default:
1134             return NOTFOUND;
1135         }
1136
1137         for (count = 0; names[count] != 0; count++) {
1138             if (!strcmp(names[count], find)) {
1139                 struct name_table_entry const *entry_ptr = _nc_get_table(FALSE);
1140                 while (entry_ptr->nte_type != state
1141                        || entry_ptr->nte_index != count)
1142                     entry_ptr++;
1143                 return entry_ptr;
1144             }
1145         }
1146     }
1147 }
1148
1149 /* parse_entry.c ends here */