xref: /openbsd-src/lib/libcurses/tinfo/comp_parse.c (revision 91421ef511f3d137bc8cbea1d63f2c50663d7a1f)
1 /*	$OpenBSD: comp_parse.c,v 1.8 2000/10/08 22:47:00 millert Exp $	*/
2 
3 /****************************************************************************
4  * Copyright (c) 1998,1999,2000 Free Software Foundation, Inc.              *
5  *                                                                          *
6  * Permission is hereby granted, free of charge, to any person obtaining a  *
7  * copy of this software and associated documentation files (the            *
8  * "Software"), to deal in the Software without restriction, including      *
9  * without limitation the rights to use, copy, modify, merge, publish,      *
10  * distribute, distribute with modifications, sublicense, and/or sell       *
11  * copies of the Software, and to permit persons to whom the Software is    *
12  * furnished to do so, subject to the following conditions:                 *
13  *                                                                          *
14  * The above copyright notice and this permission notice shall be included  *
15  * in all copies or substantial portions of the Software.                   *
16  *                                                                          *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
20  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
23  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
24  *                                                                          *
25  * Except as contained in this notice, the name(s) of the above copyright   *
26  * holders shall not be used in advertising or otherwise to promote the     *
27  * sale, use or other dealings in this Software without prior written       *
28  * authorization.                                                           *
29  ****************************************************************************/
30 
31 /****************************************************************************
32  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
33  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
34  ****************************************************************************/
35 
36 /*
37  *	comp_parse.c -- parser driver loop and use handling.
38  *
39  *	_nc_read_entry_source(FILE *, literal, bool, bool (*hook)())
40  *	_nc_resolve_uses(void)
41  *	_nc_free_entries(void)
42  *
43  *	Use this code by calling _nc_read_entry_source() on as many source
44  *	files as you like (either terminfo or termcap syntax).  If you
45  *	want use-resolution, call _nc_resolve_uses().  To free the list
46  *	storage, do _nc_free_entries().
47  *
48  */
49 
50 #include <curses.priv.h>
51 
52 #include <ctype.h>
53 
54 #include <tic.h>
55 #include <term_entry.h>
56 
57 MODULE_ID("$From: comp_parse.c,v 1.41 2000/10/03 09:53:49 tom Exp $")
58 
59 static void sanity_check(TERMTYPE *);
60 void (*_nc_check_termtype) (TERMTYPE *) = sanity_check;
61 
62 /****************************************************************************
63  *
64  * Entry queue handling
65  *
66  ****************************************************************************/
67 /*
68  *  The entry list is a doubly linked list with NULLs terminating the lists:
69  *
70  *	  ---------   ---------   ---------
71  *	  |       |   |       |   |       |   offset
72  *        |-------|   |-------|   |-------|
73  *	  |   ----+-->|   ----+-->|  NULL |   next
74  *	  |-------|   |-------|   |-------|
75  *	  |  NULL |<--+----   |<--+----   |   last
76  *	  ---------   ---------   ---------
77  *	      ^                       ^
78  *	      |                       |
79  *	      |                       |
80  *	   _nc_head                _nc_tail
81  */
82 
83 ENTRY *_nc_head = 0, *_nc_tail = 0;
84 
85 static void
86 enqueue(ENTRY * ep)
87 /* add an entry to the in-core list */
88 {
89     ENTRY *newp = _nc_copy_entry(ep);
90 
91     if (newp == 0)
92 	_nc_err_abort("Out of memory");
93 
94     newp->last = _nc_tail;
95     _nc_tail = newp;
96 
97     newp->next = 0;
98     if (newp->last)
99 	newp->last->next = newp;
100 }
101 
102 void
103 _nc_free_entries(ENTRY * headp)
104 /* free the allocated storage consumed by list entries */
105 {
106     ENTRY *ep, *next;
107 
108     for (ep = headp; ep; ep = next) {
109 	/*
110 	 * This conditional lets us disconnect storage from the list.
111 	 * To do this, copy an entry out of the list, then null out
112 	 * the string-table member in the original and any use entries
113 	 * it references.
114 	 */
115 	FreeIfNeeded(ep->tterm.str_table);
116 
117 	next = ep->next;
118 
119 	free(ep);
120 	if (ep == _nc_head)
121 	    _nc_head = 0;
122 	if (ep == _nc_tail)
123 	    _nc_tail = 0;
124     }
125 }
126 
127 static char *
128 force_bar(char *dst, char *src, size_t siz)
129 {
130     if (strchr(src, '|') == 0) {
131 	size_t len;
132 
133 	len = strlcpy(dst, src, siz);
134 	if (len >= siz - 2)
135 	    len = siz - 2;;
136 	(void) strcpy(dst + len, "|");
137 	src = dst;
138     }
139     return src;
140 }
141 
142 bool
143 _nc_entry_match(char *n1, char *n2)
144 /* do any of the aliases in a pair of terminal names match? */
145 {
146     char *pstart, *qstart, *pend, *qend;
147     char nc1[MAX_NAME_SIZE + 2], nc2[MAX_NAME_SIZE + 2];
148 
149     n1 = force_bar(nc1, n1, sizeof(nc1));
150     n2 = force_bar(nc2, n2, sizeof(nc2));
151 
152     for (pstart = n1; (pend = strchr(pstart, '|')); pstart = pend + 1)
153 	for (qstart = n2; (qend = strchr(qstart, '|')); qstart = qend + 1)
154 	    if ((pend - pstart == qend - qstart)
155 		&& memcmp(pstart, qstart, (size_t) (pend - pstart)) == 0)
156 		return (TRUE);
157 
158     return (FALSE);
159 }
160 
161 /****************************************************************************
162  *
163  * Entry compiler and resolution logic
164  *
165  ****************************************************************************/
166 
167 void
168 _nc_read_entry_source(FILE * fp, char *buf,
169     int literal, bool silent,
170     bool(*hook) (ENTRY *))
171 /* slurp all entries in the given file into core */
172 {
173     ENTRY thisentry;
174     bool oldsuppress = _nc_suppress_warnings;
175     int immediate = 0;
176 
177     if (silent)
178 	_nc_suppress_warnings = TRUE;	/* shut the lexer up, too */
179 
180     _nc_reset_input(fp, buf);
181     for (;;) {
182 	memset(&thisentry, 0, sizeof(thisentry));
183 	if (_nc_parse_entry(&thisentry, literal, silent) == ERR)
184 	    break;
185 	if (!isalnum(thisentry.tterm.term_names[0]))
186 	    _nc_err_abort("terminal names must start with letter or digit");
187 
188 	/*
189 	 * This can be used for immediate compilation of entries with no
190 	 * use references to disk, so as to avoid chewing up a lot of
191 	 * core when the resolution code could fetch entries off disk.
192 	 */
193 	if (hook != NULLHOOK && (*hook) (&thisentry))
194 	    immediate++;
195 	else
196 	    enqueue(&thisentry);
197     }
198 
199     if (_nc_tail) {
200 	/* set up the head pointer */
201 	for (_nc_head = _nc_tail; _nc_head->last; _nc_head = _nc_head->last)
202 	    continue;
203 
204 	DEBUG(1, ("head = %s", _nc_head->tterm.term_names));
205 	DEBUG(1, ("tail = %s", _nc_tail->tterm.term_names));
206     }
207 #ifdef TRACE
208     else if (!immediate)
209 	DEBUG(1, ("no entries parsed"));
210 #endif
211 
212     _nc_suppress_warnings = oldsuppress;
213 }
214 
215 int
216 _nc_resolve_uses(bool fullresolve)
217 /* try to resolve all use capabilities */
218 {
219     ENTRY *qp, *rp, *lastread = 0;
220     bool keepgoing;
221     int i, j, unresolved, total_unresolved, multiples;
222 
223     DEBUG(2, ("RESOLUTION BEGINNING"));
224 
225     /*
226      * Check for multiple occurrences of the same name.
227      */
228     multiples = 0;
229     for_entry_list(qp) {
230 	int matchcount = 0;
231 
232 	for_entry_list(rp)
233 	    if (qp > rp
234 	    && _nc_entry_match(qp->tterm.term_names, rp->tterm.term_names)) {
235 	    matchcount++;
236 	    if (matchcount == 1) {
237 		(void) fprintf(stderr, "Name collision between %s",
238 		    _nc_first_name(qp->tterm.term_names));
239 		multiples++;
240 	    }
241 	    if (matchcount >= 1)
242 		(void) fprintf(stderr, " %s", _nc_first_name(rp->tterm.term_names));
243 	}
244 	if (matchcount >= 1)
245 	    (void) putc('\n', stderr);
246     }
247     if (multiples > 0)
248 	return (FALSE);
249 
250     DEBUG(2, ("NO MULTIPLE NAME OCCURRENCES"));
251 
252     /*
253      * First resolution stage: compute link pointers corresponding to names.
254      */
255     total_unresolved = 0;
256     _nc_curr_col = -1;
257     for_entry_list(qp) {
258 	unresolved = 0;
259 	for (i = 0; i < qp->nuses; i++) {
260 	    bool foundit;
261 	    char *child = _nc_first_name(qp->tterm.term_names);
262 	    char *lookfor = qp->uses[i].name;
263 	    long lookline = qp->uses[i].line;
264 
265 	    foundit = FALSE;
266 
267 	    _nc_set_type(child);
268 
269 	    /* first, try to resolve from in-core records */
270 	    for_entry_list(rp)
271 		if (rp != qp
272 		&& _nc_name_match(rp->tterm.term_names, lookfor, "|")) {
273 		DEBUG(2, ("%s: resolving use=%s (in core)",
274 			child, lookfor));
275 
276 		qp->uses[i].link = rp;
277 		foundit = TRUE;
278 	    }
279 
280 	    /* if that didn't work, try to merge in a compiled entry */
281 	    if (!foundit) {
282 		TERMTYPE thisterm;
283 		char filename[PATH_MAX];
284 
285 		memset(&thisterm, 0, sizeof(thisterm));
286 		if (_nc_read_entry(lookfor, filename, &thisterm) == 1) {
287 		    DEBUG(2, ("%s: resolving use=%s (compiled)",
288 			    child, lookfor));
289 
290 		    rp = typeMalloc(ENTRY, 1);
291 		    if (rp == 0)
292 			_nc_err_abort("Out of memory");
293 		    rp->tterm = thisterm;
294 		    rp->nuses = 0;
295 		    rp->next = lastread;
296 		    lastread = rp;
297 
298 		    qp->uses[i].link = rp;
299 		    foundit = TRUE;
300 		}
301 	    }
302 
303 	    /* no good, mark this one unresolvable and complain */
304 	    if (!foundit) {
305 		unresolved++;
306 		total_unresolved++;
307 
308 		_nc_curr_line = lookline;
309 		_nc_warning("resolution of use=%s failed", lookfor);
310 		qp->uses[i].link = 0;
311 	    }
312 	}
313     }
314     if (total_unresolved) {
315 	/* free entries read in off disk */
316 	_nc_free_entries(lastread);
317 	return (FALSE);
318     }
319 
320     DEBUG(2, ("NAME RESOLUTION COMPLETED OK"));
321 
322     /*
323      * OK, at this point all (char *) references in `name' mwmbers
324      * have been successfully converred to (ENTRY *) pointers in
325      * `link' members.  Time to do the actual merges.
326      */
327     if (fullresolve) {
328 	do {
329 	    TERMTYPE merged;
330 
331 	    keepgoing = FALSE;
332 
333 	    for_entry_list(qp) {
334 		if (qp->nuses > 0) {
335 		    DEBUG(2, ("%s: attempting merge",
336 			    _nc_first_name(qp->tterm.term_names)));
337 		    /*
338 		     * If any of the use entries we're looking for is
339 		     * incomplete, punt.  We'll catch this entry on a
340 		     * subsequent pass.
341 		     */
342 		    for (i = 0; i < qp->nuses; i++)
343 			if (qp->uses[i].link->nuses) {
344 			    DEBUG(2, ("%s: use entry %d unresolved",
345 				    _nc_first_name(qp->tterm.term_names), i));
346 			    goto incomplete;
347 			}
348 
349 		    /*
350 		       * First, make sure there's no garbage in the
351 		       * merge block.  as a side effect, copy into
352 		       * the merged entry the name field and string
353 		       * table pointer.
354 		     */
355 		    _nc_copy_termtype(&merged, &(qp->tterm));
356 
357 		    /*
358 		     * Now merge in each use entry in the proper
359 		     * (reverse) order.
360 		     */
361 		    for (; qp->nuses; qp->nuses--)
362 			_nc_merge_entry(&merged,
363 			    &qp->uses[qp->nuses - 1].link->tterm);
364 
365 		    /*
366 		     * Now merge in the original entry.
367 		     */
368 		    _nc_merge_entry(&merged, &qp->tterm);
369 
370 		    /*
371 		     * Replace the original entry with the merged one.
372 		     */
373 		    FreeIfNeeded(qp->tterm.Booleans);
374 		    FreeIfNeeded(qp->tterm.Numbers);
375 		    FreeIfNeeded(qp->tterm.Strings);
376 		    qp->tterm = merged;
377 
378 		    /*
379 		     * We know every entry is resolvable because name resolution
380 		     * didn't bomb.  So go back for another pass.
381 		     */
382 		    /* FALLTHRU */
383 		  incomplete:
384 		    keepgoing = TRUE;
385 		}
386 	    }
387 	} while
388 	    (keepgoing);
389 
390 	DEBUG(2, ("MERGES COMPLETED OK"));
391 
392 	/*
393 	 * The exit condition of the loop above is such that all entries
394 	 * must now be resolved.  Now handle cancellations.  In a resolved
395 	 * entry there should be no cancellation markers.
396 	 */
397 	for_entry_list(qp) {
398 	    for_each_boolean(j, &(qp->tterm))
399 		if (qp->tterm.Booleans[j] == CANCELLED_BOOLEAN)
400 		qp->tterm.Booleans[j] = ABSENT_BOOLEAN;
401 	    for_each_number(j, &(qp->tterm))
402 		if (qp->tterm.Numbers[j] == CANCELLED_NUMERIC)
403 		qp->tterm.Numbers[j] = ABSENT_NUMERIC;
404 	    for_each_string(j, &(qp->tterm))
405 		if (qp->tterm.Strings[j] == CANCELLED_STRING)
406 		qp->tterm.Strings[j] = ABSENT_STRING;
407 	}
408     }
409 
410     /*
411      * We'd like to free entries read in off disk at this point, but can't.
412      * The merge_entry() code doesn't copy the strings in the use entries,
413      * it just aliases them.  If this ever changes, do a
414      * free_entries(lastread) here.
415      */
416 
417     DEBUG(2, ("RESOLUTION FINISHED"));
418 
419     if (fullresolve)
420 	if (_nc_check_termtype != 0) {
421 	    _nc_curr_col = -1;
422 	    for_entry_list(qp) {
423 		_nc_curr_line = qp->startline;
424 		_nc_set_type(_nc_first_name(qp->tterm.term_names));
425 		_nc_check_termtype(&qp->tterm);
426 	    }
427 	    DEBUG(2, ("SANITY CHECK FINISHED"));
428 	}
429 
430     return (TRUE);
431 }
432 
433 /*
434  * This bit of legerdemain turns all the terminfo variable names into
435  * references to locations in the arrays Booleans, Numbers, and Strings ---
436  * precisely what's needed.
437  */
438 
439 #undef CUR
440 #define CUR tp->
441 
442 static void
443 sanity_check(TERMTYPE * tp)
444 {
445     if (!PRESENT(exit_attribute_mode)) {
446 #ifdef __UNUSED__		/* this casts too wide a net */
447 	bool terminal_entry = !strchr(tp->term_names, '+');
448 	if (terminal_entry &&
449 	    (PRESENT(set_attributes)
450 		|| PRESENT(enter_standout_mode)
451 		|| PRESENT(enter_underline_mode)
452 		|| PRESENT(enter_blink_mode)
453 		|| PRESENT(enter_bold_mode)
454 		|| PRESENT(enter_dim_mode)
455 		|| PRESENT(enter_secure_mode)
456 		|| PRESENT(enter_protected_mode)
457 		|| PRESENT(enter_reverse_mode)))
458 	    _nc_warning("no exit_attribute_mode");
459 #endif /* __UNUSED__ */
460 	PAIRED(enter_standout_mode, exit_standout_mode)
461 	    PAIRED(enter_underline_mode, exit_underline_mode)
462     }
463 
464     /* listed in structure-member order of first argument */
465     PAIRED(enter_alt_charset_mode, exit_alt_charset_mode);
466     ANDMISSING(enter_alt_charset_mode, acs_chars);
467     ANDMISSING(exit_alt_charset_mode, acs_chars);
468     ANDMISSING(enter_blink_mode, exit_attribute_mode);
469     ANDMISSING(enter_bold_mode, exit_attribute_mode);
470     PAIRED(exit_ca_mode, enter_ca_mode);
471     PAIRED(enter_delete_mode, exit_delete_mode);
472     ANDMISSING(enter_dim_mode, exit_attribute_mode);
473     PAIRED(enter_insert_mode, exit_insert_mode);
474     ANDMISSING(enter_secure_mode, exit_attribute_mode);
475     ANDMISSING(enter_protected_mode, exit_attribute_mode);
476     ANDMISSING(enter_reverse_mode, exit_attribute_mode);
477     PAIRED(from_status_line, to_status_line);
478     PAIRED(meta_off, meta_on);
479 
480     PAIRED(prtr_on, prtr_off);
481     PAIRED(save_cursor, restore_cursor);
482     PAIRED(enter_xon_mode, exit_xon_mode);
483     PAIRED(enter_am_mode, exit_am_mode);
484     ANDMISSING(label_off, label_on);
485     PAIRED(display_clock, remove_clock);
486     ANDMISSING(set_color_pair, initialize_pair);
487 }
488