History

CWEB — Release 3.2, 1994-08-02.

The CWEB System of Structured Documentation.

Andreas Scherer committed 15 years ago

Commit 6f710fcNo parent (first commit)40 files · +18187 −0Browse files

Unified · Split

40 files
  1. Makefile +178 −0
  2. README +92 −0
  3. comm-amiga.ch +17 −0
  4. comm-bs.ch +229 −0
  5. comm-man.ch +22 −0
  6. comm-pc.ch +33 −0
  7. comm-vms.ch +81 −0
  8. common.c +1239 −0
  9. common.h +192 −0
  10. common.w +1414 −0
  11. ctang-bs.ch +202 −0
  12. ctang-man.ch +22 −0
  13. ctang-pc.ch +24 −0
  14. ctang-vms.ch +35 −0
  15. ctangle.c +1551 −0
  16. ctangle.w +1531 −0
  17. cweav-bs.ch +274 −0
  18. cweav-man.ch +22 −0
  19. cweav-pc.ch +39 −0
  20. cweav-vms.ch +37 −0
  21. cweave.w +4477 −0
  22. cweb.1 +98 −0
  23. cweb.el +222 −0
  24. cwebmac.tex +331 −0
  25. cwebman.tex +1610 −0
  26. examples/Makefile +57 −0
  27. examples/README +55 −0
  28. examples/extex.w +362 −0
  29. examples/kspell.el +223 −0
  30. examples/oemacs.el +176 −0
  31. examples/oemacs.w +896 −0
  32. examples/treeprint.w +247 −0
  33. examples/wc.w +239 −0
  34. examples/wmerg-pc.ch +21 −0
  35. examples/wmerge.w +709 −0
  36. examples/wordtest.w +539 −0
  37. examples/xlib_types.w +92 −0
  38. examples/xview_types.w +274 −0
  39. makefile.bs +60 −0
  40. prod.w +265 −0
Makefile+178−0
@@ -0,0 +1,178 @@
1# This file is part of CWEB.
2# It is distributed WITHOUT ANY WARRANTY, express or implied.
3# Version 3.0 --- June 1993
4
5# Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
6
7# Permission is granted to make and distribute verbatim copies of this
8# document provided that the copyright notice and this permission notice
9# are preserved on all copies.
10
11# Permission is granted to copy and distribute modified versions of this
12# document under the conditions for verbatim copying, provided that the
13# entire resulting derived work is given a different name and distributed
14# under the terms of a permission notice identical to this one.
15
16#
17# Read the README file, then edit this file to reflect local conditions
18#
19
20# directory for TeX inputs (cwebmac.tex goes here)
21MACROSDIR= /usr/local/lib/tex/inputs
22
23# directory for CWEB inputs in @i files
24CWEBINPUTS= /usr/local/lib/cweb
25
26# extension for manual pages ("l" distinguishes local from system stuff)
27MANEXT= l
28#MANEXT= 1
29
30# directory for manual pages (cweb.1 goes here)
31MANDIR= /usr/man/man$(MANEXT)
32
33# destination directory for executables; must end in /
34DESTDIR= /usr/local/bin/
35
36# directory for GNU EMACS Lisp code (cweb.el goes here)
37EMACSDIR= /usr/local/emacs/lisp
38
39# Set DESTPREF to null if you want to call the executables "tangle" and "weave"
40# (probably NOT a good idea; we recommend leaving DESTPREF=c)
41DESTPREF=c
42
43# Set CCHANGES to comm-foo.ch if you need changes to common.w
44CCHANGES=
45
46# Set TCHANGES to ctang-foo.ch if you need changes to ctangle.w
47TCHANGES=
48
49# Set WCHANGES to cweav-foo.ch if you need changes to cweave.w
50WCHANGES=
51
52# We keep debugging info around, for fun, but most users don't need it
53CFLAGS = -g
54#CFLAGS = -O
55LINKFLAGS = -g
56#LINKFLAGS = -s # for smaller (stripped) executables on many UNIX systems
57
58# What C compiler are you using?
59CC = cc
60
61# RM and CP are used below in case rm and cp are aliased
62RM= /bin/rm
63CP= /bin/cp
64
65########## You shouldn't have to change anything after this point #######
66
67CWEAVE = ./cweave
68CTANGLE = ./ctangle
69SOURCES = cweave.w common.w ctangle.w
70ALMOSTALL = common.w ctangle.w Makefile README common.c common.h ctangle.c \
71 cwebman.tex cwebmac.tex examples comm-vms.ch ctang-vms.ch \
72 cweav-vms.ch comm-man.ch ctang-man.ch cweav-man.ch \
73 comm-pc.ch ctang-pc.ch cweav-pc.ch comm-amiga.ch \
74 comm-bs.ch ctang-bs.ch cweav-bs.ch makefile.bs \
75 cweb.1 cweb.el prod.w
76ALL = $(ALMOSTALL) cweave.w
77
78.SUFFIXES: .dvi .tex .w
79
80.w.tex:
81 $(CWEAVE) $*
82
83.tex.dvi:
84 tex $<
85
86.w.dvi:
87 make $*.tex
88 make $*.dvi
89
90.w.c:
91 $(CTANGLE) $*
92
93.w.o:
94 make $*.c
95 make $*.o
96
97all: ctangle cweave
98
99cautiously: ctangle
100 $(CP) common.c SAVEcommon.c
101 ./ctangle common $(CCHANGES)
102 diff common.c SAVEcommon.c
103 $(RM) SAVEcommon.c
104 $(CP) ctangle.c SAVEctangle.c
105 ./ctangle ctangle $(TCHANGES)
106 diff ctangle.c SAVEctangle.c
107 $(RM) SAVEctangle.c
108
109SAVEctangle.c:
110 $(CP) ctangle.c SAVEctangle.c
111
112SAVEcommon.c:
113 $(CP) common.c SAVEcommon.c
114
115common.c: common.w $(CCHANGES)
116 $(CTANGLE) common $(CCHANGES)
117
118common.o: common.c
119 $(CC) $(CFLAGS) -DCWEBINPUTS=\"$(CWEBINPUTS)\" -c common.c
120
121ctangle: ctangle.o common.o
122 $(CC) $(LINKFLAGS) -o ctangle ctangle.o common.o
123
124ctangle.c: ctangle.w $(TCHANGES)
125 $(CTANGLE) ctangle $(TCHANGES)
126
127cweave: cweave.o common.o
128 $(CC) $(LINKFLAGS) -o cweave cweave.o common.o
129
130cweave.c: cweave.w $(WCHANGES)
131 $(CTANGLE) cweave $(WCHANGES)
132
133doc: $(SOURCES:.w=.dvi)
134
135usermanual: cwebman.tex cwebmac.tex
136 tex cwebman
137
138fullmanual: usermanual $(SOURCES) comm-man.ch ctang-man.ch cweav-man.ch
139 make cweave
140 ./cweave common.w comm-man.ch
141 tex common.tex
142 ./cweave ctangle.w ctang-man.ch
143 tex ctangle.tex
144 ./cweave cweave.w cweav-man.ch
145 tex cweave.tex
146
147# be sure to leave ctangle.c and common.c for bootstrapping
148clean:
149 $(RM) -f -r *~ *.o common.tex cweave.tex cweave.c ctangle.tex \
150 *.log *.dvi *.toc *.idx *.scn core cweave.w.[12] cweave ctangle
151
152install: all
153 $(CP) cweave $(DESTDIR)$(DESTPREF)weave
154 chmod 755 $(DESTDIR)$(DESTPREF)weave
155 $(CP) ctangle $(DESTDIR)$(DESTPREF)tangle
156 chmod 755 $(DESTDIR)$(DESTPREF)tangle
157 $(CP) cweb.1 $(MANDIR)/cweb.$(MANEXT)
158 chmod 644 $(MANDIR)/cweb.$(MANEXT)
159 $(CP) cwebmac.tex $(MACROSDIR)
160 chmod 644 $(MACROSDIR)/cwebmac.tex
161 $(CP) cweb.el $(EMACSDIR)
162 chmod 644 $(EMACSDIR)/cweb.el
163
164bundle: $(ALL)
165 sed -n '1,2200 p' cweave.w > cweave.w.1
166 sed -n '2201,$$ p' cweave.w > cweave.w.2
167 /usr/local/bin/shar -m100000 -c -v -f cweb $(ALMOSTALL) cweave.w.[12]
168
169tags: $(ALL)
170 etags -z $(ALL)
171
172cweb.tar: $(ALL)
173 tar cvhf cweb.tar $(ALL)
174
175floppy: $(ALL)
176 bar cvhf /dev/rfd0 $(ALL)
177 bar tvf /dev/rfd0
178 eject
README+92−0
@@ -0,0 +1,92 @@
1% This file is part of CWEB.
2% The CWEB programs by Silvio Levy are based on programs by D. E. Knuth.
3% They are distributed WITHOUT ANY WARRANTY, express or implied.
4% This README file last updated August 1994 by Don Knuth
5
6% Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
7
8% Permission is granted to make and distribute verbatim copies of this
9% document provided that the copyright notice and this permission notice
10% are preserved on all copies.
11
12% Permission is granted to copy and distribute modified versions of this
13% document under the conditions for verbatim copying, provided that the
14% entire resulting derived work is given a different name and distributed
15% under the terms of a permission notice identical to this one.
16
17% Please send comments, suggestions, etc. to levy@geom.umn.edu.
18
19This directory contains the following files:
20
21Makefile
22README
23comm-amiga.ch
24comm-bs.ch
25comm-man.ch
26comm-pc.ch
27comm-vms.ch
28common.c
29common.h
30common.w
31ctang-bs.ch
32ctang-man.ch
33ctang-pc.ch
34ctang-vms.ch
35ctangle.c
36ctangle.w
37cweav-bs.ch
38cweav-man.ch
39cweav-pc.ch
40cweav-vms.ch
41cweave.w
42cweb.1
43cweb.el
44cwebmac.tex
45cwebman.tex
46examples/
47makefile.bs
48prod.w
49
50(If you got cweb by mail, you may have cweave.w.1 and cweave.w.2
51instead of cweave.w. The first thing to say then is
52
53cat cweave.w.[12] > cweave.w
54
55)
56
57The file cwebman.tex is the user manual.
58The examples directory contains additional examples of the use of CWEB.
59The files common.c and ctangle.c are used for bootstrapping.
60The file cweb.1 is a manual page.
61The file cweb.el is suggested for GNU-Emacs users.
62The files *-man.ch are used if you want to make the full 227-page CWEB manual.
63The files *-bs.ch are used instead of *-pc.ch if you are doing BIG programs.
64You can use makefile.bs to make CWEB with *-bs.ch.
65The other files named *.ch are sample change files for local customization.
66
67IMPORTANT: Please touch *.c before proceeding.
68Then edit the opening lines of Makefile so that it has the proper
69directory information for your local system.
70
71To make ctangle and cweave say `make all'; this should produce roughly
72the following actions (possibly with harmless warning messages from cc):
73
74cc -g -w -c ctangle.c
75cc -g -w -DCWEBINPUTS=\"/usr/local/lib/cweb\" -c common.c
76cc -g -o ctangle ctangle.o common.o
77./ctangle cweave
78cc -g -w -c cweave.c
79cc -g -w -o cweave cweave.o common.o
80
81To get some reassurance that things are OK, you can say `make cautiously',
82which ensures that CTANGLE will reproduce itself. (Otherwise the source
83files common.w and ctangle.w won't actually have been used.)
84
85To install cweave and ctangle say `make install'. You probably need to
86be superuser to do this; but it's wise to `make all' first, BEFORE
87becoming superuser and saying `make install'.
88
89Note that change files for VMS, AMIGA, and PCs are provided. When you are
90first bootstrapping to a new system, you may need to edit common.c and
91ctangle.c by hand, but the vast majority of the change-file changes are
92minor refinements that are not necessary for a rudimentary ctangle.
comm-amiga.ch+17−0
@@ -0,0 +1,17 @@
1This is the change file for CWEB's COMMON on the Amiga
2(Contributed by Tomas Rokicki, June 1993)
3
4With Lattice C 5.1, use compilation switches -b0 -r0, and ignore the
5compiler warnings. With SAS 6.0, use compilation switches Code=far Data=far.
6
7@x section 69
8An omitted change file argument means that |"/dev/null"| should be used,
9@y
10An omitted change file argument means that |"nil:"| should be used,
11@z
12
13@x section 70
14 if (found_change<=0) strcpy(change_file_name,"/dev/null");
15@y
16 if (found_change<=0) strcpy(change_file_name,"nil:");
17@z
comm-bs.ch+229−0
@@ -0,0 +1,229 @@
1Changes for code common to CTANGLE and CWEAVE, for MSDOS
2and Borland C++ 3.1 using the following options (and perhaps others):
3
4 -mc -w-pro -Ff=5000 -Z- -O-p
5
6The options -Z- and -O-p explicitly turn off optimizations that seem to be
7dangerous for the style of code in the CWEB sources. (See makefile.bs.)
8
9The main purpose of these changes is to support MSDOS with full-size arrays
10by using "huge" pointers.
11
12(This file contributed by Barry Schwartz, trashman@crud.mn.org, 28 Jun 94;
13 revised 24 Jul 94.)
14
15
16@x Section 23.
17 cur_file_name[l]='/'; /* \UNIX/ pathname separator */
18@y
19 cur_file_name[l]='/'; /* A valid {\mc MSDOS} pathname separator */
20@z
21
22
23@x Section 27.
24@d max_names 4000 /* number of identifiers, strings, section names;
25 must be less than 10240 */
26
27@<Definitions that...@>=
28typedef struct name_info {
29 char *byte_start; /* beginning of the name in |byte_mem| */
30 @<More elements of |name_info| structure@>@;
31} name_info; /* contains information about an identifier or section name */
32typedef name_info *name_pointer; /* pointer into array of |name_info|s */
33char byte_mem[max_bytes]; /* characters of names */
34char *byte_mem_end = byte_mem+max_bytes-1; /* end of |byte_mem| */
35name_info name_dir[max_names]; /* information about names */
36name_pointer name_dir_end = name_dir+max_names-1; /* end of |name_dir| */
37@y
38@d max_names 4000 /* number of identifiers, strings, section names;
39 must be less than 10240 */
40
41@f huge extern
42
43@<Definitions that...@>=
44typedef struct name_info {
45 char huge* byte_start; /* beginning of the name in |byte_mem| */
46 @<More elements of |name_info| structure@>@;
47} name_info; /* contains information about an identifier or section name */
48typedef name_info *name_pointer; /* pointer into array of |name_info|s */
49char huge byte_mem[max_bytes]; /* characters of names */
50char huge* byte_mem_end; /* end of |byte_mem| */
51name_info name_dir[max_names]; /* information about names */
52name_pointer name_dir_end = name_dir+max_names-1;
53@z
54
55
56@x Section 29.
57char *byte_ptr; /* first unused position in |byte_mem| */
58@y
59char huge* byte_ptr; /* first unused position in |byte_mem| */
60@z
61
62
63@x Section 30.
64@ @<Init...@>=
65name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
66name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
67name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
68@y
69@ @<Init...@>=
70name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
71name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
72name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
73byte_mem_end = byte_mem+max_bytes-1;
74@z
75
76
77@x Section 42.
78void
79print_section_name(p)
80name_pointer p;
81{
82 char *ss, *s = first_chunk(p);
83@y
84void
85print_section_name(p)
86name_pointer p;
87{
88 char huge* ss, huge* s = first_chunk(p);
89@z
90
91
92@x Section 43.
93void
94sprint_section_name(dest,p)
95 char*dest;
96 name_pointer p;
97{
98 char *ss, *s = first_chunk(p);
99@y
100void
101sprint_section_name(dest,p)
102 char*dest;
103 name_pointer p;
104{
105 char huge* ss, huge* s = first_chunk(p);
106@z
107
108
109@x Section 44.
110void
111print_prefix_name(p)
112name_pointer p;
113{
114 char *s = first_chunk(p);
115@y
116void
117print_prefix_name(p)
118name_pointer p;
119{
120 char huge* s = first_chunk(p);
121@z
122
123
124@x Section 47.
125name_pointer
126add_section_name(par,c,first,last,ispref) /* install a new node in the tree */
127name_pointer par; /* parent of new node */
128int c; /* right or left? */
129char *first; /* first character of section name */
130char *last; /* last character of section name, plus one */
131int ispref; /* are we adding a prefix or a full name? */
132{
133 name_pointer p=name_ptr; /* new node */
134 char *s=first_chunk(p);
135@y
136name_pointer
137add_section_name(par,c,first,last,ispref) /* install a new node in the tree */
138name_pointer par; /* parent of new node */
139int c; /* right or left? */
140char *first; /* first character of section name */
141char *last; /* last character of section name, plus one */
142int ispref; /* are we adding a prefix or a full name? */
143{
144 name_pointer p=name_ptr; /* new node */
145 char huge* s=first_chunk(p);
146@z
147
148
149@x Section 48.
150void
151extend_section_name(p,first,last,ispref)
152name_pointer p; /* name to be extended */
153char *first; /* beginning of extension text */
154char *last; /* one beyond end of extension text */
155int ispref; /* are we adding a prefix or a full name? */
156{
157 char *s;
158@y
159void
160extend_section_name(p,first,last,ispref)
161name_pointer p; /* name to be extended */
162char *first; /* beginning of extension text */
163char *last; /* one beyond end of extension text */
164int ispref; /* are we adding a prefix or a full name? */
165{
166 char huge* s;
167@z
168
169
170@x Section 54.
171int section_name_cmp(pfirst,len,r)
172char **pfirst; /* pointer to beginning of comparison string */
173int len; /* length of string */
174name_pointer r; /* section name being compared */
175{
176 char *first=*pfirst; /* beginning of comparison string */
177 name_pointer q=r+1; /* access to subsequent chunks */
178 char *ss, *s=first_chunk(r);
179@y
180int section_name_cmp(pfirst,len,r)
181char **pfirst; /* pointer to beginning of comparison string */
182int len; /* length of string */
183name_pointer r; /* section name being compared */
184{
185 char *first=*pfirst; /* beginning of comparison string */
186 name_pointer q=r+1; /* access to subsequent chunks */
187 char huge* ss, huge* s=first_chunk(r);
188@z
189
190
191@x Section 55.
192source files, respectively; here we just declare a common field
193|equiv_or_xref| as a pointer to a |char|.
194
195@<More elements of |name...@>=
196char *equiv_or_xref; /* info corresponding to names */
197@y
198source files, respectively. Here we just declare a common field
199|ptr_union| as a union of pointers to |char|, which happen to have
200different addressing attributes.
201
202@<More elements of |name...@>=
203union {
204 char *equiv_member;
205 char huge* xref_member;
206} ptr_union; /* info corresponding to names */
207@z
208
209
210@x Section 69.
211An omitted change file argument means that |"/dev/null"| should be used,
212@y
213An omitted change file argument means that |"NUL"| should be used,
214@z
215
216
217@x Section 70.
218 else if (*s=='/') dot_pos=NULL,name_pos=++s;
219@y
220 else if (*s == ':' || *s == '\\' || *s == '/')
221 dot_pos=NULL,name_pos=++s;
222@z
223
224
225@x Section 70.
226 if (found_change<=0) strcpy(change_file_name,"/dev/null");
227@y
228 if (found_change<=0) strcpy(change_file_name,"NUL");
229@z
comm-man.ch+22−0
@@ -0,0 +1,22 @@
1Change file to help make Appendix D of the full CWEB manual
2@x
3\def\botofcontents{\vfill
4\noindent
5Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
6\bigskip\noindent
7Permission is granted to make and distribute verbatim copies of this
8document provided that the copyright notice and this permission notice
9are preserved on all copies.
10
11\smallskip\noindent
12Permission is granted to copy and distribute modified versions of this
13document under the conditions for verbatim copying, provided that the
14entire resulting derived work is given a different name and distributed
15under the terms of a permission notice identical to this one.
16}
17@y
18\def\botofcontents{\vfill\titlefalse}
19\def\contentspagenumber{23}
20\def\title{APPENDIX D: COMMON}
21\let\K=\leftarrow
22@z
comm-pc.ch+33−0
@@ -0,0 +1,33 @@
1This is the change file for CWEB's COMMON under DOS
2(Contributed by Lee Wittenberg, March 1993)
3
4Changes necessary for compiling with Borland C/C++
5Use compilation switches -mc -w-pro -Ff=5000
6
7Note: The change to section 27 is not necessary if using a compiler
8that allows >64K arrays.
9
10@x section 27
11@d max_bytes 90000 /* the number of bytes in identifiers,
12@y
13@d max_bytes (unsigned)60000 /* the number of bytes in identifiers,
14@z
15
16@x section 69
17An omitted change file argument means that |"/dev/null"| should be used,
18@y
19An omitted change file argument means that |"NUL"| should be used,
20@z
21
22@x section 70 (this change copied from comm-bs.ch, July 94)
23 else if (*s=='/') dot_pos=NULL,name_pos=++s;
24@y
25 else if (*s == ':' || *s == '\\' || *s == '/')
26 dot_pos=NULL,name_pos=++s;
27@z
28
29@x section 70
30 if (found_change<=0) strcpy(change_file_name,"/dev/null");
31@y
32 if (found_change<=0) strcpy(change_file_name,"NUL");
33@z
comm-vms.ch+81−0
@@ -0,0 +1,81 @@
1This is the change file for CWEB's COMMON under VAX/VMS.
2
3created:
4 1987 BL (Bjorn Larsen, University of Oslo)
5
6modified:
7 01-FEB-1992 ST (Stephan Trebels <trebels@ams02.dnet.gwdg.de>)
8 > include ctype,stdio,ssdef from textlibrary SYS$SHARE:VAXCDEF.TLB
9 > change error return code to SS$_ABORT
10 (perhaps better than %NONAME-E-NOMSG, Message number 2 )
11
12(also modified by Don Knuth to match changes in the master file)
13(only the two changes by BL are necessary for initial bootstrapping
14 via hand-editing of common.c)
15
16@x section 5 (01-FEB-1992 ST)
17#include <ctype.h>
18@y
19#include ctype /* VMS searches Textlibraries faster */
20@z
21
22@x section 8 (01-FEB-1992 ST)
23#include <stdio.h>
24@y
25#include stdio /* VMS searches Textlibraries faster */
26@z
27
28@x section 61 (01-FEB-1992 ST)
29programs are started. Here, for instance, we pass the operating system
30a status of 0 if and only if only harmless messages were printed.
31@y
32programs are started. Here, for instance, we pass VAX/VMS
33a status of |SS$_NORMAL| if and only if only harmless
34messages have been printed.
35A suitable status to signal an error condition to VAX/VMS could be
36|SS$_ABORT|, telling the operating system to
37print |"%SYSTEM-F-ABORT, abort"|, if |history > harmless_message|.
38@z
39
40@x section 61 (1987 BL) (01-FEB-1992 ST) (11-JAN-1993 DEK)
41 if (history > harmless_message) return(1);
42 else return(0);
43@y
44/*
45 VAX/VMS and UNIX have different error status conventions.
46 VAX/VMS uses odd values (for example |SS$_NORMAL|) to indicate success,
47 even values indicate errors, resulting in messages displayed
48 on the screen. |SS$_ABORT| has been chosen, to indicate an
49 error and display something that's not complete nonsense.
50*/
51 if (history > harmless_message) exit(SS$_ABORT);
52 else exit(SS$_NORMAL);
53@z
54
55@x section 69 (01-FEB-1992 ST)
56An omitted change file argument means that |"/dev/null"| should be used,
57when no changes are desired.
58@y
59An omitted change file argument means that the
60null device |"NL:"| should be used, when no changes are desired.
61@z
62
63@x section 70 (1987 BL) (01-FEB-1992 ST) (05-APR-1992 DEK)
64 if (found_change<=0) strcpy(change_file_name,"/dev/null");
65@y
66 if (found_change<=) strcpy(change_file_name,"NL:");
67 /* {\tt NL:} is the VAX/VMS notation for {\tt /dev/null} */
68@z
69
70@x section 82 (01-FEB-1992 ST)
71@** Index.
72@y
73@* VAX/VMS specific code.
74We have used |SS$_NORMAL| and |SS$_ABORT| as return codes,
75so we have to include the system message codes.
76
77@<Include files@>=
78#include ssdef /* we need VAX/VMS system messages */
79
80@** Index.
81@z
common.c+1239−0
@@ -0,0 +1,1239 @@
1/*1:*/
2#line 57 "common.w"
3
4/*5:*/
5#line 101 "common.w"
6
7#include <ctype.h>
8
9/*:5*//*8:*/
10#line 163 "common.w"
11
12#include <stdio.h>
13
14/*:8*//*22:*/
15#line 468 "common.w"
16
17#include <stdlib.h>
18
19/*:22*/
20#line 58 "common.w"
21
22#define ctangle 0
23#define cweave 1 \
24
25#define and_and 04
26#define lt_lt 020
27#define gt_gt 021
28#define plus_plus 013
29#define minus_minus 01
30#define minus_gt 031
31#define not_eq 032
32#define lt_eq 034
33#define gt_eq 035
34#define eq_eq 036
35#define or_or 037
36#define dot_dot_dot 016
37#define colon_colon 06
38#define period_ast 026
39#define minus_gt_ast 027 \
40
41#define buf_size 100
42#define long_buf_size 500
43#define xisspace(c)(isspace(c)&&((unsigned char)c<0200))
44#define xisupper(c)(isupper(c)&&((unsigned char)c<0200)) \
45
46#define max_include_depth 10 \
47
48#define max_file_name_length 60
49#define cur_file file[include_depth]
50#define cur_file_name file_name[include_depth]
51#define cur_line line[include_depth]
52#define web_file file[0]
53#define web_file_name file_name[0] \
54
55#define lines_dont_match (change_limit-change_buffer!=limit-buffer|| \
56strncmp(buffer,change_buffer,limit-buffer)) \
57
58#define if_section_start_make_pending(b){*limit= '!'; \
59for(loc= buffer;xisspace(*loc);loc++); \
60*limit= ' '; \
61if(*loc=='@'&&(xisspace(*(loc+1))||*(loc+1)=='*'))change_pending= b; \
62} \
63
64#define max_sections 2000 \
65 \
66
67#define too_long(){include_depth--; \
68err_print("! Include file name too long");goto restart;} \
69
70#define max_bytes 90000 \
71
72#define max_names 4000 \
73 \
74
75#define length(c)(c+1)->byte_start-(c)->byte_start
76#define print_id(c)term_write((c)->byte_start,length((c))) \
77
78#define hash_size 353 \
79
80#define llink link
81#define rlink dummy.Rlink
82#define root name_dir->rlink \
83 \
84
85#define first_chunk(p)((p)->byte_start+2)
86#define prefix_length(p)(int)((unsigned char)*((p)->byte_start)*256+ \
87(unsigned char)*((p)->byte_start+1))
88#define set_prefix_length(p,m)(*((p)->byte_start)= (m)/256, \
89*((p)->byte_start+1)= (m)%256) \
90
91#define less 0
92#define equal 1
93#define greater 2
94#define prefix 3
95#define extension 4 \
96
97#define bad_extension 5 \
98
99#define spotless 0
100#define harmless_message 1
101#define error_message 2
102#define fatal_message 3
103#define mark_harmless {if(history==spotless)history= harmless_message;}
104#define mark_error history= error_message \
105
106#define confusion(s)fatal("! This can't happen: ",s) \
107 \
108
109#define show_banner flags['b']
110#define show_progress flags['p']
111#define show_stats flags['s']
112#define show_happiness flags['h'] \
113
114#define update_terminal fflush(stdout) \
115
116#define new_line putchar('\n')
117#define putxchar putchar
118#define term_write(a,b)fflush(stdout),fwrite(a,sizeof(char),b,stdout)
119#define C_printf(c,a)fprintf(C_file,c,a)
120#define C_putc(c)putc(c,C_file) \
121
122
123#line 59 "common.w"
124
125/*2:*/
126#line 72 "common.w"
127
128typedef short boolean;
129boolean program;
130
131/*:2*//*7:*/
132#line 157 "common.w"
133
134char buffer[long_buf_size];
135char*buffer_end= buffer+buf_size-2;
136char*limit= buffer;
137char*loc= buffer;
138
139/*:7*//*10:*/
140#line 212 "common.w"
141
142int include_depth;
143FILE*file[max_include_depth];
144FILE*change_file;
145char file_name[max_include_depth][max_file_name_length];
146
147char change_file_name[max_file_name_length];
148char alt_web_file_name[max_file_name_length];
149int line[max_include_depth];
150int change_line;
151int change_depth;
152boolean input_has_ended;
153boolean changing;
154boolean web_file_open= 0;
155
156/*:10*//*20:*/
157#line 416 "common.w"
158
159typedef unsigned short sixteen_bits;
160sixteen_bits section_count;
161boolean changed_section[max_sections];
162boolean change_pending;
163
164boolean print_where= 0;
165
166/*:20*//*27:*/
167#line 586 "common.w"
168
169typedef struct name_info{
170char*byte_start;
171/*31:*/
172#line 623 "common.w"
173
174struct name_info*link;
175
176/*:31*//*40:*/
177#line 722 "common.w"
178
179union{
180struct name_info*Rlink;
181
182char Ilk;
183}dummy;
184
185/*:40*//*55:*/
186#line 1054 "common.w"
187
188char*equiv_or_xref;
189
190/*:55*/
191#line 589 "common.w"
192
193}name_info;
194typedef name_info*name_pointer;
195char byte_mem[max_bytes];
196char*byte_mem_end= byte_mem+max_bytes-1;
197name_info name_dir[max_names];
198name_pointer name_dir_end= name_dir+max_names-1;
199
200/*:27*//*29:*/
201#line 609 "common.w"
202
203name_pointer name_ptr;
204char*byte_ptr;
205
206/*:29*//*32:*/
207#line 636 "common.w"
208
209typedef name_pointer*hash_pointer;
210name_pointer hash[hash_size];
211hash_pointer hash_end= hash+hash_size-1;
212hash_pointer h;
213
214/*:32*//*56:*/
215#line 1074 "common.w"
216
217int history= spotless;
218
219/*:56*//*67:*/
220#line 1212 "common.w"
221
222int argc;
223char**argv;
224char C_file_name[max_file_name_length];
225char tex_file_name[max_file_name_length];
226char idx_file_name[max_file_name_length];
227char scn_file_name[max_file_name_length];
228boolean flags[128];
229
230/*:67*//*77:*/
231#line 1366 "common.w"
232
233FILE*C_file;
234FILE*tex_file;
235FILE*idx_file;
236FILE*scn_file;
237FILE*active_file;
238
239/*:77*/
240#line 60 "common.w"
241
242/*3:*/
243#line 82 "common.w"
244int phase;
245
246/*:3*//*11:*/
247#line 238 "common.w"
248
249char change_buffer[buf_size];
250char*change_limit;
251
252/*:11*/
253#line 61 "common.w"
254
255/*33:*/
256#line 642 "common.w"
257
258extern int names_match();
259
260/*:33*//*38:*/
261#line 695 "common.w"
262
263void init_p();
264
265/*:38*//*46:*/
266#line 844 "common.w"
267
268extern void init_node();
269
270/*:46*//*53:*/
271#line 1009 "common.w"
272
273int section_name_cmp();
274
275/*:53*//*57:*/
276#line 1084 "common.w"
277
278void err_print();
279
280/*:57*//*60:*/
281#line 1132 "common.w"
282
283int wrap_up();
284extern void print_stats();
285
286/*:60*//*63:*/
287#line 1165 "common.w"
288
289void fatal(),overflow();
290
291/*:63*//*69:*/
292#line 1243 "common.w"
293
294void scan_args();
295
296/*:69*//*81:*/
297#line 1407 "common.w"
298
299extern int strlen();
300extern int strcmp();
301extern char*strcpy();
302extern int strncmp();
303extern char*strncpy();
304
305/*:81*/
306#line 62 "common.w"
307
308
309/*:1*//*4:*/
310#line 88 "common.w"
311
312void
313common_init()
314{
315/*30:*/
316#line 613 "common.w"
317
318name_dir->byte_start= byte_ptr= byte_mem;
319name_ptr= name_dir+1;
320name_ptr->byte_start= byte_mem;
321
322/*:30*//*34:*/
323#line 647 "common.w"
324
325for(h= hash;h<=hash_end;*h++= NULL);
326
327/*:34*//*41:*/
328#line 729 "common.w"
329
330root= NULL;
331
332/*:41*/
333#line 92 "common.w"
334;
335/*68:*/
336#line 1225 "common.w"
337
338show_banner= show_happiness= show_progress= 1;
339
340/*:68*/
341#line 93 "common.w"
342;
343/*78:*/
344#line 1373 "common.w"
345
346scan_args();
347if(program==ctangle){
348if((C_file= fopen(C_file_name,"w"))==NULL)
349fatal("! Cannot open output file ",C_file_name);
350
351}
352else{
353if((tex_file= fopen(tex_file_name,"w"))==NULL)
354fatal("! Cannot open output file ",tex_file_name);
355}
356
357/*:78*/
358#line 94 "common.w"
359;
360}
361
362/*:4*//*9:*/
363#line 170 "common.w"
364
365int input_ln(fp)
366FILE*fp;
367{
368register int c= EOF;
369register char*k;
370if(feof(fp))return(0);
371limit= k= buffer;
372while(k<=buffer_end&&(c= getc(fp))!=EOF&&c!='\n')
373if((*(k++)= c)!=' ')limit= k;
374if(k>buffer_end)
375if((c= getc(fp))!=EOF&&c!='\n'){
376ungetc(c,fp);loc= buffer;err_print("! Input line too long");
377
378}
379if(c==EOF&&limit==buffer)return(0);
380
381return(1);
382}
383
384/*:9*//*12:*/
385#line 249 "common.w"
386
387void
388prime_the_change_buffer()
389{
390change_limit= change_buffer;
391/*13:*/
392#line 263 "common.w"
393
394while(1){
395change_line++;
396if(!input_ln(change_file))return;
397if(limit<buffer+2)continue;
398if(buffer[0]!='@')continue;
399if(xisupper(buffer[1]))buffer[1]= tolower(buffer[1]);
400if(buffer[1]=='x')break;
401if(buffer[1]=='y'||buffer[1]=='z'||buffer[1]=='i'){
402loc= buffer+2;
403err_print("! Missing @x in change file");
404
405}
406}
407
408/*:13*/
409#line 254 "common.w"
410;
411/*14:*/
412#line 280 "common.w"
413
414do{
415change_line++;
416if(!input_ln(change_file)){
417err_print("! Change file ended after @x");
418
419return;
420}
421}while(limit==buffer);
422
423/*:14*/
424#line 255 "common.w"
425;
426/*15:*/
427#line 290 "common.w"
428
429{
430change_limit= change_buffer-buffer+limit;
431strncpy(change_buffer,buffer,limit-buffer+1);
432}
433
434/*:15*/
435#line 256 "common.w"
436;
437}
438
439/*:12*//*16:*/
440#line 318 "common.w"
441
442void
443check_change()
444{
445int n= 0;
446if(lines_dont_match)return;
447change_pending= 0;
448if(!changed_section[section_count]){
449if_section_start_make_pending(1);
450if(!change_pending)changed_section[section_count]= 1;
451}
452while(1){
453changing= 1;print_where= 1;change_line++;
454if(!input_ln(change_file)){
455err_print("! Change file ended before @y");
456
457change_limit= change_buffer;changing= 0;
458return;
459}
460if(limit>buffer+1&&buffer[0]=='@'){
461if(xisupper(buffer[1]))buffer[1]= tolower(buffer[1]);
462/*17:*/
463#line 356 "common.w"
464
465if(buffer[1]=='x'||buffer[1]=='z'){
466loc= buffer+2;err_print("! Where is the matching @y?");
467
468}
469else if(buffer[1]=='y'){
470if(n>0){
471loc= buffer+2;
472printf("\n! Hmm... %d ",n);
473err_print("of the preceding lines failed to match");
474
475}
476change_depth= include_depth;
477return;
478}
479
480/*:17*/
481#line 340 "common.w"
482;
483}
484/*15:*/
485#line 290 "common.w"
486
487{
488change_limit= change_buffer-buffer+limit;
489strncpy(change_buffer,buffer,limit-buffer+1);
490}
491
492/*:15*/
493#line 342 "common.w"
494;
495changing= 0;cur_line++;
496while(!input_ln(cur_file)){
497if(include_depth==0){
498err_print("! CWEB file ended during a change");
499
500input_has_ended= 1;return;
501}
502include_depth--;cur_line++;
503}
504if(lines_dont_match)n++;
505}
506}
507
508/*:16*//*18:*/
509#line 376 "common.w"
510
511void
512reset_input()
513{
514limit= buffer;loc= buffer+1;buffer[0]= ' ';
515/*19:*/
516#line 391 "common.w"
517
518if((web_file= fopen(web_file_name,"r"))==NULL){
519strcpy(web_file_name,alt_web_file_name);
520if((web_file= fopen(web_file_name,"r"))==NULL)
521fatal("! Cannot open input file ",web_file_name);
522}
523
524
525web_file_open= 1;
526if((change_file= fopen(change_file_name,"r"))==NULL)
527fatal("! Cannot open change file ",change_file_name);
528
529/*:19*/
530#line 381 "common.w"
531;
532include_depth= 0;cur_line= 0;change_line= 0;
533change_depth= include_depth;
534changing= 1;prime_the_change_buffer();changing= !changing;
535limit= buffer;loc= buffer+1;buffer[0]= ' ';input_has_ended= 0;
536}
537
538/*:18*//*21:*/
539#line 424 "common.w"
540
541int get_line()
542{
543restart:
544if(changing&&include_depth==change_depth)
545/*25:*/
546#line 529 "common.w"
547{
548change_line++;
549if(!input_ln(change_file)){
550err_print("! Change file ended without @z");
551
552buffer[0]= '@';buffer[1]= 'z';limit= buffer+2;
553}
554if(limit>buffer){
555if(change_pending){
556if_section_start_make_pending(0);
557if(change_pending){
558changed_section[section_count]= 1;change_pending= 0;
559}
560}
561*limit= ' ';
562if(buffer[0]=='@'){
563if(xisupper(buffer[1]))buffer[1]= tolower(buffer[1]);
564if(buffer[1]=='x'||buffer[1]=='y'){
565loc= buffer+2;
566err_print("! Where is the matching @z?");
567
568}
569else if(buffer[1]=='z'){
570prime_the_change_buffer();changing= !changing;print_where= 1;
571}
572}
573}
574}
575
576/*:25*/
577#line 429 "common.w"
578;
579if(!changing||include_depth>change_depth){
580/*24:*/
581#line 512 "common.w"
582{
583cur_line++;
584while(!input_ln(cur_file)){
585print_where= 1;
586if(include_depth==0){input_has_ended= 1;break;}
587else{
588fclose(cur_file);include_depth--;
589if(changing&&include_depth==change_depth)break;
590cur_line++;
591}
592}
593if(!changing&&!input_has_ended)
594if(limit-buffer==change_limit-change_buffer)
595if(buffer[0]==change_buffer[0])
596if(change_limit>change_buffer)check_change();
597}
598
599/*:24*/
600#line 431 "common.w"
601;
602if(changing&&include_depth==change_depth)goto restart;
603}
604loc= buffer;*limit= ' ';
605if(*buffer=='@'&&(*(buffer+1)=='i'||*(buffer+1)=='I')){
606loc= buffer+2;
607while(loc<=limit&&(*loc==' '||*loc=='\t'||*loc=='"'))loc++;
608if(loc>=limit){
609err_print("! Include file name not given");
610
611goto restart;
612}
613if(include_depth>=max_include_depth-1){
614err_print("! Too many nested includes");
615
616goto restart;
617}
618include_depth++;
619/*23:*/
620#line 471 "common.w"
621{
622char temp_file_name[max_file_name_length];
623char*cur_file_name_end= cur_file_name+max_file_name_length-1;
624char*k= cur_file_name,*kk;
625int l;
626
627while(*loc!=' '&&*loc!='\t'&&*loc!='"'&&k<=cur_file_name_end)*k++= *loc++;
628if(k>cur_file_name_end)too_long();
629
630*k= '\0';
631if((cur_file= fopen(cur_file_name,"r"))!=NULL){
632cur_line= 0;print_where= 1;
633goto restart;
634}
635kk= getenv("CWEBINPUTS");
636if(kk!=NULL){
637if((l= strlen(kk))>max_file_name_length-2)too_long();
638strcpy(temp_file_name,kk);
639}
640else{
641#ifdef CWEBINPUTS
642if((l= strlen(CWEBINPUTS))>max_file_name_length-2)too_long();
643strcpy(temp_file_name,CWEBINPUTS);
644#else
645l= 0;
646#endif
647}
648if(l>0){
649if(k+l+2>=cur_file_name_end)too_long();
650
651for(;k>=cur_file_name;k--)*(k+l+1)= *k;
652strcpy(cur_file_name,temp_file_name);
653cur_file_name[l]= '/';
654if((cur_file= fopen(cur_file_name,"r"))!=NULL){
655cur_line= 0;print_where= 1;
656goto restart;
657}
658}
659include_depth--;err_print("! Cannot open include file");goto restart;
660}
661
662/*:23*/
663#line 449 "common.w"
664;
665}
666return(!input_has_ended);
667}
668
669/*:21*//*26:*/
670#line 561 "common.w"
671
672void
673check_complete(){
674if(change_limit!=change_buffer){
675strncpy(buffer,change_buffer,change_limit-change_buffer+1);
676limit= buffer+(int)(change_limit-change_buffer);
677changing= 1;change_depth= include_depth;loc= buffer;
678err_print("! Change file entry did not match");
679
680}
681}
682
683/*:26*//*35:*/
684#line 652 "common.w"
685
686name_pointer
687id_lookup(first,last,t)
688char*first;
689char*last;
690char t;
691{
692char*i= first;
693int h;
694int l;
695name_pointer p;
696if(last==NULL)for(last= first;*last!='\0';last++);
697l= last-first;
698/*36:*/
699#line 675 "common.w"
700
701h= (unsigned char)*i;
702while(++i<last)h= (h+h+(int)((unsigned char)*i))%hash_size;
703
704
705/*:36*/
706#line 665 "common.w"
707;
708/*37:*/
709#line 683 "common.w"
710
711p= hash[h];
712while(p&&!names_match(p,first,l,t))p= p->link;
713if(p==NULL){
714p= name_ptr;
715p->link= hash[h];hash[h]= p;
716}
717
718/*:37*/
719#line 666 "common.w"
720;
721if(p==name_ptr)/*39:*/
722#line 698 "common.w"
723{
724if(byte_ptr+l>byte_mem_end)overflow("byte memory");
725if(name_ptr>=name_dir_end)overflow("name");
726strncpy(byte_ptr,first,l);
727(++name_ptr)->byte_start= byte_ptr+= l;
728if(program==cweave)init_p(p,t);
729}
730
731/*:39*/
732#line 667 "common.w"
733;
734return(p);
735}
736
737/*:35*//*42:*/
738#line 756 "common.w"
739
740void
741print_section_name(p)
742name_pointer p;
743{
744char*ss,*s= first_chunk(p);
745name_pointer q= p+1;
746while(p!=name_dir){
747ss= (p+1)->byte_start-1;
748if(*ss==' '&&ss>=s){
749term_write(s,ss-s);p= q->link;q= p;
750}else{
751term_write(s,ss+1-s);p= name_dir;q= NULL;
752}
753s= p->byte_start;
754}
755if(q)term_write("...",3);
756}
757
758/*:42*//*43:*/
759#line 775 "common.w"
760
761void
762sprint_section_name(dest,p)
763char*dest;
764name_pointer p;
765{
766char*ss,*s= first_chunk(p);
767name_pointer q= p+1;
768while(p!=name_dir){
769ss= (p+1)->byte_start-1;
770if(*ss==' '&&ss>=s){
771p= q->link;q= p;
772}else{
773ss++;p= name_dir;
774}
775strncpy(dest,s,ss-s),dest+= ss-s;
776s= p->byte_start;
777}
778*dest= '\0';
779}
780
781/*:43*//*44:*/
782#line 796 "common.w"
783
784void
785print_prefix_name(p)
786name_pointer p;
787{
788char*s= first_chunk(p);
789int l= prefix_length(p);
790term_write(s,l);
791if(s+l<(p+1)->byte_start)term_write("...",3);
792}
793
794/*:44*//*45:*/
795#line 817 "common.w"
796
797int web_strcmp(j,j_len,k,k_len)
798char*j,*k;
799int j_len,k_len;
800{
801char*j1= j+j_len,*k1= k+k_len;
802while(k<k1&&j<j1&&*j==*k)k++,j++;
803if(k==k1)if(j==j1)return equal;
804else return extension;
805else if(j==j1)return prefix;
806else if(*j<*k)return less;
807else return greater;
808}
809
810/*:45*//*47:*/
811#line 847 "common.w"
812
813name_pointer
814add_section_name(par,c,first,last,ispref)
815name_pointer par;
816int c;
817char*first;
818char*last;
819int ispref;
820{
821name_pointer p= name_ptr;
822char*s= first_chunk(p);
823int name_len= last-first+ispref;
824if(s+name_len>byte_mem_end)overflow("byte memory");
825if(name_ptr+1>=name_dir_end)overflow("name");
826(++name_ptr)->byte_start= byte_ptr= s+name_len;
827if(ispref){
828*(byte_ptr-1)= ' ';
829name_len--;
830name_ptr->link= name_dir;
831(++name_ptr)->byte_start= byte_ptr;
832}
833set_prefix_length(p,name_len);
834strncpy(s,first,name_len);
835p->llink= NULL;
836p->rlink= NULL;
837init_node(p);
838return par==NULL?(root= p):c==less?(par->llink= p):(par->rlink= p);
839}
840
841/*:47*//*48:*/
842#line 876 "common.w"
843
844void
845extend_section_name(p,first,last,ispref)
846name_pointer p;
847char*first;
848char*last;
849int ispref;
850{
851char*s;
852name_pointer q= p+1;
853int name_len= last-first+ispref;
854if(name_ptr>=name_dir_end)overflow("name");
855while(q->link!=name_dir)q= q->link;
856q->link= name_ptr;
857s= name_ptr->byte_start;
858name_ptr->link= name_dir;
859if(s+name_len>byte_mem_end)overflow("byte memory");
860(++name_ptr)->byte_start= byte_ptr= s+name_len;
861strncpy(s,first,name_len);
862if(ispref)*(byte_ptr-1)= ' ';
863}
864
865/*:48*//*49:*/
866#line 904 "common.w"
867
868name_pointer
869section_lookup(first,last,ispref)
870char*first,*last;
871int ispref;
872{
873int c= 0;
874name_pointer p= root;
875name_pointer q= NULL;
876name_pointer r= NULL;
877name_pointer par= NULL;
878
879int name_len= last-first+1;
880/*50:*/
881#line 928 "common.w"
882
883while(p){
884c= web_strcmp(first,name_len,first_chunk(p),prefix_length(p));
885if(c==less||c==greater){
886if(r==NULL)
887par= p;
888p= (c==less?p->llink:p->rlink);
889}else{
890if(r!=NULL){
891printf("\n! Ambiguous prefix: matches <");
892
893print_prefix_name(p);
894printf(">\n and <");
895print_prefix_name(r);
896err_print(">");
897return name_dir;
898}
899r= p;
900p= p->llink;
901q= r->rlink;
902}
903if(p==NULL)
904p= q,q= NULL;
905}
906
907/*:50*/
908#line 918 "common.w"
909;
910/*51:*/
911#line 953 "common.w"
912
913if(r==NULL)
914return add_section_name(par,c,first,last+1,ispref);
915
916/*:51*/
917#line 919 "common.w"
918;
919/*52:*/
920#line 961 "common.w"
921
922switch(section_name_cmp(&first,name_len,r)){
923
924case prefix:
925if(!ispref){
926printf("\n! New name is a prefix of <");
927
928print_section_name(r);
929err_print(">");
930}
931else if(name_len<prefix_length(r))set_prefix_length(r,name_len);
932
933case equal:return r;
934case extension:if(!ispref||first<=last)
935extend_section_name(r,first,last+1,ispref);
936return r;
937case bad_extension:
938printf("\n! New name extends <");
939
940print_section_name(r);
941err_print(">");
942return r;
943default:
944printf("\n! Section name incompatible with <");
945
946print_prefix_name(r);
947printf(">,\n which abbreviates <");
948print_section_name(r);
949err_print(">");
950return r;
951}
952
953/*:52*/
954#line 920 "common.w"
955;
956}
957
958/*:49*//*54:*/
959#line 1012 "common.w"
960
961int section_name_cmp(pfirst,len,r)
962char**pfirst;
963int len;
964name_pointer r;
965{
966char*first= *pfirst;
967name_pointer q= r+1;
968char*ss,*s= first_chunk(r);
969int c;
970int ispref;
971while(1){
972ss= (r+1)->byte_start-1;
973if(*ss==' '&&ss>=r->byte_start)ispref= 1,q= q->link;
974else ispref= 0,ss++,q= name_dir;
975switch(c= web_strcmp(first,len,s,ss-s)){
976case equal:if(q==name_dir)
977if(ispref){
978*pfirst= first+(ss-s);
979return extension;
980}else return equal;
981else return(q->byte_start==(q+1)->byte_start)?equal:prefix;
982case extension:
983if(!ispref)return bad_extension;
984first+= ss-s;
985if(q!=name_dir){len-= ss-s;s= q->byte_start;r= q;continue;}
986*pfirst= first;return extension;
987default:return c;
988}
989}
990}
991
992/*:54*//*58:*/
993#line 1087 "common.w"
994
995void
996err_print(s)
997char*s;
998{
999char*k,*l;
1000printf(*s=='!'?"\n%s":"%s",s);
1001if(web_file_open)/*59:*/
1002#line 1107 "common.w"
1003
1004{if(changing&&include_depth==change_depth)
1005printf(". (l. %d of change file)\n",change_line);
1006else if(include_depth==0)printf(". (l. %d)\n",cur_line);
1007else printf(". (l. %d of include file %s)\n",cur_line,cur_file_name);
1008l= (loc>=limit?limit:loc);
1009if(l>buffer){
1010for(k= buffer;k<l;k++)
1011if(*k=='\t')putchar(' ');
1012else putchar(*k);
1013putchar('\n');
1014for(k= buffer;k<l;k++)putchar(' ');
1015}
1016for(k= l;k<limit;k++)putchar(*k);
1017if(*limit=='|')putchar('|');
1018putchar(' ');
1019}
1020
1021/*:59*/
1022#line 1094 "common.w"
1023;
1024update_terminal;mark_error;
1025}
1026
1027/*:58*//*61:*/
1028#line 1142 "common.w"
1029
1030int wrap_up(){
1031putchar('\n');
1032if(show_stats)
1033print_stats();
1034/*62:*/
1035#line 1152 "common.w"
1036
1037switch(history){
1038case spotless:if(show_happiness)printf("(No errors were found.)\n");break;
1039case harmless_message:
1040printf("(Did you see the warning message above?)\n");break;
1041case error_message:
1042printf("(Pardon me, but I think I spotted something wrong.)\n");break;
1043case fatal_message:printf("(That was a fatal error, my friend.)\n");
1044}
1045
1046/*:62*/
1047#line 1147 "common.w"
1048;
1049if(history>harmless_message)return(1);
1050else return(0);
1051}
1052
1053/*:61*//*64:*/
1054#line 1171 "common.w"
1055void
1056fatal(s,t)
1057char*s,*t;
1058{
1059if(*s)printf(s);
1060err_print(t);
1061history= fatal_message;exit(wrap_up());
1062}
1063
1064/*:64*//*65:*/
1065#line 1182 "common.w"
1066void
1067overflow(t)
1068char*t;
1069{
1070printf("\n! Sorry, %s capacity exceeded",t);fatal("","");
1071}
1072
1073
1074/*:65*//*70:*/
1075#line 1246 "common.w"
1076
1077void
1078scan_args()
1079{
1080char*dot_pos;
1081char*name_pos;
1082register char*s;
1083boolean found_web= 0,found_change= 0,found_out= 0;
1084
1085boolean flag_change;
1086
1087while(--argc>0){
1088if((**(++argv)=='-'||**argv=='+')&&*(*argv+1))/*74:*/
1089#line 1340 "common.w"
1090
1091{
1092if(**argv=='-')flag_change= 0;
1093else flag_change= 1;
1094for(dot_pos= *argv+1;*dot_pos>'\0';dot_pos++)
1095flags[*dot_pos]= flag_change;
1096}
1097
1098/*:74*/
1099#line 1258 "common.w"
1100
1101else{
1102s= name_pos= *argv;dot_pos= NULL;
1103while(*s){
1104if(*s=='.')dot_pos= s++;
1105else if(*s=='/')dot_pos= NULL,name_pos= ++s;
1106else s++;
1107}
1108if(!found_web)/*71:*/
1109#line 1284 "common.w"
1110
1111{
1112if(s-*argv>max_file_name_length-5)
1113/*76:*/
1114#line 1360 "common.w"
1115fatal("! Filename too long\n",*argv);
1116
1117
1118/*:76*/
1119#line 1287 "common.w"
1120;
1121if(dot_pos==NULL)
1122sprintf(web_file_name,"%s.w",*argv);
1123else{
1124strcpy(web_file_name,*argv);
1125*dot_pos= 0;
1126}
1127sprintf(alt_web_file_name,"%s.web",*argv);
1128sprintf(tex_file_name,"%s.tex",name_pos);
1129sprintf(idx_file_name,"%s.idx",name_pos);
1130sprintf(scn_file_name,"%s.scn",name_pos);
1131sprintf(C_file_name,"%s.c",name_pos);
1132found_web= 1;
1133}
1134
1135/*:71*/
1136#line 1267 "common.w"
1137
1138else if(!found_change)/*72:*/
1139#line 1302 "common.w"
1140
1141{
1142if(strcmp(*argv,"-")==0)found_change= -1;
1143else{
1144if(s-*argv>max_file_name_length-4)
1145/*76:*/
1146#line 1360 "common.w"
1147fatal("! Filename too long\n",*argv);
1148
1149
1150/*:76*/
1151#line 1307 "common.w"
1152;
1153if(dot_pos==NULL)
1154sprintf(change_file_name,"%s.ch",*argv);
1155else strcpy(change_file_name,*argv);
1156found_change= 1;
1157}
1158}
1159
1160/*:72*/
1161#line 1268 "common.w"
1162
1163else if(!found_out)/*73:*/
1164#line 1315 "common.w"
1165
1166{
1167if(s-*argv>max_file_name_length-5)
1168/*76:*/
1169#line 1360 "common.w"
1170fatal("! Filename too long\n",*argv);
1171
1172
1173/*:76*/
1174#line 1318 "common.w"
1175;
1176if(dot_pos==NULL){
1177sprintf(tex_file_name,"%s.tex",*argv);
1178sprintf(idx_file_name,"%s.idx",*argv);
1179sprintf(scn_file_name,"%s.scn",*argv);
1180sprintf(C_file_name,"%s.c",*argv);
1181}else{
1182strcpy(tex_file_name,*argv);
1183if(flags['x']){
1184if(program==cweave&&strcmp(*argv+strlen(*argv)-4,".tex")!=0)
1185fatal("! Output file name should end with .tex\n",*argv);
1186
1187strcpy(idx_file_name,*argv);
1188strcpy(idx_file_name+strlen(*argv)-4,".idx");
1189strcpy(scn_file_name,*argv);
1190strcpy(scn_file_name+strlen(*argv)-4,".scn");
1191}
1192strcpy(C_file_name,*argv);
1193}
1194found_out= 1;
1195}
1196
1197/*:73*/
1198#line 1269 "common.w"
1199
1200else/*75:*/
1201#line 1348 "common.w"
1202
1203{
1204if(program==ctangle)
1205fatal(
1206"! Usage: ctangle [options] webfile[.w] [{changefile[.ch]|-} [outfile[.c]]]\n"
1207,"");
1208
1209else fatal(
1210"! Usage: cweave [options] webfile[.w] [{changefile[.ch]|-} [outfile[.tex]]]\n"
1211,"");
1212}
1213
1214/*:75*/
1215#line 1270 "common.w"
1216;
1217}
1218}
1219if(!found_web)/*75:*/
1220#line 1348 "common.w"
1221
1222{
1223if(program==ctangle)
1224fatal(
1225"! Usage: ctangle [options] webfile[.w] [{changefile[.ch]|-} [outfile[.c]]]\n"
1226,"");
1227
1228else fatal(
1229"! Usage: cweave [options] webfile[.w] [{changefile[.ch]|-} [outfile[.tex]]]\n"
1230,"");
1231}
1232
1233/*:75*/
1234#line 1273 "common.w"
1235;
1236if(found_change<=0)strcpy(change_file_name,"/dev/null");
1237}
1238
1239/*:70*/
common.h+192−0
@@ -0,0 +1,192 @@
1% This file is part of CWEB.
2% This program by Silvio Levy and Donald E. Knuth
3% is based on a program by Knuth.
4% It is distributed WITHOUT ANY WARRANTY, express or implied.
5% Version 3.0 --- June 1993
6
7% Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
8
9% Permission is granted to make and distribute verbatim copies of this
10% document provided that the copyright notice and this permission notice
11% are preserved on all copies.
12
13% Permission is granted to copy and distribute modified versions of this
14% document under the conditions for verbatim copying, provided that the
15% entire resulting derived work is distributed under the terms of a
16% permission notice identical to this one.
17
18% Please send comments, suggestions, etc. to levy@@geom.umn.edu.
19
20% The next few sections contain stuff from the file |"common.w"| that has
21% to be included in both |"ctangle.w"| and |"cweave.w"|. It appears in this
22% file |"common.h"|, which needs to be updated when |"common.w"| changes.
23
24First comes general stuff:
25
26@d ctangle 0
27@d cweave 1
28
29@<Common code for \.{CWEAVE} and \.{CTANGLE}@>=
30typedef short boolean;
31typedef char unsigned eight_bits;
32extern boolean program; /* \.{CWEAVE} or \.{CTANGLE}? */
33extern int phase; /* which phase are we in? */
34
35@ @<Include files@>=
36#include <stdio.h>
37
38@ Code related to the character set:
39@^ASCII code dependencies@>
40
41@d and_and 04 /* `\.{\&\&}'\,; corresponds to MIT's {\tentex\char'4} */
42@d lt_lt 020 /* `\.{<<}'\,; corresponds to MIT's {\tentex\char'20} */
43@d gt_gt 021 /* `\.{>>}'\,; corresponds to MIT's {\tentex\char'21} */
44@d plus_plus 013 /* `\.{++}'\,; corresponds to MIT's {\tentex\char'13} */
45@d minus_minus 01 /* `\.{--}'\,; corresponds to MIT's {\tentex\char'1} */
46@d minus_gt 031 /* `\.{->}'\,; corresponds to MIT's {\tentex\char'31} */
47@d not_eq 032 /* `\.{!=}'\,; corresponds to MIT's {\tentex\char'32} */
48@d lt_eq 034 /* `\.{<=}'\,; corresponds to MIT's {\tentex\char'34} */
49@d gt_eq 035 /* `\.{>=}'\,; corresponds to MIT's {\tentex\char'35} */
50@d eq_eq 036 /* `\.{==}'\,; corresponds to MIT's {\tentex\char'36} */
51@d or_or 037 /* `\.{\v\v}'\,; corresponds to MIT's {\tentex\char'37} */
52@d dot_dot_dot 016 /* `\.{...}'\,; corresponds to MIT's {\tentex\char'16} */
53@d colon_colon 06 /* `\.{::}'\,; corresponds to MIT's {\tentex\char'6} */
54@d period_ast 026 /* `\.{.*}'\,; corresponds to MIT's {\tentex\char'26} */
55@d minus_gt_ast 027 /* `\.{->*}'\,; corresponds to MIT's {\tentex\char'27} */
56
57@<Common code...@>=
58char section_text[longest_name+1]; /* name being sought for */
59char *section_text_end = section_text+longest_name; /* end of |section_text| */
60char *id_first; /* where the current identifier begins in the buffer */
61char *id_loc; /* just after the current identifier in the buffer */
62
63@ Code related to input routines:
64
65@d xisalpha(c) (isalpha(c)&&((eight_bits)c<0200))
66@d xisdigit(c) (isdigit(c)&&((eight_bits)c<0200))
67@d xisspace(c) (isspace(c)&&((eight_bits)c<0200))
68@d xislower(c) (islower(c)&&((eight_bits)c<0200))
69@d xisupper(c) (isupper(c)&&((eight_bits)c<0200))
70@d xisxdigit(c) (isxdigit(c)&&((eight_bits)c<0200))
71
72@<Common code...@>=
73extern char buffer[]; /* where each line of input goes */
74extern char *buffer_end; /* end of |buffer| */
75extern char *loc; /* points to the next character to be read from the buffer*/
76extern char *limit; /* points to the last character in the buffer */
77
78@ Code related to identifier and section name storage:
79@d length(c) (c+1)->byte_start-(c)->byte_start /* the length of a name */
80@d print_id(c) term_write((c)->byte_start,length((c))) /* print identifier */
81@d llink link /* left link in binary search tree for section names */
82@d rlink dummy.Rlink /* right link in binary search tree for section names */
83@d root name_dir->rlink /* the root of the binary search tree
84 for section names */
85@d chunk_marker 0
86
87@<Common code...@>=
88typedef struct name_info {
89 char *byte_start; /* beginning of the name in |byte_mem| */
90 struct name_info *link;
91 union {
92 struct name_info *Rlink; /* right link in binary search tree for section
93 names */
94 char Ilk; /* used by identifiers in \.{CWEAVE} only */
95 } dummy;
96 char *equiv_or_xref; /* info corresponding to names */
97} name_info; /* contains information about an identifier or section name */
98typedef name_info *name_pointer; /* pointer into array of \&{name\_info}s */
99typedef name_pointer *hash_pointer;
100extern char byte_mem[]; /* characters of names */
101extern char *byte_mem_end; /* end of |byte_mem| */
102extern name_info name_dir[]; /* information about names */
103extern name_pointer name_dir_end; /* end of |name_dir| */
104extern name_pointer name_ptr; /* first unused position in |byte_start| */
105extern char *byte_ptr; /* first unused position in |byte_mem| */
106extern name_pointer hash[]; /* heads of hash lists */
107extern hash_pointer hash_end; /* end of |hash| */
108extern hash_pointer h; /* index into hash-head array */
109extern name_pointer id_lookup(); /* looks up a string in the identifier table */
110extern name_pointer section_lookup(); /* finds section name */
111extern void print_section_name(), sprint_section_name();
112
113@ Code related to error handling:
114@d spotless 0 /* |history| value for normal jobs */
115@d harmless_message 1 /* |history| value when non-serious info was printed */
116@d error_message 2 /* |history| value when an error was noted */
117@d fatal_message 3 /* |history| value when we had to stop prematurely */
118@d mark_harmless {if (history==spotless) history=harmless_message;}
119@d mark_error history=error_message
120@d confusion(s) fatal("! This can't happen: ",s)
121
122@<Common...@>=
123extern history; /* indicates how bad this run was */
124extern err_print(); /* print error message and context */
125extern wrap_up(); /* indicate |history| and exit */
126extern void fatal(); /* issue error message and die */
127extern void overflow(); /* succumb because a table has overflowed */
128
129@ Code related to file handling:
130@f line x /* make |line| an unreserved word */
131@d max_file_name_length 60
132@d cur_file file[include_depth] /* current file */
133@d cur_file_name file_name[include_depth] /* current file name */
134@d web_file_name file_name[0] /* main source file name */
135@d cur_line line[include_depth] /* number of current line in current file */
136
137@<Common code...@>=
138extern include_depth; /* current level of nesting */
139extern FILE *file[]; /* stack of non-change files */
140extern FILE *change_file; /* change file */
141extern char C_file_name[]; /* name of |C_file| */
142extern char tex_file_name[]; /* name of |tex_file| */
143extern char idx_file_name[]; /* name of |idx_file| */
144extern char scn_file_name[]; /* name of |scn_file| */
145extern char file_name[][max_file_name_length];
146 /* stack of non-change file names */
147extern char change_file_name[]; /* name of change file */
148extern line[]; /* number of current line in the stacked files */
149extern change_line; /* number of current line in change file */
150extern boolean input_has_ended; /* if there is no more input */
151extern boolean changing; /* if the current line is from |change_file| */
152extern boolean web_file_open; /* if the web file is being read */
153extern reset_input(); /* initialize to read the web file and change file */
154extern get_line(); /* inputs the next line */
155extern check_complete(); /* checks that all changes were picked up */
156
157@ Code related to section numbers:
158@<Common code...@>=
159typedef unsigned short sixteen_bits;
160extern sixteen_bits section_count; /* the current section number */
161extern boolean changed_section[]; /* is the section changed? */
162extern boolean change_pending; /* is a decision about change still unclear? */
163extern boolean print_where; /* tells \.{CTANGLE} to print line and file info */
164
165@ Code related to command line arguments:
166@d show_banner flags['b'] /* should the banner line be printed? */
167@d show_progress flags['p'] /* should progress reports be printed? */
168@d show_happiness flags['h'] /* should lack of errors be announced? */
169
170@<Common code...@>=
171extern int argc; /* copy of |ac| parameter to |main| */
172extern char **argv; /* copy of |av| parameter to |main| */
173extern boolean flags[]; /* an option for each 7-bit code */
174
175@ Code relating to output:
176@d update_terminal fflush(stdout) /* empty the terminal output buffer */
177@d new_line putchar('\n') @d putxchar putchar
178@d term_write(a,b) fflush(stdout),fwrite(a,sizeof(char),b,stdout)
179@d C_printf(c,a) fprintf(C_file,c,a)
180@d C_putc(c) putc(c,C_file)
181
182@<Common code...@>=
183extern FILE *C_file; /* where output of \.{CTANGLE} goes */
184extern FILE *tex_file; /* where output of \.{CWEAVE} goes */
185extern FILE *idx_file; /* where index from \.{CWEAVE} goes */
186extern FILE *scn_file; /* where list of sections from \.{CWEAVE} goes */
187extern FILE *active_file; /* currently active file for \.{CWEAVE} output */
188
189@ The procedure that gets everything rolling:
190
191@<Common code...@>=
192extern void common_init();
common.w+1414−0
@@ -0,0 +1,1414 @@
1% This file is part of CWEB.
2% This program by Silvio Levy and Donald E. Knuth
3% is based on a program by Knuth.
4% It is distributed WITHOUT ANY WARRANTY, express or implied.
5% Version 3.1 --- November 1993 (works with later versions too)
6
7% Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
8
9% Permission is granted to make and distribute verbatim copies of this
10% document provided that the copyright notice and this permission notice
11% are preserved on all copies.
12
13% Permission is granted to copy and distribute modified versions of this
14% document under the conditions for verbatim copying, provided that the
15% entire resulting derived work is given a different name and distributed
16% under the terms of a permission notice identical to this one.
17
18\def\v{\char'174} % vertical (|) in typewriter font
19
20\def\title{Common code for CTANGLE and CWEAVE (Version 3.1)}
21\def\topofcontents{\null\vfill
22 \centerline{\titlefont Common code for {\ttitlefont CTANGLE} and
23 {\ttitlefont CWEAVE}}
24 \vskip 15pt
25 \centerline{(Version 3.1)}
26 \vfill}
27\def\botofcontents{\vfill
28\noindent
29Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
30\bigskip\noindent
31Permission is granted to make and distribute verbatim copies of this
32document provided that the copyright notice and this permission notice
33are preserved on all copies.
34
35\smallskip\noindent
36Permission is granted to copy and distribute modified versions of this
37document under the conditions for verbatim copying, provided that the
38entire resulting derived work is given a different name and distributed
39under the terms of a permission notice identical to this one.
40}
41
42\pageno=\contentspagenumber \advance\pageno by 1
43\let\maybe=\iftrue
44
45@** Introduction. This file contains code common
46to both \.{CTANGLE} and \.{CWEAVE}, which roughly concerns the following
47problems: character uniformity, input routines, error handling and
48parsing of command line. We have tried to concentrate in this file
49all the system dependencies, so as to maximize portability.
50
51In the texts below we will
52sometimes use \.{CWEB} to refer to either of the two component
53programs, if no confusion can arise.
54
55The file begins with a few basic definitions.
56
57@c
58@<Include files@>@/
59@h
60@<Definitions that should agree with \.{CTANGLE} and \.{CWEAVE}@>@/
61@<Other definitions@>@/
62@<Predeclaration of procedures@>@/
63
64@ In certain cases \.{CTANGLE} and \.{CWEAVE} should do almost, but not
65quite, the same thing. In these cases we've written common code for
66both, differentiating between the two by means of the global variable
67|program|.
68
69@d ctangle 0
70@d cweave 1
71
72@<Definitions...@>=
73typedef short boolean;
74boolean program; /* \.{CWEAVE} or \.{CTANGLE}? */
75
76@ \.{CWEAVE} operates in three phases: first it inputs the source
77file and stores cross-reference data, then it inputs the source once again and
78produces the \TEX/ output file, and finally it sorts and outputs the index.
79Similarly, \.{CTANGLE} operates in two phases.
80The global variable |phase| tells which phase we are in.
81
82@<Other...@>= int phase; /* which phase are we in? */
83
84@ There's an initialization procedure that gets both \.{CTANGLE} and
85\.{CWEAVE} off to a good start. We will fill in the details of this
86procedure later.
87
88@c
89void
90common_init()
91{
92 @<Initialize pointers@>;
93 @<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>;
94 @<Scan arguments and open output files@>;
95}
96
97@*1 The character set.
98\.{CWEB} uses the conventions of \CEE/ programs found in the standard
99\.{ctype.h} header file.
100
101@<Include files@>=
102#include <ctype.h>
103
104@ A few character pairs are encoded internally as single characters,
105using the definitions below. These definitions are consistent with
106an extension of ASCII code originally developed at MIT and explained in
107Appendix~C of {\sl The \TEX/book\/}; thus, users who have such a
108character set can type things like \.{\char'32} and \.{char'4} instead
109of \.{!=} and \.{\&\&}. (However, their files will not be too portable
110until more people adopt the extended code.)
111
112If the character set is not ASCII, the definitions given here may conflict
113with existing characters; in such cases, other arbitrary codes should be
114substituted. The indexes to \.{CTANGLE} and \.{CWEAVE} mention every
115case where similar codes may have to be changed in order to
116avoid character conflicts. Look for the entry ``ASCII code dependencies''
117in those indexes.
118
119@^ASCII code dependencies@>
120@^system dependencies@>
121
122@d and_and 04 /* `\.{\&\&}'\,; corresponds to MIT's {\tentex\char'4} */
123@d lt_lt 020 /* `\.{<<}'\,; corresponds to MIT's {\tentex\char'20} */
124@d gt_gt 021 /* `\.{>>}'\,; corresponds to MIT's {\tentex\char'21} */
125@d plus_plus 013 /* `\.{++}'\,; corresponds to MIT's {\tentex\char'13} */
126@d minus_minus 01 /* `\.{--}'\,; corresponds to MIT's {\tentex\char'1} */
127@d minus_gt 031 /* `\.{->}'\,; corresponds to MIT's {\tentex\char'31} */
128@d not_eq 032 /* `\.{!=}'\,; corresponds to MIT's {\tentex\char'32} */
129@d lt_eq 034 /* `\.{<=}'\,; corresponds to MIT's {\tentex\char'34} */
130@d gt_eq 035 /* `\.{>=}'\,; corresponds to MIT's {\tentex\char'35} */
131@d eq_eq 036 /* `\.{==}'\,; corresponds to MIT's {\tentex\char'36} */
132@d or_or 037 /* `\.{\v\v}'\,; corresponds to MIT's {\tentex\char'37} */
133@d dot_dot_dot 016 /* `\.{...}'\,; corresponds to MIT's {\tentex\char'16} */
134@d colon_colon 06 /* `\.{::}'\,; corresponds to MIT's {\tentex\char'6} */
135@d period_ast 026 /* `\.{.*}'\,; corresponds to MIT's {\tentex\char'26} */
136@d minus_gt_ast 027 /* `\.{->*}'\,; corresponds to MIT's {\tentex\char'27} */
137
138@** Input routines. The lowest level of input to the \.{CWEB} programs
139is performed by |input_ln|, which must be told which file to read from.
140The return value of |input_ln| is 1 if the read is successful and 0 if
141not (generally this means the file has ended). The conventions
142of \TEX/ are followed; i.e., the characters of the next line of the file
143are copied into the |buffer| array,
144and the global variable |limit| is set to the first unoccupied position.
145Trailing blanks are ignored. The value of |limit| must be strictly less
146than |buf_size|, so that |buffer[buf_size-1]| is never filled.
147
148Since |buf_size| is strictly less than |long_buf_size|,
149some of \.{CWEB}'s routines use the fact that it is safe to refer to
150|*(limit+2)| without overstepping the bounds of the array.
151
152@d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
153@d long_buf_size 500 /* for \.{CWEAVE} */
154@d xisspace(c) (isspace(c)&&((unsigned char)c<0200))
155@d xisupper(c) (isupper(c)&&((unsigned char)c<0200))
156
157@<Definitions...@>=
158char buffer[long_buf_size]; /* where each line of input goes */
159char *buffer_end=buffer+buf_size-2; /* end of |buffer| */
160char *limit=buffer; /* points to the last character in the buffer */
161char *loc=buffer; /* points to the next character to be read from the buffer */
162
163@ @<Include files@>=
164#include <stdio.h>
165
166@ In the unlikely event that your standard I/O library does not
167support |feof|, |getc| and |ungetc| you may have to change things here.
168@^system dependencies@>
169
170@c
171int input_ln(fp) /* copies a line into |buffer| or returns 0 */
172FILE *fp; /* what file to read from */
173{
174 register int c=EOF; /* character read; initialized so some compilers won't complain */
175 register char *k; /* where next character goes */
176 if (feof(fp)) return(0); /* we have hit end-of-file */
177 limit = k = buffer; /* beginning of buffer */
178 while (k<=buffer_end && (c=getc(fp)) != EOF && c!='\n')
179 if ((*(k++) = c) != ' ') limit = k;
180 if (k>buffer_end)
181 if ((c=getc(fp))!=EOF && c!='\n') {
182 ungetc(c,fp); loc=buffer; err_print("! Input line too long");
183@.Input line too long@>
184 }
185 if (c==EOF && limit==buffer) return(0); /* there was nothing after
186 the last newline */
187 return(1);
188}
189
190@ Now comes the problem of deciding which file to read from next.
191Recall that the actual text that \.{CWEB} should process comes from two
192streams: a |web_file|, which can contain possibly nested include
193commands \.{@@i}, and a |change_file|, which might also contain
194includes. The |web_file| together with the currently open include
195files form a stack |file|, whose names are stored in a parallel stack
196|file_name|. The boolean |changing| tells whether or not we're reading
197from the |change_file|.
198
199The line number of each open file is also kept for error reporting and
200for the benefit of \.{CTANGLE}.
201
202@f line x /* make |line| an unreserved word */
203@d max_include_depth 10 /* maximum number of source files open
204 simultaneously, not counting the change file */
205@d max_file_name_length 60
206@d cur_file file[include_depth] /* current file */
207@d cur_file_name file_name[include_depth] /* current file name */
208@d cur_line line[include_depth] /* number of current line in current file */
209@d web_file file[0] /* main source file */
210@d web_file_name file_name[0] /* main source file name */
211
212@<Definitions...@>=
213int include_depth; /* current level of nesting */
214FILE *file[max_include_depth]; /* stack of non-change files */
215FILE *change_file; /* change file */
216char file_name[max_include_depth][max_file_name_length];
217 /* stack of non-change file names */
218char change_file_name[max_file_name_length]; /* name of change file */
219char alt_web_file_name[max_file_name_length]; /* alternate name to try */
220int line[max_include_depth]; /* number of current line in the stacked files */
221int change_line; /* number of current line in change file */
222int change_depth; /* where \.{@@y} originated during a change */
223boolean input_has_ended; /* if there is no more input */
224boolean changing; /* if the current line is from |change_file| */
225boolean web_file_open=0; /* if the web file is being read */
226
227@ When |changing==0|, the next line of |change_file| is kept in
228|change_buffer|, for purposes of comparison with the next
229line of |cur_file|. After the change file has been completely input, we
230set |change_limit=change_buffer|,
231so that no further matches will be made.
232
233Here's a shorthand expression for inequality between the two lines:
234
235@d lines_dont_match (change_limit-change_buffer != limit-buffer ||
236 strncmp(buffer, change_buffer, limit-buffer))
237
238@<Other...@>=
239char change_buffer[buf_size]; /* next line of |change_file| */
240char *change_limit; /* points to the last character in |change_buffer| */
241
242@ Procedure |prime_the_change_buffer|
243sets |change_buffer| in preparation for the next matching operation.
244Since blank lines in the change file are not used for matching, we have
245|(change_limit==change_buffer && !changing)| if and only if
246the change file is exhausted. This procedure is called only when
247|changing| is 1; hence error messages will be reported correctly.
248
249@c
250void
251prime_the_change_buffer()
252{
253 change_limit=change_buffer; /* this value is used if the change file ends */
254 @<Skip over comment lines in the change file; |return| if end of file@>;
255 @<Skip to the next nonblank line; |return| if end of file@>;
256 @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
257}
258
259@ While looking for a line that begins with \.{@@x} in the change file, we
260allow lines that begin with \.{@@}, as long as they don't begin with \.{@@y},
261\.{@@z} or \.{@@i} (which would probably mean that the change file is fouled up).
262
263@<Skip over comment lines in the change file...@>=
264while(1) {
265 change_line++;
266 if (!input_ln(change_file)) return;
267 if (limit<buffer+2) continue;
268 if (buffer[0]!='@@') continue;
269 if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
270 if (buffer[1]=='x') break;
271 if (buffer[1]=='y' || buffer[1]=='z' || buffer[1]=='i') {
272 loc=buffer+2;
273 err_print("! Missing @@x in change file");
274@.Missing @@x...@>
275 }
276}
277
278@ Here we are looking at lines following the \.{@@x}.
279
280@<Skip to the next nonblank line...@>=
281do {
282 change_line++;
283 if (!input_ln(change_file)) {
284 err_print("! Change file ended after @@x");
285@.Change file ended...@>
286 return;
287 }
288} while (limit==buffer);
289
290@ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
291{
292 change_limit=change_buffer-buffer+limit;
293 strncpy(change_buffer,buffer,limit-buffer+1);
294}
295
296@ The following procedure is used to see if the next change entry should
297go into effect; it is called only when |changing| is 0.
298The idea is to test whether or not the current
299contents of |buffer| matches the current contents of |change_buffer|.
300If not, there's nothing more to do; but if so, a change is called for:
301All of the text down to the \.{@@y} is supposed to match. An error
302message is issued if any discrepancy is found. Then the procedure
303prepares to read the next line from |change_file|.
304
305When a match is found, the current section is marked as changed unless
306the first line after the \.{@@x} and after the \.{@@y} both start with
307either |'@@*'| or |'@@ '| (possibly preceded by whitespace).
308
309This procedure is called only when |buffer<limit|, i.e., when the
310current line is nonempty.
311
312@d if_section_start_make_pending(b) {@+*limit='!';
313 for (loc=buffer;xisspace(*loc);loc++) ;
314 *limit=' ';
315 if (*loc=='@@' && (xisspace(*(loc+1)) || *(loc+1)=='*')) change_pending=b;
316}
317
318@c
319void
320check_change() /* switches to |change_file| if the buffers match */
321{
322 int n=0; /* the number of discrepancies found */
323 if (lines_dont_match) return;
324 change_pending=0;
325 if (!changed_section[section_count]) {
326 if_section_start_make_pending(1);
327 if (!change_pending) changed_section[section_count]=1;
328 }
329 while (1) {
330 changing=1; print_where=1; change_line++;
331 if (!input_ln(change_file)) {
332 err_print("! Change file ended before @@y");
333@.Change file ended...@>
334 change_limit=change_buffer; changing=0;
335 return;
336 }
337 if (limit>buffer+1 && buffer[0]=='@@') {
338 if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
339 @<If the current line starts with \.{@@y},
340 report any discrepancies and |return|@>;
341 }
342 @<Move |buffer| and |limit|...@>;
343 changing=0; cur_line++;
344 while (!input_ln(cur_file)) { /* pop the stack or quit */
345 if (include_depth==0) {
346 err_print("! CWEB file ended during a change");
347@.CWEB file ended...@>
348 input_has_ended=1; return;
349 }
350 include_depth--; cur_line++;
351 }
352 if (lines_dont_match) n++;
353 }
354}
355
356@ @<If the current line starts with \.{@@y}...@>=
357if (buffer[1]=='x' || buffer[1]=='z') {
358 loc=buffer+2; err_print("! Where is the matching @@y?");
359@.Where is the match...@>
360 }
361else if (buffer[1]=='y') {
362 if (n>0) {
363 loc=buffer+2;
364 printf("\n! Hmm... %d ",n);
365 err_print("of the preceding lines failed to match");
366@.Hmm... n of the preceding...@>
367 }
368 change_depth=include_depth;
369 return;
370}
371
372@ The |reset_input| procedure, which gets \.{CWEB} ready to read the
373user's \.{CWEB} input, is used at the beginning of phase one of \.{CTANGLE},
374phases one and two of \.{CWEAVE}.
375
376@c
377void
378reset_input()
379{
380 limit=buffer; loc=buffer+1; buffer[0]=' ';
381 @<Open input files@>;
382 include_depth=0; cur_line=0; change_line=0;
383 change_depth=include_depth;
384 changing=1; prime_the_change_buffer(); changing=!changing;
385 limit=buffer; loc=buffer+1; buffer[0]=' '; input_has_ended=0;
386}
387
388@ The following code opens the input files.
389@^system dependencies@>
390
391@<Open input files@>=
392if ((web_file=fopen(web_file_name,"r"))==NULL) {
393 strcpy(web_file_name,alt_web_file_name);
394 if ((web_file=fopen(web_file_name,"r"))==NULL)
395 fatal("! Cannot open input file ", web_file_name);
396}
397@.Cannot open input file@>
398@.Cannot open change file@>
399web_file_open=1;
400if ((change_file=fopen(change_file_name,"r"))==NULL)
401 fatal("! Cannot open change file ", change_file_name);
402
403@ The |get_line| procedure is called when |loc>limit|; it puts the next
404line of merged input into the buffer and updates the other variables
405appropriately. A space is placed at the right end of the line.
406This procedure returns |!input_has_ended| because we often want to
407check the value of that variable after calling the procedure.
408
409If we've just changed from the |cur_file| to the |change_file|, or if
410the |cur_file| has changed, we tell \.{CTANGLE} to print this
411information in the \CEE/ file by means of the |print_where| flag.
412
413@d max_sections 2000 /* number of identifiers, strings, section names;
414 must be less than 10240 */
415
416@<Defin...@>=
417typedef unsigned short sixteen_bits;
418sixteen_bits section_count; /* the current section number */
419boolean changed_section[max_sections]; /* is the section changed? */
420boolean change_pending; /* if the current change is not yet recorded in
421 |changed_section[section_count]| */
422boolean print_where=0; /* should \.{CTANGLE} print line and file info? */
423
424@ @c
425int get_line() /* inputs the next line */
426{
427 restart:
428 if (changing && include_depth==change_depth)
429 @<Read from |change_file| and maybe turn off |changing|@>;
430 if (! changing || include_depth>change_depth) {
431 @<Read from |cur_file| and maybe turn on |changing|@>;
432 if (changing && include_depth==change_depth) goto restart;
433 }
434 loc=buffer; *limit=' ';
435 if (*buffer=='@@' && (*(buffer+1)=='i' || *(buffer+1)=='I')) {
436 loc=buffer+2;
437 while (loc<=limit && (*loc==' '||*loc=='\t'||*loc=='"')) loc++;
438 if (loc>=limit) {
439 err_print("! Include file name not given");
440@.Include file name ...@>
441 goto restart;
442 }
443 if (include_depth>=max_include_depth-1) {
444 err_print("! Too many nested includes");
445@.Too many nested includes@>
446 goto restart;
447 }
448 include_depth++; /* push input stack */
449 @<Try to open include file, abort push if unsuccessful, go to |restart|@>;
450 }
451 return (!input_has_ended);
452}
453
454@ When an \.{@@i} line is found in the |cur_file|, we must temporarily
455stop reading it and start reading from the named include file. The
456\.{@@i} line should give a complete file name with or without
457double quotes.
458If the environment variable \.{CWEBINPUTS} is set, or if the compiler flag
459of the same name was defined at compile time,
460\.{CWEB} will look for include files in the directory thus named, if
461it cannot find them in the current directory.
462(Colon-separated paths are not supported.)
463The remainder of the \.{@@i} line after the file name is ignored.
464
465@d too_long() {include_depth--;
466 err_print("! Include file name too long"); goto restart;}
467
468@<Include...@>=
469#include <stdlib.h> /* declaration of |getenv| and |exit| */
470
471@ @<Try to open...@>= {
472 char temp_file_name[max_file_name_length];
473 char *cur_file_name_end=cur_file_name+max_file_name_length-1;
474 char *k=cur_file_name, *kk;
475 int l; /* length of file name */
476
477 while (*loc!=' '&&*loc!='\t'&&*loc!='"'&&k<=cur_file_name_end) *k++=*loc++;
478 if (k>cur_file_name_end) too_long();
479@.Include file name ...@>
480 *k='\0';
481 if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
482 cur_line=0; print_where=1;
483 goto restart; /* success */
484 }
485 kk=getenv("CWEBINPUTS");
486 if (kk!=NULL) {
487 if ((l=strlen(kk))>max_file_name_length-2) too_long();
488 strcpy(temp_file_name,kk);
489 }
490 else {
491#ifdef CWEBINPUTS
492 if ((l=strlen(CWEBINPUTS))>max_file_name_length-2) too_long();
493 strcpy(temp_file_name,CWEBINPUTS);
494#else
495 l=0;
496#endif /* |CWEBINPUTS| */
497 }
498 if (l>0) {
499 if (k+l+2>=cur_file_name_end) too_long();
500@.Include file name ...@>
501 for (; k>= cur_file_name; k--) *(k+l+1)=*k;
502 strcpy(cur_file_name,temp_file_name);
503 cur_file_name[l]='/'; /* \UNIX/ pathname separator */
504 if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
505 cur_line=0; print_where=1;
506 goto restart; /* success */
507 }
508 }
509 include_depth--; err_print("! Cannot open include file"); goto restart;
510}
511
512@ @<Read from |cur_file|...@>= {
513 cur_line++;
514 while (!input_ln(cur_file)) { /* pop the stack or quit */
515 print_where=1;
516 if (include_depth==0) {input_has_ended=1; break;}
517 else {
518 fclose(cur_file); include_depth--;
519 if (changing && include_depth==change_depth) break;
520 cur_line++;
521 }
522 }
523 if (!changing && !input_has_ended)
524 if (limit-buffer==change_limit-change_buffer)
525 if (buffer[0]==change_buffer[0])
526 if (change_limit>change_buffer) check_change();
527}
528
529@ @<Read from |change_file|...@>= {
530 change_line++;
531 if (!input_ln(change_file)) {
532 err_print("! Change file ended without @@z");
533@.Change file ended...@>
534 buffer[0]='@@'; buffer[1]='z'; limit=buffer+2;
535 }
536 if (limit>buffer) { /* check if the change has ended */
537 if (change_pending) {
538 if_section_start_make_pending(0);
539 if (change_pending) {
540 changed_section[section_count]=1; change_pending=0;
541 }
542 }
543 *limit=' ';
544 if (buffer[0]=='@@') {
545 if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
546 if (buffer[1]=='x' || buffer[1]=='y') {
547 loc=buffer+2;
548 err_print("! Where is the matching @@z?");
549@.Where is the match...@>
550 }
551 else if (buffer[1]=='z') {
552 prime_the_change_buffer(); changing=!changing; print_where=1;
553 }
554 }
555 }
556}
557
558@ At the end of the program, we will tell the user if the change file
559had a line that didn't match any relevant line in |web_file|.
560
561@c
562void
563check_complete(){
564 if (change_limit!=change_buffer) { /* |changing| is 0 */
565 strncpy(buffer,change_buffer,change_limit-change_buffer+1);
566 limit=buffer+(int)(change_limit-change_buffer);
567 changing=1; change_depth=include_depth; loc=buffer;
568 err_print("! Change file entry did not match");
569@.Change file entry did not match@>
570 }
571}
572
573@** Storage of names and strings.
574Both \.{CWEAVE} and \.{CTANGLE} store identifiers, section names and
575other strings in a large array of |char|s, called |byte_mem|.
576Information about the names is kept in the array |name_dir|, whose
577elements are structures of type |name_info|, containing a pointer into
578the |byte_mem| array (the address where the name begins) and other data.
579A |name_pointer| variable is a pointer into |name_dir|.
580
581@d max_bytes 90000 /* the number of bytes in identifiers,
582 index entries, and section names; must be less than $2^{24}$ */
583@d max_names 4000 /* number of identifiers, strings, section names;
584 must be less than 10240 */
585
586@<Definitions that...@>=
587typedef struct name_info {
588 char *byte_start; /* beginning of the name in |byte_mem| */
589 @<More elements of |name_info| structure@>@;
590} name_info; /* contains information about an identifier or section name */
591typedef name_info *name_pointer; /* pointer into array of |name_info|s */
592char byte_mem[max_bytes]; /* characters of names */
593char *byte_mem_end = byte_mem+max_bytes-1; /* end of |byte_mem| */
594name_info name_dir[max_names]; /* information about names */
595name_pointer name_dir_end = name_dir+max_names-1; /* end of |name_dir| */
596
597@ The actual sequence of characters in the name pointed to by a |name_pointer
598p| appears in positions |p->byte_start| to |(p+1)->byte_start-1|, inclusive.
599The |print_id| macro prints this text on the user's terminal.
600
601@d length(c) (c+1)->byte_start-(c)->byte_start /* the length of a name */
602@d print_id(c) term_write((c)->byte_start,length((c))) /* print identifier */
603
604@ The first unused position in |byte_mem| and |name_dir| is
605kept in |byte_ptr| and |name_ptr|, respectively. Thus we
606usually have |name_ptr->byte_start==byte_ptr|, and certainly
607we want to keep |name_ptr<=name_dir_end| and |byte_ptr<=byte_mem_end|.
608
609@<Defini...@>=
610name_pointer name_ptr; /* first unused position in |byte_start| */
611char *byte_ptr; /* first unused position in |byte_mem| */
612
613@ @<Init...@>=
614name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
615name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
616name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
617
618@ The names of identifiers are found by computing a hash address |h| and
619then looking at strings of bytes signified by the |name_pointer|s
620|hash[h]|, |hash[h]->link|, |hash[h]->link->link|, \dots,
621until either finding the desired name or encountering the null pointer.
622
623@<More elements of |name...@>=
624struct name_info *link;
625
626@ The hash table itself
627consists of |hash_size| entries of type |name_pointer|, and is
628updated by the |id_lookup| procedure, which finds a given identifier
629and returns the appropriate |name_pointer|. The matching is done by the
630function |names_match|, which is slightly different in
631\.{CWEAVE} and \.{CTANGLE}. If there is no match for the identifier,
632it is inserted into the table.
633
634@d hash_size 353 /* should be prime */
635
636@<Defini...@>=
637typedef name_pointer *hash_pointer;
638name_pointer hash[hash_size]; /* heads of hash lists */
639hash_pointer hash_end = hash+hash_size-1; /* end of |hash| */
640hash_pointer h; /* index into hash-head array */
641
642@ @<Predec...@>=
643extern int names_match();
644
645@ Initially all the hash lists are empty.
646
647@<Init...@>=
648for (h=hash; h<=hash_end; *h++=NULL) ;
649
650@ Here is the main procedure for finding identifiers:
651
652@c
653name_pointer
654id_lookup(first,last,t) /* looks up a string in the identifier table */
655char *first; /* first character of string */
656char *last; /* last character of string plus one */
657char t; /* the |ilk|; used by \.{CWEAVE} only */
658{
659 char *i=first; /* position in |buffer| */
660 int h; /* hash code */
661 int l; /* length of the given identifier */
662 name_pointer p; /* where the identifier is being sought */
663 if (last==NULL) for (last=first; *last!='\0'; last++);
664 l=last-first; /* compute the length */
665 @<Compute the hash code |h|@>;
666 @<Compute the name location |p|@>;
667 if (p==name_ptr) @<Enter a new name into the table at position |p|@>;
668 return(p);
669}
670
671@ A simple hash code is used: If the sequence of
672character codes is $c_1c_2\ldots c_n$, its hash value will be
673$$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
674
675@<Compute the hash...@>=
676h=(unsigned char)*i;
677while (++i<last) h=(h+h+(int)((unsigned char)*i)) % hash_size;
678@^high-bit character handling@>
679
680@ If the identifier is new, it will be placed in position |p=name_ptr|,
681otherwise |p| will point to its existing location.
682
683@<Compute the name location...@>=
684p=hash[h];
685while (p && !names_match(p,first,l,t)) p=p->link;
686if (p==NULL) {
687 p=name_ptr; /* the current identifier is new */
688 p->link=hash[h]; hash[h]=p; /* insert |p| at beginning of hash list */
689}
690
691@ The information associated with a new identifier must be initialized
692in a slightly different way in \.{CWEAVE} than in \.{CTANGLE}; hence the
693|init_p| procedure.
694
695@<Pred...@>=
696void init_p();
697
698@ @<Enter a new name...@>= {
699 if (byte_ptr+l>byte_mem_end) overflow("byte memory");
700 if (name_ptr>=name_dir_end) overflow("name");
701 strncpy(byte_ptr,first,l);
702 (++name_ptr)->byte_start=byte_ptr+=l;
703 if (program==cweave) init_p(p,t);
704}
705
706@ The names of sections are stored in |byte_mem| together
707with the identifier names, but a hash table is not used for them because
708\.{CTANGLE} needs to be able to recognize a section name when given a prefix of
709that name. A conventional binary search tree is used to retrieve section names,
710with fields called |llink| and |rlink| (where |llink| takes the place
711of |link|). The root of this tree is stored in |name_dir->rlink|;
712this will be the only information in |name_dir[0]|.
713
714Since the space used by |rlink| has a different function for
715identifiers than for section names, we declare it as a |union|.
716
717@d llink link /* left link in binary search tree for section names */
718@d rlink dummy.Rlink /* right link in binary search tree for section names */
719@d root name_dir->rlink /* the root of the binary search tree
720 for section names */
721
722@<More elements of |name...@>=
723union {
724 struct name_info *Rlink; /* right link in binary search tree for section
725 names */
726 char Ilk; /* used by identifiers in \.{CWEAVE} only */
727} dummy;
728
729@ @<Init...@>=
730root=NULL; /* the binary search tree starts out with nothing in it */
731
732@ If |p| is a |name_pointer| variable, as we have seen,
733|p->byte_start| is the beginning of the area where the name
734corresponding to |p| is stored. However, if |p| refers to a section
735name, the name may need to be stored in chunks, because it may
736``grow'': a prefix of the section name may be encountered before
737the full name. Furthermore we need to know the length of the shortest
738prefix of the name that was ever encountered.
739
740We solve this problem by inserting two extra bytes at |p->byte_start|,
741representing the length of the shortest prefix, when |p| is a
742section name. Furthermore, the last byte of the name will be a blank
743space if |p| is a prefix. In the latter case, the name pointer
744|p+1| will allow us to access additional chunks of the name:
745The second chunk will begin at the name pointer |(p+1)->link|,
746and if it too is a prefix (ending with blank) its |link| will point
747to additional chunks in the same way. Null links are represented by
748|name_dir|.
749
750@d first_chunk(p) ((p)->byte_start+2)
751@d prefix_length(p) (int)((unsigned char)*((p)->byte_start)*256 +
752 (unsigned char)*((p)->byte_start+1))
753@d set_prefix_length(p,m) (*((p)->byte_start)=(m)/256,
754 *((p)->byte_start+1)=(m)%256)
755
756@c
757void
758print_section_name(p)
759name_pointer p;
760{
761 char *ss, *s = first_chunk(p);
762 name_pointer q = p+1;
763 while (p!=name_dir) {
764 ss = (p+1)->byte_start-1;
765 if (*ss==' ' && ss>=s) {
766 term_write(s,ss-s); p=q->link; q=p;
767 } else {
768 term_write(s,ss+1-s); p=name_dir; q=NULL;
769 }
770 s = p->byte_start;
771 }
772 if (q) term_write("...",3); /* complete name not yet known */
773}
774
775@ @c
776void
777sprint_section_name(dest,p)
778 char*dest;
779 name_pointer p;
780{
781 char *ss, *s = first_chunk(p);
782 name_pointer q = p+1;
783 while (p!=name_dir) {
784 ss = (p+1)->byte_start-1;
785 if (*ss==' ' && ss>=s) {
786 p=q->link; q=p;
787 } else {
788 ss++; p=name_dir;
789 }
790 strncpy(dest,s,ss-s), dest+=ss-s;
791 s = p->byte_start;
792 }
793 *dest='\0';
794}
795
796@ @c
797void
798print_prefix_name(p)
799name_pointer p;
800{
801 char *s = first_chunk(p);
802 int l = prefix_length(p);
803 term_write(s,l);
804 if (s+l<(p+1)->byte_start) term_write("...",3);
805}
806
807@ When we compare two section names, we'll need a function analogous to
808|strcmp|. But we do not assume the strings
809are null-terminated, and we keep an eye open for prefixes and extensions.
810
811@d less 0 /* the first name is lexicographically less than the second */
812@d equal 1 /* the first name is equal to the second */
813@d greater 2 /* the first name is lexicographically greater than the second */
814@d prefix 3 /* the first name is a proper prefix of the second */
815@d extension 4 /* the first name is a proper extension of the second */
816
817@c
818int web_strcmp(j,j_len,k,k_len) /* fuller comparison than |strcmp| */
819 char *j, *k; /* beginning of first and second strings */
820 int j_len, k_len; /* length of strings */
821{
822 char *j1=j+j_len, *k1=k+k_len;
823 while (k<k1 && j<j1 && *j==*k) k++, j++;
824 if (k==k1) if (j==j1) return equal;
825 else return extension;
826 else if (j==j1) return prefix;
827 else if (*j<*k) return less;
828 else return greater;
829}
830
831@ Adding a section name to the tree is straightforward if we know its
832parent and whether it's the |rlink| or |llink| of the parent. As a
833special case, when the name is the first section being added, we set the
834``parent'' to |NULL|. When a section name is created, it has only one
835chunk, which however may be just a prefix: the full name will
836hopefully be unveiled later. Obviously, |prefix_length| starts
837out as the length of the first chunk, though it may decrease later.
838
839The information associated with a new node must be initialized
840differently in \.{CWEAVE} and \.{CTANGLE}; hence the
841|init_node| procedure, which is defined differently in \.{cweave.w}
842and \.{ctangle.w}.
843
844@<Prede...@>=
845extern void init_node();
846
847@ @c
848name_pointer
849add_section_name(par,c,first,last,ispref) /* install a new node in the tree */
850name_pointer par; /* parent of new node */
851int c; /* right or left? */
852char *first; /* first character of section name */
853char *last; /* last character of section name, plus one */
854int ispref; /* are we adding a prefix or a full name? */
855{
856 name_pointer p=name_ptr; /* new node */
857 char *s=first_chunk(p);
858 int name_len=last-first+ispref; /* length of section name */
859 if (s+name_len>byte_mem_end) overflow("byte memory");
860 if (name_ptr+1>=name_dir_end) overflow("name");
861 (++name_ptr)->byte_start=byte_ptr=s+name_len;
862 if (ispref) {
863 *(byte_ptr-1)=' ';
864 name_len--;
865 name_ptr->link=name_dir;
866 (++name_ptr)->byte_start=byte_ptr;
867 }
868 set_prefix_length(p,name_len);
869 strncpy(s,first,name_len);
870 p->llink=NULL;
871 p->rlink=NULL;
872 init_node(p);
873 return par==NULL ? (root=p) : c==less ? (par->llink=p) : (par->rlink=p);
874}
875
876@ @c
877void
878extend_section_name(p,first,last,ispref)
879name_pointer p; /* name to be extended */
880char *first; /* beginning of extension text */
881char *last; /* one beyond end of extension text */
882int ispref; /* are we adding a prefix or a full name? */
883{
884 char *s;
885 name_pointer q=p+1;
886 int name_len=last-first+ispref;
887 if (name_ptr>=name_dir_end) overflow("name");
888 while (q->link!=name_dir) q=q->link;
889 q->link=name_ptr;
890 s=name_ptr->byte_start;
891 name_ptr->link=name_dir;
892 if (s+name_len>byte_mem_end) overflow("byte memory");
893 (++name_ptr)->byte_start=byte_ptr=s+name_len;
894 strncpy(s,first,name_len);
895 if (ispref) *(byte_ptr-1)=' ';
896}
897
898@ The |section_lookup| procedure is supposed to find a
899section name that matches a new name, installing the new name if
900its doesn't match an existing one. The new name is the string
901between |first| and |last|; a ``match'' means that the new name
902exactly equals or is a prefix or extension of a name in the tree.
903
904@c
905name_pointer
906section_lookup(first,last,ispref) /* find or install section name in tree */
907char *first, *last; /* first and last characters of new name */
908int ispref; /* is the new name a prefix or a full name? */
909{
910 int c=0; /* comparison between two names; initialized so some compilers won't complain */
911 name_pointer p=root; /* current node of the search tree */
912 name_pointer q=NULL; /* another place to look in the tree */
913 name_pointer r=NULL; /* where a match has been found */
914 name_pointer par=NULL; /* parent of |p|, if |r| is |NULL|;
915 otherwise parent of |r| */
916 int name_len=last-first+1;
917 @<Look for matches for new name among shortest prefixes, complaining
918 if more than one is found@>;
919 @<If no match found, add new name to tree@>;
920 @<If one match found, check for compatibility and return match@>;
921}
922
923@ A legal new name matches an existing section name if and only if it
924matches the shortest prefix of that section name. Therefore we can
925limit our search for matches to shortest prefixes, which eliminates
926the need for chunk-chasing at this stage.
927
928@<Look for matches for new name among...@>=
929while (p) { /* compare shortest prefix of |p| with new name */
930 c=web_strcmp(first,name_len,first_chunk(p),prefix_length(p));
931 if (c==less || c==greater) { /* new name does not match |p| */
932 if (r==NULL) /* no previous matches have been found */
933 par=p;
934 p=(c==less?p->llink:p->rlink);
935 } else { /* new name matches |p| */
936 if (r!=NULL) { /* and also |r|: illegal */
937 printf("\n! Ambiguous prefix: matches <");
938@.Ambiguous prefix ... @>
939 print_prefix_name(p);
940 printf(">\n and <");
941 print_prefix_name(r);
942 err_print(">");
943 return name_dir; /* the unsection */
944 }
945 r=p; /* remember match */
946 p=p->llink; /* try another */
947 q=r->rlink; /* we'll get back here if the new |p| doesn't match */
948 }
949 if (p==NULL)
950 p=q, q=NULL; /* |q| held the other branch of |r| */
951}
952
953@ @<If no match ...@>=
954 if (r==NULL) /* no matches were found */
955 return add_section_name(par,c,first,last+1,ispref);
956
957@ Although error messages are given in anomalous cases, we do return the
958unique best match when a discrepancy is found, because users often
959change a title in one place while forgetting to change it elsewhere.
960
961@<If one match found, check for compatibility and return match@>=
962switch(section_name_cmp(&first,name_len,r)) {
963 /* compare all of |r| with new name */
964 case prefix:
965 if (!ispref) {
966 printf("\n! New name is a prefix of <");
967@.New name is a prefix...@>
968 print_section_name(r);
969 err_print(">");
970 }
971 else if (name_len<prefix_length(r)) set_prefix_length(r,name_len);
972 /* fall through */
973 case equal: return r;
974 case extension: if (!ispref || first<=last)
975 extend_section_name(r,first,last+1,ispref);
976 return r;
977 case bad_extension:
978 printf("\n! New name extends <");
979@.New name extends...@>
980 print_section_name(r);
981 err_print(">");
982 return r;
983 default: /* no match: illegal */
984 printf("\n! Section name incompatible with <");
985@.Section name incompatible...@>
986 print_prefix_name(r);
987 printf(">,\n which abbreviates <");
988 print_section_name(r);
989 err_print(">");
990 return r;
991}
992
993@ The return codes of |section_name_cmp|, which compares a string with
994the full name of a section, are those of |web_strcmp| plus
995|bad_extension|, used when the string is an extension of a
996supposedly already complete section name. This function has a side
997effect when the comparison string is an extension: it advances the
998address of the first character of the string by an amount equal to
999the length of the known part of the section name.
1000
1001The name \.{@@<foo...@@>} should be an acceptable ``abbreviation''
1002for \.{@@<foo@@>}. If such an abbreviation comes after the complete
1003name, there's no trouble recognizing it. If it comes before the
1004complete name, we simply append a null chunk. This logic requires
1005us to regard \.{@@<foo...@@>} as an ``extension'' of itself.
1006
1007@d bad_extension 5
1008
1009@<Predec...@>=
1010int section_name_cmp();
1011
1012@ @c
1013int section_name_cmp(pfirst,len,r)
1014char **pfirst; /* pointer to beginning of comparison string */
1015int len; /* length of string */
1016name_pointer r; /* section name being compared */
1017{
1018 char *first=*pfirst; /* beginning of comparison string */
1019 name_pointer q=r+1; /* access to subsequent chunks */
1020 char *ss, *s=first_chunk(r);
1021 int c; /* comparison */
1022 int ispref; /* is chunk |r| a prefix? */
1023 while (1) {
1024 ss=(r+1)->byte_start-1;
1025 if (*ss==' ' && ss>=r->byte_start) ispref=1,q=q->link;
1026 else ispref=0,ss++,q=name_dir;
1027 switch(c=web_strcmp(first,len,s,ss-s)) {
1028 case equal: if (q==name_dir)
1029 if (ispref) {
1030 *pfirst=first+(ss-s);
1031 return extension; /* null extension */
1032 } else return equal;
1033 else return (q->byte_start==(q+1)->byte_start)? equal: prefix;
1034 case extension:
1035 if (!ispref) return bad_extension;
1036 first += ss-s;
1037 if (q!=name_dir) {len -= ss-s; s=q->byte_start; r=q; continue;}
1038 *pfirst=first; return extension;
1039 default: return c;
1040 }
1041 }
1042}
1043
1044@ The last component of |name_info| is different for \.{CTANGLE} and
1045\.{CWEAVE}. In \.{CTANGLE}, if |p| is a pointer to a section name,
1046|p->equiv| is a pointer to its replacement text, an element of the
1047array |text_info|. In \.{CWEAVE}, on the other hand, if
1048|p| points to an identifier, |p->xref| is a pointer to its
1049list of cross-references, an element of the array |xmem|. The make-up
1050of |text_info| and |xmem| is discussed in the \.{CTANGLE} and \.{CWEAVE}
1051source files, respectively; here we just declare a common field
1052|equiv_or_xref| as a pointer to a |char|.
1053
1054@<More elements of |name...@>=
1055char *equiv_or_xref; /* info corresponding to names */
1056
1057@** Reporting errors to the user.
1058A global variable called |history| will contain one of four values
1059at the end of every run: |spotless| means that no unusual messages were
1060printed; |harmless_message| means that a message of possible interest
1061was printed but no serious errors were detected; |error_message| means that
1062at least one error was found; |fatal_message| means that the program
1063terminated abnormally. The value of |history| does not influence the
1064behavior of the program; it is simply computed for the convenience
1065of systems that might want to use such information.
1066
1067@d spotless 0 /* |history| value for normal jobs */
1068@d harmless_message 1 /* |history| value when non-serious info was printed */
1069@d error_message 2 /* |history| value when an error was noted */
1070@d fatal_message 3 /* |history| value when we had to stop prematurely */
1071@d mark_harmless {if (history==spotless) history=harmless_message;}
1072@d mark_error history=error_message
1073
1074@<Definit...@>=
1075int history=spotless; /* indicates how bad this run was */
1076
1077@ The command `|err_print("! Error message")|' will report a syntax error to
1078the user, by printing the error message at the beginning of a new line and
1079then giving an indication of where the error was spotted in the source file.
1080Note that no period follows the error message, since the error routine
1081will automatically supply a period. A newline is automatically supplied
1082if the string begins with |"|"|.
1083
1084@<Predecl...@>=
1085void err_print();
1086
1087@ @c
1088void
1089err_print(s) /* prints `\..' and location of error message */
1090char *s;
1091{
1092 char *k,*l; /* pointers into |buffer| */
1093 printf(*s=='!'? "\n%s" : "%s",s);
1094 if(web_file_open) @<Print error location based on input buffer@>;
1095 update_terminal; mark_error;
1096}
1097
1098@ The error locations can be indicated by using the global variables
1099|loc|, |cur_line|, |cur_file_name| and |changing|,
1100which tell respectively the first
1101unlooked-at position in |buffer|, the current line number, the current
1102file, and whether the current line is from |change_file| or |cur_file|.
1103This routine should be modified on systems whose standard text editor
1104has special line-numbering conventions.
1105@^system dependencies@>
1106
1107@<Print error location based on input buffer@>=
1108{if (changing && include_depth==change_depth)
1109 printf(". (l. %d of change file)\n", change_line);
1110else if (include_depth==0) printf(". (l. %d)\n", cur_line);
1111 else printf(". (l. %d of include file %s)\n", cur_line, cur_file_name);
1112l= (loc>=limit? limit: loc);
1113if (l>buffer) {
1114 for (k=buffer; k<l; k++)
1115 if (*k=='\t') putchar(' ');
1116 else putchar(*k); /* print the characters already read */
1117 putchar('\n');
1118 for (k=buffer; k<l; k++) putchar(' '); /* space out the next line */
1119}
1120for (k=l; k<limit; k++) putchar(*k); /* print the part not yet read */
1121if (*limit=='|') putchar('|'); /* end of \CEE/ text in section names */
1122putchar(' '); /* to separate the message from future asterisks */
1123}
1124
1125@ When no recovery from some error has been provided, we have to wrap
1126up and quit as graciously as possible. This is done by calling the
1127function |wrap_up| at the end of the code.
1128
1129\.{CTANGLE} and \.{CWEAVE} have their own notions about how to
1130print the job statistics.
1131
1132@<Prede...@>=
1133int wrap_up();
1134extern void print_stats();
1135
1136@ Some implementations may wish to pass the |history| value to the
1137operating system so that it can be used to govern whether or not other
1138programs are started. Here, for instance, we pass the operating system
1139a status of 0 if and only if only harmless messages were printed.
1140@^system dependencies@>
1141
1142@c
1143int wrap_up() {
1144 putchar('\n');
1145 if (show_stats)
1146 print_stats(); /* print statistics about memory usage */
1147 @<Print the job |history|@>;
1148 if (history > harmless_message) return(1);
1149 else return(0);
1150}
1151
1152@ @<Print the job |history|@>=
1153switch (history) {
1154case spotless: if (show_happiness) printf("(No errors were found.)\n"); break;
1155case harmless_message:
1156 printf("(Did you see the warning message above?)\n"); break;
1157case error_message:
1158 printf("(Pardon me, but I think I spotted something wrong.)\n"); break;
1159case fatal_message: printf("(That was a fatal error, my friend.)\n");
1160} /* there are no other cases */
1161
1162@ When there is no way to recover from an error, the |fatal| subroutine is
1163invoked. This happens most often when |overflow| occurs.
1164
1165@<Predec...@>=
1166void fatal(), overflow();
1167
1168@ The two parameters to |fatal| are strings that are essentially
1169concatenated to print the final error message.
1170
1171@c void
1172fatal(s,t)
1173 char *s,*t;
1174{
1175 if (*s) printf(s);
1176 err_print(t);
1177 history=fatal_message; exit(wrap_up());
1178}
1179
1180@ An overflow stop occurs if \.{CWEB}'s tables aren't large enough.
1181
1182@c void
1183overflow(t)
1184 char *t;
1185{
1186 printf("\n! Sorry, %s capacity exceeded",t); fatal("","");
1187}
1188@.Sorry, capacity exceeded@>
1189
1190@ Sometimes the program's behavior is far different from what it should be,
1191and \.{CWEB} prints an error message that is really for the \.{CWEB}
1192maintenance person, not the user. In such cases the program says
1193|confusion("indication of where we are")|.
1194
1195@d confusion(s) fatal("! This can't happen: ",s)
1196@.This can't happen@>
1197
1198@** Command line arguments.
1199The user calls \.{CWEAVE} and \.{CTANGLE} with arguments on the command line.
1200These are either file names or flags to be turned off (beginning with |"-"|)
1201or flags to be turned on (beginning with |"+"|.
1202The following globals are for communicating the user's desires to the rest
1203of the program. The various file name variables contain strings with
1204the names of those files. Most of the 128 flags are undefined but available
1205for future extensions.
1206
1207@d show_banner flags['b'] /* should the banner line be printed? */
1208@d show_progress flags['p'] /* should progress reports be printed? */
1209@d show_stats flags['s'] /* should statistics be printed at end of run? */
1210@d show_happiness flags['h'] /* should lack of errors be announced? */
1211
1212@<Defin...@>=
1213int argc; /* copy of |ac| parameter to |main| */
1214char **argv; /* copy of |av| parameter to |main| */
1215char C_file_name[max_file_name_length]; /* name of |C_file| */
1216char tex_file_name[max_file_name_length]; /* name of |tex_file| */
1217char idx_file_name[max_file_name_length]; /* name of |idx_file| */
1218char scn_file_name[max_file_name_length]; /* name of |scn_file| */
1219boolean flags[128]; /* an option for each 7-bit code */
1220
1221@ The |flags| will be initially zero. Some of them are set to~1 before
1222scanning the arguments; if additional flags are 1 by default they
1223should be set before calling |common_init|.
1224
1225@<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>=
1226show_banner=show_happiness=show_progress=1;
1227
1228@ We now must look at the command line arguments and set the file names
1229accordingly. At least one file name must be present: the \.{CWEB}
1230file. It may have an extension, or it may omit the extension to get |".w"| or
1231|".web"| added. The \TEX/ output file name is formed by replacing the \.{CWEB}
1232file name extension by |".tex"|, and the \CEE/ file name by replacing
1233the extension by |".c"|, after removing the directory name (if any).
1234
1235If there is a second file name present among the arguments, it is the
1236change file, again either with an extension or without one to get |".ch"|.
1237An omitted change file argument means that |"/dev/null"| should be used,
1238when no changes are desired.
1239@^system dependencies@>
1240
1241If there's a third file name, it will be the output file.
1242
1243@<Pred...@>=
1244void scan_args();
1245
1246@ @c
1247void
1248scan_args()
1249{
1250 char *dot_pos; /* position of |'.'| in the argument */
1251 char *name_pos; /* file name beginning, sans directory */
1252 register char *s; /* register for scanning strings */
1253 boolean found_web=0,found_change=0,found_out=0;
1254 /* have these names have been seen? */
1255 boolean flag_change;
1256
1257 while (--argc > 0) {
1258 if ((**(++argv)=='-'||**argv=='+')&&*(*argv+1)) @<Handle flag argument@>@;
1259 else {
1260 s=name_pos=*argv;@+dot_pos=NULL;
1261 while (*s) {
1262 if (*s=='.') dot_pos=s++;
1263 else if (*s=='/') dot_pos=NULL,name_pos=++s;
1264 else s++;
1265 }
1266 if (!found_web) @<Make
1267 |web_file_name|, |tex_file_name| and |C_file_name|@>@;
1268 else if (!found_change) @<Make |change_file_name| from |fname|@>@;
1269 else if (!found_out) @<Override |tex_file_name| and |C_file_name|@>@;
1270 else @<Print usage error message and quit@>;
1271 }
1272 }
1273 if (!found_web) @<Print usage error message and quit@>;
1274 if (found_change<=0) strcpy(change_file_name,"/dev/null");
1275}
1276
1277@ We use all of |*argv| for the |web_file_name| if there is a |'.'| in it,
1278otherwise we add |".w"|. If this file can't be opened, we prepare an
1279|alt_web_file_name| by adding |"web"| after the dot.
1280The other file names come from adding other things
1281after the dot. We must check that there is enough room in
1282|web_file_name| and the other arrays for the argument.
1283
1284@<Make |web_file_name|...@>=
1285{
1286 if (s-*argv > max_file_name_length-5)
1287 @<Complain about argument length@>;
1288 if (dot_pos==NULL)
1289 sprintf(web_file_name,"%s.w",*argv);
1290 else {
1291 strcpy(web_file_name,*argv);
1292 *dot_pos=0; /* string now ends where the dot was */
1293 }
1294 sprintf(alt_web_file_name,"%s.web",*argv);
1295 sprintf(tex_file_name,"%s.tex",name_pos); /* strip off directory name */
1296 sprintf(idx_file_name,"%s.idx",name_pos);
1297 sprintf(scn_file_name,"%s.scn",name_pos);
1298 sprintf(C_file_name,"%s.c",name_pos);
1299 found_web=1;
1300}
1301
1302@ @<Make |change_file_name|...@>=
1303{
1304 if (strcmp(*argv,"-")==0) found_change=-1;
1305 else {
1306 if (s-*argv > max_file_name_length-4)
1307 @<Complain about argument length@>;
1308 if (dot_pos==NULL)
1309 sprintf(change_file_name,"%s.ch",*argv);
1310 else strcpy(change_file_name,*argv);
1311 found_change=1;
1312 }
1313}
1314
1315@ @<Override...@>=
1316{
1317 if (s-*argv > max_file_name_length-5)
1318 @<Complain about argument length@>;
1319 if (dot_pos==NULL) {
1320 sprintf(tex_file_name,"%s.tex",*argv);
1321 sprintf(idx_file_name,"%s.idx",*argv);
1322 sprintf(scn_file_name,"%s.scn",*argv);
1323 sprintf(C_file_name,"%s.c",*argv);
1324 } else {
1325 strcpy(tex_file_name,*argv);
1326 if (flags['x']) { /* indexes will be generated */
1327 if (program==cweave && strcmp(*argv+strlen(*argv)-4,".tex")!=0)
1328 fatal("! Output file name should end with .tex\n",*argv);
1329@.Output file name...tex@>
1330 strcpy(idx_file_name,*argv);
1331 strcpy(idx_file_name+strlen(*argv)-4,".idx");
1332 strcpy(scn_file_name,*argv);
1333 strcpy(scn_file_name+strlen(*argv)-4,".scn");
1334 }
1335 strcpy(C_file_name,*argv);
1336 }
1337 found_out=1;
1338}
1339
1340@ @<Handle flag...@>=
1341{
1342 if (**argv=='-') flag_change=0;
1343 else flag_change=1;
1344 for(dot_pos=*argv+1;*dot_pos>'\0';dot_pos++)
1345 flags[*dot_pos]=flag_change;
1346}
1347
1348@ @<Print usage error message and quit@>=
1349{
1350if (program==ctangle)
1351 fatal(
1352"! Usage: ctangle [options] webfile[.w] [{changefile[.ch]|-} [outfile[.c]]]\n"
1353 ,"");
1354@.Usage:@>
1355else fatal(
1356"! Usage: cweave [options] webfile[.w] [{changefile[.ch]|-} [outfile[.tex]]]\n"
1357 ,"");
1358}
1359
1360@ @<Complain about arg...@>= fatal("! Filename too long\n", *argv);
1361@.Filename too long@>
1362
1363@** Output. Here is the code that opens the output file:
1364@^system dependencies@>
1365
1366@<Defin...@>=
1367FILE *C_file; /* where output of \.{CTANGLE} goes */
1368FILE *tex_file; /* where output of \.{CWEAVE} goes */
1369FILE *idx_file; /* where index from \.{CWEAVE} goes */
1370FILE *scn_file; /* where list of sections from \.{CWEAVE} goes */
1371FILE *active_file; /* currently active file for \.{CWEAVE} output */
1372
1373@ @<Scan arguments and open output files@>=
1374scan_args();
1375if (program==ctangle) {
1376 if ((C_file=fopen(C_file_name,"w"))==NULL)
1377 fatal("! Cannot open output file ", C_file_name);
1378@.Cannot open output file@>
1379}
1380else {
1381 if ((tex_file=fopen(tex_file_name,"w"))==NULL)
1382 fatal("! Cannot open output file ", tex_file_name);
1383}
1384
1385@ The |update_terminal| procedure is called when we want
1386to make sure that everything we have output to the terminal so far has
1387actually left the computer's internal buffers and been sent.
1388@^system dependencies@>
1389
1390@d update_terminal fflush(stdout) /* empty the terminal output buffer */
1391
1392@ Terminal output uses |putchar| and |putc| when we have to
1393translate from \.{CWEB}'s code into the external character code,
1394and |printf| when we just want to print strings.
1395Several macros make other kinds of output convenient.
1396@^system dependencies@>
1397@d new_line putchar('\n') @d putxchar putchar
1398@d term_write(a,b) fflush(stdout),fwrite(a,sizeof(char),b,stdout)
1399@d C_printf(c,a) fprintf(C_file,c,a)
1400@d C_putc(c) putc(c,C_file) /* isn't \CEE/ wonderfully consistent? */
1401
1402@ We predeclare several standard system functions here instead of including
1403their system header files, because the names of the header files are not as
1404standard as the names of the functions. (For example, some \CEE/ environments
1405have \.{<string.h>} where others have \.{<strings.h>}.)
1406
1407@<Predecl...@>=
1408extern int strlen(); /* length of string */
1409extern int strcmp(); /* compare strings lexicographically */
1410extern char* strcpy(); /* copy one string to another */
1411extern int strncmp(); /* compare up to $n$ string characters */
1412extern char* strncpy(); /* copy up to $n$ string characters */
1413
1414@** Index.
ctang-bs.ch+202−0
@@ -0,0 +1,202 @@
1Changes for CTANGLE for MSDOS and Borland C++ 3.1 using the following
2options (and perhaps others):
3
4 -mc -w-pro -Ff=5000 -Z- -O-p
5
6The options -Z- and -O-p explicitly turn off optimizations that break
7the code. (See makefile.bs.)
8
9The main purpose of these changes is to support MSDOS with full-size arrays
10by using "huge" pointers.
11
12(This file contributed by Barry Schwartz, trashman@crud.mn.org, 28 Jun 94;
13 revised 24 Jul 94.)
14
15
16@x Section 1.
17The ``banner line'' defined here should be changed whenever \.{CTANGLE}
18is modified.
19
20@d banner "This is CTANGLE (Version 3.2)\n"
21@y
22The ``banner line'' defined here should be changed whenever \.{CTANGLE}
23is modified.
24
25@d banner "This is CTANGLE (Version 3.2pc/big)\n"
26@z
27
28
29@x Section 4.
30@ The following parameters were sufficient in the original \.{TANGLE} to
31handle \TEX/,
32so they should be sufficient for most applications of \.{CTANGLE}.
33If you change |max_bytes|, |max_names| or |hash_size| you should also
34change them in the file |"common.w"|.
35
36@d max_bytes 90000 /* the number of bytes in identifiers,
37 index entries, and section names; used in |"common.w"| */
38@d max_toks 270000 /* number of bytes in compressed \CEE/ code */
39@d max_names 4000 /* number of identifiers, strings, section names;
40 must be less than 10240; used in |"common.w"| */
41@d max_texts 2500 /* number of replacement texts, must be less than 10240 */
42@d hash_size 353 /* should be prime; used in |"common.w"| */
43@d longest_name 1000 /* section names shouldn't be longer than this */
44@d stack_size 50 /* number of simultaneous levels of macro expansion */
45@d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
46@y
47@ The following parameters were sufficient in the original \.{TANGLE} to
48handle \TEX/,
49so they should be sufficient for most applications of \.{CTANGLE}.
50If you change |max_bytes|, |max_names| or |hash_size| you should also
51change them in the file |"common.w"|.
52
53(This is a modified version of \.{CTANGLE}, and in fact one of the parameters
54has been reduced in value. The parameter |max_toks|
55has been reduced from 270000 [which
56was sufficient to handle \TEX/] to
57170000, so that \.{CTANGLE}
58may be run on {\mc MSDOS}
59systems that are tight on memory. Consider, for
60instance, an 80286-based machine with several TSRs and drivers, trying
61to run \.{CTANGLE} from a makefile.)
62
63@d max_bytes 90000 /* the number of bytes in identifiers,
64 index entries, and section names; used in |"common.w"| */
65@d max_toks 170000 /* number of bytes in compressed \CEE/ code */
66@d max_names 4000 /* number of identifiers, strings, section names;
67 must be less than 10240; used in |"common.w"| */
68@d max_texts 2500 /* number of replacement texts, must be less than 10240 */
69@d hash_size 353 /* should be prime; used in |"common.w"| */
70@d longest_name 1000 /* section names shouldn't be longer than this */
71@d stack_size 50 /* number of simultaneous levels of macro expansion */
72@d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
73@z
74
75
76@x Section 9.
77@d chunk_marker 0
78
79@<Common code...@>=
80typedef struct name_info {
81 char *byte_start; /* beginning of the name in |byte_mem| */
82 struct name_info *link;
83 union {
84 struct name_info *Rlink; /* right link in binary search tree for section
85 names */
86 char Ilk; /* used by identifiers in \.{CWEAVE} only */
87 } dummy;
88 char *equiv_or_xref; /* info corresponding to names */
89} name_info; /* contains information about an identifier or section name */
90typedef name_info *name_pointer; /* pointer into array of \&{name\_info}s */
91typedef name_pointer *hash_pointer;
92extern char byte_mem[]; /* characters of names */
93extern char *byte_mem_end; /* end of |byte_mem| */
94extern name_info name_dir[]; /* information about names */
95extern name_pointer name_dir_end; /* end of |name_dir| */
96extern name_pointer name_ptr; /* first unused position in |byte_start| */
97extern char *byte_ptr; /* first unused position in |byte_mem| */
98extern name_pointer hash[]; /* heads of hash lists */
99extern hash_pointer hash_end; /* end of |hash| */
100extern hash_pointer h; /* index into hash-head array */
101extern name_pointer id_lookup(); /* looks up a string in the identifier table */
102extern name_pointer section_lookup(); /* finds section name */
103extern void print_section_name(), sprint_section_name();
104@y
105@d chunk_marker 0
106
107@f huge extern
108
109@<Common code...@>=
110typedef struct name_info {
111 char huge* byte_start; /* beginning of the name in |byte_mem| */
112 struct name_info *link;
113 union {
114 struct name_info *Rlink; /* right link in binary search tree for section
115 names */
116 char Ilk; /* used by identifiers in \.{CWEAVE} only */
117 } dummy;
118 union {
119 char *equiv_member;
120 char huge* xref_member;
121 } ptr_union; /* info corresponding to names */
122} name_info; /* contains information about an identifier or section name */
123typedef name_info *name_pointer; /* pointer into array of \&{name\_info}s */
124typedef name_pointer *hash_pointer;
125extern char huge byte_mem[]; /* characters of names */
126extern char huge* byte_mem_end; /* end of |byte_mem| */
127extern name_info name_dir[]; /* information about names */
128extern name_pointer name_dir_end; /* end of |name_dir| */
129extern name_pointer name_ptr; /* first unused position in |byte_start| */
130extern char huge* byte_ptr; /* first unused position in |byte_mem| */
131extern name_pointer hash[]; /* heads of hash lists */
132extern hash_pointer hash_end; /* end of |hash| */
133extern hash_pointer h; /* index into hash-head array */
134extern name_pointer id_lookup(); /* looks up a string in the identifier table */
135extern name_pointer section_lookup(); /* finds section name */
136extern void print_section_name(), sprint_section_name();
137@z
138
139
140@x Section 16.
141 eight_bits *tok_start; /* pointer into |tok_mem| */
142 sixteen_bits text_link; /* relates replacement texts */
143} text;
144typedef text *text_pointer;
145@y
146 eight_bits huge* tok_start; /* pointer into |tok_mem| */
147 sixteen_bits text_link; /* relates replacement texts */
148} text;
149typedef text *text_pointer;
150@z
151
152
153@x Section 17.
154eight_bits tok_mem[max_toks];
155eight_bits *tok_mem_end=tok_mem+max_toks-1;
156eight_bits *tok_ptr; /* first unused position in |tok_mem| */
157@y
158eight_bits huge tok_mem[max_toks];
159eight_bits huge* tok_mem_end;
160eight_bits huge* tok_ptr; /* first unused position in |tok_mem| */
161@z
162
163
164@x Section 18.
165text_info->tok_start=tok_ptr=tok_mem;
166text_ptr=text_info+1; text_ptr->tok_start=tok_mem;
167 /* this makes replacement text 0 of length zero */
168@y
169tok_mem_end=tok_mem+max_toks-1;
170text_info->tok_start=tok_ptr=tok_mem;
171text_ptr=text_info+1; text_ptr->tok_start=tok_mem;
172 /* this makes replacement text 0 of length zero */
173@z
174
175
176@x Section 19.
177@d equiv equiv_or_xref /* info corresponding to names */
178@y
179@d equiv ptr_union.equiv_member /* info corresponding to names */
180@z
181
182
183@x Section 27.
184 eight_bits *end_field; /* ending location of replacement text */
185 eight_bits *byte_field; /* present location within replacement text */
186@y
187 eight_bits huge* end_field; /* ending location of replacement text */
188 eight_bits huge* byte_field; /* present location within replacement text */
189@z
190
191
192@x Section 49.
193out_char(cur_char)
194eight_bits cur_char;
195{
196 char *j, *k; /* pointer into |byte_mem| */
197@y
198out_char(cur_char)
199eight_bits cur_char;
200{
201 char huge* j, huge* k; /* pointer into |byte_mem| */
202@z
ctang-man.ch+22−0
@@ -0,0 +1,22 @@
1Change file to help make Appendix E of the full CWEB manual
2@x
3\def\botofcontents{\vfill
4\noindent
5Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
6\bigskip\noindent
7Permission is granted to make and distribute verbatim copies of this
8document provided that the copyright notice and this permission notice
9are preserved on all copies.
10
11\smallskip\noindent
12Permission is granted to copy and distribute modified versions of this
13document under the conditions for verbatim copying, provided that the
14entire resulting derived work is given a different name and distributed
15under the terms of a permission notice identical to this one.
16}
17@y
18\def\botofcontents{\vfill\titlefalse}
19\def\contentspagenumber{58}
20\def\title{APPENDIX E: CTANGLE}
21\let\K=\leftarrow
22@z
ctang-pc.ch+24−0
@@ -0,0 +1,24 @@
1This is the change file for CWEB's CTANGLE under DOS
2(Contributed by Lee Wittenberg, March 1993)
3
4Changes necessary for compiling with Borland C/C++
5Use compilation switches -mc -w-pro -Ff=5000
6
7Note: The changes to section 4 are not necessary if using a compiler
8that allows >64K arrays. If you need lots of bytes and toks, try the
9alternate change files with -bs suffix instead of -pc.
10
11@x section 1
12@d banner "This is CTANGLE (Version 3.2)\n"
13@y
14@d banner "This is CTANGLE (Version 3.2pc)\n"
15@z
16@x section 4
17@d max_bytes 90000 /* the number of bytes in identifiers,
18 index entries, and section names; used in |"common.w"| */
19@d max_toks 270000 /* number of bytes in compressed \CEE/ code */
20@y (note that CWEAVE itself needs only about 42K toks)
21@d max_bytes (unsigned)60000 /* the number of bytes in identifiers,
22 index entries, and section names; used in |"common.w"| */
23@d max_toks (unsigned)60000 /* number of bytes in compressed \CEE/ code */
24@z
ctang-vms.ch+35−0
@@ -0,0 +1,35 @@
1This is the change file for CWEB's CTANGLE for VAX/VMS.
2
3created:
4 01-FEB-1992 ST (Stephan Trebels <trebels@ams02.dnet.gwdg.de>)
5 > include ctype,stdio from textlibrary SYS$SHARE:VAXCDEF.TLB
6 > change banner line to include (VAX/VMS)
7 ? will someone make a CLD interface? (should be easy)
8
9(also modified by Don Knuth to keep version numbers uptodate)
10(these changes not necessary for initial bootstrapping)
11
12@x section 1 (01-FEB-1992 ST)
13@d banner "This is CTANGLE (Version 3.2)\n"
14@y
15@d banner "This is CTANGLE (VAX/VMS Version 3.2)\n"
16@z
17
18@x section 6 (from common.h) (01-FEB-1992 ST)
19#include <stdio.h>
20@y
21#include stdio /* VMS searches Textlibraries faster */
22@z
23
24@x section 62 (01-FEB-1992 ST)
25#include <ctype.h> /* definition of |isalpha|, |isdigit| and so on */
26@y
27#include ctype /* definition of |isalpha|, |isdigit| and so on */
28 /* VMS searches text libraries faster */
29@z
30
31@x section 63 (01-FEB-1992 ST)
32@d isxalpha(c) ((c)=='_') /* non-alpha character allowed in identifier */
33@y
34@d isxalpha(c) ((c)=='_' || (c)=='$') /* non-alpha characters allowed in id */
35@z
ctangle.c+1551−0
@@ -0,0 +1,1551 @@
1/*1:*/
2#line 61 "ctangle.w"
3
4/*6:*/
5#line 35 "common.h"
6
7#include <stdio.h>
8
9/*:6*//*62:*/
10#line 874 "ctangle.w"
11
12#include <ctype.h>
13#include <stdlib.h>
14
15/*:62*/
16#line 62 "ctangle.w"
17
18#define banner "This is CTANGLE (Version 3.2)\n" \
19
20#define max_bytes 90000 \
21
22#define max_toks 270000
23#define max_names 4000 \
24
25#define max_texts 2500
26#define hash_size 353
27#define longest_name 1000
28#define stack_size 50
29#define buf_size 100 \
30
31#define ctangle 0
32#define cweave 1 \
33
34#define and_and 04
35#define lt_lt 020
36#define gt_gt 021
37#define plus_plus 013
38#define minus_minus 01
39#define minus_gt 031
40#define not_eq 032
41#define lt_eq 034
42#define gt_eq 035
43#define eq_eq 036
44#define or_or 037
45#define dot_dot_dot 016
46#define colon_colon 06
47#define period_ast 026
48#define minus_gt_ast 027 \
49
50#define xisalpha(c)(isalpha(c)&&((eight_bits)c<0200))
51#define xisdigit(c)(isdigit(c)&&((eight_bits)c<0200))
52#define xisspace(c)(isspace(c)&&((eight_bits)c<0200))
53#define xislower(c)(islower(c)&&((eight_bits)c<0200))
54#define xisupper(c)(isupper(c)&&((eight_bits)c<0200))
55#define xisxdigit(c)(isxdigit(c)&&((eight_bits)c<0200)) \
56
57#define length(c)(c+1)->byte_start-(c)->byte_start
58#define print_id(c)term_write((c)->byte_start,length((c)))
59#define llink link
60#define rlink dummy.Rlink
61#define root name_dir->rlink \
62
63#define chunk_marker 0 \
64
65#define spotless 0
66#define harmless_message 1
67#define error_message 2
68#define fatal_message 3
69#define mark_harmless {if(history==spotless)history= harmless_message;}
70#define mark_error history= error_message
71#define confusion(s)fatal("! This can't happen: ",s) \
72
73#define max_file_name_length 60
74#define cur_file file[include_depth]
75#define cur_file_name file_name[include_depth]
76#define web_file_name file_name[0]
77#define cur_line line[include_depth] \
78
79#define show_banner flags['b']
80#define show_progress flags['p']
81#define show_happiness flags['h'] \
82
83#define update_terminal fflush(stdout)
84#define new_line putchar('\n')
85#define putxchar putchar
86#define term_write(a,b)fflush(stdout),fwrite(a,sizeof(char),b,stdout)
87#define C_printf(c,a)fprintf(C_file,c,a)
88#define C_putc(c)putc(c,C_file) \
89
90#define equiv equiv_or_xref \
91
92#define section_flag max_texts \
93
94#define string 02
95#define join 0177
96#define output_defs_flag (2*024000-1) \
97
98#define cur_end cur_state.end_field
99#define cur_byte cur_state.byte_field
100#define cur_name cur_state.name_field
101#define cur_repl cur_state.repl_field
102#define cur_section cur_state.section_field \
103
104#define section_number 0201
105#define identifier 0202 \
106
107#define normal 0
108#define num_or_id 1
109#define unbreakable 3
110#define verbatim 4 \
111
112#define max_files 256
113#define translit_length 10 \
114
115#define ignore 0
116#define ord 0302
117#define control_text 0303
118#define translit_code 0304
119#define output_defs_code 0305
120#define format_code 0306
121#define definition 0307
122#define begin_C 0310
123#define section_name 0311
124#define new_section 0312 \
125
126#define constant 03 \
127
128#define isxalpha(c)((c)=='_')
129#define ishigh(c)((unsigned char)(c)>0177) \
130 \
131
132#define compress(c)if(loc++<=limit)return(c) \
133
134#define macro 0
135#define app_repl(c){if(tok_ptr==tok_mem_end)overflow("token");*tok_ptr++= c;} \
136
137
138#line 63 "ctangle.w"
139
140/*5:*/
141#line 29 "common.h"
142
143typedef short boolean;
144typedef char unsigned eight_bits;
145extern boolean program;
146extern int phase;
147
148/*:5*//*7:*/
149#line 57 "common.h"
150
151char section_text[longest_name+1];
152char*section_text_end= section_text+longest_name;
153char*id_first;
154char*id_loc;
155
156/*:7*//*8:*/
157#line 72 "common.h"
158
159extern char buffer[];
160extern char*buffer_end;
161extern char*loc;
162extern char*limit;
163
164/*:8*//*9:*/
165#line 87 "common.h"
166
167typedef struct name_info{
168char*byte_start;
169struct name_info*link;
170union{
171struct name_info*Rlink;
172
173char Ilk;
174}dummy;
175char*equiv_or_xref;
176}name_info;
177typedef name_info*name_pointer;
178typedef name_pointer*hash_pointer;
179extern char byte_mem[];
180extern char*byte_mem_end;
181extern name_info name_dir[];
182extern name_pointer name_dir_end;
183extern name_pointer name_ptr;
184extern char*byte_ptr;
185extern name_pointer hash[];
186extern hash_pointer hash_end;
187extern hash_pointer h;
188extern name_pointer id_lookup();
189extern name_pointer section_lookup();
190extern void print_section_name(),sprint_section_name();
191
192/*:9*//*10:*/
193#line 122 "common.h"
194
195extern history;
196extern err_print();
197extern wrap_up();
198extern void fatal();
199extern void overflow();
200
201/*:10*//*11:*/
202#line 137 "common.h"
203
204extern include_depth;
205extern FILE*file[];
206extern FILE*change_file;
207extern char C_file_name[];
208extern char tex_file_name[];
209extern char idx_file_name[];
210extern char scn_file_name[];
211extern char file_name[][max_file_name_length];
212
213extern char change_file_name[];
214extern line[];
215extern change_line;
216extern boolean input_has_ended;
217extern boolean changing;
218extern boolean web_file_open;
219extern reset_input();
220extern get_line();
221extern check_complete();
222
223/*:11*//*12:*/
224#line 158 "common.h"
225
226typedef unsigned short sixteen_bits;
227extern sixteen_bits section_count;
228extern boolean changed_section[];
229extern boolean change_pending;
230extern boolean print_where;
231
232/*:12*//*13:*/
233#line 170 "common.h"
234
235extern int argc;
236extern char**argv;
237extern boolean flags[];
238
239/*:13*//*14:*/
240#line 182 "common.h"
241
242extern FILE*C_file;
243extern FILE*tex_file;
244extern FILE*idx_file;
245extern FILE*scn_file;
246extern FILE*active_file;
247
248/*:14*//*15:*/
249#line 191 "common.h"
250
251extern void common_init();
252#line 125 "ctangle.w"
253
254/*:15*/
255#line 64 "ctangle.w"
256
257/*16:*/
258#line 149 "ctangle.w"
259
260typedef struct{
261eight_bits*tok_start;
262sixteen_bits text_link;
263}text;
264typedef text*text_pointer;
265
266/*:16*//*27:*/
267#line 293 "ctangle.w"
268
269typedef struct{
270eight_bits*end_field;
271eight_bits*byte_field;
272name_pointer name_field;
273text_pointer repl_field;
274sixteen_bits section_field;
275}output_state;
276typedef output_state*stack_pointer;
277
278/*:27*/
279#line 65 "ctangle.w"
280
281/*17:*/
282#line 156 "ctangle.w"
283
284text text_info[max_texts];
285text_pointer text_info_end= text_info+max_texts-1;
286text_pointer text_ptr;
287eight_bits tok_mem[max_toks];
288eight_bits*tok_mem_end= tok_mem+max_toks-1;
289eight_bits*tok_ptr;
290
291/*:17*//*23:*/
292#line 224 "ctangle.w"
293
294text_pointer last_unnamed;
295
296/*:23*//*28:*/
297#line 309 "ctangle.w"
298
299output_state cur_state;
300
301output_state stack[stack_size+1];
302stack_pointer stack_ptr;
303stack_pointer stack_end= stack+stack_size;
304
305/*:28*//*32:*/
306#line 381 "ctangle.w"
307
308int cur_val;
309
310/*:32*//*36:*/
311#line 467 "ctangle.w"
312
313eight_bits out_state;
314boolean protect;
315
316/*:36*//*38:*/
317#line 496 "ctangle.w"
318
319name_pointer output_files[max_files];
320name_pointer*cur_out_file,*end_output_files,*an_output_file;
321char cur_section_name_char;
322char output_file_name[longest_name];
323
324/*:38*//*45:*/
325#line 593 "ctangle.w"
326
327boolean output_defs_seen= 0;
328
329/*:45*//*51:*/
330#line 700 "ctangle.w"
331
332char translit[128][translit_length];
333
334/*:51*//*56:*/
335#line 776 "ctangle.w"
336
337eight_bits ccode[256];
338
339/*:56*//*59:*/
340#line 832 "ctangle.w"
341
342boolean comment_continues= 0;
343
344/*:59*//*61:*/
345#line 871 "ctangle.w"
346
347name_pointer cur_section_name;
348
349/*:61*//*75:*/
350#line 1181 "ctangle.w"
351
352text_pointer cur_text;
353eight_bits next_control;
354
355/*:75*//*82:*/
356#line 1328 "ctangle.w"
357
358extern sixteen_bits section_count;
359
360/*:82*/
361#line 66 "ctangle.w"
362
363/*2:*/
364#line 74 "ctangle.w"
365
366extern int strlen();
367extern int strcmp();
368extern char*strcpy();
369extern int strncmp();
370extern char*strncpy();
371
372/*:2*//*41:*/
373#line 527 "ctangle.w"
374
375void phase_two();
376
377/*:41*//*46:*/
378#line 596 "ctangle.w"
379
380void output_defs();
381
382/*:46*//*48:*/
383#line 642 "ctangle.w"
384
385void out_char();
386
387/*:48*//*90:*/
388#line 1434 "ctangle.w"
389
390void phase_one();
391
392/*:90*//*92:*/
393#line 1452 "ctangle.w"
394
395void skip_limbo();
396
397/*:92*/
398#line 67 "ctangle.w"
399
400
401/*:1*//*3:*/
402#line 88 "ctangle.w"
403
404int main(ac,av)
405int ac;
406char**av;
407{
408argc= ac;argv= av;
409program= ctangle;
410/*18:*/
411#line 164 "ctangle.w"
412
413text_info->tok_start= tok_ptr= tok_mem;
414text_ptr= text_info+1;text_ptr->tok_start= tok_mem;
415
416
417/*:18*//*20:*/
418#line 174 "ctangle.w"
419
420name_dir->equiv= (char*)text_info;
421
422/*:20*//*24:*/
423#line 227 "ctangle.w"
424last_unnamed= text_info;text_info->text_link= 0;
425
426/*:24*//*39:*/
427#line 506 "ctangle.w"
428
429cur_out_file= end_output_files= output_files+max_files;
430
431/*:39*//*52:*/
432#line 703 "ctangle.w"
433
434{
435int i;
436for(i= 0;i<128;i++)sprintf(translit[i],"X%02X",(unsigned)(128+i));
437}
438
439/*:52*//*57:*/
440#line 779 "ctangle.w"
441{
442int c;
443for(c= 0;c<256;c++)ccode[c]= ignore;
444ccode[' ']= ccode['\t']= ccode['\n']= ccode['\v']= ccode['\r']= ccode['\f']
445= ccode['*']= new_section;
446ccode['@']= '@';ccode['=']= string;
447ccode['d']= ccode['D']= definition;
448ccode['f']= ccode['F']= ccode['s']= ccode['S']= format_code;
449ccode['c']= ccode['C']= ccode['p']= ccode['P']= begin_C;
450ccode['^']= ccode[':']= ccode['.']= ccode['t']= ccode['T']=
451ccode['q']= ccode['Q']= control_text;
452ccode['h']= ccode['H']= output_defs_code;
453ccode['l']= ccode['L']= translit_code;
454ccode['&']= join;
455ccode['<']= ccode['(']= section_name;
456ccode['\'']= ord;
457}
458
459/*:57*//*71:*/
460#line 1105 "ctangle.w"
461section_text[0]= ' ';
462
463/*:71*/
464#line 95 "ctangle.w"
465;
466common_init();
467if(show_banner)printf(banner);
468phase_one();
469phase_two();
470return wrap_up();
471}
472
473/*:3*//*21:*/
474#line 180 "ctangle.w"
475
476int names_match(p,first,l)
477name_pointer p;
478char*first;
479int l;
480{
481if(length(p)!=l)return 0;
482return!strncmp(first,p->byte_start,l);
483}
484
485/*:21*//*22:*/
486#line 195 "ctangle.w"
487
488void
489init_node(node)
490name_pointer node;
491{
492node->equiv= (char*)text_info;
493}
494void
495init_p(){}
496
497/*:22*//*26:*/
498#line 257 "ctangle.w"
499
500void
501store_two_bytes(x)
502sixteen_bits x;
503{
504if(tok_ptr+2>tok_mem_end)overflow("token");
505*tok_ptr++= x>>8;
506*tok_ptr++= x&0377;
507}
508
509/*:26*//*30:*/
510#line 333 "ctangle.w"
511
512void
513push_level(p)
514name_pointer p;
515{
516if(stack_ptr==stack_end)overflow("stack");
517*stack_ptr= cur_state;
518stack_ptr++;
519if(p!=NULL){
520cur_name= p;cur_repl= (text_pointer)p->equiv;
521cur_byte= cur_repl->tok_start;cur_end= (cur_repl+1)->tok_start;
522cur_section= 0;
523}
524}
525
526/*:30*//*31:*/
527#line 352 "ctangle.w"
528
529void
530pop_level(flag)
531int flag;
532{
533if(flag&&cur_repl->text_link<section_flag){
534cur_repl= cur_repl->text_link+text_info;
535cur_byte= cur_repl->tok_start;cur_end= (cur_repl+1)->tok_start;
536return;
537}
538stack_ptr--;
539if(stack_ptr>stack)cur_state= *stack_ptr;
540}
541
542/*:31*//*33:*/
543#line 388 "ctangle.w"
544
545void
546get_output()
547{
548sixteen_bits a;
549restart:if(stack_ptr==stack)return;
550if(cur_byte==cur_end){
551cur_val= -((int)cur_section);
552pop_level(1);
553if(cur_val==0)goto restart;
554out_char(section_number);return;
555}
556a= *cur_byte++;
557if(out_state==verbatim&&a!=string&&a!=constant&&a!='\n')
558C_putc(a);
559else if(a<0200)out_char(a);
560else{
561a= (a-0200)*0400+*cur_byte++;
562switch(a/024000){
563case 0:cur_val= a;out_char(identifier);break;
564case 1:if(a==output_defs_flag)output_defs();
565else/*34:*/
566#line 420 "ctangle.w"
567
568{
569a-= 024000;
570if((a+name_dir)->equiv!=(char*)text_info)push_level(a+name_dir);
571else if(a!=0){
572printf("\n! Not present: <");
573print_section_name(a+name_dir);err_print(">");
574
575}
576goto restart;
577}
578
579/*:34*/
580#line 409 "ctangle.w"
581;
582break;
583default:cur_val= a-050000;if(cur_val>0)cur_section= cur_val;
584out_char(section_number);
585}
586}
587}
588
589/*:33*//*37:*/
590#line 475 "ctangle.w"
591
592void
593flush_buffer()
594{
595C_putc('\n');
596if(cur_line%100==0&&show_progress){
597printf(".");
598if(cur_line%500==0)printf("%d",cur_line);
599update_terminal;
600}
601cur_line++;
602}
603
604/*:37*//*42:*/
605#line 530 "ctangle.w"
606
607void
608phase_two(){
609web_file_open= 0;
610cur_line= 1;
611/*29:*/
612#line 322 "ctangle.w"
613
614stack_ptr= stack+1;cur_name= name_dir;cur_repl= text_info->text_link+text_info;
615cur_byte= cur_repl->tok_start;cur_end= (cur_repl+1)->tok_start;cur_section= 0;
616
617/*:29*/
618#line 535 "ctangle.w"
619;
620/*44:*/
621#line 589 "ctangle.w"
622
623if(!output_defs_seen)
624output_defs();
625
626/*:44*/
627#line 536 "ctangle.w"
628;
629if(text_info->text_link==0&&cur_out_file==end_output_files){
630printf("\n! No program text was specified.");mark_harmless;
631
632}
633else{
634if(cur_out_file==end_output_files){
635if(show_progress)
636printf("\nWriting the output file (%s):",C_file_name);
637}
638else{
639if(show_progress){
640printf("\nWriting the output files:");
641
642printf(" (%s)",C_file_name);
643update_terminal;
644}
645if(text_info->text_link==0)goto writeloop;
646}
647while(stack_ptr>stack)get_output();
648flush_buffer();
649writeloop:/*43:*/
650#line 566 "ctangle.w"
651
652for(an_output_file= end_output_files;an_output_file>cur_out_file;){
653an_output_file--;
654sprint_section_name(output_file_name,*an_output_file);
655fclose(C_file);
656C_file= fopen(output_file_name,"w");
657if(C_file==0)fatal("! Cannot open output file:",output_file_name);
658
659printf("\n(%s)",output_file_name);update_terminal;
660cur_line= 1;
661stack_ptr= stack+1;
662cur_name= (*an_output_file);
663cur_repl= (text_pointer)cur_name->equiv;
664cur_byte= cur_repl->tok_start;
665cur_end= (cur_repl+1)->tok_start;
666while(stack_ptr>stack)get_output();
667flush_buffer();
668}
669
670/*:43*/
671#line 557 "ctangle.w"
672;
673if(show_happiness)printf("\nDone.");
674}
675}
676
677/*:42*//*47:*/
678#line 599 "ctangle.w"
679
680void
681output_defs()
682{
683sixteen_bits a;
684push_level(NULL);
685for(cur_text= text_info+1;cur_text<text_ptr;cur_text++)
686if(cur_text->text_link==0){
687cur_byte= cur_text->tok_start;
688cur_end= (cur_text+1)->tok_start;
689C_printf("%s","#define ");
690out_state= normal;
691protect= 1;
692while(cur_byte<cur_end){
693a= *cur_byte++;
694if(cur_byte==cur_end&&a=='\n')break;
695if(out_state==verbatim&&a!=string&&a!=constant&&a!='\n')
696C_putc(a);
697
698else if(a<0200)out_char(a);
699else{
700a= (a-0200)*0400+*cur_byte++;
701if(a<024000){
702cur_val= a;out_char(identifier);
703}
704else if(a<050000){confusion("macro defs have strange char");}
705else{
706cur_val= a-050000;cur_section= cur_val;out_char(section_number);
707}
708
709}
710}
711protect= 0;
712flush_buffer();
713}
714pop_level(0);
715}
716
717/*:47*//*49:*/
718#line 645 "ctangle.w"
719
720void
721out_char(cur_char)
722eight_bits cur_char;
723{
724char*j,*k;
725restart:
726switch(cur_char){
727case'\n':if(protect)C_putc(' ');
728if(protect||out_state==verbatim)C_putc('\\');
729flush_buffer();if(out_state!=verbatim)out_state= normal;break;
730/*53:*/
731#line 709 "ctangle.w"
732
733case identifier:
734if(out_state==num_or_id)C_putc(' ');
735j= (cur_val+name_dir)->byte_start;
736k= (cur_val+name_dir+1)->byte_start;
737while(j<k){
738if((unsigned char)(*j)<0200)C_putc(*j);
739
740else C_printf("%s",translit[(unsigned char)(*j)-0200]);
741j++;
742}
743out_state= num_or_id;break;
744
745/*:53*/
746#line 656 "ctangle.w"
747;
748/*54:*/
749#line 722 "ctangle.w"
750
751case section_number:
752if(cur_val>0)C_printf("/*%d:*/",cur_val);
753else if(cur_val<0)C_printf("/*:%d*/",-cur_val);
754else if(protect){
755cur_byte+= 4;
756cur_char= '\n';
757goto restart;
758}else{
759sixteen_bits a;
760a= 0400**cur_byte++;
761a+= *cur_byte++;
762C_printf("\n#line %d \"",a);
763
764cur_val= *cur_byte++;
765cur_val= 0400*(cur_val-0200)+*cur_byte++;
766for(j= (cur_val+name_dir)->byte_start,k= (cur_val+name_dir+1)->byte_start;
767j<k;j++)C_putc(*j);
768C_printf("%s","\"\n");
769}
770break;
771
772/*:54*/
773#line 657 "ctangle.w"
774;
775/*50:*/
776#line 671 "ctangle.w"
777
778case plus_plus:C_putc('+');C_putc('+');out_state= normal;break;
779case minus_minus:C_putc('-');C_putc('-');out_state= normal;break;
780case minus_gt:C_putc('-');C_putc('>');out_state= normal;break;
781case gt_gt:C_putc('>');C_putc('>');out_state= normal;break;
782case eq_eq:C_putc('=');C_putc('=');out_state= normal;break;
783case lt_lt:C_putc('<');C_putc('<');out_state= normal;break;
784case gt_eq:C_putc('>');C_putc('=');out_state= normal;break;
785case lt_eq:C_putc('<');C_putc('=');out_state= normal;break;
786case not_eq:C_putc('!');C_putc('=');out_state= normal;break;
787case and_and:C_putc('&');C_putc('&');out_state= normal;break;
788case or_or:C_putc('|');C_putc('|');out_state= normal;break;
789case dot_dot_dot:C_putc('.');C_putc('.');C_putc('.');out_state= normal;
790break;
791case colon_colon:C_putc(':');C_putc(':');out_state= normal;break;
792case period_ast:C_putc('.');C_putc('*');out_state= normal;break;
793case minus_gt_ast:C_putc('-');C_putc('>');C_putc('*');out_state= normal;
794break;
795
796/*:50*/
797#line 658 "ctangle.w"
798;
799case'=':C_putc('=');C_putc(' ');out_state= normal;break;
800case join:out_state= unbreakable;break;
801case constant:if(out_state==verbatim){
802out_state= num_or_id;break;
803}
804if(out_state==num_or_id)C_putc(' ');out_state= verbatim;break;
805case string:if(out_state==verbatim)out_state= normal;
806else out_state= verbatim;break;
807default:C_putc(cur_char);out_state= normal;break;
808}
809}
810
811/*:49*//*58:*/
812#line 800 "ctangle.w"
813
814eight_bits
815skip_ahead()
816{
817eight_bits c;
818while(1){
819if(loc>limit&&(get_line()==0))return(new_section);
820*(limit+1)= '@';
821while(*loc!='@')loc++;
822if(loc<=limit){
823loc++;c= ccode[(eight_bits)*loc];loc++;
824if(c!=ignore||*(loc-1)=='>')return(c);
825}
826}
827}
828
829/*:58*//*60:*/
830#line 835 "ctangle.w"
831
832int skip_comment(is_long_comment)
833boolean is_long_comment;
834{
835char c;
836while(1){
837if(loc>limit){
838if(is_long_comment){
839if(get_line())return(comment_continues= 1);
840else{
841err_print("! Input ended in mid-comment");
842
843return(comment_continues= 0);
844}
845}
846else return(comment_continues= 0);
847}
848c= *(loc++);
849if(is_long_comment&&c=='*'&&*loc=='/'){
850loc++;return(comment_continues= 0);
851}
852if(c=='@'){
853if(ccode[(eight_bits)*loc]==new_section){
854err_print("! Section name ended in mid-comment");loc--;
855
856return(comment_continues= 0);
857}
858else loc++;
859}
860}
861}
862
863/*:60*//*63:*/
864#line 885 "ctangle.w"
865
866eight_bits
867get_next()
868{
869static int preprocessing= 0;
870eight_bits c;
871while(1){
872if(loc>limit){
873if(preprocessing&&*(limit-1)!='\\')preprocessing= 0;
874if(get_line()==0)return(new_section);
875else if(print_where){
876print_where= 0;
877/*77:*/
878#line 1208 "ctangle.w"
879
880store_two_bytes(0150000);
881if(changing)id_first= change_file_name;
882else id_first= cur_file_name;
883id_loc= id_first+strlen(id_first);
884if(changing)store_two_bytes((sixteen_bits)change_line);
885else store_two_bytes((sixteen_bits)cur_line);
886{int a= id_lookup(id_first,id_loc)-name_dir;app_repl((a/0400)+0200);
887app_repl(a%0400);}
888
889/*:77*/
890#line 897 "ctangle.w"
891;
892}
893else return('\n');
894}
895c= *loc;
896if(comment_continues||(c=='/'&&(*(loc+1)=='*'||*(loc+1)=='/'))){
897skip_comment(comment_continues||*(loc+1)=='*');
898
899if(comment_continues)return('\n');
900else continue;
901}
902loc++;
903if(xisdigit(c)||c=='\\'||c=='.')/*66:*/
904#line 963 "ctangle.w"
905{
906id_first= loc-1;
907if(*id_first=='.'&&!xisdigit(*loc))goto mistake;
908if(*id_first=='\\')while(xisdigit(*loc))loc++;
909else{
910if(*id_first=='0'){
911if(*loc=='x'||*loc=='X'){
912loc++;while(xisxdigit(*loc))loc++;goto found;
913}
914}
915while(xisdigit(*loc))loc++;
916if(*loc=='.'){
917loc++;
918while(xisdigit(*loc))loc++;
919}
920if(*loc=='e'||*loc=='E'){
921if(*++loc=='+'||*loc=='-')loc++;
922while(xisdigit(*loc))loc++;
923}
924}
925found:while(*loc=='u'||*loc=='U'||*loc=='l'||*loc=='L'
926||*loc=='f'||*loc=='F')loc++;
927id_loc= loc;
928return(constant);
929}
930
931/*:66*/
932#line 909 "ctangle.w"
933
934else if(c=='\''||c=='"'||(c=='L'&&(*loc=='\''||*loc=='"')))
935/*67:*/
936#line 994 "ctangle.w"
937{
938char delim= c;
939id_first= section_text+1;
940id_loc= section_text;*++id_loc= delim;
941if(delim=='L'){
942delim= *loc++;*++id_loc= delim;
943}
944while(1){
945if(loc>=limit){
946if(*(limit-1)!='\\'){
947err_print("! String didn't end");loc= limit;break;
948
949}
950if(get_line()==0){
951err_print("! Input ended in middle of string");loc= buffer;break;
952
953}
954else if(++id_loc<=section_text_end)*id_loc= '\n';
955
956}
957if((c= *loc++)==delim){
958if(++id_loc<=section_text_end)*id_loc= c;
959break;
960}
961if(c=='\\'){
962if(loc>=limit)continue;
963if(++id_loc<=section_text_end)*id_loc= '\\';
964c= *loc++;
965}
966if(++id_loc<=section_text_end)*id_loc= c;
967}
968if(id_loc>=section_text_end){
969printf("\n! String too long: ");
970
971term_write(section_text+1,25);
972err_print("...");
973}
974id_loc++;
975return(string);
976}
977
978/*:67*/
979#line 911 "ctangle.w"
980
981else if(isalpha(c)||isxalpha(c)||ishigh(c))
982/*65:*/
983#line 957 "ctangle.w"
984{
985id_first= --loc;
986while(isalpha(*++loc)||isdigit(*loc)||isxalpha(*loc)||ishigh(*loc));
987id_loc= loc;return(identifier);
988}
989
990/*:65*/
991#line 913 "ctangle.w"
992
993else if(c=='@')/*68:*/
994#line 1038 "ctangle.w"
995{
996c= ccode[(eight_bits)*loc++];
997switch(c){
998case ignore:continue;
999case output_defs_code:output_defs_seen= 1;return(c);
1000case translit_code:err_print("! Use @l in limbo only");continue;
1001
1002case control_text:while((c= skip_ahead())=='@');
1003
1004if(*(loc-1)!='>')
1005err_print("! Double @ should be used in control text");
1006
1007continue;
1008case section_name:
1009cur_section_name_char= *(loc-1);
1010/*70:*/
1011#line 1087 "ctangle.w"
1012{
1013char*k;
1014/*72:*/
1015#line 1107 "ctangle.w"
1016
1017k= section_text;
1018while(1){
1019if(loc>limit&&get_line()==0){
1020err_print("! Input ended in section name");
1021
1022loc= buffer+1;break;
1023}
1024c= *loc;
1025/*73:*/
1026#line 1131 "ctangle.w"
1027
1028if(c=='@'){
1029c= *(loc+1);
1030if(c=='>'){
1031loc+= 2;break;
1032}
1033if(ccode[(eight_bits)c]==new_section){
1034err_print("! Section name didn't end");break;
1035
1036}
1037if(ccode[(eight_bits)c]==section_name){
1038err_print("! Nesting of section names not allowed");break;
1039
1040}
1041*(++k)= '@';loc++;
1042}
1043
1044/*:73*/
1045#line 1116 "ctangle.w"
1046;
1047loc++;if(k<section_text_end)k++;
1048if(xisspace(c)){
1049c= ' ';if(*(k-1)==' ')k--;
1050}
1051*k= c;
1052}
1053if(k>=section_text_end){
1054printf("\n! Section name too long: ");
1055
1056term_write(section_text+1,25);
1057printf("...");mark_harmless;
1058}
1059if(*k==' '&&k>section_text)k--;
1060
1061/*:72*/
1062#line 1089 "ctangle.w"
1063;
1064if(k-section_text>3&&strncmp(k-2,"...",3)==0)
1065cur_section_name= section_lookup(section_text+1,k-3,1);
1066else cur_section_name= section_lookup(section_text+1,k,0);
1067if(cur_section_name_char=='(')
1068/*40:*/
1069#line 510 "ctangle.w"
1070
1071{
1072for(an_output_file= cur_out_file;
1073an_output_file<end_output_files;an_output_file++)
1074if(*an_output_file==cur_section_name)break;
1075if(an_output_file==end_output_files){
1076if(cur_out_file>output_files)
1077*--cur_out_file= cur_section_name;
1078else{
1079overflow("output files");
1080}
1081}
1082}
1083
1084/*:40*/
1085#line 1095 "ctangle.w"
1086;
1087return(section_name);
1088}
1089
1090/*:70*/
1091#line 1053 "ctangle.w"
1092;
1093case string:/*74:*/
1094#line 1153 "ctangle.w"
1095{
1096id_first= loc++;*(limit+1)= '@';*(limit+2)= '>';
1097while(*loc!='@'||*(loc+1)!='>')loc++;
1098if(loc>=limit)err_print("! Verbatim string didn't end");
1099
1100id_loc= loc;loc+= 2;
1101return(string);
1102}
1103
1104/*:74*/
1105#line 1054 "ctangle.w"
1106;
1107case ord:/*69:*/
1108#line 1066 "ctangle.w"
1109
1110id_first= loc;
1111if(*loc=='\\'){
1112if(*++loc=='\'')loc++;
1113}
1114while(*loc!='\''){
1115if(*loc=='@'){
1116if(*(loc+1)!='@')
1117err_print("! Double @ should be used in ASCII constant");
1118
1119else loc++;
1120}
1121loc++;
1122if(loc>limit){
1123err_print("! String didn't end");loc= limit-1;break;
1124
1125}
1126}
1127loc++;
1128return(ord);
1129
1130/*:69*/
1131#line 1055 "ctangle.w"
1132;
1133default:return(c);
1134}
1135}
1136
1137/*:68*/
1138#line 914 "ctangle.w"
1139
1140else if(xisspace(c)){
1141if(!preprocessing||loc>limit)continue;
1142
1143else return(' ');
1144}
1145else if(c=='#'&&loc==buffer+1)preprocessing= 1;
1146mistake:/*64:*/
1147#line 935 "ctangle.w"
1148
1149switch(c){
1150case'+':if(*loc=='+')compress(plus_plus);break;
1151case'-':if(*loc=='-'){compress(minus_minus);}
1152else if(*loc=='>')if(*(loc+1)=='*'){loc++;compress(minus_gt_ast);}
1153else compress(minus_gt);break;
1154case'.':if(*loc=='*'){compress(period_ast);}
1155else if(*loc=='.'&&*(loc+1)=='.'){
1156loc++;compress(dot_dot_dot);
1157}
1158break;
1159case':':if(*loc==':')compress(colon_colon);break;
1160case'=':if(*loc=='=')compress(eq_eq);break;
1161case'>':if(*loc=='='){compress(gt_eq);}
1162else if(*loc=='>')compress(gt_gt);break;
1163case'<':if(*loc=='='){compress(lt_eq);}
1164else if(*loc=='<')compress(lt_lt);break;
1165case'&':if(*loc=='&')compress(and_and);break;
1166case'|':if(*loc=='|')compress(or_or);break;
1167case'!':if(*loc=='=')compress(not_eq);break;
1168}
1169
1170/*:64*/
1171#line 921 "ctangle.w"
1172
1173return(c);
1174}
1175}
1176
1177/*:63*//*76:*/
1178#line 1185 "ctangle.w"
1179
1180void
1181scan_repl(t)
1182eight_bits t;
1183{
1184sixteen_bits a;
1185if(t==section_name){/*77:*/
1186#line 1208 "ctangle.w"
1187
1188store_two_bytes(0150000);
1189if(changing)id_first= change_file_name;
1190else id_first= cur_file_name;
1191id_loc= id_first+strlen(id_first);
1192if(changing)store_two_bytes((sixteen_bits)change_line);
1193else store_two_bytes((sixteen_bits)cur_line);
1194{int a= id_lookup(id_first,id_loc)-name_dir;app_repl((a/0400)+0200);
1195app_repl(a%0400);}
1196
1197/*:77*/
1198#line 1191 "ctangle.w"
1199;}
1200while(1)switch(a= get_next()){
1201/*78:*/
1202#line 1218 "ctangle.w"
1203
1204case identifier:a= id_lookup(id_first,id_loc)-name_dir;
1205app_repl((a/0400)+0200);
1206app_repl(a%0400);break;
1207case section_name:if(t!=section_name)goto done;
1208else{
1209/*79:*/
1210#line 1246 "ctangle.w"
1211{
1212char*try_loc= loc;
1213while(*try_loc==' '&&try_loc<limit)try_loc++;
1214if(*try_loc=='+'&&try_loc<limit)try_loc++;
1215while(*try_loc==' '&&try_loc<limit)try_loc++;
1216if(*try_loc=='=')err_print("! Missing `@ ' before a named section");
1217
1218
1219
1220}
1221
1222/*:79*/
1223#line 1224 "ctangle.w"
1224;
1225a= cur_section_name-name_dir;
1226app_repl((a/0400)+0250);
1227app_repl(a%0400);
1228/*77:*/
1229#line 1208 "ctangle.w"
1230
1231store_two_bytes(0150000);
1232if(changing)id_first= change_file_name;
1233else id_first= cur_file_name;
1234id_loc= id_first+strlen(id_first);
1235if(changing)store_two_bytes((sixteen_bits)change_line);
1236else store_two_bytes((sixteen_bits)cur_line);
1237{int a= id_lookup(id_first,id_loc)-name_dir;app_repl((a/0400)+0200);
1238app_repl(a%0400);}
1239
1240/*:77*/
1241#line 1228 "ctangle.w"
1242;break;
1243}
1244case output_defs_code:
1245a= output_defs_flag;
1246app_repl((a/0400)+0200);
1247app_repl(a%0400);
1248/*77:*/
1249#line 1208 "ctangle.w"
1250
1251store_two_bytes(0150000);
1252if(changing)id_first= change_file_name;
1253else id_first= cur_file_name;
1254id_loc= id_first+strlen(id_first);
1255if(changing)store_two_bytes((sixteen_bits)change_line);
1256else store_two_bytes((sixteen_bits)cur_line);
1257{int a= id_lookup(id_first,id_loc)-name_dir;app_repl((a/0400)+0200);
1258app_repl(a%0400);}
1259
1260/*:77*/
1261#line 1234 "ctangle.w"
1262;break;
1263case constant:case string:
1264/*80:*/
1265#line 1257 "ctangle.w"
1266
1267app_repl(a);
1268while(id_first<id_loc){
1269if(*id_first=='@'){
1270if(*(id_first+1)=='@')id_first++;
1271else err_print("! Double @ should be used in string");
1272
1273}
1274app_repl(*id_first++);
1275}
1276app_repl(a);break;
1277
1278/*:80*/
1279#line 1236 "ctangle.w"
1280;
1281case ord:
1282/*81:*/
1283#line 1273 "ctangle.w"
1284{
1285int c= (eight_bits)*id_first;
1286if(c=='\\'){
1287c= *++id_first;
1288if(c>='0'&&c<='7'){
1289c-= '0';
1290if(*(id_first+1)>='0'&&*(id_first+1)<='7'){
1291c= 8*c+*(++id_first)-'0';
1292if(*(id_first+1)>='0'&&*(id_first+1)<='7'&&c<32)
1293c= 8*c+*(++id_first)-'0';
1294}
1295}
1296else switch(c){
1297case't':c= '\t';break;
1298case'n':c= '\n';break;
1299case'b':c= '\b';break;
1300case'f':c= '\f';break;
1301case'v':c= '\v';break;
1302case'r':c= '\r';break;
1303case'a':c= '\7';break;
1304case'?':c= '?';break;
1305case'x':
1306if(xisdigit(*(id_first+1)))c= *(++id_first)-'0';
1307else if(xisxdigit(*(id_first+1))){
1308++id_first;
1309c= toupper(*id_first)-'A'+10;
1310}
1311if(xisdigit(*(id_first+1)))c= 16*c+*(++id_first)-'0';
1312else if(xisxdigit(*(id_first+1))){
1313++id_first;
1314c= 16*c+toupper(*id_first)-'A'+10;
1315}
1316break;
1317case'\\':c= '\\';break;
1318case'\'':c= '\'';break;
1319case'\"':c= '\"';break;
1320default:err_print("! Unrecognized escape sequence");
1321
1322}
1323}
1324
1325app_repl(constant);
1326if(c>=100)app_repl('0'+c/100);
1327if(c>=10)app_repl('0'+(c/10)%10);
1328app_repl('0'+c%10);
1329app_repl(constant);
1330}
1331break;
1332
1333/*:81*/
1334#line 1238 "ctangle.w"
1335;
1336case definition:case format_code:case begin_C:if(t!=section_name)goto done;
1337else{
1338err_print("! @d, @f and @c are ignored in C text");continue;
1339
1340}
1341case new_section:goto done;
1342
1343/*:78*/
1344#line 1196 "ctangle.w"
1345
1346default:app_repl(a);
1347}
1348done:next_control= (eight_bits)a;
1349if(text_ptr>text_info_end)overflow("text");
1350cur_text= text_ptr;(++text_ptr)->tok_start= tok_ptr;
1351}
1352
1353/*:76*//*83:*/
1354#line 1335 "ctangle.w"
1355
1356void
1357scan_section()
1358{
1359name_pointer p;
1360text_pointer q;
1361sixteen_bits a;
1362section_count++;
1363if(*(loc-1)=='*'&&show_progress){
1364printf("*%d",section_count);update_terminal;
1365}
1366next_control= 0;
1367while(1){
1368/*84:*/
1369#line 1373 "ctangle.w"
1370
1371while(next_control<definition)
1372
1373if((next_control= skip_ahead())==section_name){
1374loc-= 2;next_control= get_next();
1375}
1376
1377/*:84*/
1378#line 1349 "ctangle.w"
1379;
1380if(next_control==definition){
1381/*85:*/
1382#line 1380 "ctangle.w"
1383{
1384while((next_control= get_next())=='\n');
1385if(next_control!=identifier){
1386err_print("! Definition flushed, must start with identifier");
1387
1388continue;
1389}
1390app_repl(((a= id_lookup(id_first,id_loc)-name_dir)/0400)+0200);
1391
1392app_repl(a%0400);
1393if(*loc!='('){
1394app_repl(string);app_repl(' ');app_repl(string);
1395}
1396print_where= 0;scan_repl(macro);
1397cur_text->text_link= 0;
1398}
1399
1400/*:85*/
1401#line 1351 "ctangle.w"
1402
1403continue;
1404}
1405if(next_control==begin_C){
1406p= name_dir;break;
1407}
1408if(next_control==section_name){
1409p= cur_section_name;
1410/*86:*/
1411#line 1405 "ctangle.w"
1412
1413while((next_control= get_next())=='+');
1414if(next_control!='='&&next_control!=eq_eq)
1415continue;
1416
1417/*:86*/
1418#line 1359 "ctangle.w"
1419;
1420break;
1421}
1422return;
1423}
1424/*87:*/
1425#line 1410 "ctangle.w"
1426
1427/*88:*/
1428#line 1415 "ctangle.w"
1429
1430store_two_bytes((sixteen_bits)(0150000+section_count));
1431
1432
1433/*:88*/
1434#line 1411 "ctangle.w"
1435;
1436scan_repl(section_name);
1437/*89:*/
1438#line 1419 "ctangle.w"
1439
1440if(p==name_dir||p==0){
1441(last_unnamed)->text_link= cur_text-text_info;last_unnamed= cur_text;
1442}
1443else if(p->equiv==(char*)text_info)p->equiv= (char*)cur_text;
1444
1445else{
1446q= (text_pointer)p->equiv;
1447while(q->text_link<section_flag)
1448q= q->text_link+text_info;
1449q->text_link= cur_text-text_info;
1450}
1451cur_text->text_link= section_flag;
1452
1453
1454/*:89*/
1455#line 1413 "ctangle.w"
1456;
1457
1458/*:87*/
1459#line 1364 "ctangle.w"
1460;
1461}
1462
1463/*:83*//*91:*/
1464#line 1437 "ctangle.w"
1465
1466void
1467phase_one(){
1468phase= 1;
1469section_count= 0;
1470reset_input();
1471skip_limbo();
1472while(!input_has_ended)scan_section();
1473check_complete();
1474phase= 2;
1475}
1476
1477/*:91*//*93:*/
1478#line 1455 "ctangle.w"
1479
1480void
1481skip_limbo()
1482{
1483char c;
1484while(1){
1485if(loc>limit&&get_line()==0)return;
1486*(limit+1)= '@';
1487while(*loc!='@')loc++;
1488if(loc++<=limit){
1489c= *loc++;
1490if(ccode[(eight_bits)c]==new_section)break;
1491switch(ccode[(eight_bits)c]){
1492case translit_code:/*94:*/
1493#line 1484 "ctangle.w"
1494
1495while(xisspace(*loc)&&loc<limit)loc++;
1496loc+= 3;
1497if(loc>limit||!xisxdigit(*(loc-3))||!xisxdigit(*(loc-2))
1498||(*(loc-3)>='0'&&*(loc-3)<='7')||!xisspace(*(loc-1)))
1499err_print("! Improper hex number following @l");
1500
1501else{
1502unsigned i;
1503char*beg;
1504sscanf(loc-3,"%x",&i);
1505while(xisspace(*loc)&&loc<limit)loc++;
1506beg= loc;
1507while(loc<limit&&(xisalpha(*loc)||xisdigit(*loc)||*loc=='_'))loc++;
1508if(loc-beg>=translit_length)
1509err_print("! Replacement string in @l too long");
1510
1511else{
1512strncpy(translit[i-0200],beg,loc-beg);
1513translit[i-0200][loc-beg]= '\0';
1514}
1515}
1516
1517/*:94*/
1518#line 1468 "ctangle.w"
1519;break;
1520case format_code:case'@':break;
1521case control_text:if(c=='q'||c=='Q'){
1522while((c= skip_ahead())=='@');
1523if(*(loc-1)!='>')
1524err_print("! Double @ should be used in control text");
1525
1526break;
1527}
1528default:err_print("! Double @ should be used in limbo");
1529
1530}
1531}
1532}
1533}
1534
1535/*:93*//*95:*/
1536#line 1510 "ctangle.w"
1537
1538void
1539print_stats(){
1540printf("\nMemory usage statistics:\n");
1541printf("%ld names (out of %ld)\n",
1542(long)(name_ptr-name_dir),(long)max_names);
1543printf("%ld replacement texts (out of %ld)\n",
1544(long)(text_ptr-text_info),(long)max_texts);
1545printf("%ld bytes (out of %ld)\n",
1546(long)(byte_ptr-byte_mem),(long)max_bytes);
1547printf("%ld tokens (out of %ld)\n",
1548(long)(tok_ptr-tok_mem),(long)max_toks);
1549}
1550
1551/*:95*/
ctangle.w+1531−0
@@ -0,0 +1,1531 @@
1% This file is part of CWEB.
2% This program by Silvio Levy and Donald E. Knuth
3% is based on a program by Knuth.
4% It is distributed WITHOUT ANY WARRANTY, express or implied.
5% Version 3.2 --- July 1994
6
7% Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
8
9% Permission is granted to make and distribute verbatim copies of this
10% document provided that the copyright notice and this permission notice
11% are preserved on all copies.
12
13% Permission is granted to copy and distribute modified versions of this
14% document under the conditions for verbatim copying, provided that the
15% entire resulting derived work is given a different name and distributed
16% under the terms of a permission notice identical to this one.
17
18% Here is TeX material that gets inserted after \input cwebmac
19\def\hang{\hangindent 3em\indent\ignorespaces}
20\def\pb{$\.|\ldots\.|$} % C brackets (|...|)
21\def\v{\char'174} % vertical (|) in typewriter font
22\mathchardef\RA="3221 % right arrow
23\mathchardef\BA="3224 % double arrow
24
25\def\title{CTANGLE (Version 3.2)}
26\def\topofcontents{\null\vfill
27 \centerline{\titlefont The {\ttitlefont CTANGLE} processor}
28 \vskip 15pt
29 \centerline{(Version 3.2)}
30 \vfill}
31\def\botofcontents{\vfill
32\noindent
33Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
34\bigskip\noindent
35Permission is granted to make and distribute verbatim copies of this
36document provided that the copyright notice and this permission notice
37are preserved on all copies.
38
39\smallskip\noindent
40Permission is granted to copy and distribute modified versions of this
41document under the conditions for verbatim copying, provided that the
42entire resulting derived work is given a different name and distributed
43under the terms of a permission notice identical to this one.
44}
45\pageno=\contentspagenumber \advance\pageno by 1
46\let\maybe=\iftrue
47
48@** Introduction.
49This is the \.{CTANGLE} program by Silvio Levy and Donald E. Knuth,
50based on \.{TANGLE} by Knuth.
51We are thankful to
52Nelson Beebe, Hans-Hermann Bode (to whom the \CPLUSPLUS/ adaptation is due),
53Klaus Guntermann, Norman Ramsey, Tomas Rokicki, Joachim Schnitter,
54Joachim Schrod, Lee Wittenberg, and others who have contributed improvements.
55
56The ``banner line'' defined here should be changed whenever \.{CTANGLE}
57is modified.
58
59@d banner "This is CTANGLE (Version 3.2)\n"
60
61@c
62@<Include files@>@/
63@h
64@<Common code for \.{CWEAVE} and \.{CTANGLE}@>@/
65@<Typedef declarations@>@/
66@<Global variables@>@/
67@<Predeclaration of procedures@>@/
68
69@ We predeclare several standard system functions here instead of including
70their system header files, because the names of the header files are not as
71standard as the names of the functions. (For example, some \CEE/ environments
72have \.{<string.h>} where others have \.{<strings.h>}.)
73
74@<Predecl...@>=
75extern int strlen(); /* length of string */
76extern int strcmp(); /* compare strings lexicographically */
77extern char* strcpy(); /* copy one string to another */
78extern int strncmp(); /* compare up to $n$ string characters */
79extern char* strncpy(); /* copy up to $n$ string characters */
80
81@ \.{CTANGLE} has a fairly straightforward outline. It operates in
82two phases: first it reads the source file, saving the \CEE/ code in
83compressed form; then outputs the code, after shuffling it around.
84
85Please read the documentation for \.{common}, the set of routines common
86to \.{CTANGLE} and \.{CWEAVE}, before proceeding further.
87
88@c
89int main (ac, av)
90int ac;
91char **av;
92{
93 argc=ac; argv=av;
94 program=ctangle;
95 @<Set initial values@>;
96 common_init();
97 if (show_banner) printf(banner); /* print a ``banner line'' */
98 phase_one(); /* read all the user's text and compress it into |tok_mem| */
99 phase_two(); /* output the contents of the compressed tables */
100 return wrap_up(); /* and exit gracefully */
101}
102
103@ The following parameters were sufficient in the original \.{TANGLE} to
104handle \TEX/,
105so they should be sufficient for most applications of \.{CTANGLE}.
106If you change |max_bytes|, |max_names| or |hash_size| you should also
107change them in the file |"common.w"|.
108
109@d max_bytes 90000 /* the number of bytes in identifiers,
110 index entries, and section names; used in |"common.w"| */
111@d max_toks 270000 /* number of bytes in compressed \CEE/ code */
112@d max_names 4000 /* number of identifiers, strings, section names;
113 must be less than 10240; used in |"common.w"| */
114@d max_texts 2500 /* number of replacement texts, must be less than 10240 */
115@d hash_size 353 /* should be prime; used in |"common.w"| */
116@d longest_name 1000 /* section names shouldn't be longer than this */
117@d stack_size 50 /* number of simultaneous levels of macro expansion */
118@d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
119
120@ The next few sections contain stuff from the file |"common.w"| that must
121be included in both |"ctangle.w"| and |"cweave.w"|. It appears in
122file |"common.h"|, which needs to be updated when |"common.w"| changes.
123
124@i common.h
125
126@* Data structures exclusive to {\tt CTANGLE}.
127We've already seen that the |byte_mem| array holds the names of identifiers,
128strings, and sections;
129the |tok_mem| array holds the replacement texts
130for sections. Allocation is sequential, since things are deleted only
131during Phase II, and only in a last-in-first-out manner.
132
133A \&{text} variable is a structure containing a pointer into
134|tok_mem|, which tells where the corresponding text starts, and an
135integer |text_link|, which, as we shall see later, is used to connect
136pieces of text that have the same name. All the \&{text}s are stored in
137the array |text_info|, and we use a |text_pointer| variable to refer
138to them.
139
140The first position of |tok_mem| that is unoccupied by
141replacement text is called |tok_ptr|, and the first unused location of
142|text_info| is called |text_ptr|. Thus we usually have the identity
143|text_ptr->tok_start==tok_ptr|.
144
145If your machine does not support |unsigned char| you should change
146the definition of \&{eight\_bits} to |unsigned short|.
147@^system dependencies@>
148
149@<Typed...@>=
150typedef struct {
151 eight_bits *tok_start; /* pointer into |tok_mem| */
152 sixteen_bits text_link; /* relates replacement texts */
153} text;
154typedef text *text_pointer;
155
156@ @<Glob...@>=
157text text_info[max_texts];
158text_pointer text_info_end=text_info+max_texts-1;
159text_pointer text_ptr; /* first unused position in |text_info| */
160eight_bits tok_mem[max_toks];
161eight_bits *tok_mem_end=tok_mem+max_toks-1;
162eight_bits *tok_ptr; /* first unused position in |tok_mem| */
163
164@ @<Set init...@>=
165text_info->tok_start=tok_ptr=tok_mem;
166text_ptr=text_info+1; text_ptr->tok_start=tok_mem;
167 /* this makes replacement text 0 of length zero */
168
169@ If |p| is a pointer to a section name, |p->equiv| is a pointer to its
170replacement text, an element of the array |text_info|.
171
172@d equiv equiv_or_xref /* info corresponding to names */
173
174@ @<Set init...@>=
175name_dir->equiv=(char *)text_info; /* the undefined section has no replacement text */
176
177@ Here's the procedure that decides whether a name of length |l|
178starting at position |first| equals the identifier pointed to by |p|:
179
180@c
181int names_match(p,first,l)
182name_pointer p; /* points to the proposed match */
183char *first; /* position of first character of string */
184int l; /* length of identifier */
185{
186 if (length(p)!=l) return 0;
187 return !strncmp(first,p->byte_start,l);
188}
189
190@ The common lookup routine refers to separate routines |init_node| and
191|init_p| when the data structure grows. Actually |init_p| is called only by
192\.{CWEAVE}, but we need to declare a dummy version so that
193the loader won't complain of its absence.
194
195@c
196void
197init_node(node)
198name_pointer node;
199{
200 node->equiv=(char *)text_info;
201}
202void
203init_p() {}
204
205@* Tokens.
206Replacement texts, which represent \CEE/ code in a compressed format,
207appear in |tok_mem| as mentioned above. The codes in
208these texts are called `tokens'; some tokens occupy two consecutive
209eight-bit byte positions, and the others take just one byte.
210
211If $p$ points to a replacement text, |p->tok_start| is the |tok_mem| position
212of the first eight-bit code of that text. If |p->text_link==0|,
213this is the replacement text for a macro, otherwise it is the replacement
214text for a section. In the latter case |p->text_link| is either equal to
215|section_flag|, which means that there is no further text for this section, or
216|p->text_link| points to a continuation of this replacement text; such
217links are created when several sections have \CEE/ texts with the same
218name, and they also tie together all the \CEE/ texts of unnamed sections.
219The replacement text pointer for the first unnamed section appears in
220|text_info->text_link|, and the most recent such pointer is |last_unnamed|.
221
222@d section_flag max_texts /* final |text_link| in section replacement texts */
223
224@<Glob...@>=
225text_pointer last_unnamed; /* most recent replacement text of unnamed section */
226
227@ @<Set init...@>= last_unnamed=text_info; text_info->text_link=0;
228
229@ If the first byte of a token is less than |0200|, the token occupies a
230single byte. Otherwise we make a sixteen-bit token by combining two consecutive
231bytes |a| and |b|. If |0200<=a<0250|, then |(a-0200)@t${}\times2^8$@>+b|
232points to an identifier; if |0250<=a<0320|, then
233|(a-0250)@t${}\times2^8$@>+b| points to a section name
234(or, if it has the special value |output_defs_flag|,
235to the area where the preprocessor definitions are stored); and if
236|0320<=a<0400|, then |(a-0320)@t${}\times2^8$@>+b| is the number of the section
237in which the current replacement text appears.
238
239Codes less than |0200| are 7-bit |char| codes that represent themselves.
240Some of the 7-bit codes will not be present, however, so we can
241use them for special purposes. The following symbolic names are used:
242
243\yskip \hang |join| denotes the concatenation of adjacent items with no
244space or line breaks allowed between them (the \.{@@\&} operation of \.{CWEB}).
245
246\hang |string| denotes the beginning or end of a string, verbatim
247construction or numerical constant.
248@^ASCII code dependencies@>
249
250@d string 02 /* takes the place of extended ASCII \.{\char2} */
251@d join 0177 /* takes the place of ASCII delete */
252@d output_defs_flag (2*024000-1)
253
254@ The following procedure is used to enter a two-byte value into
255|tok_mem| when a replacement text is being generated.
256
257@c
258void
259store_two_bytes(x)
260sixteen_bits x;
261{
262 if (tok_ptr+2>tok_mem_end) overflow("token");
263 *tok_ptr++=x>>8; /* store high byte */
264 *tok_ptr++=x&0377; /* store low byte */
265}
266
267@** Stacks for output. The output process uses a stack to keep track
268of what is going on at different ``levels'' as the sections are being
269written out. Entries on this stack have five parts:
270
271\yskip\hang |end_field| is the |tok_mem| location where the replacement
272text of a particular level will end;
273
274\hang |byte_field| is the |tok_mem| location from which the next token
275on a particular level will be read;
276
277\hang |name_field| points to the name corresponding to a particular level;
278
279\hang |repl_field| points to the replacement text currently being read
280at a particular level;
281
282\hang |section_field| is the section number, or zero if this is a macro.
283
284\yskip\noindent The current values of these five quantities are referred to
285quite frequently, so they are stored in a separate place instead of in
286the |stack| array. We call the current values |cur_end|, |cur_byte|,
287|cur_name|, |cur_repl|, and |cur_section|.
288
289The global variable |stack_ptr| tells how many levels of output are
290currently in progress. The end of all output occurs when the stack is
291empty, i.e., when |stack_ptr==stack|.
292
293@<Typed...@>=
294typedef struct {
295 eight_bits *end_field; /* ending location of replacement text */
296 eight_bits *byte_field; /* present location within replacement text */
297 name_pointer name_field; /* |byte_start| index for text being output */
298 text_pointer repl_field; /* |tok_start| index for text being output */
299 sixteen_bits section_field; /* section number or zero if not a section */
300} output_state;
301typedef output_state *stack_pointer;
302
303@ @d cur_end cur_state.end_field /* current ending location in |tok_mem| */
304@d cur_byte cur_state.byte_field /* location of next output byte in |tok_mem|*/
305@d cur_name cur_state.name_field /* pointer to current name being expanded */
306@d cur_repl cur_state.repl_field /* pointer to current replacement text */
307@d cur_section cur_state.section_field /* current section number being expanded */
308
309@<Global...@>=
310output_state cur_state; /* |cur_end|, |cur_byte|, |cur_name|, |cur_repl|
311 and |cur_section| */
312output_state stack[stack_size+1]; /* info for non-current levels */
313stack_pointer stack_ptr; /* first unused location in the output state stack */
314stack_pointer stack_end=stack+stack_size; /* end of |stack| */
315
316@ To get the output process started, we will perform the following
317initialization steps. We may assume that |text_info->text_link| is nonzero,
318since it points to the \CEE/ text in the first unnamed section that generates
319code; if there are no such sections, there is nothing to output, and an
320error message will have been generated before we do any of the initialization.
321
322@<Initialize the output stacks@>=
323stack_ptr=stack+1; cur_name=name_dir; cur_repl=text_info->text_link+text_info;
324cur_byte=cur_repl->tok_start; cur_end=(cur_repl+1)->tok_start; cur_section=0;
325
326@ When the replacement text for name |p| is to be inserted into the output,
327the following subroutine is called to save the old level of output and get
328the new one going.
329
330We assume that the \CEE/ compiler can copy structures.
331@^system dependencies@>
332
333@c
334void
335push_level(p) /* suspends the current level */
336name_pointer p;
337{
338 if (stack_ptr==stack_end) overflow("stack");
339 *stack_ptr=cur_state;
340 stack_ptr++;
341 if (p!=NULL) { /* |p==NULL| means we are in |output_defs| */
342 cur_name=p; cur_repl=(text_pointer)p->equiv;
343 cur_byte=cur_repl->tok_start; cur_end=(cur_repl+1)->tok_start;
344 cur_section=0;
345 }
346}
347
348@ When we come to the end of a replacement text, the |pop_level| subroutine
349does the right thing: It either moves to the continuation of this replacement
350text or returns the state to the most recently stacked level.
351
352@c
353void
354pop_level(flag) /* do this when |cur_byte| reaches |cur_end| */
355int flag; /* |flag==0| means we are in |output_defs| */
356{
357 if (flag && cur_repl->text_link<section_flag) { /* link to a continuation */
358 cur_repl=cur_repl->text_link+text_info; /* stay on the same level */
359 cur_byte=cur_repl->tok_start; cur_end=(cur_repl+1)->tok_start;
360 return;
361 }
362 stack_ptr--; /* go down to the previous level */
363 if (stack_ptr>stack) cur_state=*stack_ptr;
364}
365
366@ The heart of the output procedure is the function |get_output|,
367which produces the next token of output and sends it on to the lower-level
368function |out_char|. The main purpose of |get_output| is to handle the
369necessary stacking and unstacking. It sends the value |section_number|
370if the next output begins or ends the replacement text of some section,
371in which case |cur_val| is that section's number (if beginning) or the
372negative of that value (if ending). (A section number of 0 indicates
373not the beginning or ending of a section, but a \&{\#line} command.)
374And it sends the value |identifier|
375if the next output is an identifier, in which case
376|cur_val| points to that identifier name.
377
378@d section_number 0201 /* code returned by |get_output| for section numbers */
379@d identifier 0202 /* code returned by |get_output| for identifiers */
380
381@<Global...@>=
382int cur_val; /* additional information corresponding to output token */
383
384@ If |get_output| finds that no more output remains, it returns with
385|stack_ptr==stack|.
386@^high-bit character handling@>
387
388@c
389void
390get_output() /* sends next token to |out_char| */
391{
392 sixteen_bits a; /* value of current byte */
393 restart: if (stack_ptr==stack) return;
394 if (cur_byte==cur_end) {
395 cur_val=-((int)cur_section); /* cast needed because of sign extension */
396 pop_level(1);
397 if (cur_val==0) goto restart;
398 out_char(section_number); return;
399 }
400 a=*cur_byte++;
401 if (out_state==verbatim && a!=string && a!=constant && a!='\n')
402 C_putc(a); /* a high-bit character can occur in a string */
403 else if (a<0200) out_char(a); /* one-byte token */
404 else {
405 a=(a-0200)*0400+*cur_byte++;
406 switch (a/024000) { /* |024000==(0250-0200)*0400| */
407 case 0: cur_val=a; out_char(identifier); break;
408 case 1: if (a==output_defs_flag) output_defs();
409 else @<Expand section |a-024000|, |goto restart|@>;
410 break;
411 default: cur_val=a-050000; if (cur_val>0) cur_section=cur_val;
412 out_char(section_number);
413 }
414 }
415}
416
417@ The user may have forgotten to give any \CEE/ text for a section name,
418or the \CEE/ text may have been associated with a different name by mistake.
419
420@<Expand section |a-...@>=
421{
422 a-=024000;
423 if ((a+name_dir)->equiv!=(char *)text_info) push_level(a+name_dir);
424 else if (a!=0) {
425 printf("\n! Not present: <");
426 print_section_name(a+name_dir); err_print(">");
427@.Not present: <section name>@>
428 }
429 goto restart;
430}
431
432@* Producing the output.
433The |get_output| routine above handles most of the complexity of output
434generation, but there are two further considerations that have a nontrivial
435effect on \.{CTANGLE}'s algorithms.
436
437@ First,
438we want to make sure that the output has spaces and line breaks in
439the right places (e.g., not in the middle of a string or a constant or an
440identifier, not at a `\.{@@\&}' position
441where quantities are being joined together, and certainly after an \.=
442because the \CEE/ compiler thinks \.{=-} is ambiguous).
443
444The output process can be in one of following states:
445
446\yskip\hang |num_or_id| means that the last item in the buffer is a number or
447identifier, hence a blank space or line break must be inserted if the next
448item is also a number or identifier.
449
450\yskip\hang |unbreakable| means that the last item in the buffer was followed
451by the \.{@@\&} operation that inhibits spaces between it and the next item.
452
453\yskip\hang |verbatim| means we're copying only character tokens, and
454that they are to be output exactly as stored. This is the case during
455strings, verbatim constructions and numerical constants.
456
457\yskip\hang |normal| means none of the above.
458
459\yskip\noindent Furthermore, if the variable |protect| is positive, newlines
460are preceded by a `\.\\'.
461
462@d normal 0 /* non-unusual state */
463@d num_or_id 1 /* state associated with numbers and identifiers */
464@d unbreakable 3 /* state associated with \.{@@\&} */
465@d verbatim 4 /* state in the middle of a string */
466
467@<Global...@>=
468eight_bits out_state; /* current status of partial output */
469boolean protect; /* should newline characters be quoted? */
470
471@ Here is a routine that is invoked when we want to output the current line.
472During the output process, |cur_line| equals the number of the next line
473to be output.
474
475@c
476void
477flush_buffer() /* writes one line to output file */
478{
479 C_putc('\n');
480 if (cur_line % 100 == 0 && show_progress) {
481 printf(".");
482 if (cur_line % 500 == 0) printf("%d",cur_line);
483 update_terminal; /* progress report */
484 }
485 cur_line++;
486}
487
488@ Second, we have modified the original \.{TANGLE} so that it will write output
489on multiple files.
490If a section name is introduced in at least one place by \.{@@(}
491instead of \.{@@<}, we treat it as the name of a file.
492All these special sections are saved on a stack, |output_files|.
493We write them out after we've done the unnamed section.
494
495@d max_files 256
496@<Glob...@>=
497name_pointer output_files[max_files];
498name_pointer *cur_out_file, *end_output_files, *an_output_file;
499char cur_section_name_char; /* is it |'<'| or |'('| */
500char output_file_name[longest_name]; /* name of the file */
501
502@ We make |end_output_files| point just beyond the end of
503|output_files|. The stack pointer
504|cur_out_file| starts out there. Every time we see a new file, we
505decrement |cur_out_file| and then write it in.
506@<Set initial...@>=
507cur_out_file=end_output_files=output_files+max_files;
508
509@ @<If it's not there, add |cur_section_name| to the output file stack, or
510complain we're out of room@>=
511{
512 for (an_output_file=cur_out_file;
513 an_output_file<end_output_files; an_output_file++)
514 if (*an_output_file==cur_section_name) break;
515 if (an_output_file==end_output_files) {
516 if (cur_out_file>output_files)
517 *--cur_out_file=cur_section_name;
518 else {
519 overflow("output files");
520 }
521 }
522}
523
524@* The big output switch. Here then is the routine that does the
525output.
526
527@<Predecl...@>=
528void phase_two();
529
530@ @c
531void
532phase_two () {
533 web_file_open=0;
534 cur_line=1;
535 @<Initialize the output stacks@>;
536 @<Output macro definitions if appropriate@>;
537 if (text_info->text_link==0 && cur_out_file==end_output_files) {
538 printf("\n! No program text was specified."); mark_harmless;
539@.No program text...@>
540 }
541 else {
542 if(cur_out_file==end_output_files) {
543 if(show_progress)
544 printf("\nWriting the output file (%s):",C_file_name);
545 }
546 else {
547 if (show_progress) {
548 printf("\nWriting the output files:");
549@.Writing the output...@>
550 printf(" (%s)",C_file_name);
551 update_terminal;
552 }
553 if (text_info->text_link==0) goto writeloop;
554 }
555 while (stack_ptr>stack) get_output();
556 flush_buffer();
557writeloop: @<Write all the named output files@>;
558 if(show_happiness) printf("\nDone.");
559 }
560}
561
562@ To write the named output files, we proceed as for the unnamed
563section.
564The only subtlety is that we have to open each one.
565
566@<Write all the named output files@>=
567for (an_output_file=end_output_files; an_output_file>cur_out_file;) {
568 an_output_file--;
569 sprint_section_name(output_file_name,*an_output_file);
570 fclose(C_file);
571 C_file=fopen(output_file_name,"w");
572 if (C_file ==0) fatal("! Cannot open output file:",output_file_name);
573@.Cannot open output file@>
574 printf("\n(%s)",output_file_name); update_terminal;
575 cur_line=1;
576 stack_ptr=stack+1;
577 cur_name= (*an_output_file);
578 cur_repl= (text_pointer)cur_name->equiv;
579 cur_byte=cur_repl->tok_start;
580 cur_end=(cur_repl+1)->tok_start;
581 while (stack_ptr > stack) get_output();
582 flush_buffer();
583}
584
585@ If a \.{@@h} was not encountered in the input,
586we go through the list of replacement texts and copy the ones
587that refer to macros, preceded by the \.{\#define} preprocessor command.
588
589@<Output macro definitions if appropriate@>=
590 if (!output_defs_seen)
591 output_defs();
592
593@ @<Glob...@>=
594boolean output_defs_seen=0;
595
596@ @<Predecl...@>=
597void output_defs();
598
599@ @c
600void
601output_defs()
602{
603 sixteen_bits a;
604 push_level(NULL);
605 for (cur_text=text_info+1; cur_text<text_ptr; cur_text++)
606 if (cur_text->text_link==0) { /* |cur_text| is the text for a macro */
607 cur_byte=cur_text->tok_start;
608 cur_end=(cur_text+1)->tok_start;
609 C_printf("%s","#define ");
610 out_state=normal;
611 protect=1; /* newlines should be preceded by |'\\'| */
612 while (cur_byte<cur_end) {
613 a=*cur_byte++;
614 if (cur_byte==cur_end && a=='\n') break; /* disregard a final newline */
615 if (out_state==verbatim && a!=string && a!=constant && a!='\n')
616 C_putc(a); /* a high-bit character can occur in a string */
617@^high-bit character handling@>
618 else if (a<0200) out_char(a); /* one-byte token */
619 else {
620 a=(a-0200)*0400+*cur_byte++;
621 if (a<024000) { /* |024000==(0250-0200)*0400| */
622 cur_val=a; out_char(identifier);
623 }
624 else if (a<050000) { confusion("macro defs have strange char");}
625 else {
626 cur_val=a-050000; cur_section=cur_val; out_char(section_number);
627 }
628 /* no other cases */
629 }
630 }
631 protect=0;
632 flush_buffer();
633 }
634 pop_level(0);
635}
636
637@ A many-way switch is used to send the output. Note that this function
638is not called if |out_state==verbatim|, except perhaps with arguments
639|'\n'| (protect the newline), |string| (end the string), or |constant|
640(end the constant).
641
642@<Predecl...@>=
643void out_char();
644
645@ @c
646void
647out_char(cur_char)
648eight_bits cur_char;
649{
650 char *j, *k; /* pointer into |byte_mem| */
651restart:
652 switch (cur_char) {
653 case '\n': if (protect) C_putc(' ');
654 if (protect || out_state==verbatim) C_putc('\\');
655 flush_buffer(); if (out_state!=verbatim) out_state=normal; break;
656 @/@t\4@>@<Case of an identifier@>;
657 @/@t\4@>@<Case of a section number@>;
658 @/@t\4@>@<Cases like \.{!=}@>;
659 case '=': C_putc('='); C_putc(' '); out_state=normal; break;
660 case join: out_state=unbreakable; break;
661 case constant: if (out_state==verbatim) {
662 out_state=num_or_id; break;
663 }
664 if(out_state==num_or_id) C_putc(' '); out_state=verbatim; break;
665 case string: if (out_state==verbatim) out_state=normal;
666 else out_state=verbatim; break;
667 default: C_putc(cur_char); out_state=normal; break;
668 }
669}
670
671@ @<Cases like \.{!=}@>=
672case plus_plus: C_putc('+'); C_putc('+'); out_state=normal; break;
673case minus_minus: C_putc('-'); C_putc('-'); out_state=normal; break;
674case minus_gt: C_putc('-'); C_putc('>'); out_state=normal; break;
675case gt_gt: C_putc('>'); C_putc('>'); out_state=normal; break;
676case eq_eq: C_putc('='); C_putc('='); out_state=normal; break;
677case lt_lt: C_putc('<'); C_putc('<'); out_state=normal; break;
678case gt_eq: C_putc('>'); C_putc('='); out_state=normal; break;
679case lt_eq: C_putc('<'); C_putc('='); out_state=normal; break;
680case not_eq: C_putc('!'); C_putc('='); out_state=normal; break;
681case and_and: C_putc('&'); C_putc('&'); out_state=normal; break;
682case or_or: C_putc('|'); C_putc('|'); out_state=normal; break;
683case dot_dot_dot: C_putc('.'); C_putc('.'); C_putc('.'); out_state=normal;
684 break;
685case colon_colon: C_putc(':'); C_putc(':'); out_state=normal; break;
686case period_ast: C_putc('.'); C_putc('*'); out_state=normal; break;
687case minus_gt_ast: C_putc('-'); C_putc('>'); C_putc('*'); out_state=normal;
688 break;
689
690@ When an identifier is output to the \CEE/ file, characters in the
691range 128--255 must be changed into something else, so the \CEE/
692compiler won't complain. By default, \.{CTANGLE} converts the
693character with code $16 x+y$ to the three characters `\.X$xy$', but
694a different transliteration table can be specified. Thus a German
695might want {\it gr\"un\/} to appear as a still readable \.{gruen}.
696This makes debugging a lot less confusing.
697
698@d translit_length 10
699
700@<Glo...@>=
701char translit[128][translit_length];
702
703@ @<Set init...@>=
704{
705 int i;
706 for (i=0;i<128;i++) sprintf(translit[i],"X%02X",(unsigned)(128+i));
707}
708
709@ @<Case of an identifier@>=
710case identifier:
711 if (out_state==num_or_id) C_putc(' ');
712 j=(cur_val+name_dir)->byte_start;
713 k=(cur_val+name_dir+1)->byte_start;
714 while (j<k) {
715 if ((unsigned char)(*j)<0200) C_putc(*j);
716@^high-bit character handling@>
717 else C_printf("%s",translit[(unsigned char)(*j)-0200]);
718 j++;
719 }
720 out_state=num_or_id; break;
721
722@ @<Case of a sec...@>=
723case section_number:
724 if (cur_val>0) C_printf("/*%d:*/",cur_val);
725 else if(cur_val<0) C_printf("/*:%d*/",-cur_val);
726 else if (protect) {
727 cur_byte +=4; /* skip line number and file name */
728 cur_char = '\n';
729 goto restart;
730 } else {
731 sixteen_bits a;
732 a=0400* *cur_byte++;
733 a+=*cur_byte++; /* gets the line number */
734 C_printf("\n#line %d \"",a);
735@:line}{\.{\#line}@>
736 cur_val=*cur_byte++;
737 cur_val=0400*(cur_val-0200)+ *cur_byte++; /* points to the file name */
738 for (j=(cur_val+name_dir)->byte_start, k=(cur_val+name_dir+1)->byte_start;
739 j<k; j++) C_putc(*j);
740 C_printf("%s","\"\n");
741 }
742 break;
743
744@** Introduction to the input phase.
745We have now seen that \.{CTANGLE} will be able to output the full
746\CEE/ program, if we can only get that program into the byte memory in
747the proper format. The input process is something like the output process
748in reverse, since we compress the text as we read it in and we expand it
749as we write it out.
750
751There are three main input routines. The most interesting is the one that gets
752the next token of a \CEE/ text; the other two are used to scan rapidly past
753\TEX/ text in the \.{CWEB} source code. One of the latter routines will jump to
754the next token that starts with `\.{@@}', and the other skips to the end
755of a \CEE/ comment.
756
757@ Control codes in \.{CWEB} begin with `\.{@@}', and the next character
758identifies the code. Some of these are of interest only to \.{CWEAVE},
759so \.{CTANGLE} ignores them; the others are converted by \.{CTANGLE} into
760internal code numbers by the |ccode| table below. The ordering
761of these internal code numbers has been chosen to simplify the program logic;
762larger numbers are given to the control codes that denote more significant
763milestones.
764
765@d ignore 0 /* control code of no interest to \.{CTANGLE} */
766@d ord 0302 /* control code for `\.{@@'}' */
767@d control_text 0303 /* control code for `\.{@@t}', `\.{@@\^}', etc. */
768@d translit_code 0304 /* control code for `\.{@@l}' */
769@d output_defs_code 0305 /* control code for `\.{@@h}' */
770@d format_code 0306 /* control code for `\.{@@f}' */
771@d definition 0307 /* control code for `\.{@@d}' */
772@d begin_C 0310 /* control code for `\.{@@c}' */
773@d section_name 0311 /* control code for `\.{@@<}' */
774@d new_section 0312 /* control code for `\.{@@\ }' and `\.{@@*}' */
775
776@<Global...@>=
777eight_bits ccode[256]; /* meaning of a char following \.{@@} */
778
779@ @<Set ini...@>= {
780 int c; /* must be |int| so the |for| loop will end */
781 for (c=0; c<256; c++) ccode[c]=ignore;
782 ccode[' ']=ccode['\t']=ccode['\n']=ccode['\v']=ccode['\r']=ccode['\f']
783 =ccode['*']=new_section;
784 ccode['@@']='@@'; ccode['=']=string;
785 ccode['d']=ccode['D']=definition;
786 ccode['f']=ccode['F']=ccode['s']=ccode['S']=format_code;
787 ccode['c']=ccode['C']=ccode['p']=ccode['P']=begin_C;
788 ccode['^']=ccode[':']=ccode['.']=ccode['t']=ccode['T']=
789 ccode['q']=ccode['Q']=control_text;
790 ccode['h']=ccode['H']=output_defs_code;
791 ccode['l']=ccode['L']=translit_code;
792 ccode['&']=join;
793 ccode['<']=ccode['(']=section_name;
794 ccode['\'']=ord;
795}
796
797@ The |skip_ahead| procedure reads through the input at fairly high speed
798until finding the next non-ignorable control code, which it returns.
799
800@c
801eight_bits
802skip_ahead() /* skip to next control code */
803{
804 eight_bits c; /* control code found */
805 while (1) {
806 if (loc>limit && (get_line()==0)) return(new_section);
807 *(limit+1)='@@';
808 while (*loc!='@@') loc++;
809 if (loc<=limit) {
810 loc++; c=ccode[(eight_bits)*loc]; loc++;
811 if (c!=ignore || *(loc-1)=='>') return(c);
812 }
813 }
814}
815
816@ The |skip_comment| procedure reads through the input at somewhat high
817speed in order to pass over comments, which \.{CTANGLE} does not transmit
818to the output. If the comment is introduced by \.{/*}, |skip_comment|
819proceeds until finding the end-comment token \.{*/} or a newline; in the
820latter case |skip_comment| will be called again by |get_next|, since the
821comment is not finished. This is done so that the each newline in the
822\CEE/ part of a section is copied to the output; otherwise the \&{\#line}
823commands inserted into the \CEE/ file by the output routines become useless.
824On the other hand, if the comment is introduced by \.{//} (i.e., if it
825is a \CPLUSPLUS/ ``short comment''), it always is simply delimited by the next
826newline. The boolean argument |is_long_comment| distinguishes between
827the two types of comments.
828
829If |skip_comment| comes to the end of the section, it prints an error message.
830No comment, long or short, is allowed to contain `\.{@@ }' or `\.{@@*}'.
831
832@<Global...@>=
833boolean comment_continues=0; /* are we scanning a comment? */
834
835@ @c
836int skip_comment(is_long_comment) /* skips over comments */
837boolean is_long_comment;
838{
839 char c; /* current character */
840 while (1) {
841 if (loc>limit) {
842 if (is_long_comment) {
843 if(get_line()) return(comment_continues=1);
844 else{
845 err_print("! Input ended in mid-comment");
846@.Input ended in mid-comment@>
847 return(comment_continues=0);
848 }
849 }
850 else return(comment_continues=0);
851 }
852 c=*(loc++);
853 if (is_long_comment && c=='*' && *loc=='/') {
854 loc++; return(comment_continues=0);
855 }
856 if (c=='@@') {
857 if (ccode[(eight_bits)*loc]==new_section) {
858 err_print("! Section name ended in mid-comment"); loc--;
859@.Section name ended in mid-comment@>
860 return(comment_continues=0);
861 }
862 else loc++;
863 }
864 }
865}
866
867@* Inputting the next token.
868
869@d constant 03
870
871@<Global...@>=
872name_pointer cur_section_name; /* name of section just scanned */
873
874@ @<Include...@>=
875#include <ctype.h> /* definition of |isalpha|, |isdigit| and so on */
876#include <stdlib.h> /* definition of |exit| */
877
878@ As one might expect, |get_next| consists mostly of a big switch
879that branches to the various special cases that can arise.
880
881@d isxalpha(c) ((c)=='_') /* non-alpha character allowed in identifier */
882@d ishigh(c) ((unsigned char)(c)>0177)
883@^high-bit character handling@>
884
885@c
886eight_bits
887get_next() /* produces the next input token */
888{
889 static int preprocessing=0;
890 eight_bits c; /* the current character */
891 while (1) {
892 if (loc>limit) {
893 if (preprocessing && *(limit-1)!='\\') preprocessing=0;
894 if (get_line()==0) return(new_section);
895 else if (print_where) {
896 print_where=0;
897 @<Insert the line number into |tok_mem|@>;
898 }
899 else return ('\n');
900 }
901 c=*loc;
902 if (comment_continues || (c=='/' && (*(loc+1)=='*' || *(loc+1)=='/'))) {
903 skip_comment(comment_continues||*(loc+1)=='*');
904 /* scan to end of comment or newline */
905 if (comment_continues) return('\n');
906 else continue;
907 }
908 loc++;
909 if (xisdigit(c) || c=='\\' || c=='.') @<Get a constant@>@;
910 else if (c=='\'' || c=='"' || (c=='L'&&(*loc=='\'' || *loc=='"')))
911 @<Get a string@>@;
912 else if (isalpha(c) || isxalpha(c) || ishigh(c))
913 @<Get an identifier@>@;
914 else if (c=='@@') @<Get control code and possible section name@>@;
915 else if (xisspace(c)) {
916 if (!preprocessing || loc>limit) continue;
917 /* we don't want a blank after a final backslash */
918 else return(' '); /* ignore spaces and tabs, unless preprocessing */
919 }
920 else if (c=='#' && loc==buffer+1) preprocessing=1;
921 mistake: @<Compress two-symbol operator@>@;
922 return(c);
923 }
924}
925
926@ The following code assigns values to the combinations \.{++},
927\.{--}, \.{->}, \.{>=}, \.{<=}, \.{==}, \.{<<}, \.{>>}, \.{!=}, \.{||} and
928\.{\&\&}, and to the \CPLUSPLUS/
929combinations \.{...}, \.{::}, \.{.*} and \.{->*}.
930The compound assignment operators (e.g., \.{+=}) are
931treated as separate tokens.
932
933@d compress(c) if (loc++<=limit) return(c)
934
935@<Compress tw...@>=
936switch(c) {
937 case '+': if (*loc=='+') compress(plus_plus); break;
938 case '-': if (*loc=='-') {compress(minus_minus);}
939 else if (*loc=='>') if (*(loc+1)=='*') {loc++; compress(minus_gt_ast);}
940 else compress(minus_gt); break;
941 case '.': if (*loc=='*') {compress(period_ast);}
942 else if (*loc=='.' && *(loc+1)=='.') {
943 loc++; compress(dot_dot_dot);
944 }
945 break;
946 case ':': if (*loc==':') compress(colon_colon); break;
947 case '=': if (*loc=='=') compress(eq_eq); break;
948 case '>': if (*loc=='=') {compress(gt_eq);}
949 else if (*loc=='>') compress(gt_gt); break;
950 case '<': if (*loc=='=') {compress(lt_eq);}
951 else if (*loc=='<') compress(lt_lt); break;
952 case '&': if (*loc=='&') compress(and_and); break;
953 case '|': if (*loc=='|') compress(or_or); break;
954 case '!': if (*loc=='=') compress(not_eq); break;
955}
956
957@ @<Get an identifier@>= {
958 id_first=--loc;
959 while (isalpha(*++loc) || isdigit(*loc) || isxalpha(*loc) || ishigh(*loc));
960 id_loc=loc; return(identifier);
961}
962
963@ @<Get a constant@>= {
964 id_first=loc-1;
965 if (*id_first=='.' && !xisdigit(*loc)) goto mistake; /* not a constant */
966 if (*id_first=='\\') while (xisdigit(*loc)) loc++; /* octal constant */
967 else {
968 if (*id_first=='0') {
969 if (*loc=='x' || *loc=='X') { /* hex constant */
970 loc++; while (xisxdigit(*loc)) loc++; goto found;
971 }
972 }
973 while (xisdigit(*loc)) loc++;
974 if (*loc=='.') {
975 loc++;
976 while (xisdigit(*loc)) loc++;
977 }
978 if (*loc=='e' || *loc=='E') { /* float constant */
979 if (*++loc=='+' || *loc=='-') loc++;
980 while (xisdigit(*loc)) loc++;
981 }
982 }
983 found: while (*loc=='u' || *loc=='U' || *loc=='l' || *loc=='L'
984 || *loc=='f' || *loc=='F') loc++;
985 id_loc=loc;
986 return(constant);
987}
988
989@ \CEE/ strings and character constants, delimited by double and single
990quotes, respectively, can contain newlines or instances of their own
991delimiters if they are protected by a backslash. We follow this
992convention, but do not allow the string to be longer than |longest_name|.
993
994@<Get a string@>= {
995 char delim = c; /* what started the string */
996 id_first = section_text+1;
997 id_loc = section_text; *++id_loc=delim;
998 if (delim=='L') { /* wide character constant */
999 delim=*loc++; *++id_loc=delim;
1000 }
1001 while (1) {
1002 if (loc>=limit) {
1003 if(*(limit-1)!='\\') {
1004 err_print("! String didn't end"); loc=limit; break;
1005@.String didn't end@>
1006 }
1007 if(get_line()==0) {
1008 err_print("! Input ended in middle of string"); loc=buffer; break;
1009@.Input ended in middle of string@>
1010 }
1011 else if (++id_loc<=section_text_end) *id_loc='\n'; /* will print as
1012 \.{"\\\\\\n"} */
1013 }
1014 if ((c=*loc++)==delim) {
1015 if (++id_loc<=section_text_end) *id_loc=c;
1016 break;
1017 }
1018 if (c=='\\') {
1019 if (loc>=limit) continue;
1020 if (++id_loc<=section_text_end) *id_loc = '\\';
1021 c=*loc++;
1022 }
1023 if (++id_loc<=section_text_end) *id_loc=c;
1024 }
1025 if (id_loc>=section_text_end) {
1026 printf("\n! String too long: ");
1027@.String too long@>
1028 term_write(section_text+1,25);
1029 err_print("...");
1030 }
1031 id_loc++;
1032 return(string);
1033}
1034
1035@ After an \.{@@} sign has been scanned, the next character tells us
1036whether there is more work to do.
1037
1038@<Get control code and possible section name@>= {
1039 c=ccode[(eight_bits)*loc++];
1040 switch(c) {
1041 case ignore: continue;
1042 case output_defs_code: output_defs_seen=1; return(c);
1043 case translit_code: err_print("! Use @@l in limbo only"); continue;
1044@.Use @@l in limbo...@>
1045 case control_text: while ((c=skip_ahead())=='@@');
1046 /* only \.{@@@@} and \.{@@>} are expected */
1047 if (*(loc-1)!='>')
1048 err_print("! Double @@ should be used in control text");
1049@.Double @@ should be used...@>
1050 continue;
1051 case section_name:
1052 cur_section_name_char=*(loc-1);
1053 @<Scan the section name and make |cur_section_name| point to it@>;
1054 case string: @<Scan a verbatim string@>;
1055 case ord: @<Scan an ASCII constant@>;
1056 default: return(c);
1057 }
1058}
1059
1060@ After scanning a valid ASCII constant that follows
1061\.{@@'}, this code plows ahead until it finds the next single quote.
1062(Special care is taken if the quote is part of the constant.)
1063Anything after a valid ASCII constant is ignored;
1064thus, \.{@@'\\nopq'} gives the same result as \.{@@'\\n'}.
1065
1066@<Scan an ASCII constant@>=
1067 id_first=loc;
1068 if (*loc=='\\') {
1069 if (*++loc=='\'') loc++;
1070 }
1071 while (*loc!='\'') {
1072 if (*loc=='@@') {
1073 if (*(loc+1)!='@@')
1074 err_print("! Double @@ should be used in ASCII constant");
1075@.Double @@ should be used...@>
1076 else loc++;
1077 }
1078 loc++;
1079 if (loc>limit) {
1080 err_print("! String didn't end"); loc=limit-1; break;
1081@.String didn't end@>
1082 }
1083 }
1084 loc++;
1085 return(ord);
1086
1087@ @<Scan the section name...@>= {
1088 char *k; /* pointer into |section_text| */
1089 @<Put section name into |section_text|@>;
1090 if (k-section_text>3 && strncmp(k-2,"...",3)==0)
1091 cur_section_name=section_lookup(section_text+1,k-3,1); /* 1 means is a prefix */
1092 else cur_section_name=section_lookup(section_text+1,k,0);
1093 if (cur_section_name_char=='(')
1094 @<If it's not there, add |cur_section_name| to the output file stack, or
1095 complain we're out of room@>;
1096 return(section_name);
1097}
1098
1099@ Section names are placed into the |section_text| array with consecutive spaces,
1100tabs, and carriage-returns replaced by single spaces. There will be no
1101spaces at the beginning or the end. (We set |section_text[0]=' '| to facilitate
1102this, since the |section_lookup| routine uses |section_text[1]| as the first
1103character of the name.)
1104
1105@<Set init...@>=section_text[0]=' ';
1106
1107@ @<Put section name...@>=
1108k=section_text;
1109while (1) {
1110 if (loc>limit && get_line()==0) {
1111 err_print("! Input ended in section name");
1112@.Input ended in section name@>
1113 loc=buffer+1; break;
1114 }
1115 c=*loc;
1116 @<If end of name or erroneous nesting, |break|@>;
1117 loc++; if (k<section_text_end) k++;
1118 if (xisspace(c)) {
1119 c=' '; if (*(k-1)==' ') k--;
1120 }
1121*k=c;
1122}
1123if (k>=section_text_end) {
1124 printf("\n! Section name too long: ");
1125@.Section name too long@>
1126 term_write(section_text+1,25);
1127 printf("..."); mark_harmless;
1128}
1129if (*k==' ' && k>section_text) k--;
1130
1131@ @<If end of name or erroneous nesting,...@>=
1132if (c=='@@') {
1133 c=*(loc+1);
1134 if (c=='>') {
1135 loc+=2; break;
1136 }
1137 if (ccode[(eight_bits)c]==new_section) {
1138 err_print("! Section name didn't end"); break;
1139@.Section name didn't end@>
1140 }
1141 if (ccode[(eight_bits)c]==section_name) {
1142 err_print("! Nesting of section names not allowed"); break;
1143@.Nesting of section names...@>
1144 }
1145 *(++k)='@@'; loc++; /* now |c==*loc| again */
1146}
1147
1148@ At the present point in the program we
1149have |*(loc-1)==string|; we set |id_first| to the beginning
1150of the string itself, and |id_loc| to its ending-plus-one location in the
1151buffer. We also set |loc| to the position just after the ending delimiter.
1152
1153@<Scan a verbatim string@>= {
1154 id_first=loc++; *(limit+1)='@@'; *(limit+2)='>';
1155 while (*loc!='@@' || *(loc+1)!='>') loc++;
1156 if (loc>=limit) err_print("! Verbatim string didn't end");
1157@.Verbatim string didn't end@>
1158 id_loc=loc; loc+=2;
1159 return(string);
1160}
1161
1162@* Scanning a macro definition.
1163The rules for generating the replacement texts corresponding to macros and
1164\CEE/ texts of a section are almost identical; the only differences are that
1165
1166\yskip \item{a)}Section names are not allowed in macros;
1167in fact, the appearance of a section name terminates such macros and denotes
1168the name of the current section.
1169
1170\item{b)}The symbols \.{@@d} and \.{@@f} and \.{@@c} are not allowed after
1171section names, while they terminate macro definitions.
1172
1173\yskip Therefore there is a single procedure |scan_repl| whose parameter
1174|t| specifies either |macro| or |section_name|. After |scan_repl| has
1175acted, |cur_text| will point to the replacement text just generated, and
1176|next_control| will contain the control code that terminated the activity.
1177
1178@d macro 0
1179@d app_repl(c) {if (tok_ptr==tok_mem_end) overflow("token"); *tok_ptr++=c;}
1180
1181@<Global...@>=
1182text_pointer cur_text; /* replacement text formed by |scan_repl| */
1183eight_bits next_control;
1184
1185@ @c
1186void
1187scan_repl(t) /* creates a replacement text */
1188eight_bits t;
1189{
1190 sixteen_bits a; /* the current token */
1191 if (t==section_name) {@<Insert the line number into |tok_mem|@>;}
1192 while (1) switch (a=get_next()) {
1193 @<In cases that |a| is a non-|char| token (|identifier|,
1194 |section_name|, etc.), either process it and change |a| to a byte
1195 that should be stored, or |continue| if |a| should be ignored,
1196 or |goto done| if |a| signals the end of this replacement text@>@;
1197 default: app_repl(a); /* store |a| in |tok_mem| */
1198 }
1199 done: next_control=(eight_bits) a;
1200 if (text_ptr>text_info_end) overflow("text");
1201 cur_text=text_ptr; (++text_ptr)->tok_start=tok_ptr;
1202}
1203
1204@ Here is the code for the line number: first a |sixteen_bits| equal
1205to |0150000|; then the numeric line number; then a pointer to the
1206file name.
1207
1208@<Insert the line...@>=
1209store_two_bytes(0150000);
1210if (changing) id_first=change_file_name;
1211else id_first=cur_file_name;
1212id_loc=id_first+strlen(id_first);
1213if (changing) store_two_bytes((sixteen_bits)change_line);
1214else store_two_bytes((sixteen_bits)cur_line);
1215{int a=id_lookup(id_first,id_loc)-name_dir; app_repl((a / 0400)+0200);
1216 app_repl(a % 0400);}
1217
1218@ @<In cases that |a| is...@>=
1219case identifier: a=id_lookup(id_first,id_loc)-name_dir;
1220 app_repl((a / 0400)+0200);
1221 app_repl(a % 0400); break;
1222case section_name: if (t!=section_name) goto done;
1223 else {
1224 @<Was an `@@' missed here?@>;
1225 a=cur_section_name-name_dir;
1226 app_repl((a / 0400)+0250);
1227 app_repl(a % 0400);
1228 @<Insert the line number into |tok_mem|@>; break;
1229 }
1230case output_defs_code:
1231 a=output_defs_flag;
1232 app_repl((a / 0400)+0200);
1233 app_repl(a % 0400);
1234 @<Insert the line number into |tok_mem|@>; break;
1235case constant: case string:
1236 @<Copy a string or verbatim construction or numerical constant@>;
1237case ord:
1238 @<Copy an ASCII constant@>;
1239case definition: case format_code: case begin_C: if (t!=section_name) goto done;
1240 else {
1241 err_print("! @@d, @@f and @@c are ignored in C text"); continue;
1242@.@@d, @@f and @@c are ignored in C text@>
1243 }
1244case new_section: goto done;
1245
1246@ @<Was an `@@'...@>= {
1247 char *try_loc=loc;
1248 while (*try_loc==' ' && try_loc<limit) try_loc++;
1249 if (*try_loc=='+' && try_loc<limit) try_loc++;
1250 while (*try_loc==' ' && try_loc<limit) try_loc++;
1251 if (*try_loc=='=') err_print ("! Missing `@@ ' before a named section");
1252@.Missing `@@ '...@>
1253 /* user who isn't defining a section should put newline after the name,
1254 as explained in the manual */
1255}
1256
1257@ @<Copy a string...@>=
1258 app_repl(a); /* |string| or |constant| */
1259 while (id_first < id_loc) { /* simplify \.{@@@@} pairs */
1260 if (*id_first=='@@') {
1261 if (*(id_first+1)=='@@') id_first++;
1262 else err_print("! Double @@ should be used in string");
1263@.Double @@ should be used...@>
1264 }
1265 app_repl(*id_first++);
1266 }
1267 app_repl(a); break;
1268
1269@ This section should be rewritten on machines that don't use ASCII
1270code internally.
1271@^ASCII code dependencies@>
1272
1273@<Copy an ASCII constant@>= {
1274 int c=(eight_bits) *id_first;
1275 if (c=='\\') {
1276 c=*++id_first;
1277 if (c>='0' && c<='7') {
1278 c-='0';
1279 if (*(id_first+1)>='0' && *(id_first+1)<='7') {
1280 c=8*c+*(++id_first) - '0';
1281 if (*(id_first+1)>='0' && *(id_first+1)<='7' && c<32)
1282 c=8*c+*(++id_first)- '0';
1283 }
1284 }
1285 else switch (c) {
1286 case 't':c='\t';@+break;
1287 case 'n':c='\n';@+break;
1288 case 'b':c='\b';@+break;
1289 case 'f':c='\f';@+break;
1290 case 'v':c='\v';@+break;
1291 case 'r':c='\r';@+break;
1292 case 'a':c='\7';@+break;
1293 case '?':c='?';@+break;
1294 case 'x':
1295 if (xisdigit(*(id_first+1))) c=*(++id_first)-'0';
1296 else if (xisxdigit(*(id_first+1))) {
1297 ++id_first;
1298 c=toupper(*id_first)-'A'+10;
1299 }
1300 if (xisdigit(*(id_first+1))) c=16*c+*(++id_first)-'0';
1301 else if (xisxdigit(*(id_first+1))) {
1302 ++id_first;
1303 c=16*c+toupper(*id_first)-'A'+10;
1304 }
1305 break;
1306 case '\\':c='\\';@+break;
1307 case '\'':c='\'';@+break;
1308 case '\"':c='\"';@+break;
1309 default: err_print("! Unrecognized escape sequence");
1310@.Unrecognized escape sequence@>
1311 }
1312 }@/
1313 /* at this point |c| should have been converted to its ASCII code number */
1314 app_repl(constant);
1315 if (c>=100) app_repl('0'+c/100);
1316 if (c>=10) app_repl('0'+(c/10)%10);
1317 app_repl('0'+c%10);
1318 app_repl(constant);
1319}
1320break;
1321
1322@* Scanning a section.
1323The |scan_section| procedure starts when `\.{@@\ }' or `\.{@@*}' has been
1324sensed in the input, and it proceeds until the end of that section. It
1325uses |section_count| to keep track of the current section number; with luck,
1326\.{CWEAVE} and \.{CTANGLE} will both assign the same numbers to sections.
1327
1328@<Global...@>=
1329extern sixteen_bits section_count; /* the current section number */
1330
1331@ The body of |scan_section| is a loop where we look for control codes
1332that are significant to \.{CTANGLE}: those
1333that delimit a definition, the \CEE/ part of a module, or a new module.
1334
1335@c
1336void
1337scan_section()
1338{
1339 name_pointer p; /* section name for the current section */
1340 text_pointer q; /* text for the current section */
1341 sixteen_bits a; /* token for left-hand side of definition */
1342 section_count++;
1343 if (*(loc-1)=='*' && show_progress) { /* starred section */
1344 printf("*%d",section_count); update_terminal;
1345 }
1346 next_control=0;
1347 while (1) {
1348 @<Skip ahead until |next_control| corresponds to \.{@@d}, \.{@@<},
1349 \.{@@\ } or the like@>;
1350 if (next_control == definition) { /* \.{@@d} */
1351 @<Scan a definition@>@;
1352 continue;
1353 }
1354 if (next_control == begin_C) { /* \.{@@c} or \.{@@p} */
1355 p=name_dir; break;
1356 }
1357 if (next_control == section_name) { /* \.{@@<} or \.{@@(} */
1358 p=cur_section_name;
1359 @<If section is not being defined, |continue| @>;
1360 break;
1361 }
1362 return; /* \.{@@\ } or \.{@@*} */
1363 }
1364 @<Scan the \CEE/ part of the current section@>;
1365}
1366
1367@ At the top of this loop, if |next_control==section_name|, the
1368section name has already been scanned (see |@<Get control code
1369and...@>|). Thus, if we encounter |next_control==section_name| in the
1370skip-ahead process, we should likewise scan the section name, so later
1371processing will be the same in both cases.
1372
1373@<Skip ahead until |next_control| ...@>=
1374while (next_control<definition)
1375 /* |definition| is the lowest of the ``significant'' codes */
1376 if((next_control=skip_ahead())==section_name){
1377 loc-=2; next_control=get_next();
1378 }
1379
1380@ @<Scan a definition@>= {
1381 while ((next_control=get_next())=='\n'); /*allow newline before definition */
1382 if (next_control!=identifier) {
1383 err_print("! Definition flushed, must start with identifier");
1384@.Definition flushed...@>
1385 continue;
1386 }
1387 app_repl(((a=id_lookup(id_first,id_loc)-name_dir) / 0400)+0200);
1388 /* append the lhs */
1389 app_repl(a % 0400);
1390 if (*loc!='(') { /* identifier must be separated from replacement text */
1391 app_repl(string); app_repl(' '); app_repl(string);
1392 }
1393 print_where=0; scan_repl(macro);
1394 cur_text->text_link=0; /* |text_link==0| characterizes a macro */
1395}
1396
1397@ If the section name is not followed by \.{=} or \.{+=}, no \CEE/
1398code is forthcoming: the section is being cited, not being
1399defined. This use is illegal after the definition part of the
1400current section has started, except inside a comment, but
1401\.{CTANGLE} does not enforce this rule: it simply ignores the offending
1402section name and everything following it, up to the next significant
1403control code.
1404
1405@<If section is not being defined, |continue| @>=
1406while ((next_control=get_next())=='+'); /* allow optional \.{+=} */
1407if (next_control!='=' && next_control!=eq_eq)
1408 continue;
1409
1410@ @<Scan the \CEE/...@>=
1411@<Insert the section number into |tok_mem|@>;
1412scan_repl(section_name); /* now |cur_text| points to the replacement text */
1413@<Update the data structure so that the replacement text is accessible@>;
1414
1415@ @<Insert the section number...@>=
1416store_two_bytes((sixteen_bits)(0150000+section_count));
1417 /* |0150000==0320*0400| */
1418
1419@ @<Update the data...@>=
1420if (p==name_dir||p==0) { /* unnamed section, or bad section name */
1421 (last_unnamed)->text_link=cur_text-text_info; last_unnamed=cur_text;
1422}
1423else if (p->equiv==(char *)text_info) p->equiv=(char *)cur_text;
1424 /* first section of this name */
1425else {
1426 q=(text_pointer)p->equiv;
1427 while (q->text_link<section_flag)
1428 q=q->text_link+text_info; /* find end of list */
1429 q->text_link=cur_text-text_info;
1430}
1431cur_text->text_link=section_flag;
1432 /* mark this replacement text as a nonmacro */
1433
1434@ @<Predec...@>=
1435void phase_one();
1436
1437@ @c
1438void
1439phase_one() {
1440 phase=1;
1441 section_count=0;
1442 reset_input();
1443 skip_limbo();
1444 while (!input_has_ended) scan_section();
1445 check_complete();
1446 phase=2;
1447}
1448
1449@ Only a small subset of the control codes is legal in limbo, so limbo
1450processing is straightforward.
1451
1452@<Predecl...@>=
1453void skip_limbo();
1454
1455@ @c
1456void
1457skip_limbo()
1458{
1459 char c;
1460 while (1) {
1461 if (loc>limit && get_line()==0) return;
1462 *(limit+1)='@@';
1463 while (*loc!='@@') loc++;
1464 if (loc++<=limit) {
1465 c=*loc++;
1466 if (ccode[(eight_bits)c]==new_section) break;
1467 switch (ccode[(eight_bits)c]) {
1468 case translit_code: @<Read in transliteration of a character@>; break;
1469 case format_code: case '@@': break;
1470 case control_text: if (c=='q' || c=='Q') {
1471 while ((c=skip_ahead())=='@@');
1472 if (*(loc-1)!='>')
1473 err_print("! Double @@ should be used in control text");
1474@.Double @@ should be used...@>
1475 break;
1476 } /* otherwise fall through */
1477 default: err_print("! Double @@ should be used in limbo");
1478@.Double @@ should be used...@>
1479 }
1480 }
1481 }
1482}
1483
1484@ @<Read in transliteration of a character@>=
1485 while(xisspace(*loc)&&loc<limit) loc++;
1486 loc+=3;
1487 if (loc>limit || !xisxdigit(*(loc-3)) || !xisxdigit(*(loc-2)) @|
1488 || (*(loc-3)>='0' && *(loc-3)<='7') || !xisspace(*(loc-1)))
1489 err_print("! Improper hex number following @@l");
1490@.Improper hex number...@>
1491 else {
1492 unsigned i;
1493 char *beg;
1494 sscanf(loc-3,"%x",&i);
1495 while(xisspace(*loc)&&loc<limit) loc++;
1496 beg=loc;
1497 while(loc<limit&&(xisalpha(*loc)||xisdigit(*loc)||*loc=='_')) loc++;
1498 if (loc-beg>=translit_length)
1499 err_print("! Replacement string in @@l too long");
1500@.Replacement string in @@l...@>
1501 else{
1502 strncpy(translit[i-0200],beg,loc-beg);
1503 translit[i-0200][loc-beg]='\0';
1504 }
1505 }
1506
1507@ Because on some systems the difference between two pointers is a |long|
1508but not an |int|, we use \.{\%ld} to print these quantities.
1509
1510@c
1511void
1512print_stats() {
1513 printf("\nMemory usage statistics:\n");
1514 printf("%ld names (out of %ld)\n",
1515 (long)(name_ptr-name_dir),(long)max_names);
1516 printf("%ld replacement texts (out of %ld)\n",
1517 (long)(text_ptr-text_info),(long)max_texts);
1518 printf("%ld bytes (out of %ld)\n",
1519 (long)(byte_ptr-byte_mem),(long)max_bytes);
1520 printf("%ld tokens (out of %ld)\n",
1521 (long)(tok_ptr-tok_mem),(long)max_toks);
1522}
1523
1524@** Index.
1525Here is a cross-reference table for \.{CTANGLE}.
1526All sections in which an identifier is
1527used are listed with that identifier, except that reserved words are
1528indexed only when they appear in format definitions, and the appearances
1529of identifiers in section names are not indexed. Underlined entries
1530correspond to where the identifier was declared. Error messages and
1531a few other things like ``ASCII code dependencies'' are indexed here too.
cweav-bs.ch+274−0
@@ -0,0 +1,274 @@
1Changes for CWEAVE for MSDOS and Borland C++ 3.1 using the following
2options (and perhaps others):
3
4 -mc -w-pro -Ff=5000 -Z- -O-p
5
6The options -Z- and -O-p explicitly turn off optimizations that break
7the code. (See makefile.bs.)
8
9The main purpose of these changes is to support MSDOS with full-size arrays
10by using "huge" pointers.
11
12(This file contributed by Barry Schwartz, trashman@crud.mn.org, 28 Jun 94;
13 revised 24 Jul 94.)
14(Includes workaround for compiler bug [pointers wrapping around at
15 segment boundaries], November 1993, contributed by Jorge Fernandez Arnaiz
16 -- arnaiz@redvax1.dgsca.unam.mx)
17
18
19@x Section 1.
20The ``banner line'' defined here should be changed whenever \.{CWEAVE}
21is modified.
22
23@d banner "This is CWEAVE (Version 3.2)\n"
24@y
25The ``banner line'' defined here should be changed whenever \.{CWEAVE}
26is modified.
27
28@d banner "This is CWEAVE (Version 3.2pc/big)\n"
29@z
30
31
32@x Section 9.
33@d chunk_marker 0
34
35@<Common code...@>=
36typedef struct name_info {
37 char *byte_start; /* beginning of the name in |byte_mem| */
38 struct name_info *link;
39 union {
40 struct name_info *Rlink; /* right link in binary search tree for section
41 names */
42 char Ilk; /* used by identifiers in \.{CWEAVE} only */
43 } dummy;
44 char *equiv_or_xref; /* info corresponding to names */
45} name_info; /* contains information about an identifier or section name */
46typedef name_info *name_pointer; /* pointer into array of \&{name\_info}s */
47typedef name_pointer *hash_pointer;
48extern char byte_mem[]; /* characters of names */
49extern char *byte_mem_end; /* end of |byte_mem| */
50extern name_info name_dir[]; /* information about names */
51extern name_pointer name_dir_end; /* end of |name_dir| */
52extern name_pointer name_ptr; /* first unused position in |byte_start| */
53extern char *byte_ptr; /* first unused position in |byte_mem| */
54extern name_pointer hash[]; /* heads of hash lists */
55extern hash_pointer hash_end; /* end of |hash| */
56extern hash_pointer h; /* index into hash-head array */
57extern name_pointer id_lookup(); /* looks up a string in the identifier table */
58extern name_pointer section_lookup(); /* finds section name */
59extern void print_section_name(), sprint_section_name();
60@y
61@d chunk_marker 0
62
63@f huge extern
64
65@<Common code...@>=
66typedef struct name_info {
67 char huge* byte_start; /* beginning of the name in |byte_mem| */
68 struct name_info *link;
69 union {
70 struct name_info *Rlink; /* right link in binary search tree for section
71 names */
72 char Ilk; /* used by identifiers in \.{CWEAVE} only */
73 } dummy;
74 union {
75 char *equiv_member;
76 char huge* xref_member;
77 } ptr_union; /* info corresponding to names */
78} name_info; /* contains information about an identifier or section name */
79typedef name_info *name_pointer; /* pointer into array of \&{name\_info}s */
80typedef name_pointer *hash_pointer;
81extern char huge byte_mem[]; /* characters of names */
82extern char huge* byte_mem_end; /* end of |byte_mem| */
83extern name_info name_dir[]; /* information about names */
84extern name_pointer name_dir_end; /* end of |name_dir| */
85extern name_pointer name_ptr; /* first unused position in |byte_start| */
86extern char huge* byte_ptr; /* first unused position in |byte_mem| */
87extern name_pointer hash[]; /* heads of hash lists */
88extern hash_pointer hash_end; /* end of |hash| */
89extern hash_pointer h; /* index into hash-head array */
90extern name_pointer id_lookup(); /* looks up a string in the identifier table */
91extern name_pointer section_lookup(); /* finds section name */
92extern void print_section_name(), sprint_section_name();
93@z
94
95
96@x Section 18.
97typedef struct xref_info {
98 sixteen_bits num; /* section number plus zero or |def_flag| */
99 struct xref_info *xlink; /* pointer to the previous cross-reference */
100} xref_info;
101typedef xref_info *xref_pointer;
102@y
103typedef struct xref_info {
104 sixteen_bits num; /* section number plus zero or |def_flag| */
105 struct xref_info huge* xlink; /* pointer to the previous cross-reference */
106} xref_info;
107typedef xref_info huge* xref_pointer;
108@z
109
110
111@x Section 19.
112xref_info xmem[max_refs]; /* contains cross-reference information */
113xref_pointer xmem_end = xmem+max_refs-1;
114@y
115xref_info huge xmem[max_refs]; /* contains cross-reference information */
116xref_pointer xmem_end;
117@z
118
119
120@x Section 20.
121@d xref equiv_or_xref
122@y
123@d xref ptr_union.xref_member
124@z
125
126
127@x Section 20.
128xref_ptr=xmem; name_dir->xref=(char*)xmem; xref_switch=0; section_xref_switch=0;
129xmem->num=0; /* sentinel value */
130@y
131xmem_end = xmem + max_refs - 1;
132xref_ptr=xmem; name_dir->xref=(char*)xmem; xref_switch=0; section_xref_switch=0;
133xmem->num=0; /* sentinel value */
134@z
135
136
137@x Section 21.
138 append_xref(m); xref_ptr->xlink=q; p->xref=(char*)xref_ptr;
139@y
140 append_xref(m); xref_ptr->xlink=q; p->xref=(char huge*)xref_ptr;
141@z
142
143
144@x Section 22.
145 if (r==xmem) p->xref=(char*)xref_ptr;
146@y
147 if (r==xmem) p->xref=(char huge*)xref_ptr;
148@z
149
150
151@x Section 23.
152 q=(xref_pointer)p->xref;
153 if (q->num==file_flag) return;
154 append_xref(file_flag);
155 xref_ptr->xlink = q;
156 p->xref = (char *)xref_ptr;
157@y
158 q=(xref_pointer)p->xref;
159 if (q->num==file_flag) return;
160 append_xref(file_flag);
161 xref_ptr->xlink = q;
162 p->xref = (char huge*)xref_ptr;
163@z
164
165
166@x Section 27.
167 p->ilk=t; p->xref=(char*)xmem;
168@y
169 p->ilk=t; p->xref=(char huge*)xmem;
170@z
171
172
173@x Section 27.
174 p->xref=(char*)xmem;
175@y
176 p->xref=(char*)xmem;
177@z
178
179
180@x Section 70.
181 if (unindexed(lhs)) { /* retain only underlined entries */
182 xref_pointer q,r=NULL;
183 for (q=(xref_pointer)lhs->xref;q>xmem;q=q->xlink)
184 if (q->num<def_flag)
185 if (r) r->xlink=q->xlink;
186 else lhs->xref=(char*)q->xlink;
187 else r=q;
188 }
189@y
190 if (unindexed(lhs)) { /* retain only underlined entries */
191 xref_pointer q,r=NULL;
192 for (q=(xref_pointer)lhs->xref;q>xmem;q=q->xlink)
193 if (q->num<def_flag)
194 if (r) r->xlink=q->xlink;
195 else lhs->xref=(char huge*)q->xlink;
196 else r=q;
197 }
198@z
199
200
201@x Section 87.
202 char *k, *k_end=(p+1)->byte_start; /* pointers into |byte_mem| */
203 out('{');
204 for (k=p->byte_start; k<k_end; k++) {
205@y
206 char huge* k, huge* k_end=(p+1)->byte_start; /* pointers into |byte_mem| */
207 out('{');
208 for (k=p->byte_start; k<k_end; k++) {
209@z
210
211
212@x Section 116.
213 append_xref(0); /* this number doesn't matter */
214 xref_ptr->xlink=(xref_pointer)p->xref; r=xref_ptr;
215 p->xref=(char*)xref_ptr;
216 while (r->xlink!=q) {r->num=r->xlink->num; r=r->xlink;}
217 r->num=m; /* everything from |q| on is left undisturbed */
218@y
219 append_xref(0); /* this number doesn't matter */
220 xref_ptr->xlink=(xref_pointer)p->xref; r=xref_ptr;
221 p->xref=(char huge*)xref_ptr;
222 while (r->xlink!=q) {r->num=r->xlink->num; r=r->xlink;}
223 r->num=m; /* everything from |q| on is left undisturbed */
224@z
225
226
227@x Section 163.
228@ @<Change |pp| to $\max...@>=
229@y
230@ @<Change |pp| to $\max...@>=
231#ifdef __MSDOS__
232if (d<0 && pp+d>pp) pp=scrap_base; /* segmented architecture caused wrap */
233else
234#endif
235@z
236
237
238@x Section 194.
239 char *p; /* index into |byte_mem| */
240@y
241 char huge *p; /* index into |byte_mem| */
242@z
243
244
245@x Section 229.
246 if (cur_name->xref!=(char*)xmem) {
247@y
248 if (cur_name->xref!=(char huge*)xmem) {
249@z
250
251
252@x Section 232.
253char *cur_byte; /* index into |byte_mem| */
254@y
255char huge* cur_byte; /* index into |byte_mem| */
256@z
257
258
259@x Section 241.
260switch (cur_name->ilk) {
261 case normal: if (is_tiny(cur_name)) out_str("\\|");
262 else {char *j;
263@y
264switch (cur_name->ilk) {
265 case normal: if (is_tiny(cur_name)) out_str("\\|");
266 else {char huge* j;
267@z
268
269
270@x Section 241.
271 case custom: case quoted: {char *j; out_str("$\\");
272@y
273 case custom: case quoted: {char huge* j; out_str("$\\");
274@z
cweav-man.ch+22−0
@@ -0,0 +1,22 @@
1Change file to help make Appendix F of the full CWEB manual
2@x
3\def\botofcontents{\vfill
4\noindent
5Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
6\bigskip\noindent
7Permission is granted to make and distribute verbatim copies of this
8document provided that the copyright notice and this permission notice
9are preserved on all copies.
10
11\smallskip\noindent
12Permission is granted to copy and distribute modified versions of this
13document under the conditions for verbatim copying, provided that the
14entire resulting derived work is given a different name and distributed
15under the terms of a permission notice identical to this one.
16}
17@y
18\def\botofcontents{\vfill\titlefalse}
19\def\contentspagenumber{103}
20\def\title{APPENDIX F: CWEAVE}
21\let\K=\leftarrow
22@z
cweav-pc.ch+39−0
@@ -0,0 +1,39 @@
1This is the change file for CWEB's CWEAVE under DOS
2(Contributed by Lee Wittenberg, March 1993)
3(Also includes workaround for compiler bug, November 1993,
4 contributed by Jorge Fernandez Arnaiz -- arnaiz@redvax1.dgsca.unam.mx)
5
6Changes necessary for compiling with Borland C/C++
7Use compilation switches -mc -w-pro -Ff=5000
8
9Note: The changes to section 4 are not necessary if using a compiler
10that allows >64K arrays. (If you need lots more bytes, try the alternate
11change files that have -bs in their name instead of -pc.)
12
13@x section 1
14@d banner "This is CWEAVE (Version 3.2)\n"
15@y
16@d banner "This is CWEAVE (Version 3.2pc)\n"
17@z
18
19@x section 4
20@d max_bytes 90000 /* the number of bytes in identifiers,
21@y
22@d max_bytes (unsigned)60000 /* the number of bytes in identifiers,
23@z
24@x
25@d max_refs 20000 /* number of cross-references; must be less than 65536 */
26@y
27@d max_refs 10000 /* number of cross-references; must be less than 65536 */
28@z
29
30@x section 163
31@ @<Change |pp| to $\max...@>=
32@y
33@ @<Change |pp| to $\max...@>=
34#ifdef __MSDOS__
35if (d<0 && pp+d>pp) pp=scrap_base; /* segmented architecture caused wrap */
36else
37#endif
38@z
39
cweav-vms.ch+37−0
@@ -0,0 +1,37 @@
1This is the change file for CWEB's CWEAVE for VAX/VMS.
2
3created:
4 1991 JM (John Mulhollen, Science Applications International Corporation)
5
6modified:
7 01-FEB-1992 ST (Stephan Trebels <trebels@ams02.dnet.gwdg.de>)
8 > include ctype,stdio from textlibrary SYS$SHARE:VAXCDEF.TLB
9 > change banner line to include (VAX/VMS)
10 > allow $ in identifiers (*necessary* for VAX/VMS)
11 ? will someone eventally make a CLD interface? (should be easy)
12
13(also modified by Don Knuth to keep version numbers uptodate)
14
15@x section 1 (01-FEB-1992 ST)
16@d banner "This is CWEAVE (Version 3.2)\n"
17@y
18@d banner "This is CWEAVE (VAX/VMS Version 3.2)\n"
19@z
20
21@x section 6 (from common.h) (01-FEB-1992 ST)
22#include <stdio.h>
23@y
24#include stdio /* VMS searches Textlibraries faster */
25@z
26
27@x section 38 (1991 JM) (01-FEB-1992 ST)
28#include <ctype.h> /* definition of |isalpha|, |isdigit| and so on */
29@y
30#include ctype /* VMS searches Textlibraries faster */
31@z
32
33@x section 39 (01-FEB-1992 ST)
34@d isxalpha(c) ((c)=='_') /* non-alpha character allowed in identifier */
35@y
36@d isxalpha(c) ((c)=='_' || (c)=='$') /* non-alpha characters allowed in id */
37@z
cweave.w+4477−0
@@ -0,0 +1,4477 @@
1% This file is part of CWEB.
2% This program by Silvio Levy and Donald E. Knuth
3% is based on a program by Knuth.
4% It is distributed WITHOUT ANY WARRANTY, express or implied.
5% Version 3.2 --- July 1994
6
7% Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
8
9% Permission is granted to make and distribute verbatim copies of this
10% document provided that the copyright notice and this permission notice
11% are preserved on all copies.
12
13% Permission is granted to copy and distribute modified versions of this
14% document under the conditions for verbatim copying, provided that the
15% entire resulting derived work is given a different name and distributed
16% under the terms of a permission notice identical to this one.
17
18% Here is TeX material that gets inserted after \input cwebmac
19\def\hang{\hangindent 3em\indent\ignorespaces}
20\def\pb{$\.|\ldots\.|$} % C brackets (|...|)
21\def\v{\char'174} % vertical (|) in typewriter font
22\def\dleft{[\![} \def\dright{]\!]} % double brackets
23\mathchardef\RA="3221 % right arrow
24\mathchardef\BA="3224 % double arrow
25\def\({} % ) kludge for alphabetizing certain section names
26\def\TeXxstring{\\{\TEX/\_string}}
27\def\skipxTeX{\\{skip\_\TEX/}}
28\def\copyxTeX{\\{copy\_\TEX/}}
29
30\def\title{CWEAVE (Version 3.2)}
31\def\topofcontents{\null\vfill
32 \centerline{\titlefont The {\ttitlefont CWEAVE} processor}
33 \vskip 15pt
34 \centerline{(Version 3.2)}
35 \vfill}
36\def\botofcontents{\vfill
37\noindent
38Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
39\bigskip\noindent
40Permission is granted to make and distribute verbatim copies of this
41document provided that the copyright notice and this permission notice
42are preserved on all copies.
43
44\smallskip\noindent
45Permission is granted to copy and distribute modified versions of this
46document under the conditions for verbatim copying, provided that the
47entire resulting derived work is given a different name and distributed
48under the terms of a permission notice identical to this one.
49}
50\pageno=\contentspagenumber \advance\pageno by 1
51\let\maybe=\iftrue
52
53@** Introduction.
54This is the \.{CWEAVE} program by Silvio Levy and Donald E. Knuth,
55based on \.{WEAVE} by Knuth.
56We are thankful to Steve Avery,
57Nelson Beebe, Hans-Hermann Bode (to whom the \CPLUSPLUS/ adaptation is due),
58Klaus Guntermann, Norman Ramsey, Tomas Rokicki, Joachim Schnitter,
59Joachim Schrod, Lee Wittenberg, and others who have contributed improvements.
60
61The ``banner line'' defined here should be changed whenever \.{CWEAVE}
62is modified.
63
64@d banner "This is CWEAVE (Version 3.2)\n"
65
66@c @<Include files@>@/
67@h
68@<Common code for \.{CWEAVE} and \.{CTANGLE}@>@/
69@<Typedef declarations@>@/
70@<Global variables@>@/
71@<Predeclaration of procedures@>
72
73@ We predeclare several standard system functions here instead of including
74their system header files, because the names of the header files are not as
75standard as the names of the functions. (For example, some \CEE/ environments
76have \.{<string.h>} where others have \.{<strings.h>}.)
77
78@<Predecl...@>=
79extern int strlen(); /* length of string */
80extern int strcmp(); /* compare strings lexicographically */
81extern char* strcpy(); /* copy one string to another */
82extern int strncmp(); /* compare up to $n$ string characters */
83extern char* strncpy(); /* copy up to $n$ string characters */
84
85@ \.{CWEAVE} has a fairly straightforward outline. It operates in
86three phases: First it inputs the source file and stores cross-reference
87data, then it inputs the source once again and produces the \TEX/ output
88file, finally it sorts and outputs the index.
89
90Please read the documentation for \.{common}, the set of routines common
91to \.{CTANGLE} and \.{CWEAVE}, before proceeding further.
92
93@c
94int main (ac, av)
95int ac; /* argument count */
96char **av; /* argument values */
97{
98 argc=ac; argv=av;
99 program=cweave;
100 make_xrefs=force_lines=1; /* controlled by command-line options */
101 common_init();
102 @<Set initial values@>;
103 if (show_banner) printf(banner); /* print a ``banner line'' */
104 @<Store all the reserved words@>;
105 phase_one(); /* read all the user's text and store the cross-references */
106 phase_two(); /* read all the text again and translate it to \TEX/ form */
107 phase_three(); /* output the cross-reference index */
108 return wrap_up(); /* and exit gracefully */
109}
110
111@ The following parameters were sufficient in the original \.{WEAVE} to
112handle \TEX/, so they should be sufficient for most applications of \.{CWEAVE}.
113If you change |max_bytes|, |max_names|, |hash_size| or |buf_size|
114you have to change them also in the file |"common.w"|.
115
116@d max_bytes 90000 /* the number of bytes in identifiers,
117 index entries, and section names */
118@d max_names 4000 /* number of identifiers, strings, section names;
119 must be less than 10240; used in |"common.w"| */
120@d max_sections 2000 /* greater than the total number of sections */
121@d hash_size 353 /* should be prime */
122@d buf_size 100 /* maximum length of input line, plus one */
123@d longest_name 1000 /* section names and strings shouldn't be longer than this */
124@d long_buf_size (buf_size+longest_name)
125@d line_length 80 /* lines of \TEX/ output have at most this many characters;
126 should be less than 256 */
127@d max_refs 20000 /* number of cross-references; must be less than 65536 */
128@d max_toks 20000 /* number of symbols in \CEE/ texts being parsed;
129 must be less than 65536 */
130@d max_texts 4000 /* number of phrases in \CEE/ texts being parsed;
131 must be less than 10240 */
132@d max_scraps 2000 /* number of tokens in \CEE/ texts being parsed */
133@d stack_size 400 /* number of simultaneous output levels */
134
135@ The next few sections contain stuff from the file |"common.w"| that must
136be included in both |"ctangle.w"| and |"cweave.w"|. It appears in
137file |"common.h"|, which needs to be updated when |"common.w"| changes.
138
139@i common.h
140
141@* Data structures exclusive to {\tt CWEAVE}.
142As explained in \.{common.w}, the field of a |name_info| structure
143that contains the |rlink| of a section name is used for a completely
144different purpose in the case of identifiers. It is then called the
145|ilk| of the identifier, and it is used to
146distinguish between various types of identifiers, as follows:
147
148\yskip\hang |normal| identifiers are part of the \CEE/ program and
149will appear in italic type.
150
151\yskip\hang |roman| identifiers are index entries that appear after
152\.{@@\^} in the \.{CWEB} file.
153
154\yskip\hang |wildcard| identifiers are index entries that appear after
155\.{@@:} in the \.{CWEB} file.
156
157\yskip\hang |typewriter| identifiers are index entries that appear after
158\.{@@.} in the \.{CWEB} file.
159
160\yskip\hang |else_like|, \dots, |typedef_like|
161identifiers are \CEE/ reserved words whose |ilk| explains how they are
162to be treated when \CEE/ code is being formatted.
163
164@d ilk dummy.Ilk
165@d normal 0 /* ordinary identifiers have |normal| ilk */
166@d roman 1 /* normal index entries have |roman| ilk */
167@d wildcard 2 /* user-formatted index entries have |wildcard| ilk */
168@d typewriter 3 /* `typewriter type' entries have |typewriter| ilk */
169@d abnormal(a) (a->ilk>typewriter) /* tells if a name is special */
170@d custom 4 /* identifiers with user-given control sequence */
171@d unindexed(a) (a->ilk>custom) /* tells if uses of a name are to be indexed */
172@d quoted 5 /* \.{NULL} */
173@d else_like 26 /* \&{else} */
174@d public_like 40 /* \&{public}, \&{private}, \&{protected} */
175@d operator_like 41 /* \&{operator} */
176@d new_like 42 /* \&{new} */
177@d catch_like 43 /* \&{catch} */
178@d for_like 45 /* \.{for}, \&{switch}, \&{while} */
179@d do_like 46 /* \&{do} */
180@d if_like 47 /* \&{if}, \&{ifdef}, \&{endif}, \&{pragma}, \dots */
181@d raw_rpar 48 /* `\.)' or `\.]' when looking for \&{const} following */
182@d raw_unorbin 49 /* `\.\&' or `\.*' when looking for \&{const} following */
183@d const_like 50 /* \&{const}, \&{volatile} */
184@d raw_int 51 /* \&{int}, \&{char}, \&{extern}, \dots */
185@d int_like 52 /* same, when not followed by left parenthesis */
186@d case_like 53 /* \&{case}, \&{return}, \&{goto}, \&{break}, \&{continue} */
187@d sizeof_like 54 /* \&{sizeof} */
188@d struct_like 55 /* \&{struct}, \&{union}, \&{enum}, \&{class} */
189@d typedef_like 56 /* \&{typedef} */
190@d define_like 57 /* \&{define} */
191
192@ We keep track of the current section number in |section_count|, which
193is the total number of sections that have started. Sections which have
194been altered by a change file entry have their |changed_section| flag
195turned on during the first phase.
196
197@<Global...@>=
198boolean change_exists; /* has any section changed? */
199
200@ The other large memory area in \.{CWEAVE} keeps the cross-reference data.
201All uses of the name |p| are recorded in a linked list beginning at
202|p->xref|, which points into the |xmem| array. The elements of |xmem|
203are structures consisting of an integer, |num|, and a pointer |xlink|
204to another element of |xmem|. If |x=p->xref| is a pointer into |xmem|,
205the value of |x->num| is either a section number where |p| is used,
206or |cite_flag| plus a section number where |p| is mentioned,
207or |def_flag| plus a section number where |p| is defined;
208and |x->xlink| points to the next such cross-reference for |p|,
209if any. This list of cross-references is in decreasing order by
210section number. The next unused slot in |xmem| is |xref_ptr|.
211The linked list ends at |&xmem[0]|.
212
213The global variable |xref_switch| is set either to |def_flag| or to zero,
214depending on whether the next cross-reference to an identifier is to be
215underlined or not in the index. This switch is set to |def_flag| when
216\.{@@!} or \.{@@d} is scanned, and it is cleared to zero when
217the next identifier or index entry cross-reference has been made.
218Similarly, the global variable |section_xref_switch| is either
219|def_flag| or |cite_flag| or zero, depending
220on whether a section name is being defined, cited or used in \CEE/ text.
221
222@<Type...@>=
223typedef struct xref_info {
224 sixteen_bits num; /* section number plus zero or |def_flag| */
225 struct xref_info *xlink; /* pointer to the previous cross-reference */
226} xref_info;
227typedef xref_info *xref_pointer;
228
229@ @<Global...@>=
230xref_info xmem[max_refs]; /* contains cross-reference information */
231xref_pointer xmem_end = xmem+max_refs-1;
232xref_pointer xref_ptr; /* the largest occupied position in |xmem| */
233sixteen_bits xref_switch,section_xref_switch; /* either zero or |def_flag| */
234
235@ A section that is used for multi-file output (with the \.{@@(} feature)
236has a special first cross-reference whose |num| field is |file_flag|.
237
238@d file_flag (3*cite_flag)
239@d def_flag (2*cite_flag)
240@d cite_flag 10240 /* must be strictly larger than |max_sections| */
241@d xref equiv_or_xref
242
243@<Set init...@>=
244xref_ptr=xmem; name_dir->xref=(char*)xmem; xref_switch=0; section_xref_switch=0;
245xmem->num=0; /* sentinel value */
246
247@ A new cross-reference for an identifier is formed by calling |new_xref|,
248which discards duplicate entries and ignores non-underlined references
249to one-letter identifiers or \CEE/'s reserved words.
250
251If the user has sent the |no_xref| flag (the \.{-x} option of the command line),
252it is unnecessary to keep track of cross-references for identifiers.
253If one were careful, one could probably make more changes around section
254100 to avoid a lot of identifier looking up.
255
256@d append_xref(c) if (xref_ptr==xmem_end) overflow("cross-reference");
257 else (++xref_ptr)->num=c;
258@d no_xref (flags['x']==0)
259@d make_xrefs flags['x'] /* should cross references be output? */
260@d is_tiny(p) ((p+1)->byte_start==(p)->byte_start+1)
261
262@c
263void
264new_xref(p)
265name_pointer p;
266{
267 xref_pointer q; /* pointer to previous cross-reference */
268 sixteen_bits m, n; /* new and previous cross-reference value */
269 if (no_xref) return;
270 if ((unindexed(p) || is_tiny(p)) && xref_switch==0) return;
271 m=section_count+xref_switch; xref_switch=0; q=(xref_pointer)p->xref;
272 if (q != xmem) {
273 n=q->num;
274 if (n==m || n==m+def_flag) return;
275 else if (m==n+def_flag) {
276 q->num=m; return;
277 }
278 }
279 append_xref(m); xref_ptr->xlink=q; p->xref=(char*)xref_ptr;
280}
281
282@ The cross-reference lists for section names are slightly different.
283Suppose that a section name is defined in sections $m_1$, \dots,
284$m_k$, cited in sections $n_1$, \dots, $n_l$, and used in sections
285$p_1$, \dots, $p_j$. Then its list will contain $m_1+|def_flag|$,
286\dots, $m_k+|def_flag|$, $n_1+|cite_flag|$, \dots,
287$n_l+|cite_flag|$, $p_1$, \dots, $p_j$, in this order.
288
289Although this method of storage take quadratic time on the length of
290the list, under foreseeable uses of \.{CWEAVE} this inefficiency is
291insignificant.
292
293@c
294void
295new_section_xref(p)
296name_pointer p;
297{
298 xref_pointer q,r; /* pointers to previous cross-references */
299 q=(xref_pointer)p->xref; r=xmem;
300 if (q>xmem)
301 while (q->num>section_xref_switch) {r=q; q=q->xlink;}
302 if (r->num==section_count+section_xref_switch)
303 return; /* don't duplicate entries */
304 append_xref(section_count+section_xref_switch);
305 xref_ptr->xlink=q; section_xref_switch=0;
306 if (r==xmem) p->xref=(char*)xref_ptr;
307 else r->xlink=xref_ptr;
308}
309
310@ The cross-reference list for a section name may also begin with
311|file_flag|. Here's how that flag gets put~in.
312
313@c
314void
315set_file_flag(p)
316name_pointer p;
317{
318 xref_pointer q;
319 q=(xref_pointer)p->xref;
320 if (q->num==file_flag) return;
321 append_xref(file_flag);
322 xref_ptr->xlink = q;
323 p->xref = (char *)xref_ptr;
324}
325
326@ A third large area of memory is used for sixteen-bit `tokens', which appear
327in short lists similar to the strings of characters in |byte_mem|. Token lists
328are used to contain the result of \CEE/ code translated into \TEX/ form;
329further details about them will be explained later. A |text_pointer| variable
330is an index into |tok_start|.
331
332@<Typed...@>=
333typedef sixteen_bits token;
334typedef token *token_pointer;
335typedef token_pointer *text_pointer;
336
337@ The first position of |tok_mem|
338that is unoccupied by replacement text is called |tok_ptr|, and the first
339unused location of |tok_start| is called |text_ptr|.
340Thus, we usually have |*text_ptr==tok_ptr|.
341
342@<Global...@>=
343token tok_mem[max_toks]; /* tokens */
344token_pointer tok_mem_end = tok_mem+max_toks-1; /* end of |tok_mem| */
345token_pointer tok_start[max_texts]; /* directory into |tok_mem| */
346token_pointer tok_ptr; /* first unused position in |tok_mem| */
347text_pointer text_ptr; /* first unused position in |tok_start| */
348text_pointer tok_start_end = tok_start+max_texts-1; /* end of |tok_start| */
349token_pointer max_tok_ptr; /* largest value of |tok_ptr| */
350text_pointer max_text_ptr; /* largest value of |text_ptr| */
351
352@ @<Set init...@>=
353tok_ptr=tok_mem+1; text_ptr=tok_start+1; tok_start[0]=tok_mem+1;
354tok_start[1]=tok_mem+1;
355max_tok_ptr=tok_mem+1; max_text_ptr=tok_start+1;
356
357@ Here are the three procedures needed to complete |id_lookup|:
358@c
359int names_match(p,first,l,t)
360name_pointer p; /* points to the proposed match */
361char *first; /* position of first character of string */
362int l; /* length of identifier */
363eight_bits t; /* desired ilk */
364{
365 if (length(p)!=l) return 0;
366 if (p->ilk!=t && !(t==normal && abnormal(p))) return 0;
367 return !strncmp(first,p->byte_start,l);
368}
369
370void
371init_p(p,t)
372name_pointer p;
373eight_bits t;
374{
375 p->ilk=t; p->xref=(char*)xmem;
376}
377
378void
379init_node(p)
380name_pointer p;
381{
382 p->xref=(char*)xmem;
383}
384
385@ We have to get \CEE/'s
386reserved words into the hash table, and the simplest way to do this is
387to insert them every time \.{CWEAVE} is run. Fortunately there are relatively
388few reserved words. (Some of these are not strictly ``reserved,'' but
389are defined in header files of the ISO Standard \CEE/ Library.)
390@^reserved words@>
391
392@<Store all the reserved words@>=
393id_lookup("asm",NULL,sizeof_like);
394id_lookup("auto",NULL,int_like);
395id_lookup("break",NULL,case_like);
396id_lookup("case",NULL,case_like);
397id_lookup("catch",NULL,catch_like);
398id_lookup("char",NULL,raw_int);
399id_lookup("class",NULL,struct_like);
400id_lookup("clock_t",NULL,raw_int);
401id_lookup("const",NULL,const_like);
402id_lookup("continue",NULL,case_like);
403id_lookup("default",NULL,case_like);
404id_lookup("define",NULL,define_like);
405id_lookup("defined",NULL,sizeof_like);
406id_lookup("delete",NULL,sizeof_like);
407id_lookup("div_t",NULL,raw_int);
408id_lookup("do",NULL,do_like);
409id_lookup("double",NULL,raw_int);
410id_lookup("elif",NULL,if_like);
411id_lookup("else",NULL,else_like);
412id_lookup("endif",NULL,if_like);
413id_lookup("enum",NULL,struct_like);
414id_lookup("error",NULL,if_like);
415id_lookup("extern",NULL,int_like);
416id_lookup("FILE",NULL,raw_int);
417id_lookup("float",NULL,raw_int);
418id_lookup("for",NULL,for_like);
419id_lookup("fpos_t",NULL,raw_int);
420id_lookup("friend",NULL,int_like);
421id_lookup("goto",NULL,case_like);
422id_lookup("if",NULL,if_like);
423id_lookup("ifdef",NULL,if_like);
424id_lookup("ifndef",NULL,if_like);
425id_lookup("include",NULL,if_like);
426id_lookup("inline",NULL,int_like);
427id_lookup("int",NULL,raw_int);
428id_lookup("jmp_buf",NULL,raw_int);
429id_lookup("ldiv_t",NULL,raw_int);
430id_lookup("line",NULL,if_like);
431id_lookup("long",NULL,raw_int);
432id_lookup("new",NULL,new_like);
433id_lookup("NULL",NULL,quoted);
434id_lookup("offsetof",NULL,sizeof_like);
435id_lookup("operator",NULL,operator_like);
436id_lookup("pragma",NULL,if_like);
437id_lookup("private",NULL,public_like);
438id_lookup("protected",NULL,public_like);
439id_lookup("ptrdiff_t",NULL,raw_int);
440id_lookup("public",NULL,public_like);
441id_lookup("register",NULL,int_like);
442id_lookup("return",NULL,case_like);
443id_lookup("short",NULL,raw_int);
444id_lookup("sig_atomic_t",NULL,raw_int);
445id_lookup("signed",NULL,raw_int);
446id_lookup("size_t",NULL,raw_int);
447id_lookup("sizeof",NULL,sizeof_like);
448id_lookup("static",NULL,int_like);
449id_lookup("struct",NULL,struct_like);
450id_lookup("switch",NULL,for_like);
451id_lookup("template",NULL,int_like);
452id_lookup("TeX",NULL,custom);
453id_lookup("this",NULL,quoted);
454id_lookup("throw",NULL,case_like);
455id_lookup("time_t",NULL,raw_int);
456id_lookup("try",NULL,else_like);
457id_lookup("typedef",NULL,typedef_like);
458id_lookup("undef",NULL,if_like);
459id_lookup("union",NULL,struct_like);
460id_lookup("unsigned",NULL,raw_int);
461id_lookup("va_dcl",NULL,decl); /* Berkeley's variable-arg-list convention */
462id_lookup("va_list",NULL,raw_int); /* ditto */
463id_lookup("virtual",NULL,int_like);
464id_lookup("void",NULL,raw_int);
465id_lookup("volatile",NULL,const_like);
466id_lookup("wchar_t",NULL,raw_int);
467id_lookup("while",NULL,for_like);
468
469@* Lexical scanning.
470Let us now consider the subroutines that read the \.{CWEB} source file
471and break it into meaningful units. There are four such procedures:
472One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
473section; another passes over the \TEX/ text at the beginning of a
474section; the third passes over the \TEX/ text in a \CEE/ comment;
475and the last, which is the most interesting, gets the next token of
476a \CEE/ text. They all use the pointers |limit| and |loc| into
477the line of input currently being studied.
478
479@ Control codes in \.{CWEB}, which begin with `\.{@@}', are converted
480into a numeric code designed to simplify \.{CWEAVE}'s logic; for example,
481larger numbers are given to the control codes that denote more significant
482milestones, and the code of |new_section| should be the largest of
483all. Some of these numeric control codes take the place of |char|
484control codes that will not otherwise appear in the output of the
485scanning routines.
486@^ASCII code dependencies@>
487
488@d ignore 00 /* control code of no interest to \.{CWEAVE} */
489@d verbatim 02 /* takes the place of extended ASCII \.{\char2} */
490@d begin_short_comment 03 /* \CPLUSPLUS/ short comment */
491@d begin_comment '\t' /* tab marks will not appear */
492@d underline '\n' /* this code will be intercepted without confusion */
493@d noop 0177 /* takes the place of ASCII delete */
494@d xref_roman 0203 /* control code for `\.{@@\^}' */
495@d xref_wildcard 0204 /* control code for `\.{@@:}' */
496@d xref_typewriter 0205 /* control code for `\.{@@.}' */
497@d TeX_string 0206 /* control code for `\.{@@t}' */
498@f TeX_string TeX
499@d ord 0207 /* control code for `\.{@@'}' */
500@d join 0210 /* control code for `\.{@@\&}' */
501@d thin_space 0211 /* control code for `\.{@@,}' */
502@d math_break 0212 /* control code for `\.{@@\v}' */
503@d line_break 0213 /* control code for `\.{@@/}' */
504@d big_line_break 0214 /* control code for `\.{@@\#}' */
505@d no_line_break 0215 /* control code for `\.{@@+}' */
506@d pseudo_semi 0216 /* control code for `\.{@@;}' */
507@d macro_arg_open 0220 /* control code for `\.{@@[}' */
508@d macro_arg_close 0221 /* control code for `\.{@@]}' */
509@d trace 0222 /* control code for `\.{@@0}', `\.{@@1}' and `\.{@@2}' */
510@d translit_code 0223 /* control code for `\.{@@l}' */
511@d output_defs_code 0224 /* control code for `\.{@@h}' */
512@d format_code 0225 /* control code for `\.{@@f}' and `\.{@@s}' */
513@d definition 0226 /* control code for `\.{@@d}' */
514@d begin_C 0227 /* control code for `\.{@@c}' */
515@d section_name 0230 /* control code for `\.{@@<}' */
516@d new_section 0231 /* control code for `\.{@@\ }' and `\.{@@*}' */
517
518@ Control codes are converted to \.{CWEAVE}'s internal
519representation by means of the table |ccode|.
520
521@<Global...@>=
522eight_bits ccode[256]; /* meaning of a char following \.{@@} */
523
524@ @<Set ini...@>=
525{int c; for (c=0; c<256; c++) ccode[c]=0;}
526ccode[' ']=ccode['\t']=ccode['\n']=ccode['\v']=ccode['\r']=ccode['\f']
527 =ccode['*']=new_section;
528ccode['@@']='@@'; /* `quoted' at sign */
529ccode['=']=verbatim;
530ccode['d']=ccode['D']=definition;
531ccode['f']=ccode['F']=ccode['s']=ccode['S']=format_code;
532ccode['c']=ccode['C']=ccode['p']=ccode['P']=begin_C;
533ccode['t']=ccode['T']=TeX_string;
534ccode['l']=ccode['L']=translit_code;
535ccode['q']=ccode['Q']=noop;
536ccode['h']=ccode['H']=output_defs_code;
537ccode['&']=join; ccode['<']=ccode['(']=section_name;
538ccode['!']=underline; ccode['^']=xref_roman;
539ccode[':']=xref_wildcard; ccode['.']=xref_typewriter; ccode[',']=thin_space;
540ccode['|']=math_break; ccode['/']=line_break; ccode['#']=big_line_break;
541ccode['+']=no_line_break; ccode[';']=pseudo_semi;
542ccode['[']=macro_arg_open; ccode[']']=macro_arg_close;
543ccode['\'']=ord;
544@<Special control codes for debugging@>@;
545
546@ Users can write
547\.{@@2}, \.{@@1}, and \.{@@0} to turn tracing fully on, partly on,
548and off, respectively.
549
550@<Special control codes...@>=
551ccode['0']=ccode['1']=ccode['2']=trace;
552
553@ The |skip_limbo| routine is used on the first pass to skip through
554portions of the input that are not in any sections, i.e., that precede
555the first section. After this procedure has been called, the value of
556|input_has_ended| will tell whether or not a section has actually been found.
557
558There's a complication that we will postpone until later: If the \.{@@s}
559operation appears in limbo, we want to use it to adjust the default
560interpretation of identifiers.
561
562@<Predec...@>=
563void skip_limbo();
564
565@ @c
566void
567skip_limbo() {
568 while(1) {
569 if (loc>limit && get_line()==0) return;
570 *(limit+1)='@@';
571 while (*loc!='@@') loc++; /* look for '@@', then skip two chars */
572 if (loc++ <=limit) { int c=ccode[(eight_bits)*loc++];
573 if (c==new_section) return;
574 if (c==noop) skip_restricted();
575 else if (c==format_code) @<Process simple format in limbo@>;
576 }
577 }
578}
579
580@ The |skip_TeX| routine is used on the first pass to skip through
581the \TEX/ code at the beginning of a section. It returns the next
582control code or `\.{\v}' found in the input. A |new_section| is
583assumed to exist at the very end of the file.
584
585@f skip_TeX TeX
586
587@c
588unsigned
589skip_TeX() /* skip past pure \TEX/ code */
590{
591 while (1) {
592 if (loc>limit && get_line()==0) return(new_section);
593 *(limit+1)='@@';
594 while (*loc!='@@' && *loc!='|') loc++;
595 if (*loc++ =='|') return('|');
596 if (loc<=limit) return(ccode[(eight_bits)*(loc++)]);
597 }
598}
599
600@*1 Inputting the next token.
601As stated above, \.{CWEAVE}'s most interesting lexical scanning routine is the
602|get_next| function that inputs the next token of \CEE/ input. However,
603|get_next| is not especially complicated.
604
605The result of |get_next| is either a |char| code for some special character,
606or it is a special code representing a pair of characters (e.g., `\.{!=}'),
607or it is the numeric value computed by the |ccode|
608table, or it is one of the following special codes:
609
610\yskip\hang |identifier|: In this case the global variables |id_first| and
611|id_loc| will have been set to the beginning and ending-plus-one locations
612in the buffer, as required by the |id_lookup| routine.
613
614\yskip\hang |string|: The string will have been copied into the array
615|section_text|; |id_first| and |id_loc| are set as above (now they are
616pointers into |section_text|).
617
618\yskip\hang |constant|: The constant is copied into |section_text|, with
619slight modifications; |id_first| and |id_loc| are set.
620
621\yskip\noindent Furthermore, some of the control codes cause
622|get_next| to take additional actions:
623
624\yskip\hang |xref_roman|, |xref_wildcard|, |xref_typewriter|, |TeX_string|,
625|verbatim|: The values of |id_first| and |id_loc| will have been set to
626the beginning and ending-plus-one locations in the buffer.
627
628\yskip\hang |section_name|: In this case the global variable |cur_section| will
629point to the |byte_start| entry for the section name that has just been scanned.
630The value of |cur_section_char| will be |'('| if the section name was
631preceded by \.{@@(} instead of \.{@@<}.
632
633\yskip\noindent If |get_next| sees `\.{@@!}'
634it sets |xref_switch| to |def_flag| and goes on to the next token.
635
636@d constant 0200 /* \CEE/ constant */
637@d string 0201 /* \CEE/ string */
638@d identifier 0202 /* \CEE/ identifier or reserved word */
639
640@<Global...@>=
641name_pointer cur_section; /* name of section just scanned */
642char cur_section_char; /* the character just before that name */
643
644@ @<Include...@>=
645#include <ctype.h> /* definition of |isalpha|, |isdigit| and so on */
646#include <stdlib.h> /* definition of |exit| */
647
648@ As one might expect, |get_next| consists mostly of a big switch
649that branches to the various special cases that can arise.
650
651@d isxalpha(c) ((c)=='_') /* non-alpha character allowed in identifier */
652@d ishigh(c) ((eight_bits)(c)>0177)
653@^high-bit character handling@>
654
655@<Predecl...@>=
656eight_bits get_next();
657
658@ @c
659eight_bits
660get_next() /* produces the next input token */
661{@+eight_bits c; /* the current character */
662 while (1) {
663 @<Check if we're at the end of a preprocessor command@>;
664 if (loc>limit && get_line()==0) return(new_section);
665 c=*(loc++);
666 if (xisdigit(c) || c=='\\' || c=='.') @<Get a constant@>@;
667 else if (c=='\'' || c=='"' || (c=='L'&&(*loc=='\'' || *loc=='"'))@|
668 || (c=='<' && sharp_include_line==1))
669 @<Get a string@>@;
670 else if (xisalpha(c) || isxalpha(c) || ishigh(c))
671 @<Get an identifier@>@;
672 else if (c=='@@') @<Get control code and possible section name@>@;
673 else if (xisspace(c)) continue; /* ignore spaces and tabs */
674 if (c=='#' && loc==buffer+1) @<Raise preprocessor flag@>;
675 mistake: @<Compress two-symbol operator@>@;
676 return(c);
677 }
678}
679
680@ Because preprocessor commands do not fit in with the rest of the syntax
681of \CEE/,
682we have to deal with them separately. One solution is to enclose such
683commands between special markers. Thus, when a \.\# is seen as the
684first character of a line, |get_next| returns a special code
685|left_preproc| and raises a flag |preprocessing|.
686
687We can use the same internal code number for |left_preproc| as we do
688for |ord|, since |get_next| changes |ord| into a string.
689
690@d left_preproc ord /* begins a preprocessor command */
691@d right_preproc 0217 /* ends a preprocessor command */
692
693@<Glob...@>=
694boolean preprocessing=0; /* are we scanning a preprocessor command? */
695
696@ @<Raise prep...@>= {
697 preprocessing=1;
698 @<Check if next token is |include|@>;
699 return (left_preproc);
700}
701
702@ An additional complication is the freakish use of \.< and \.> to delimit
703a file name in lines that start with \.{\#include}. We must treat this file
704name as a string.
705
706@<Glob...@>=
707boolean sharp_include_line=0; /* are we scanning a |#include| line? */
708
709@ @<Check if next token is |include|@>=
710while (loc<=buffer_end-7 && xisspace(*loc)) loc++;
711if (loc<=buffer_end-6 && strncmp(loc,"include",7)==0) sharp_include_line=1;
712
713@ When we get to the end of a preprocessor line,
714we lower the flag and send a code |right_preproc|, unless
715the last character was a \.\\.
716
717@<Check if we're at...@>=
718 while (loc==limit-1 && preprocessing && *loc=='\\')
719 if (get_line()==0) return(new_section); /* still in preprocessor mode */
720 if (loc>=limit && preprocessing) {
721 preprocessing=sharp_include_line=0;
722 return(right_preproc);
723 }
724
725@ The following code assigns values to the combinations \.{++},
726\.{--}, \.{->}, \.{>=}, \.{<=}, \.{==}, \.{<<}, \.{>>}, \.{!=}, \.{\v\v}, and
727\.{\&\&}, and to the \CPLUSPLUS/
728combinations \.{...}, \.{::}, \.{.*} and \.{->*}.
729The compound assignment operators (e.g., \.{+=}) are
730treated as separate tokens.
731
732@d compress(c) if (loc++<=limit) return(c)
733
734@<Compress tw...@>=
735switch(c) {
736 case '/': if (*loc=='*') {compress(begin_comment);}
737 else if (*loc=='/') compress(begin_short_comment); break;
738 case '+': if (*loc=='+') compress(plus_plus); break;
739 case '-': if (*loc=='-') {compress(minus_minus);}
740 else if (*loc=='>') if (*(loc+1)=='*') {loc++; compress(minus_gt_ast);}
741 else compress(minus_gt); break;
742 case '.': if (*loc=='*') {compress(period_ast);}
743 else if (*loc=='.' && *(loc+1)=='.') {
744 loc++; compress(dot_dot_dot);
745 }
746 break;
747 case ':': if (*loc==':') compress(colon_colon); break;
748 case '=': if (*loc=='=') compress(eq_eq); break;
749 case '>': if (*loc=='=') {compress(gt_eq);}
750 else if (*loc=='>') compress(gt_gt); break;
751 case '<': if (*loc=='=') {compress(lt_eq);}
752 else if (*loc=='<') compress(lt_lt); break;
753 case '&': if (*loc=='&') compress(and_and); break;
754 case '|': if (*loc=='|') compress(or_or); break;
755 case '!': if (*loc=='=') compress(not_eq); break;
756}
757
758@ @<Get an identifier@>= {
759 id_first=--loc;
760 while (isalpha(*++loc) || isdigit(*loc) || isxalpha(*loc) || ishigh(*loc));
761 id_loc=loc; return(identifier);
762}
763
764@ Different conventions are followed by \TEX/ and \CEE/ to express octal
765and hexadecimal numbers; it is reasonable to stick to each convention
766within its realm. Thus the \CEE/ part of a \.{CWEB} file has octals
767introduced by \.0 and hexadecimals by \.{0x}, but \.{CWEAVE} will print
768in italics or typewriter font, respectively, and introduced by single
769or double quotes. In order to simplify the \TEX/ macro used to print
770such constants, we replace some of the characters.
771
772Notice that in this section and the next, |id_first| and |id_loc|
773are pointers into the array |section_text|, not into |buffer|.
774
775@<Get a constant@>= {
776 id_first=id_loc=section_text+1;
777 if (*(loc-1)=='\\') {*id_loc++='~';
778 while (xisdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
779 else if (*(loc-1)=='0') {
780 if (*loc=='x' || *loc=='X') {*id_loc++='^'; loc++;
781 while (xisxdigit(*loc)) *id_loc++=*loc++;} /* hex constant */
782 else if (xisdigit(*loc)) {*id_loc++='~';
783 while (xisdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
784 else goto dec; /* decimal constant */
785 }
786 else { /* decimal constant */
787 if (*(loc-1)=='.' && !xisdigit(*loc)) goto mistake; /* not a constant */
788 dec: *id_loc++=*(loc-1);
789 while (xisdigit(*loc) || *loc=='.') *id_loc++=*loc++;
790 if (*loc=='e' || *loc=='E') { /* float constant */
791 *id_loc++='_'; loc++;
792 if (*loc=='+' || *loc=='-') *id_loc++=*loc++;
793 while (xisdigit(*loc)) *id_loc++=*loc++;
794 }
795 }
796 while (*loc=='u' || *loc=='U' || *loc=='l' || *loc=='L'
797 || *loc=='f' || *loc=='F') {
798 *id_loc++='$'; *id_loc++=toupper(*loc++);
799 }
800 return(constant);
801}
802
803@ \CEE/ strings and character constants, delimited by double and single
804quotes, respectively, can contain newlines or instances of their own
805delimiters if they are protected by a backslash. We follow this
806convention, but do not allow the string to be longer than |longest_name|.
807
808@<Get a string@>= {
809 char delim = c; /* what started the string */
810 id_first = section_text+1;
811 id_loc = section_text;
812 if (delim=='\'' && *(loc-2)=='@@') {*++id_loc='@@'; *++id_loc='@@';}
813 *++id_loc=delim;
814 if (delim=='L') { /* wide character constant */
815 delim=*loc++; *++id_loc=delim;
816 }
817 if (delim=='<') delim='>'; /* for file names in |#include| lines */
818 while (1) {
819 if (loc>=limit) {
820 if(*(limit-1)!='\\') {
821 err_print("! String didn't end"); loc=limit; break;
822@.String didn't end@>
823 }
824 if(get_line()==0) {
825 err_print("! Input ended in middle of string"); loc=buffer; break;
826@.Input ended in middle of string@>
827 }
828 }
829 if ((c=*loc++)==delim) {
830 if (++id_loc<=section_text_end) *id_loc=c;
831 break;
832 }
833 if (c=='\\') if (loc>=limit) continue;
834 else if (++id_loc<=section_text_end) {
835 *id_loc = '\\'; c=*loc++;
836 }
837 if (++id_loc<=section_text_end) *id_loc=c;
838 }
839 if (id_loc>=section_text_end) {
840 printf("\n! String too long: ");
841@.String too long@>
842 term_write(section_text+1,25);
843 printf("..."); mark_error;
844 }
845 id_loc++;
846 return(string);
847}
848
849@ After an \.{@@} sign has been scanned, the next character tells us
850whether there is more work to do.
851
852@<Get control code and possible section name@>= {
853 c=*loc++;
854 switch(ccode[(eight_bits)c]) {
855 case translit_code: err_print("! Use @@l in limbo only"); continue;
856@.Use @@l in limbo...@>
857 case underline: xref_switch=def_flag; continue;
858 case trace: tracing=c-'0'; continue;
859 case xref_roman: case xref_wildcard: case xref_typewriter:
860 case noop: case TeX_string: c=ccode[c]; skip_restricted(); return(c);
861 case section_name:
862 @<Scan the section name and make |cur_section| point to it@>;
863 case verbatim: @<Scan a verbatim string@>;
864 case ord: @<Get a string@>;
865 default: return(ccode[(eight_bits)c]);
866 }
867}
868
869@ The occurrence of a section name sets |xref_switch| to zero,
870because the section name might (for example) follow \&{int}.
871
872@<Scan the section name...@>= {
873 char *k; /* pointer into |section_text| */
874 cur_section_char=*(loc-1);
875 @<Put section name into |section_text|@>;
876 if (k-section_text>3 && strncmp(k-2,"...",3)==0)
877 cur_section=section_lookup(section_text+1,k-3,1); /* 1 indicates a prefix */
878 else cur_section=section_lookup(section_text+1,k,0);
879 xref_switch=0; return(section_name);
880}
881
882@ Section names are placed into the |section_text| array with consecutive spaces,
883tabs, and carriage-returns replaced by single spaces. There will be no
884spaces at the beginning or the end. (We set |section_text[0]=' '| to facilitate
885this, since the |section_lookup| routine uses |section_text[1]| as the first
886character of the name.)
887
888@<Set init...@>=section_text[0]=' ';
889
890@ @<Put section name...@>=
891k=section_text;
892while (1) {
893 if (loc>limit && get_line()==0) {
894 err_print("! Input ended in section name");
895@.Input ended in section name@>
896 loc=buffer+1; break;
897 }
898 c=*loc;
899 @<If end of name or erroneous control code, |break|@>;
900 loc++; if (k<section_text_end) k++;
901 if (xisspace(c)) {
902 c=' '; if (*(k-1)==' ') k--;
903 }
904*k=c;
905}
906if (k>=section_text_end) {
907 printf("\n! Section name too long: ");
908@.Section name too long@>
909 term_write(section_text+1,25);
910 printf("..."); mark_harmless;
911}
912if (*k==' ' && k>section_text) k--;
913
914@ @<If end of name...@>=
915if (c=='@@') {
916 c=*(loc+1);
917 if (c=='>') {
918 loc+=2; break;
919 }
920 if (ccode[(eight_bits)c]==new_section) {
921 err_print("! Section name didn't end"); break;
922@.Section name didn't end@>
923 }
924 if (c!='@@') {
925 err_print("! Control codes are forbidden in section name"); break;
926@.Control codes are forbidden...@>
927 }
928 *(++k)='@@'; loc++; /* now |c==*loc| again */
929}
930
931@ This function skips over a restricted context at relatively high speed.
932
933@<Predecl...@>=
934void skip_restricted();
935
936@ @c
937void
938skip_restricted()
939{
940 id_first=loc; *(limit+1)='@@';
941false_alarm:
942 while (*loc!='@@') loc++;
943 id_loc=loc;
944 if (loc++>limit) {
945 err_print("! Control text didn't end"); loc=limit;
946@.Control text didn't end@>
947 }
948 else {
949 if (*loc=='@@'&&loc<=limit) {loc++; goto false_alarm;}
950 if (*loc++!='>')
951 err_print("! Control codes are forbidden in control text");
952@.Control codes are forbidden...@>
953 }
954}
955
956@ At the present point in the program we
957have |*(loc-1)==verbatim|; we set |id_first| to the beginning
958of the string itself, and |id_loc| to its ending-plus-one location in the
959buffer. We also set |loc| to the position just after the ending delimiter.
960
961@<Scan a verbatim string@>= {
962 id_first=loc++; *(limit+1)='@@'; *(limit+2)='>';
963 while (*loc!='@@' || *(loc+1)!='>') loc++;
964 if (loc>=limit) err_print("! Verbatim string didn't end");
965@.Verbatim string didn't end@>
966 id_loc=loc; loc+=2;
967 return (verbatim);
968}
969
970@** Phase one processing.
971We now have accumulated enough subroutines to make it possible to carry out
972\.{CWEAVE}'s first pass over the source file. If everything works right,
973both phase one and phase two of \.{CWEAVE} will assign the same numbers to
974sections, and these numbers will agree with what \.{CTANGLE} does.
975
976The global variable |next_control| often contains the most recent output of
977|get_next|; in interesting cases, this will be the control code that
978ended a section or part of a section.
979
980@<Global...@>=
981eight_bits next_control; /* control code waiting to be acting upon */
982
983@ The overall processing strategy in phase one has the following
984straightforward outline.
985
986@<Predecl...@>=
987void phase_one();
988
989@ @c
990void
991phase_one() {
992 phase=1; reset_input(); section_count=0;
993 skip_limbo(); change_exists=0;
994 while (!input_has_ended)
995 @<Store cross-reference data for the current section@>;
996 changed_section[section_count]=change_exists;
997 /* the index changes if anything does */
998 phase=2; /* prepare for second phase */
999 @<Print error messages about unused or undefined section names@>;
1000}
1001
1002@ @<Store cross-reference data...@>=
1003{
1004 if (++section_count==max_sections) overflow("section number");
1005 changed_section[section_count]=changing;
1006 /* it will become 1 if any line changes */
1007 if (*(loc-1)=='*' && show_progress) {
1008 printf("*%d",section_count);
1009 update_terminal; /* print a progress report */
1010 }
1011 @<Store cross-references in the \TEX/ part of a section@>;
1012 @<Store cross-references in the definition part of a section@>;
1013 @<Store cross-references in the \CEE/ part of a section@>;
1014 if (changed_section[section_count]) change_exists=1;
1015}
1016
1017@ The |C_xref| subroutine stores references to identifiers in
1018\CEE/ text material beginning with the current value of |next_control|
1019and continuing until |next_control| is `\.\{' or `\.{\v}', or until the next
1020``milestone'' is passed (i.e., |next_control>=format_code|). If
1021|next_control>=format_code| when |C_xref| is called, nothing will happen;
1022but if |next_control=='|'| upon entry, the procedure assumes that this is
1023the `\.{\v}' preceding \CEE/ text that is to be processed.
1024
1025The parameter |spec_ctrl| is used to change this behavior. In most cases
1026|C_xref| is called with |spec_ctrl==ignore|, which triggers the default
1027processing described above. If |spec_ctrl==section_name|, section names will
1028be gobbled. This is used when \CEE/ text in the \TEX/ part or inside comments
1029is parsed: It allows for section names to appear in \pb, but these
1030strings will not be entered into the cross reference lists since they are not
1031definitions of section names.
1032
1033The program uses the fact that our internal code numbers satisfy
1034the relations |xref_roman==identifier+roman| and |xref_wildcard==identifier
1035+wildcard| and |xref_typewriter==identifier+typewriter| and |normal==0|.
1036
1037@<Predecl...@>=
1038void C_xref();
1039
1040@ @c
1041void
1042C_xref( spec_ctrl ) /* makes cross-references for \CEE/ identifiers */
1043 eight_bits spec_ctrl;
1044{
1045 name_pointer p; /* a referenced name */
1046 while (next_control<format_code || next_control==spec_ctrl) {
1047 if (next_control>=identifier && next_control<=xref_typewriter) {
1048 if (next_control>identifier) @<Replace |"@@@@"| by |"@@"| @>@;
1049 p=id_lookup(id_first, id_loc,next_control-identifier); new_xref(p);
1050 }
1051 if (next_control==section_name) {
1052 section_xref_switch=cite_flag;
1053 new_section_xref(cur_section);
1054 }
1055 next_control=get_next();
1056 if (next_control=='|' || next_control==begin_comment ||
1057 next_control==begin_short_comment) return;
1058 }
1059}
1060
1061@ The |outer_xref| subroutine is like |C_xref| except that it begins
1062with |next_control!='|'| and ends with |next_control>=format_code|. Thus, it
1063handles \CEE/ text with embedded comments.
1064
1065@<Predecl...@>=
1066void outer_xref();
1067
1068@ @c
1069void
1070outer_xref() /* extension of |C_xref| */
1071{
1072 int bal; /* brace level in comment */
1073 while (next_control<format_code)
1074 if (next_control!=begin_comment && next_control!=begin_short_comment)
1075 C_xref(ignore);
1076 else {
1077 boolean is_long_comment=(next_control==begin_comment);
1078 bal=copy_comment(is_long_comment,1); next_control='|';
1079 while (bal>0) {
1080 C_xref(section_name); /* do not reference section names in comments */
1081 if (next_control=='|') bal=copy_comment(is_long_comment,bal);
1082 else bal=0; /* an error message will occur in phase two */
1083 }
1084 }
1085}
1086
1087@ In the \TEX/ part of a section, cross-reference entries are made only for
1088the identifiers in \CEE/ texts enclosed in \pb, or for control texts
1089enclosed in \.{@@\^}$\,\ldots\,$\.{@@>} or \.{@@.}$\,\ldots\,$\.{@@>}
1090or \.{@@:}$\,\ldots\,$\.{@@>}.
1091
1092@<Store cross-references in the \T...@>=
1093while (1) {
1094 switch (next_control=skip_TeX()) {
1095 case translit_code: err_print("! Use @@l in limbo only"); continue;
1096@.Use @@l in limbo...@>
1097 case underline: xref_switch=def_flag; continue;
1098 case trace: tracing=*(loc-1)-'0'; continue;
1099 case '|': C_xref(section_name); break;
1100 case xref_roman: case xref_wildcard: case xref_typewriter:
1101 case noop: case section_name:
1102 loc-=2; next_control=get_next(); /* scan to \.{@@>} */
1103 if (next_control>=xref_roman && next_control<=xref_typewriter) {
1104 @<Replace |"@@@@"| by |"@@"| @>@;
1105 new_xref(id_lookup(id_first, id_loc,next_control-identifier));
1106 }
1107 break;
1108 }
1109 if (next_control>=format_code) break;
1110}
1111
1112@ @<Replace |"@@@@"| by |"@@"| @>=
1113{
1114 char *src=id_first,*dst=id_first;
1115 while(src<id_loc){
1116 if(*src=='@@') src++;
1117 *dst++=*src++;
1118 }
1119 id_loc=dst;
1120 while (dst<src) *dst++=' '; /* clean up in case of error message display */
1121}
1122
1123@ During the definition and \CEE/ parts of a section, cross-references
1124are made for all identifiers except reserved words. However, the right
1125identifier in a format definition is not referenced, and the left
1126identifier is referenced only if it has been explicitly
1127underlined (preceded by \.{@@!}).
1128The \TEX/ code in comments is, of course, ignored, except for
1129\CEE/ portions enclosed in \pb; the text of a section name is skipped
1130entirely, even if it contains \pb\ constructions.
1131
1132The variables |lhs| and |rhs| point to the respective identifiers involved
1133in a format definition.
1134
1135@<Global...@>=
1136name_pointer lhs, rhs; /* pointers to |byte_start| for format identifiers */
1137
1138@ When we get to the following code we have |next_control>=format_code|.
1139
1140@<Store cross-references in the d...@>=
1141while (next_control<=definition) { /* |format_code| or |definition| */
1142 if (next_control==definition) {
1143 xref_switch=def_flag; /* implied \.{@@!} */
1144 next_control=get_next();
1145 } else @<Process a format definition@>;
1146 outer_xref();
1147}
1148
1149@ Error messages for improper format definitions will be issued in phase
1150two. Our job in phase one is to define the |ilk| of a properly formatted
1151identifier, and to remove cross-references to identifiers that we now
1152discover should be unindexed.
1153
1154@<Process a form...@>= {
1155 next_control=get_next();
1156 if (next_control==identifier) {
1157 lhs=id_lookup(id_first, id_loc,normal); lhs->ilk=normal;
1158 if (xref_switch) new_xref(lhs);
1159 next_control=get_next();
1160 if (next_control==identifier) {
1161 rhs=id_lookup(id_first, id_loc,normal);
1162 lhs->ilk=rhs->ilk;
1163 if (unindexed(lhs)) { /* retain only underlined entries */
1164 xref_pointer q,r=NULL;
1165 for (q=(xref_pointer)lhs->xref;q>xmem;q=q->xlink)
1166 if (q->num<def_flag)
1167 if (r) r->xlink=q->xlink;
1168 else lhs->xref=(char*)q->xlink;
1169 else r=q;
1170 }
1171 next_control=get_next();
1172 }
1173 }
1174}
1175
1176@ A much simpler processing of format definitions occurs when the
1177definition is found in limbo.
1178
1179@<Process simple format in limbo@>=
1180{
1181 if (get_next()!=identifier)
1182 err_print("! Missing left identifier of @@s");
1183@.Missing left identifier...@>
1184 else {
1185 lhs=id_lookup(id_first,id_loc,normal);
1186 if (get_next()!=identifier)
1187 err_print("! Missing right identifier of @@s");
1188@.Missing right identifier...@>
1189 else {
1190 rhs=id_lookup(id_first,id_loc,normal);
1191 lhs->ilk=rhs->ilk;
1192 }
1193 }
1194}
1195
1196@ Finally, when the \TEX/ and definition parts have been treated, we have
1197|next_control>=begin_C|.
1198
1199@<Store cross-references in the \CEE/...@>=
1200if (next_control<=section_name) { /* |begin_C| or |section_name| */
1201 if (next_control==begin_C) section_xref_switch=0;
1202 else {
1203 section_xref_switch=def_flag;
1204 if(cur_section_char=='(' && cur_section!=name_dir)
1205 set_file_flag(cur_section);
1206 }
1207 do {
1208 if (next_control==section_name && cur_section!=name_dir)
1209 new_section_xref(cur_section);
1210 next_control=get_next(); outer_xref();
1211 } while ( next_control<=section_name);
1212}
1213
1214@ After phase one has looked at everything, we want to check that each
1215section name was both defined and used. The variable |cur_xref| will point
1216to cross-references for the current section name of interest.
1217
1218@<Global...@>=
1219xref_pointer cur_xref; /* temporary cross-reference pointer */
1220boolean an_output; /* did |file_flag| precede |cur_xref|? */
1221
1222@ The following recursive procedure
1223walks through the tree of section names and prints out anomalies.
1224@^recursion@>
1225
1226@<Predecl...@>=
1227void section_check();
1228
1229@ @c
1230void
1231section_check(p)
1232name_pointer p; /* print anomalies in subtree |p| */
1233{
1234 if (p) {
1235 section_check(p->llink);
1236 cur_xref=(xref_pointer)p->xref;
1237 if (cur_xref->num==file_flag) {an_output=1; cur_xref=cur_xref->xlink;}
1238 else an_output=0;
1239 if (cur_xref->num <def_flag) {
1240 printf("\n! Never defined: <"); print_section_name(p); putchar('>'); mark_harmless;
1241@.Never defined: <section name>@>
1242 }
1243 while (cur_xref->num >=cite_flag) cur_xref=cur_xref->xlink;
1244 if (cur_xref==xmem && !an_output) {
1245 printf("\n! Never used: <"); print_section_name(p); putchar('>'); mark_harmless;
1246@.Never used: <section name>@>
1247 }
1248 section_check(p->rlink);
1249 }
1250}
1251
1252@ @<Print error messages about un...@>=section_check(root)
1253
1254@* Low-level output routines.
1255The \TEX/ output is supposed to appear in lines at most |line_length|
1256characters long, so we place it into an output buffer. During the output
1257process, |out_line| will hold the current line number of the line about to
1258be output.
1259
1260@<Global...@>=
1261char out_buf[line_length+1]; /* assembled characters */
1262char *out_ptr; /* just after last character in |out_buf| */
1263char *out_buf_end = out_buf+line_length; /* end of |out_buf| */
1264int out_line; /* number of next line to be output */
1265
1266@ The |flush_buffer| routine empties the buffer up to a given breakpoint,
1267and moves any remaining characters to the beginning of the next line.
1268If the |per_cent| parameter is 1 a |'%'| is appended to the line
1269that is being output; in this case the breakpoint |b| should be strictly
1270less than |out_buf_end|. If the |per_cent| parameter is |0|,
1271trailing blanks are suppressed.
1272The characters emptied from the buffer form a new line of output;
1273if the |carryover| parameter is true, a |"%"| in that line will be
1274carried over to the next line (so that \TEX/ will ignore the completion
1275of commented-out text).
1276
1277@d c_line_write(c) fflush(active_file),fwrite(out_buf+1,sizeof(char),c,active_file)
1278@d tex_putc(c) putc(c,active_file)
1279@d tex_new_line putc('\n',active_file)
1280@d tex_printf(c) fprintf(active_file,c)
1281
1282@c
1283void
1284flush_buffer(b,per_cent,carryover)
1285char *b; /* outputs from |out_buf+1| to |b|,where |b<=out_ptr| */
1286boolean per_cent,carryover;
1287{
1288 char *j; j=b; /* pointer into |out_buf| */
1289 if (! per_cent) /* remove trailing blanks */
1290 while (j>out_buf && *j==' ') j--;
1291 c_line_write(j-out_buf);
1292 if (per_cent) tex_putc('%');
1293 tex_new_line; out_line++;
1294 if (carryover)
1295 while (j>out_buf)
1296 if (*j--=='%' && (j==out_buf || *j!='\\')) {
1297 *b--='%'; break;
1298 }
1299 if (b<out_ptr) strncpy(out_buf+1,b+1,out_ptr-b);
1300 out_ptr-=b-out_buf;
1301}
1302
1303@ When we are copying \TEX/ source material, we retain line breaks
1304that occur in the input, except that an empty line is not
1305output when the \TEX/ source line was nonempty. For example, a line
1306of the \TEX/ file that contains only an index cross-reference entry
1307will not be copied. The |finish_line| routine is called just before
1308|get_line| inputs a new line, and just after a line break token has
1309been emitted during the output of translated \CEE/ text.
1310
1311@c
1312void
1313finish_line() /* do this at the end of a line */
1314{
1315 char *k; /* pointer into |buffer| */
1316 if (out_ptr>out_buf) flush_buffer(out_ptr,0,0);
1317 else {
1318 for (k=buffer; k<=limit; k++)
1319 if (!(xisspace(*k))) return;
1320 flush_buffer(out_buf,0,0);
1321 }
1322}
1323
1324@ In particular, the |finish_line| procedure is called near the very
1325beginning of phase two. We initialize the output variables in a slightly
1326tricky way so that the first line of the output file will be
1327`\.{\\input cwebmac}'.
1328
1329@<Set init...@>=
1330out_ptr=out_buf+1; out_line=1; active_file=tex_file;
1331*out_ptr='c'; tex_printf("\\input cwebma");
1332
1333@ When we wish to append one character |c| to the output buffer, we write
1334`|out(c)|'; this will cause the buffer to be emptied if it was already
1335full. If we want to append more than one character at once, we say
1336|out_str(s)|, where |s| is a string containing the characters.
1337
1338A line break will occur at a space or after a single-nonletter
1339\TEX/ control sequence.
1340
1341@d out(c) {if (out_ptr>=out_buf_end) break_out(); *(++out_ptr)=c;}
1342
1343@c
1344void
1345out_str(s) /* output characters from |s| to end of string */
1346char *s;
1347{
1348 while (*s) out(*s++);
1349}
1350
1351@ The |break_out| routine is called just before the output buffer is about
1352to overflow. To make this routine a little faster, we initialize position
13530 of the output buffer to `\.\\'; this character isn't really output.
1354
1355@<Set init...@>=
1356out_buf[0]='\\';
1357
1358@ A long line is broken at a blank space or just before a backslash that isn't
1359preceded by another backslash. In the latter case, a |'%'| is output at
1360the break.
1361
1362@<Predecl...@>=
1363void break_out();
1364
1365@ @c
1366void
1367break_out() /* finds a way to break the output line */
1368{
1369 char *k=out_ptr; /* pointer into |out_buf| */
1370 while (1) {
1371 if (k==out_buf) @<Print warning message, break the line, |return|@>;
1372 if (*k==' ') {
1373 flush_buffer(k,0,1); return;
1374 }
1375 if (*(k--)=='\\' && *k!='\\') { /* we've decreased |k| */
1376 flush_buffer(k,1,1); return;
1377 }
1378 }
1379}
1380
1381@ We get to this section only in the unusual case that the entire output line
1382consists of a string of backslashes followed by a string of nonblank
1383non-backslashes. In such cases it is almost always safe to break the
1384line by putting a |'%'| just before the last character.
1385
1386@<Print warning message...@>=
1387{
1388 printf("\n! Line had to be broken (output l. %d):\n",out_line);
1389@.Line had to be broken@>
1390 term_write(out_buf+1, out_ptr-out_buf-1);
1391 new_line; mark_harmless;
1392 flush_buffer(out_ptr-1,1,1); return;
1393}
1394
1395@ Here is a macro that outputs a section number in decimal notation.
1396The number to be converted by |out_section| is known to be less than
1397|def_flag|, so it cannot have more than five decimal digits. If
1398the section is changed, we output `\.{\\*}' just after the number.
1399
1400@c
1401void
1402out_section(n)
1403sixteen_bits n;
1404{
1405 char s[6];
1406 sprintf(s,"%d",n); out_str(s);
1407 if(changed_section[n]) out_str ("\\*");
1408@.\\*@>
1409}
1410
1411@ The |out_name| procedure is used to output an identifier or index
1412entry, enclosing it in braces.
1413
1414@c
1415void
1416out_name(p)
1417name_pointer p;
1418{
1419 char *k, *k_end=(p+1)->byte_start; /* pointers into |byte_mem| */
1420 out('{');
1421 for (k=p->byte_start; k<k_end; k++) {
1422 if (isxalpha(*k)) out('\\');
1423 out(*k);
1424 }
1425 out('}');
1426}
1427
1428@* Routines that copy \TEX/ material.
1429During phase two, we use subroutines |copy_limbo|, |copy_TeX|, and
1430|copy_comment| in place of the analogous |skip_limbo|, |skip_TeX|, and
1431|skip_comment| that were used in phase one. (Well, |copy_comment|
1432was actually written in such a way that it functions as |skip_comment|
1433in phase one.)
1434
1435The |copy_limbo| routine, for example, takes \TEX/ material that is not
1436part of any section and transcribes it almost verbatim to the output file.
1437The use of `\.{@@}' signs is severely restricted in such material:
1438`\.{@@@@}' pairs are replaced by singletons; `\.{@@l}' and `\.{@@q}' and
1439`\.{@@s}' are interpreted.
1440
1441@c
1442void
1443copy_limbo()
1444{
1445 char c;
1446 while (1) {
1447 if (loc>limit && (finish_line(), get_line()==0)) return;
1448 *(limit+1)='@@';
1449 while (*loc!='@@') out(*(loc++));
1450 if (loc++<=limit) {
1451 c=*loc++;
1452 if (ccode[(eight_bits)c]==new_section) break;
1453 switch (ccode[(eight_bits)c]) {
1454 case translit_code: out_str("\\ATL"); break;
1455@.\\ATL@>
1456 case '@@': out('@@'); break;
1457 case noop: skip_restricted(); break;
1458 case format_code: if (get_next()==identifier) get_next();
1459 if (loc>=limit) get_line(); /* avoid blank lines in output */
1460 break; /* the operands of \.{@@s} are ignored on this pass */
1461 default: err_print("! Double @@ should be used in limbo");
1462@.Double @@ should be used...@>
1463 out('@@');
1464 }
1465 }
1466 }
1467}
1468
1469@ The |copy_TeX| routine processes the \TEX/ code at the beginning of a
1470section; for example, the words you are now reading were copied in this
1471way. It returns the next control code or `\.{\v}' found in the input.
1472We don't copy spaces or tab marks into the beginning of a line. This
1473makes the test for empty lines in |finish_line| work.
1474
1475@ @f copy_TeX TeX
1476@c
1477eight_bits
1478copy_TeX()
1479{
1480 char c; /* current character being copied */
1481 while (1) {
1482 if (loc>limit && (finish_line(), get_line()==0)) return(new_section);
1483 *(limit+1)='@@';
1484 while ((c=*(loc++))!='|' && c!='@@') {
1485 out(c);
1486 if (out_ptr==out_buf+1 && (xisspace(c))) out_ptr--;
1487 }
1488 if (c=='|') return('|');
1489 if (loc<=limit) return(ccode[(eight_bits)*(loc++)]);
1490 }
1491}
1492
1493@ The |copy_comment| function issues a warning if more braces are opened than
1494closed, and in the case of a more serious error it supplies enough
1495braces to keep \TEX/ from complaining about unbalanced braces.
1496Instead of copying the \TEX/ material
1497into the output buffer, this function copies it into the token memory
1498(in phase two only).
1499The abbreviation |app_tok(t)| is used to append token |t| to the current
1500token list, and it also makes sure that it is possible to append at least
1501one further token without overflow.
1502
1503@d app_tok(c) {if (tok_ptr+2>tok_mem_end) overflow("token"); *(tok_ptr++)=c;}
1504
1505@<Predec...@>=
1506int copy_comment();
1507
1508@ @c
1509int copy_comment(is_long_comment,bal) /* copies \TEX/ code in comments */
1510boolean is_long_comment; /* is this a traditional \CEE/ comment? */
1511int bal; /* brace balance */
1512{
1513 char c; /* current character being copied */
1514 while (1) {
1515 if (loc>limit) {
1516 if (is_long_comment) {
1517 if (get_line()==0) {
1518 err_print("! Input ended in mid-comment");
1519@.Input ended in mid-comment@>
1520 loc=buffer+1; goto done;
1521 }
1522 }
1523 else {
1524 if (bal>1) err_print("! Missing } in comment");
1525@.Missing \} in comment@>
1526 goto done;
1527 }
1528 }
1529 c=*(loc++);
1530 if (c=='|') return(bal);
1531 if (is_long_comment) @<Check for end of comment@>;
1532 if (phase==2) {
1533 if (ishigh(c)) app_tok(quoted_char);
1534 app_tok(c);
1535 }
1536 @<Copy special things when |c=='@@', '\\'|@>;
1537 if (c=='{') bal++;
1538 else if (c=='}') {
1539 if(bal>1) bal--;
1540 else {err_print("! Extra } in comment");
1541@.Extra \} in comment@>
1542 if (phase==2) tok_ptr--;
1543 }
1544 }
1545 }
1546done:@<Clear |bal| and |return|@>;
1547}
1548
1549@ @<Check for end of comment@>=
1550if (c=='*' && *loc=='/') {
1551 loc++;
1552 if (bal>1) err_print("! Missing } in comment");
1553@.Missing \} in comment@>
1554 goto done;
1555}
1556
1557@ @<Copy special things when |c=='@@'...@>=
1558if (c=='@@') {
1559 if (*(loc++)!='@@') {
1560 err_print("! Illegal use of @@ in comment");
1561@.Illegal use of @@...@>
1562 loc-=2; if (phase==2) *(tok_ptr-1)=' '; goto done;
1563 }
1564}
1565else if (c=='\\' && *loc!='@@')
1566 if (phase==2) app_tok(*(loc++)) else loc++;
1567
1568@ We output
1569enough right braces to keep \TEX/ happy.
1570
1571@<Clear |bal|...@>=
1572if (phase==2) while (bal-- >0) app_tok('}');
1573return(0);
1574
1575@** Parsing.
1576The most intricate part of \.{CWEAVE} is its mechanism for converting
1577\CEE/-like code into \TEX/ code, and we might as well plunge into this
1578aspect of the program now. A ``bottom up'' approach is used to parse the
1579\CEE/-like material, since \.{CWEAVE} must deal with fragmentary
1580constructions whose overall ``part of speech'' is not known.
1581
1582At the lowest level, the input is represented as a sequence of entities
1583that we shall call {\it scraps}, where each scrap of information consists
1584of two parts, its {\it category} and its {\it translation}. The category
1585is essentially a syntactic class, and the translation is a token list that
1586represents \TEX/ code. Rules of syntax and semantics tell us how to
1587combine adjacent scraps into larger ones, and if we are lucky an entire
1588\CEE/ text that starts out as hundreds of small scraps will join
1589together into one gigantic scrap whose translation is the desired \TEX/
1590code. If we are unlucky, we will be left with several scraps that don't
1591combine; their translations will simply be output, one by one.
1592
1593The combination rules are given as context-sensitive productions that are
1594applied from left to right. Suppose that we are currently working on the
1595sequence of scraps $s_1\,s_2\ldots s_n$. We try first to find the longest
1596production that applies to an initial substring $s_1\,s_2\ldots\,$; but if
1597no such productions exist, we find to find the longest production
1598applicable to the next substring $s_2\,s_3\ldots\,$; and if that fails, we
1599try to match $s_3\,s_4\ldots\,$, etc.
1600
1601A production applies if the category codes have a given pattern. For
1602example, one of the productions (see rule~3) is
1603$$\hbox{|exp| }\left\{\matrix{\hbox{|binop|}\cr\hbox{|unorbinop|}}\right\}
1604\hbox{ |exp| }\RA\hbox{ |exp|}$$
1605and it means that three consecutive scraps whose respective categories are
1606|exp|, |binop| (or |unorbinop|),
1607and |exp| are converted to one scrap whose category
1608is |exp|. The translations of the original
1609scraps are simply concatenated. The case of
1610$$\hbox{|exp| |comma| |exp| $\RA$ |exp|} \hskip4emE_1C\,\\{opt}9\,E_2$$
1611(rule 4) is only slightly more complicated:
1612Here the resulting |exp| translation
1613consists not only of the three original translations, but also of the
1614tokens |opt| and 9 between the translations of the
1615|comma| and the following |exp|.
1616In the \TEX/ file, this will specify an optional line break after the
1617comma, with penalty 90.
1618
1619At each opportunity the longest possible production is applied. For
1620example, if the current sequence of scraps is |int_like| |cast|
1621|lbrace|, rule 31 is applied; but if the sequence is |int_like| |cast|
1622followed by anything other than |lbrace|, rule 32 takes effect.
1623
1624Translation rules such as `$E_1C\,\\{opt}9\,E_2$' above use subscripts
1625to distinguish between translations of scraps whose categories have the
1626same initial letter; these subscripts are assigned from left to right.
1627
1628@ Here is a list of the category codes that scraps can have.
1629(A few others, like |int_like|, have already been defined; the
1630|cat_name| array contains a complete list.)
1631
1632@d exp 1 /* denotes an expression, including perhaps a single identifier */
1633@d unop 2 /* denotes a unary operator */
1634@d binop 3 /* denotes a binary operator */
1635@d unorbinop 4
1636 /* denotes an operator that can be unary or binary, depending on context */
1637@d cast 5 /* denotes a cast */
1638@d question 6 /* denotes a question mark and possibly the expressions flanking it */
1639@d lbrace 7 /* denotes a left brace */
1640@d rbrace 8 /* denotes a right brace */
1641@d decl_head 9 /* denotes an incomplete declaration */
1642@d comma 10 /* denotes a comma */
1643@d lpar 11 /* denotes a left parenthesis or left bracket */
1644@d rpar 12 /* denotes a right parenthesis or right bracket */
1645@d prelangle 13 /* denotes `$<$' before we know what it is */
1646@d prerangle 14 /* denotes `$>$' before we know what it is */
1647@d langle 15 /* denotes `$<$' when it's used as angle bracket in a template */
1648@d colcol 18 /* denotes `::' */
1649@d base 19 /* denotes a colon that introduces a base specifier */
1650@d decl 20 /* denotes a complete declaration */
1651@d struct_head 21 /* denotes the beginning of a structure specifier */
1652@d stmt 23 /* denotes a complete statement */
1653@d function 24 /* denotes a complete function */
1654@d fn_decl 25 /* denotes a function declarator */
1655@d semi 27 /* denotes a semicolon */
1656@d colon 28 /* denotes a colon */
1657@d tag 29 /* denotes a statement label */
1658@d if_head 30 /* denotes the beginning of a compound conditional */
1659@d else_head 31 /* denotes a prefix for a compound statement */
1660@d if_clause 32 /* pending \.{if} together with a condition */
1661@d lproc 35 /* begins a preprocessor command */
1662@d rproc 36 /* ends a preprocessor command */
1663@d insert 37 /* a scrap that gets combined with its neighbor */
1664@d section_scrap 38 /* section name */
1665@d dead 39 /* scrap that won't combine */
1666@d begin_arg 58 /* \.{@@[} */
1667@d end_arg 59 /* \.{@@]} */
1668
1669@<Glo...@>=
1670char cat_name[256][12];
1671eight_bits cat_index;
1672
1673@ @<Set in...@>=
1674 for (cat_index=0;cat_index<255;cat_index++)
1675 strcpy(cat_name[cat_index],"UNKNOWN");
1676 strcpy(cat_name[exp],"exp");
1677 strcpy(cat_name[unop],"unop");
1678 strcpy(cat_name[binop],"binop");
1679 strcpy(cat_name[unorbinop],"unorbinop");
1680 strcpy(cat_name[cast],"cast");
1681 strcpy(cat_name[question],"?");
1682 strcpy(cat_name[lbrace],"{"@q}@>);
1683 strcpy(cat_name[rbrace],@q{@>"}");
1684 strcpy(cat_name[decl_head],"decl_head");
1685 strcpy(cat_name[comma],",");
1686 strcpy(cat_name[lpar],"(");
1687 strcpy(cat_name[rpar],")");
1688 strcpy(cat_name[prelangle],"<");
1689 strcpy(cat_name[prerangle],">");
1690 strcpy(cat_name[langle],"\\<");
1691 strcpy(cat_name[colcol],"::");
1692 strcpy(cat_name[base],"\\:");
1693 strcpy(cat_name[decl],"decl");
1694 strcpy(cat_name[struct_head],"struct_head");
1695 strcpy(cat_name[stmt],"stmt");
1696 strcpy(cat_name[function],"function");
1697 strcpy(cat_name[fn_decl],"fn_decl");
1698 strcpy(cat_name[else_like],"else_like");
1699 strcpy(cat_name[semi],";");
1700 strcpy(cat_name[colon],":");
1701 strcpy(cat_name[tag],"tag");
1702 strcpy(cat_name[if_head],"if_head");
1703 strcpy(cat_name[else_head],"else_head");
1704 strcpy(cat_name[if_clause],"if()");
1705 strcpy(cat_name[lproc],"#{"@q}@>);
1706 strcpy(cat_name[rproc],@q{@>"#}");
1707 strcpy(cat_name[insert],"insert");
1708 strcpy(cat_name[section_scrap],"section");
1709 strcpy(cat_name[dead],"@@d");
1710 strcpy(cat_name[public_like],"public");
1711 strcpy(cat_name[operator_like],"operator");
1712 strcpy(cat_name[new_like],"new");
1713 strcpy(cat_name[catch_like],"catch");
1714 strcpy(cat_name[for_like],"for");
1715 strcpy(cat_name[do_like],"do");
1716 strcpy(cat_name[if_like],"if");
1717 strcpy(cat_name[raw_rpar],")?");
1718 strcpy(cat_name[raw_unorbin],"unorbinop?");
1719 strcpy(cat_name[const_like],"const");
1720 strcpy(cat_name[raw_int],"raw");
1721 strcpy(cat_name[int_like],"int");
1722 strcpy(cat_name[case_like],"case");
1723 strcpy(cat_name[sizeof_like],"sizeof");
1724 strcpy(cat_name[struct_like],"struct");
1725 strcpy(cat_name[typedef_like],"typedef");
1726 strcpy(cat_name[define_like],"define");
1727 strcpy(cat_name[begin_arg],"@@["@q]@>);
1728 strcpy(cat_name[end_arg],@q[@>"@@]");
1729 strcpy(cat_name[0],"zero");
1730
1731@ This code allows \.{CWEAVE} to display its parsing steps.
1732
1733@c
1734void
1735print_cat(c) /* symbolic printout of a category */
1736eight_bits c;
1737{
1738 printf(cat_name[c]);
1739}
1740
1741@ The token lists for translated \TEX/ output contain some special control
1742symbols as well as ordinary characters. These control symbols are
1743interpreted by \.{CWEAVE} before they are written to the output file.
1744
1745\yskip\hang |break_space| denotes an optional line break or an en space;
1746
1747\yskip\hang |force| denotes a line break;
1748
1749\yskip\hang |big_force| denotes a line break with additional vertical space;
1750
1751\yskip\hang |preproc_line| denotes that the line will be printed flush left;
1752
1753\yskip\hang |opt| denotes an optional line break (with the continuation
1754line indented two ems with respect to the normal starting position)---this
1755code is followed by an integer |n|, and the break will occur with penalty
1756$10n$;
1757
1758\yskip\hang |backup| denotes a backspace of one em;
1759
1760\yskip\hang |cancel| obliterates any |break_space|, |opt|, |force|, or
1761|big_force| tokens that immediately precede or follow it and also cancels any
1762|backup| tokens that follow it;
1763
1764\yskip\hang |indent| causes future lines to be indented one more em;
1765
1766\yskip\hang |outdent| causes future lines to be indented one less em.
1767
1768\yskip\noindent All of these tokens are removed from the \TEX/ output that
1769comes from \CEE/ text between \pb\ signs; |break_space| and |force| and
1770|big_force| become single spaces in this mode. The translation of other
1771\CEE/ texts results in \TEX/ control sequences \.{\\1}, \.{\\2},
1772\.{\\3}, \.{\\4}, \.{\\5}, \.{\\6}, \.{\\7}, \.{\\8}
1773corresponding respectively to
1774|indent|, |outdent|, |opt|, |backup|, |break_space|, |force|,
1775|big_force| and |preproc_line|.
1776However, a sequence of consecutive `\.\ ', |break_space|,
1777|force|, and/or |big_force| tokens is first replaced by a single token
1778(the maximum of the given ones).
1779
1780The token |math_rel| will be translated into
1781\.{\\MRL\{}, and it will get a matching \.\} later.
1782Other control sequences in the \TEX/ output will be
1783`\.{\\\\\{}$\,\ldots\,$\.\}'
1784surrounding identifiers, `\.{\\\&\{}$\,\ldots\,$\.\}' surrounding
1785reserved words, `\.{\\.\{}$\,\ldots\,$\.\}' surrounding strings,
1786`\.{\\C\{}$\,\ldots\,$\.\}$\,$|force|' surrounding comments, and
1787`\.{\\X$n$:}$\,\ldots\,$\.{\\X}' surrounding section names, where
1788|n| is the section number.
1789
1790@d math_rel 0206
1791@d big_cancel 0210 /* like |cancel|, also overrides spaces */
1792@d cancel 0211 /* overrides |backup|, |break_space|, |force|, |big_force| */
1793@d indent 0212 /* one more tab (\.{\\1}) */
1794@d outdent 0213 /* one less tab (\.{\\2}) */
1795@d opt 0214 /* optional break in mid-statement (\.{\\3}) */
1796@d backup 0215 /* stick out one unit to the left (\.{\\4}) */
1797@d break_space 0216 /* optional break between statements (\.{\\5}) */
1798@d force 0217 /* forced break between statements (\.{\\6}) */
1799@d big_force 0220 /* forced break with additional space (\.{\\7}) */
1800@d preproc_line 0221 /* begin line without indentation (\.{\\8}) */
1801@^high-bit character handling@>
1802@d quoted_char 0222
1803 /* introduces a character token in the range |0200|--|0377| */
1804@d end_translation 0223 /* special sentinel token at end of list */
1805@d inserted 0224 /* sentinel to mark translations of inserts */
1806
1807@ The raw input is converted into scraps according to the following table,
1808which gives category codes followed by the translations.
1809\def\stars {\.{**}}%
1810The symbol `\stars' stands for `\.{\\\&\{{\rm identifier}\}}',
1811i.e., the identifier itself treated as a reserved word.
1812The right-hand column is the so-called |mathness|, which is explained
1813further below.
1814
1815An identifier |c| of length 1 is translated as \.{\\\v c} instead of
1816as \.{\\\\\{c\}}. An identifier \.{CAPS} in all caps is translated as
1817\.{\\.\{CAPS\}} instead of as \.{\\\\\{CAPS\}}. An identifier that has
1818become a reserved word via |typedef| is translated with \.{\\\&} replacing
1819\.{\\\\} and |raw_int| replacing |exp|.
1820
1821A string of length greater than 20 is broken into pieces of size at most~20
1822with discretionary breaks in between.
1823
1824\yskip\halign{\quad#\hfil&\quad#\hfil&\quad\hfil#\hfil\cr
1825\.{!=}&|binop|: \.{\\I}&yes\cr
1826\.{<=}&|binop|: \.{\\Z}&yes\cr
1827\.{>=}&|binop|: \.{\\G}&yes\cr
1828\.{==}&|binop|: \.{\\E}&yes\cr
1829\.{\&\&}&|binop|: \.{\\W}&yes\cr
1830\.{\v\v}&|binop|: \.{\\V}&yes\cr
1831\.{++}&|binop|: \.{\\PP}&yes\cr
1832\.{--}&|binop|: \.{\\MM}&yes\cr
1833\.{->}&|binop|: \.{\\MG}&yes\cr
1834\.{>>}&|binop|: \.{\\GG}&yes\cr
1835\.{<<}&|binop|: \.{\\LL}&yes\cr
1836\.{::}&|colcol|: \.{\\DC}&maybe\cr
1837\.{.*}&|binop|: \.{\\PA}&yes\cr
1838\.{->*}&|binop|: \.{\\MGA}&yes\cr
1839\.{...}&|exp|: \.{\\,\\ldots\\,}&yes\cr
1840\."string\."&|exp|: \.{\\.\{}string with special characters quoted\.\}&maybe\cr
1841\.{@@=}string\.{@@>}&|exp|: \.{\\vb\{}string with special characters
1842 quoted\.\}&maybe\cr
1843\.{@@'7'}&|exp|: \.{\\.\{@@'7'\}}&maybe\cr
1844\.{077} or \.{\\77}&|exp|: \.{\\T\{\\\~77\}}&maybe\cr
1845\.{0x7f}&|exp|: \.{\\T\{\\\^7f\}}&maybe\cr
1846\.{77}&|exp|: \.{\\T\{77\}}&maybe\cr
1847\.{77L}&|exp|: \.{\\T\{77\\\$L\}}&maybe\cr
1848\.{0.1E5}&|exp|: \.{\\T\{0.1\\\_5\}}&maybe\cr
1849\.+&|unorbinop|: \.+&yes\cr
1850\.-&|unorbinop|: \.-&yes\cr
1851\.*&|raw_unorbin|: \.*&yes\cr
1852\./&|binop|: \./&yes\cr
1853\.<&|binop|: \.<&yes\cr
1854\.=&|binop|: \.{\\K}&yes\cr
1855\.>&|binop|: \.>&yes\cr
1856\..&|binop|: \..&yes\cr
1857\.{\v}&|binop|: \.{\\OR}&yes\cr
1858\.\^&|binop|: \.{\\XOR}&yes\cr
1859\.\%&|binop|: \.{\\MOD}&yes\cr
1860\.?&|question|: \.{\\?}&yes\cr
1861\.!&|unop|: \.{\\R}&yes\cr
1862\.\~&|unop|: \.{\\CM}&yes\cr
1863\.\&&|raw_unorbin|: \.{\\AND}&yes\cr
1864\.(&|lpar|: \.(&maybe\cr
1865\.[&|lpar|: \.[&maybe\cr
1866\.)&|raw_rpar|: \.)&maybe\cr
1867\.]&|raw_rpar|: \.]&maybe\cr
1868\.\{&|lbrace|: \.\{&yes\cr
1869\.\}&|lbrace|: \.\}&yes\cr
1870\.,&|comma|: \.,&yes\cr
1871\.;&|semi|: \.;&maybe\cr
1872\.:&|colon|: \.:&maybe\cr
1873\.\# (within line)&|unorbinop|: \.{\\\#}&yes\cr
1874\.\# (at beginning)&|lproc|: |force| |preproc_line| \.{\\\#}&no\cr
1875end of \.\# line&|rproc|: |force|&no\cr
1876identifier&|exp|: \.{\\\\\{}identifier with underlines quoted\.\}&maybe\cr
1877\.{asm}&|sizeof_like|: \stars&maybe\cr
1878\.{auto}&|int_like|: \stars&maybe\cr
1879\.{break}&|case_like|: \stars&maybe\cr
1880\.{case}&|case_like|: \stars&maybe\cr
1881\.{catch}&|catch_like|: \stars&maybe\cr
1882\.{char}&|raw_int|: \stars&maybe\cr
1883\.{class}&|struct_like|: \stars&maybe\cr
1884\.{clock\_t}&|raw_int|: \stars&maybe\cr
1885\.{const}&|const_like|: \stars&maybe\cr
1886\.{continue}&|case_like|: \stars&maybe\cr
1887\.{default}&|case_like|: \stars&maybe\cr
1888\.{define}&|define_like|: \stars&maybe\cr
1889\.{defined}&|sizeof_like|: \stars&maybe\cr
1890\.{delete}&|sizeof_like|: \stars&maybe\cr
1891\.{div\_t}&|raw_int|: \stars&maybe\cr
1892\.{do}&|do_like|: \stars&maybe\cr
1893\.{double}&|raw_int|: \stars&maybe\cr
1894\.{elif}&|if_like|: \stars&maybe\cr
1895\.{else}&|else_like|: \stars&maybe\cr
1896\.{endif}&|if_like|: \stars&maybe\cr
1897\.{enum}&|struct_like|: \stars&maybe\cr
1898\.{error}&|if_like|: \stars&maybe\cr
1899\.{extern}&|int_like|: \stars&maybe\cr
1900\.{FILE}&|raw_int|: \stars&maybe\cr
1901\.{float}&|raw_int|: \stars&maybe\cr
1902\.{for}&|for_like|: \stars&maybe\cr
1903\.{fpos\_t}&|raw_int|: \stars&maybe\cr
1904\.{friend}&|int_like|: \stars&maybe\cr
1905\.{goto}&|case_like|: \stars&maybe\cr
1906\.{if}&|if_like|: \stars&maybe\cr
1907\.{ifdef}&|if_like|: \stars&maybe\cr
1908\.{ifndef}&|if_like|: \stars&maybe\cr
1909\.{include}&|if_like|: \stars&maybe\cr
1910\.{inline}&|int_like|: \stars&maybe\cr
1911\.{int}&|raw_int|: \stars&maybe\cr
1912\.{jmp\_buf}&|raw_int|: \stars&maybe\cr
1913\.{ldiv\_t}&|raw_int|: \stars&maybe\cr
1914\.{line}&|if_like|: \stars&maybe\cr
1915\.{long}&|raw_int|: \stars&maybe\cr
1916\.{new}&|new_like|: \stars&maybe\cr
1917\.{NULL}&|exp|: \.{\\NULL}&yes\cr
1918\.{offsetof}&|sizeof_like|: \stars&maybe\cr
1919\.{operator}&|operator_like|: \stars&maybe\cr
1920\.{pragma}&|if_like|: \stars&maybe\cr
1921\.{private}&|public_like|: \stars&maybe\cr
1922\.{protected}&|public_like|: \stars&maybe\cr
1923\.{ptrdiff\_t}&|raw_int|: \stars&maybe\cr
1924\.{public}&|public_like|: \stars&maybe\cr
1925\.{register}&|int_like|: \stars&maybe\cr
1926\.{return}&|case_like|: \stars&maybe\cr
1927\.{short}&|raw_int|: \stars&maybe\cr
1928\.{sig\_atomic\_t}&|raw_int|: \stars&maybe\cr
1929\.{signed}&|raw_int|: \stars&maybe\cr
1930\.{size\_t}&|raw_int|: \stars&maybe\cr
1931\.{sizeof}&|sizeof_like|: \stars&maybe\cr
1932\.{static}&|int_like|: \stars&maybe\cr
1933\.{struct}&|struct_like|: \stars&maybe\cr
1934\.{switch}&|if_like|: \stars&maybe\cr
1935\.{template}&|int_like|: \stars&maybe\cr
1936\.{TeX}&|exp|: \.{\\TeX}&yes\cr
1937\.{this}&|exp|: \.{\\this}&yes\cr
1938\.{throw}&|case_like|: \stars&maybe\cr
1939\.{time\_t}&|raw_int|: \stars&maybe\cr
1940\.{try}&|else_like|: \stars&maybe\cr
1941\.{typedef}&|typedef_like|: \stars&maybe\cr
1942\.{undef}&|if_like|: \stars&maybe\cr
1943\.{union}&|struct_like|: \stars&maybe\cr
1944\.{unsigned}&|raw_int|: \stars&maybe\cr
1945\.{va\_dcl}&|decl|: \stars&maybe\cr
1946\.{va\_list}&|raw_int|: \stars&maybe\cr
1947\.{virtual}&|int_like|: \stars&maybe\cr
1948\.{void}&|raw_int|: \stars&maybe\cr
1949\.{volatile}&|const_like|: \stars&maybe\cr
1950\.{wchar\_t}&|raw_int|: \stars&maybe\cr
1951\.{while}&|if_like|: \stars&maybe\cr
1952\.{@@,}&|insert|: \.{\\,}&maybe\cr
1953\.{@@\v}&|insert|: |opt| \.0&maybe\cr
1954\.{@@/}&|insert|: |force|&no\cr
1955\.{@@\#}&|insert|: |big_force|&no\cr
1956\.{@@+}&|insert|: |big_cancel| \.{\{\}} |break_space|
1957 \.{\{\}} |big_cancel|&no\cr
1958\.{@@;}&|semi|: &maybe\cr
1959\.{@@[@q]@>}&|begin_arg|: &maybe\cr
1960\.{@q[@>@@]}&|end_arg|: &maybe\cr
1961\.{@@\&}&|insert|: \.{\\J}&maybe\cr
1962\.{@@h}&|insert|: |force| \.{\\ATH} |force|&no\cr
1963\.{@@<}\thinspace section name\thinspace\.{@@>}&|section_scrap|:
1964 \.{\\X}$n$\.:translated section name\.{\\X}&maybe\cr
1965\.{@@(@q)@>}\thinspace section name\thinspace\.{@@>}&|section_scrap|:
1966 \.{\\X}$n$\.{:\\.\{}section name with special characters
1967 quoted\.{\ \}\\X}&maybe\cr
1968\.{/*}comment\.{*/}&|insert|: |cancel|
1969 \.{\\C\{}translated comment\.\} |force|&no\cr
1970\.{//}comment&|insert|: |cancel|
1971 \.{\\SHC\{}translated comment\.\} |force|&no\cr
1972}
1973
1974The construction \.{@@t}\thinspace stuff\/\thinspace\.{@@>} contributes
1975\.{\\hbox\{}\thinspace stuff\/\thinspace\.\} to the following scrap.
1976
1977@i prod.w
1978
1979@* Implementing the productions.
1980More specifically, a scrap is a structure consisting of a category
1981|cat| and a |text_pointer| |trans|, which points to the translation in
1982|tok_start|. When \CEE/ text is to be processed with the grammar above,
1983we form an array |scrap_info| containing the initial scraps.
1984Our production rules have the nice property that the right-hand side is never
1985longer than the left-hand side. Therefore it is convenient to use sequential
1986allocation for the current sequence of scraps. Five pointers are used to
1987manage the parsing:
1988
1989\yskip\hang |pp| is a pointer into |scrap_info|. We will try to match
1990the category codes |pp->cat,@,@,(pp+1)->cat|$,\,\,\ldots\,$
1991to the left-hand sides of productions.
1992
1993\yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
1994the current sequence of scraps appears in positions |scrap_base| through
1995|lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
1996|trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
1997been examined, while those in positions |>=hi_ptr| have not yet been
1998looked at by the parsing process.
1999
2000\yskip\noindent Initially |scrap_ptr| is set to the position of the final
2001scrap to be parsed, and it doesn't change its value. The parsing process
2002makes sure that |lo_ptr>=pp+3|, since productions have as many as four terms,
2003by moving scraps from |hi_ptr| to |lo_ptr|. If there are
2004fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
2005blanks that will not match in any productions. Parsing stops when
2006|pp==lo_ptr+1| and |hi_ptr==scrap_ptr+1|.
2007
2008Since the |scrap| structure will later be used for other purposes, we
2009declare its second element as unions.
2010
2011@<Type...@>=
2012typedef struct {
2013 eight_bits cat;
2014 eight_bits mathness;
2015 union {
2016 text_pointer Trans;
2017 @<Rest of |trans_plus| union@>@;
2018 } trans_plus;
2019} scrap;
2020typedef scrap *scrap_pointer;
2021
2022@ @d trans trans_plus.Trans /* translation texts of scraps */
2023
2024@<Global...@>=
2025scrap scrap_info[max_scraps]; /* memory array for scraps */
2026scrap_pointer scrap_info_end=scrap_info+max_scraps -1; /* end of |scrap_info| */
2027scrap_pointer pp; /* current position for reducing productions */
2028scrap_pointer scrap_base; /* beginning of the current scrap sequence */
2029scrap_pointer scrap_ptr; /* ending of the current scrap sequence */
2030scrap_pointer lo_ptr; /* last scrap that has been examined */
2031scrap_pointer hi_ptr; /* first scrap that has not been examined */
2032scrap_pointer max_scr_ptr; /* largest value assumed by |scrap_ptr| */
2033
2034@ @<Set init...@>=
2035scrap_base=scrap_info+1;
2036max_scr_ptr=scrap_ptr=scrap_info;
2037
2038@ Token lists in |@!tok_mem| are composed of the following kinds of
2039items for \TEX/ output.
2040
2041\yskip\item{$\bullet$}Character codes and special codes like |force| and
2042|math_rel| represent themselves;
2043
2044\item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};
2045
2046\item{$\bullet$}|res_flag+p| represents \.{\\\&\{{\rm identifier $p$}\}};
2047
2048\item{$\bullet$}|section_flag+p| represents section name |p|;
2049
2050\item{$\bullet$}|tok_flag+p| represents token list number |p|;
2051
2052\item{$\bullet$}|inner_tok_flag+p| represents token list number |p|, to be
2053translated without line-break controls.
2054
2055@d id_flag 10240 /* signifies an identifier */
2056@d res_flag 2*id_flag /* signifies a reserved word */
2057@d section_flag 3*id_flag /* signifies a section name */
2058@d tok_flag 4*id_flag /* signifies a token list */
2059@d inner_tok_flag 5*id_flag /* signifies a token list in `\pb' */
2060
2061@c
2062void
2063print_text(p) /* prints a token list for debugging; not used in |main| */
2064text_pointer p;
2065{
2066 token_pointer j; /* index into |tok_mem| */
2067 sixteen_bits r; /* remainder of token after the flag has been stripped off */
2068 if (p>=text_ptr) printf("BAD");
2069 else for (j=*p; j<*(p+1); j++) {
2070 r=*j%id_flag;
2071 switch (*j/id_flag) {
2072 case 1: printf("\\\\{"@q}@>); print_id((name_dir+r)); printf(@q{@>"}");
2073 break; /* |id_flag| */
2074 case 2: printf("\\&{"@q}@>); print_id((name_dir+r)); printf(@q{@>"}");
2075 break; /* |res_flag| */
2076 case 3: printf("<"); print_section_name((name_dir+r)); printf(">");
2077 break; /* |section_flag| */
2078 case 4: printf("[[%d]]",r); break; /* |tok_flag| */
2079 case 5: printf("|[[%d]]|",r); break; /* |inner_tok_flag| */
2080 default: @<Print token |r| in symbolic form@>;
2081 }
2082 }
2083 fflush(stdout);
2084}
2085
2086@ @<Print token |r|...@>=
2087switch (r) {
2088 case math_rel: printf("\\mathrel{"@q}@>); break;
2089 case big_cancel: printf("[ccancel]"); break;
2090 case cancel: printf("[cancel]"); break;
2091 case indent: printf("[indent]"); break;
2092 case outdent: printf("[outdent]"); break;
2093 case backup: printf("[backup]"); break;
2094 case opt: printf("[opt]"); break;
2095 case break_space: printf("[break]"); break;
2096 case force: printf("[force]"); break;
2097 case big_force: printf("[fforce]"); break;
2098 case preproc_line: printf("[preproc]"); break;
2099 case quoted_char: j++; printf("[%o]",(unsigned)*j); break;
2100 case end_translation: printf("[quit]"); break;
2101 case inserted: printf("[inserted]"); break;
2102 default: putxchar(r);
2103}
2104
2105@ The production rules listed above are embedded directly into \.{CWEAVE},
2106since it is easier to do this than to write an interpretive system
2107that would handle production systems in general. Several macros are defined
2108here so that the program for each production is fairly short.
2109
2110All of our productions conform to the general notion that some |k|
2111consecutive scraps starting at some position |j| are to be replaced by a
2112single scrap of some category |c| whose translation is composed from the
2113translations of the disappearing scraps. After this production has been
2114applied, the production pointer |pp| should change by an amount |d|. Such
2115a production can be represented by the quadruple |(j,k,c,d)|. For example,
2116the production `|exp@,comma@,exp| $\RA$ |exp|' would be represented by
2117`|(pp,3,exp,-2)|'; in this case the pointer |pp| should decrease by 2
2118after the production has been applied, because some productions with
2119|exp| in their second or third positions might now match,
2120but no productions have
2121|exp| in the fourth position of their left-hand sides. Note that
2122the value of |d| is determined by the whole collection of productions, not
2123by an individual one.
2124The determination of |d| has been
2125done by hand in each case, based on the full set of productions but not on
2126the grammar of \CEE/ or on the rules for constructing the initial
2127scraps.
2128
2129We also attach a serial number to each production, so that additional
2130information is available when debugging. For example, the program below
2131contains the statement `|reduce(pp,3,exp,-2,4)|' when it implements
2132the production just mentioned.
2133
2134Before calling |reduce|, the program should have appended the tokens of
2135the new translation to the |tok_mem| array. We commonly want to append
2136copies of several existing translations, and macros are defined to
2137simplify these common cases. For example, \\{app2}|(pp)| will append the
2138translations of two consecutive scraps, |pp->trans| and |(pp+1)->trans|, to
2139the current token list. If the entire new translation is formed in this
2140way, we write `|squash(j,k,c,d,n)|' instead of `|reduce(j,k,c,d,n)|'. For
2141example, `|squash(pp,3,exp,-2,3)|' is an abbreviation for `\\{app3}|(pp);
2142reduce(pp,3,exp,-2,3)|'.
2143
2144A couple more words of explanation:
2145Both |big_app| and |app| append a token (while |big_app1| to |big_app4|
2146append the specified number of scrap translations) to the current token list.
2147The difference between |big_app| and |app| is simply that |big_app|
2148checks whether there can be a conflict between math and non-math
2149tokens, and intercalates a `\.{\$}' token if necessary. When in
2150doubt what to use, use |big_app|.
2151
2152The |mathness| is an attribute of scraps that says whether they are
2153to be printed in a math mode context or not. It is separate from the
2154``part of speech'' (the |cat|) because to make each |cat| have
2155a fixed |mathness| (as in the original \.{WEAVE}) would multiply the
2156number of necessary production rules.
2157
2158The low two bits (i.e. |mathness % 4|) control the left boundary.
2159(We need two bits because we allow cases |yes_math|, |no_math| and
2160|maybe_math|, which can go either way.)
2161The next two bits (i.e. |mathness / 4|) control the right boundary.
2162If we combine two scraps and the right boundary of the first has
2163a different mathness from the left boundary of the second, we
2164insert a \.{\$} in between. Similarly, if at printing time some
2165irreducible scrap has a |yes_math| boundary the scrap gets preceded
2166or followed by a \.{\$}. The left boundary is |maybe_math| if and
2167only if the right boundary is.
2168
2169The code below is an exact translation of the production rules into
2170\CEE/, using such macros, and the reader should have no difficulty
2171understanding the format by comparing the code with the symbolic
2172productions as they were listed earlier.
2173
2174@d no_math 2 /* should be in horizontal mode */
2175@d yes_math 1 /* should be in math mode */
2176@d maybe_math 0 /* works in either horizontal or math mode */
2177@d big_app2(a) big_app1(a);big_app1(a+1)
2178@d big_app3(a) big_app2(a);big_app1(a+2)
2179@d big_app4(a) big_app3(a);big_app1(a+3)
2180@d app(a) *(tok_ptr++)=a
2181@d app1(a) *(tok_ptr++)=tok_flag+(int)((a)->trans-tok_start)
2182
2183@<Global...@>=
2184int cur_mathness, init_mathness;
2185
2186@ @c
2187void
2188app_str(s)
2189char *s;
2190{
2191 while (*s) app_tok(*(s++));
2192}
2193
2194void
2195big_app(a)
2196token a;
2197{
2198 if (a==' ' || (a>=big_cancel && a<=big_force)) /* non-math token */ {
2199 if (cur_mathness==maybe_math) init_mathness=no_math;
2200 else if (cur_mathness==yes_math) app_str("{}$");
2201 cur_mathness=no_math;
2202 }
2203 else {
2204 if (cur_mathness==maybe_math) init_mathness=yes_math;
2205 else if (cur_mathness==no_math) app_str("${}");
2206 cur_mathness=yes_math;
2207 }
2208 app(a);
2209}
2210
2211void
2212big_app1(a)
2213scrap_pointer a;
2214{
2215 switch (a->mathness % 4) { /* left boundary */
2216 case (no_math):
2217 if (cur_mathness==maybe_math) init_mathness=no_math;
2218 else if (cur_mathness==yes_math) app_str("{}$");
2219 cur_mathness=a->mathness / 4; /* right boundary */
2220 break;
2221 case (yes_math):
2222 if (cur_mathness==maybe_math) init_mathness=yes_math;
2223 else if (cur_mathness==no_math) app_str("${}");
2224 cur_mathness=a->mathness / 4; /* right boundary */
2225 break;
2226 case (maybe_math): /* no changes */ break;
2227 }
2228 app(tok_flag+(int)((a)->trans-tok_start));
2229}
2230
2231@ Let us consider the big switch for productions now, before looking
2232at its context. We want to design the program so that this switch
2233works, so we might as well not keep ourselves in suspense about exactly what
2234code needs to be provided with a proper environment.
2235
2236@d cat1 (pp+1)->cat
2237@d cat2 (pp+2)->cat
2238@d cat3 (pp+3)->cat
2239@d lhs_not_simple (pp->cat!=semi && pp->cat!=raw_int && pp->cat!=raw_unorbin
2240 && pp->cat!=raw_rpar && pp->cat!=const_like)
2241
2242@<Match a production at |pp|, or increase |pp| if there is no match@>= {
2243 if (cat1==end_arg && lhs_not_simple)
2244 if (pp->cat==begin_arg) squash(pp,2,exp,-2,110);
2245 else squash(pp,2,end_arg,-1,111);
2246 else if (cat1==insert) squash(pp,2,pp->cat,-2,0);
2247 else if (cat2==insert) squash(pp+1,2,(pp+1)->cat,-1,0);
2248 else if (cat3==insert) squash(pp+2,2,(pp+2)->cat,0,0);
2249 else
2250 switch (pp->cat) {
2251 case exp: @<Cases for |exp|@>; @+break;
2252 case lpar: @<Cases for |lpar|@>; @+break;
2253 case question: @<Cases for |question|@>; @+break;
2254 case unop: @<Cases for |unop|@>; @+break;
2255 case unorbinop: @<Cases for |unorbinop|@>; @+break;
2256 case binop: @<Cases for |binop|@>; @+break;
2257 case cast: @<Cases for |cast|@>; @+break;
2258 case sizeof_like: @<Cases for |sizeof_like|@>; @+break;
2259 case int_like: @<Cases for |int_like|@>; @+break;
2260 case decl_head: @<Cases for |decl_head|@>; @+break;
2261 case decl: @<Cases for |decl|@>; @+break;
2262 case typedef_like: @<Cases for |typedef_like|@>; @+break;
2263 case struct_like: @<Cases for |struct_like|@>; @+break;
2264 case struct_head: @<Cases for |struct_head|@>; @+break;
2265 case fn_decl: @<Cases for |fn_decl|@>; @+break;
2266 case function: @<Cases for |function|@>; @+break;
2267 case lbrace: @<Cases for |lbrace|@>; @+break;
2268 case do_like: @<Cases for |do_like|@>; @+break;
2269 case if_like: @<Cases for |if_like|@>; @+break;
2270 case for_like: @<Cases for |for_like|@>; @+break;
2271 case else_like: @<Cases for |else_like|@>; @+break;
2272 case if_clause: @<Cases for |if_clause|@>; @+break;
2273 case if_head: @<Cases for |if_head|@>; @+break;
2274 case else_head: @<Cases for |else_head|@>; @+break;
2275 case case_like: @<Cases for |case_like|@>; @+break;
2276 case stmt: @<Cases for |stmt|@>; @+break;
2277 case tag: @<Cases for |tag|@>; @+break;
2278 case semi: @<Cases for |semi|@>; @+break;
2279 case lproc: @<Cases for |lproc|@>; @+break;
2280 case section_scrap: @<Cases for |section_scrap|@>; @+break;
2281 case insert: @<Cases for |insert|@>; @+break;
2282 case prelangle: @<Cases for |prelangle|@>; @+break;
2283 case prerangle: @<Cases for |prerangle|@>; @+break;
2284 case langle: @<Cases for |langle|@>; @+break;
2285 case public_like: @<Cases for |public_like|@>; @+break;
2286 case colcol: @<Cases for |colcol|@>; @+break;
2287 case new_like: @<Cases for |new_like|@>; @+break;
2288 case operator_like: @<Cases for |operator_like|@>; @+break;
2289 case catch_like: @<Cases for |catch_like|@>; @+break;
2290 case base: @<Cases for |base|@>; @+break;
2291 case raw_rpar: @<Cases for |raw_rpar|@>; @+break;
2292 case raw_unorbin: @<Cases for |raw_unorbin|@>; @+break;
2293 case const_like: @<Cases for |const_like|@>; @+break;
2294 case raw_int: @<Cases for |raw_int|@>; @+break;
2295 }
2296 pp++; /* if no match was found, we move to the right */
2297}
2298
2299@ In \CEE/, new specifier names can be defined via |typedef|, and we want
2300to make the parser recognize future occurrences of the identifier thus
2301defined as specifiers. This is done by the procedure |make_reserved|,
2302which changes the |ilk| of the relevant identifier.
2303
2304We first need a procedure to recursively seek the first
2305identifier in a token list, because the identifier might
2306be enclosed in parentheses, as when one defines a function
2307returning a pointer.
2308
2309@d no_ident_found 0 /* distinct from any identifier token */
2310
2311@c
2312token_pointer
2313find_first_ident(p)
2314text_pointer p;
2315{
2316 token_pointer q; /* token to be returned */
2317 token_pointer j; /* token being looked at */
2318 sixteen_bits r; /* remainder of token after the flag has been stripped off */
2319 if (p>=text_ptr) confusion("find_first_ident");
2320 for (j=*p; j<*(p+1); j++) {
2321 r=*j%id_flag;
2322 switch (*j/id_flag) {
2323 case 1: case 2: return j;
2324 case 4: case 5: /* |tok_flag| or |inner_tok_flag| */
2325 if ((q=find_first_ident(tok_start+r))!=no_ident_found)
2326 return q;
2327 default: ; /* char, |section_flag|, fall thru: move on to next token */
2328 if (*j==inserted) return no_ident_found; /* ignore inserts */
2329 }
2330 }
2331 return no_ident_found;
2332}
2333
2334@ The scraps currently being parsed must be inspected for any
2335occurrence of the identifier that we're making reserved; hence
2336the |for| loop below.
2337
2338@c
2339void
2340make_reserved(p) /* make the first identifier in |p->trans| like |int| */
2341scrap_pointer p;
2342{
2343 sixteen_bits tok_value; /* the name of this identifier, plus its flag*/
2344 token_pointer tok_loc; /* pointer to |tok_value| */
2345 if ((tok_loc=find_first_ident(p->trans))==no_ident_found)
2346 return; /* this should not happen */
2347 tok_value=*tok_loc;
2348 for (;p<=scrap_ptr; p==lo_ptr? p=hi_ptr: p++) {
2349 if (p->cat==exp) {
2350 if (**(p->trans)==tok_value) {
2351 p->cat=raw_int;
2352 **(p->trans)=tok_value%id_flag+res_flag;
2353 }
2354 }
2355 }
2356 (name_dir+(sixteen_bits)(tok_value%id_flag))->ilk=raw_int;
2357 *tok_loc=tok_value%id_flag+res_flag;
2358}
2359
2360@ In the following situations we want to mark the occurrence of
2361an identifier as a definition: when |make_reserved| is just about to be
2362used; after a specifier, as in |char **argv|;
2363before a colon, as in \\{found}:; and in the declaration of a function,
2364as in \\{main}()$\{\ldots;\}$. This is accomplished by the invocation
2365of |make_underlined| at appropriate times. Notice that, in the declaration
2366of a function, we only find out that the identifier is being defined after
2367it has been swallowed up by an |exp|.
2368
2369@c
2370void
2371make_underlined(p)
2372/* underline the entry for the first identifier in |p->trans| */
2373scrap_pointer p;
2374{
2375 token_pointer tok_loc; /* where the first identifier appears */
2376 if ((tok_loc=find_first_ident(p->trans))==no_ident_found)
2377 return; /* this happens after parsing the |()| in |double f();| */
2378 xref_switch=def_flag;
2379 underline_xref(*tok_loc%id_flag+name_dir);
2380}
2381
2382@ We cannot use |new_xref| to underline a cross-reference at this point
2383because this would just make a new cross-reference at the end of the list.
2384We actually have to search through the list for the existing
2385cross-reference.
2386
2387@<Predecl...@>=
2388void underline_xref();
2389
2390@ @c
2391void
2392underline_xref(p)
2393name_pointer p;
2394{
2395 xref_pointer q=(xref_pointer)p->xref; /* pointer to cross-reference being examined */
2396 xref_pointer r; /* temporary pointer for permuting cross-references */
2397 sixteen_bits m; /* cross-reference value to be installed */
2398 sixteen_bits n; /* cross-reference value being examined */
2399 if (no_xref) return;
2400 m=section_count+xref_switch;
2401 while (q != xmem) {
2402 n=q->num;
2403 if (n==m) return;
2404 else if (m==n+def_flag) {
2405 q->num=m; return;
2406 }
2407 else if (n>=def_flag && n<m) break;
2408 q=q->xlink;
2409 }
2410 @<Insert new cross-reference at |q|, not at beginning of list@>;
2411}
2412
2413@ We get to this section only when the identifier is one letter long,
2414so it didn't get a non-underlined entry during phase one. But it may
2415have got some explicitly underlined entries in later sections, so in order
2416to preserve the numerical order of the entries in the index, we have
2417to insert the new cross-reference not at the beginning of the list
2418(namely, at |p->xref|), but rather right before |q|.
2419
2420@<Insert new cross-reference at |q|...@>=
2421 append_xref(0); /* this number doesn't matter */
2422 xref_ptr->xlink=(xref_pointer)p->xref; r=xref_ptr;
2423 p->xref=(char*)xref_ptr;
2424 while (r->xlink!=q) {r->num=r->xlink->num; r=r->xlink;}
2425 r->num=m; /* everything from |q| on is left undisturbed */
2426
2427@ Now comes the code that tries to match each production starting
2428with a particular type of scrap. Whenever a match is discovered,
2429the |squash| or |reduce| macro will cause the appropriate action
2430to be performed, followed by |goto found|.
2431
2432@<Cases for |exp|@>=
2433if (cat1==lbrace || cat1==int_like || cat1==decl) {
2434 make_underlined(pp); big_app1(pp); big_app(indent); app(indent);
2435 reduce(pp,1,fn_decl,0,1);
2436}
2437else if (cat1==unop) squash(pp,2,exp,-2,2);
2438else if ((cat1==binop || cat1==unorbinop) && cat2==exp)
2439 squash(pp,3,exp,-2,3);
2440else if (cat1==comma && cat2==exp) {
2441 big_app2(pp);
2442 app(opt); app('9'); big_app1(pp+2); reduce(pp,3,exp,-2,4);
2443}
2444else if (cat1==exp || cat1==cast) squash(pp,2,exp,-2,5);
2445else if (cat1==semi) squash(pp,2,stmt,-1,6);
2446else if (cat1==colon) {
2447 make_underlined (pp); squash(pp,2,tag,0,7);
2448}
2449else if (cat1==base) {
2450 if (cat2==int_like && cat3==comma) {
2451 big_app1(pp+1); big_app(' '); big_app2(pp+2);
2452 app(opt); app('9'); reduce(pp+1,3,base,0,8);
2453 }
2454 else if (cat2==int_like && cat3==lbrace) {
2455 big_app1(pp); big_app(' '); big_app1(pp+1); big_app(' '); big_app1(pp+2);
2456 reduce(pp,3,exp,-1,9);
2457 }
2458}
2459else if (cat1==rbrace) squash(pp,1,stmt,-1,10);
2460
2461@ @<Cases for |lpar|@>=
2462if ((cat1==exp||cat1==unorbinop) && cat2==rpar) squash(pp,3,exp,-2,11);
2463else if (cat1==rpar) {
2464 big_app1(pp); app('\\'); app(','); big_app1(pp+1);
2465@.\\,@>
2466 reduce(pp,2,exp,-2,12);
2467}
2468else if (cat1==decl_head || cat1==int_like || cat1==exp) {
2469 if (cat2==rpar) squash(pp,3,cast,-2,13);
2470 else if (cat2==comma) {
2471 big_app3(pp); app(opt); app('9'); reduce(pp,3,lpar,0,14);
2472 }
2473}
2474else if (cat1==stmt || cat1==decl) {
2475 big_app2(pp); big_app(' '); reduce(pp,2,lpar,0,15);
2476}
2477
2478@ @<Cases for |question|@>=
2479if (cat1==exp && cat2==colon) squash(pp,3,binop,-2,16);
2480
2481@ @<Cases for |unop|@>=
2482if (cat1==exp || cat1==int_like) squash(pp,2,cat1,-2,17);
2483
2484@ @<Cases for |unorbinop|@>=
2485if (cat1==exp || cat1==int_like) {
2486 big_app('{'); big_app1(pp); big_app('}'); big_app1(pp+1);
2487 reduce(pp,2,cat1,-2,18);
2488}
2489else if (cat1==binop) {
2490 big_app(math_rel); big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
2491 big_app('}'); reduce(pp,2,binop,-1,19);
2492}
2493
2494@ @<Cases for |binop|@>=
2495if (cat1==binop) {
2496 big_app(math_rel); big_app('{'); big_app1(pp); big_app('}');
2497 big_app('{'); big_app1(pp+1); big_app('}');
2498 big_app('}'); reduce(pp,2,binop,-1,20);
2499}
2500
2501@ @<Cases for |cast|@>=
2502if (cat1==exp) {
2503 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,21);
2504}
2505else if (cat1==semi) squash(pp,1,exp,-2,22);
2506
2507@ @<Cases for |sizeof_like|@>=
2508if (cat1==cast) squash(pp,2,exp,-2,23);
2509else if (cat1==exp) {
2510 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,24);
2511}
2512
2513@ @<Cases for |int_like|@>=
2514if (cat1==int_like|| cat1==struct_like) {
2515 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,cat1,-2,25);
2516}
2517else if (cat1==exp && (cat2==raw_int||cat2==struct_like))
2518 squash(pp,2,int_like,-2,26);
2519else if (cat1==exp || cat1==unorbinop || cat1==semi) {
2520 big_app1(pp);
2521 if (cat1!=semi) big_app(' ');
2522 reduce(pp,1,decl_head,-1,27);
2523}
2524else if (cat1==colon) {
2525 big_app1(pp); big_app(' '); reduce(pp,1,decl_head,0,28);
2526}
2527else if (cat1==prelangle) squash(pp+1,1,langle,1,29);
2528else if (cat1==colcol && (cat2==exp||cat2==int_like)) squash(pp,3,cat2,-2,30);
2529else if (cat1==cast) {
2530 if (cat2==lbrace) {
2531 big_app2(pp); big_app(indent); big_app(indent);
2532 reduce(pp,2,fn_decl,1,31);
2533 }
2534 else squash(pp,2,int_like,-2,32);
2535}
2536
2537@ @<Cases for |decl_head|@>=
2538if (cat1==comma) {
2539 big_app2(pp); big_app(' '); reduce(pp,2,decl_head,-1,33);
2540}
2541else if (cat1==unorbinop) {
2542 big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
2543 reduce(pp,2,decl_head,-1,34);
2544}
2545else if (cat1==exp && cat2!=lpar && cat2!=exp) {
2546 make_underlined(pp+1); squash(pp,2,decl_head,-1,35);
2547}
2548else if ((cat1==binop||cat1==colon) && cat2==exp && (cat3==comma ||
2549 cat3==semi || cat3==rpar))
2550 squash(pp,3,decl_head,-1,36);
2551else if (cat1==cast) squash(pp,2,decl_head,-1,37);
2552else if (cat1==lbrace || (cat1==int_like&&cat2!=colcol) || cat1==decl) {
2553 big_app1(pp); big_app(indent); app(indent); reduce(pp,1,fn_decl,0,38);
2554}
2555else if (cat1==semi) squash(pp,2,decl,-1,39);
2556
2557@ @<Cases for |decl|@>=
2558if (cat1==decl) {
2559 big_app1(pp); big_app(force); big_app1(pp+1);
2560 reduce(pp,2,decl,-1,40);
2561}
2562else if (cat1==stmt || cat1==function) {
2563 big_app1(pp); big_app(big_force);
2564 big_app1(pp+1); reduce(pp,2,cat1,-1,41);
2565}
2566
2567@ @<Cases for |typedef_like|@>=
2568if (cat1==decl_head)
2569 if ((cat2==exp&&cat3!=lpar&&cat3!=exp)||cat2==int_like) {
2570 make_underlined(pp+2); make_reserved(pp+2);
2571 big_app2(pp+1); reduce(pp+1,2,decl_head,0,42);
2572 }
2573 else if (cat2==semi) {
2574 big_app1(pp); big_app(' '); big_app2(pp+1); reduce(pp,3,decl,-1,43);
2575 }
2576
2577@ @<Cases for |struct_like|@>=
2578if (cat1==lbrace) {
2579 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,struct_head,0,44);
2580}
2581else if (cat1==exp||cat1==int_like) {
2582 if (cat2==lbrace || cat2==semi) {
2583 make_underlined(pp+1); make_reserved(pp+1);
2584 big_app1(pp); big_app(' '); big_app1(pp+1);
2585 if (cat2==semi) reduce(pp,2,decl_head,0,45);
2586 else {
2587 big_app(' '); big_app1(pp+2);reduce(pp,3,struct_head,0,46);
2588 }
2589 }
2590 else if (cat2==colon) squash(pp+2,1,base,-1,47);
2591 else if (cat2!=base) {
2592 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,int_like,-2,48);
2593 }
2594}
2595
2596@ @<Cases for |struct_head|@>=
2597if ((cat1==decl || cat1==stmt || cat1==function) && cat2==rbrace) {
2598 big_app1(pp); big_app(indent); big_app(force); big_app1(pp+1);
2599 big_app(outdent); big_app(force); big_app1(pp+2);
2600 reduce(pp,3,int_like,-2,49);
2601}
2602else if (cat1==rbrace) {
2603 big_app1(pp); app_str("\\,"); big_app1(pp+1);
2604@.\\,@>
2605 reduce(pp,2,int_like,-2,50);
2606}
2607
2608@ @<Cases for |fn_decl|@>=
2609if (cat1==decl) {
2610 big_app1(pp); big_app(force); big_app1(pp+1); reduce(pp,2,fn_decl,0,51);
2611}
2612else if (cat1==stmt) {
2613 big_app1(pp); app(outdent); app(outdent); big_app(force);
2614 big_app1(pp+1); reduce(pp,2,function,-1,52);
2615}
2616
2617@ @<Cases for |function|@>=
2618if (cat1==function || cat1==decl || cat1==stmt) {
2619 big_app1(pp); big_app(big_force); big_app1(pp+1); reduce(pp,2,cat1,-1,53);
2620}
2621
2622@ @<Cases for |lbrace|@>=
2623if (cat1==rbrace) {
2624 big_app1(pp); app('\\'); app(','); big_app1(pp+1);
2625@.\\,@>
2626 reduce(pp,2,stmt,-1,54);
2627}
2628else if ((cat1==stmt||cat1==decl||cat1==function) && cat2==rbrace) {
2629 big_app(force); big_app1(pp); big_app(indent); big_app(force);
2630 big_app1(pp+1); big_app(force); big_app(backup); big_app1(pp+2);
2631 big_app(outdent); big_app(force); reduce(pp,3,stmt,-1,55);
2632}
2633else if (cat1==exp) {
2634 if (cat2==rbrace) squash(pp,3,exp,-2,56);
2635 else if (cat2==comma && cat3==rbrace) squash(pp,4,exp,-2,56);
2636}
2637
2638@ @<Cases for |if_like|@>=
2639if (cat1==exp) {
2640 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,if_clause,0,57);
2641}
2642
2643@ @<Cases for |for_like|@>=
2644if (cat1==exp) {
2645 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,else_like,-2,58);
2646}
2647
2648@ @<Cases for |else_like|@>=
2649if (cat1==lbrace) squash(pp,1,else_head,0,59);
2650else if (cat1==stmt) {
2651 big_app(force); big_app1(pp); big_app(indent); big_app(break_space);
2652 big_app1(pp+1); big_app(outdent); big_app(force);
2653 reduce(pp,2,stmt,-1,60);
2654}
2655
2656@ @<Cases for |else_head|@>=
2657if (cat1==stmt || cat1==exp) {
2658 big_app(force); big_app1(pp); big_app(break_space); app(noop);
2659 big_app(cancel); big_app1(pp+1); big_app(force);
2660 reduce(pp,2,stmt,-1,61);
2661}
2662
2663@ @<Cases for |if_clause|@>=
2664if (cat1==lbrace) squash(pp,1,if_head,0,62);
2665else if (cat1==stmt) {
2666 if (cat2==else_like) {
2667 big_app(force); big_app1(pp); big_app(indent); big_app(break_space);
2668 big_app1(pp+1); big_app(outdent); big_app(force); big_app1(pp+2);
2669 if (cat3==if_like) {
2670 big_app(' '); big_app1(pp+3); reduce(pp,4,if_like,0,63);
2671 }@+else reduce(pp,3,else_like,0,64);
2672 }
2673 else squash(pp,1,else_like,0,65);
2674}
2675
2676@ @<Cases for |if_head|@>=
2677if (cat1==stmt || cat1==exp) {
2678 if (cat2==else_like) {
2679 big_app(force); big_app1(pp); big_app(break_space); app(noop);
2680 big_app(cancel); big_app1(pp+1); big_app(force); big_app1(pp+2);
2681 if (cat3==if_like) {
2682 big_app(' '); big_app1(pp+3); reduce(pp,4,if_like,0,66);
2683 }@+else reduce(pp,3,else_like,0,67);
2684 }
2685 else squash(pp,1,else_head,0,68);
2686}
2687
2688@ @<Cases for |do_like|@>=
2689if (cat1==stmt && cat2==else_like && cat3==semi) {
2690 big_app1(pp); big_app(break_space); app(noop); big_app(cancel);
2691 big_app1(pp+1); big_app(cancel); app(noop); big_app(break_space);
2692 big_app2(pp+2); reduce(pp,4,stmt,-1,69);
2693}
2694
2695@ @<Cases for |case_like|@>=
2696if (cat1==semi) squash(pp,2,stmt,-1,70);
2697else if (cat1==colon) squash(pp,2,tag,-1,71);
2698else if (cat1==exp) {
2699 if (cat2==semi) {
2700 big_app1(pp); big_app(' '); big_app1(pp+1); big_app1(pp+2);
2701 reduce(pp,3,stmt,-1,72);
2702 }
2703 else if (cat2==colon) {
2704 big_app1(pp); big_app(' '); big_app1(pp+1); big_app1(pp+2);
2705 reduce(pp,3,tag,-1,73);
2706 }
2707}
2708
2709@ @<Cases for |tag|@>=
2710if (cat1==tag) {
2711 big_app1(pp); big_app(break_space); big_app1(pp+1); reduce(pp,2,tag,-1,74);
2712}
2713else if (cat1==stmt||cat1==decl||cat1==function) {
2714 big_app(force); big_app(backup); big_app1(pp); big_app(break_space);
2715 big_app1(pp+1); reduce(pp,2,cat1,-1,75);
2716}
2717
2718@ The user can decide at run-time whether short statements should be
2719grouped together on the same line.
2720
2721@d force_lines flags['f'] /* should each statement be on its own line? */
2722@<Cases for |stmt|@>=
2723if (cat1==stmt||cat1==decl||cat1==function) {
2724 big_app1(pp);
2725 if (cat1==function) big_app(big_force);
2726 else if (cat1==decl) big_app(big_force);
2727 else if (force_lines) big_app(force);
2728 else big_app(break_space);
2729 big_app1(pp+1); reduce(pp,2,cat1,-1,76);
2730}
2731
2732@ @<Cases for |semi|@>=
2733big_app(' '); big_app1(pp); reduce(pp,1,stmt,-1,77);
2734
2735@ @<Cases for |lproc|@>=
2736if (cat1==define_like) make_underlined(pp+2);
2737if (cat1==else_like || cat1==if_like ||cat1==define_like)
2738 squash(pp,2,lproc,0,78);
2739else if (cat1==rproc) {
2740 app(inserted); big_app2(pp); reduce(pp,2,insert,-1,79);
2741} else if (cat1==exp || cat1==function) {
2742 if (cat2==rproc) {
2743 app(inserted); big_app1(pp); big_app(' '); big_app2(pp+1);
2744 reduce(pp,3,insert,-1,80);
2745 }
2746 else if (cat2==exp && cat3==rproc && cat1==exp) {
2747 app(inserted); big_app1(pp); big_app(' '); big_app1(pp+1); app_str(" \\5");
2748@.\\5@>
2749 big_app2(pp+2); reduce(pp,4,insert,-1,80);
2750 }
2751}
2752
2753@ @<Cases for |section_scrap|@>=
2754if (cat1==semi) {
2755 big_app2(pp); big_app(force); reduce(pp,2,stmt,-2,81);
2756}
2757else squash(pp,1,exp,-2,82);
2758
2759@ @<Cases for |insert|@>=
2760if (cat1)
2761 squash(pp,2,cat1,0,83);
2762
2763@ @<Cases for |prelangle|@>=
2764init_mathness=cur_mathness=yes_math;
2765app('<'); reduce(pp,1,binop,-2,84);
2766
2767@ @<Cases for |prerangle|@>=
2768init_mathness=cur_mathness=yes_math;
2769app('>'); reduce(pp,1,binop,-2,85);
2770
2771@ @<Cases for |langle|@>=
2772if (cat1==exp && cat2==prerangle) squash(pp,3,cast,-1,86);
2773else if (cat1==prerangle) {
2774 big_app1(pp); app('\\'); app(','); big_app1(pp+1);
2775@.\\,@>
2776 reduce(pp,2,cast,-1,87);
2777}
2778else if (cat1==decl_head || cat1==int_like) {
2779 if (cat2==prerangle) squash(pp,3,cast,-1,88);
2780 else if (cat2==comma) {
2781 big_app3(pp); app(opt); app('9'); reduce(pp,3,langle,0,89);
2782 }
2783}
2784
2785@ @<Cases for |public_like|@>=
2786if (cat1==colon) squash(pp,2,tag,-1,90);
2787else squash(pp,1,int_like,-2,91);
2788
2789@ @<Cases for |colcol|@>=
2790if (cat1==exp||cat1==int_like) squash(pp,2,cat1,-2,92);
2791
2792@ @<Cases for |new_like|@>=
2793if (cat1==exp || (cat1==raw_int&&cat2!=prelangle&&cat2!=langle)) {
2794 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,new_like,0,93);
2795}
2796else if (cat1==raw_unorbin || cat1==colcol)
2797 squash(pp,2,new_like,0,94);
2798else if (cat1==cast) squash(pp,2,exp,-2,95);
2799else if (cat1!=lpar && cat1!=raw_int && cat1!=struct_like)
2800 squash(pp,1,exp,-2,96);
2801
2802@ @<Cases for |operator_like|@>=
2803if (cat1==binop || cat1==unop || cat1==unorbinop) {
2804 if (cat2==binop) break;
2805 big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
2806 reduce(pp,2,exp,-2,97);
2807}
2808else if (cat1==new_like || cat1==sizeof_like) {
2809 big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,98);
2810}
2811else squash(pp,1,new_like,0,99);
2812
2813@ @<Cases for |catch_like|@>=
2814if (cat1==cast || cat1==exp) {
2815 big_app2(pp); big_app(indent); big_app(indent);
2816 reduce(pp,2,fn_decl,0,100);
2817}
2818
2819@ @<Cases for |base|@>=
2820if (cat1==public_like && cat2==exp) {
2821 if (cat3==comma) {
2822 big_app2(pp); big_app(' '); big_app2(pp+2);
2823 reduce(pp,4,base,0,101);
2824 } else {
2825 big_app1(pp+1); big_app(' '); big_app1(pp+2);
2826 reduce(pp+1,2,int_like,-1,102);
2827 }
2828}
2829
2830@ @<Cases for |raw_rpar|@>=
2831if (cat1==const_like) {
2832 big_app1(pp); big_app(' ');
2833 big_app1(pp+1); reduce(pp,2,raw_rpar,0,103);
2834} else squash(pp,1,rpar,-3,104);
2835
2836@ @<Cases for |raw_unorbin|@>=
2837if (cat1==const_like) {
2838 big_app2(pp); app_str("\\ "); reduce(pp,2,raw_unorbin,0,105);
2839@.\\ @>
2840} else squash(pp,1,unorbinop,-2,106);
2841
2842@ @<Cases for |const_like|@>=
2843squash(pp,1,int_like,-2,107);
2844
2845@ @<Cases for |raw_int|@>=
2846if (cat1==lpar) squash(pp,1,exp,-2,108);
2847else squash(pp,1,int_like,-3,109);
2848
2849@ The `|freeze_text|' macro is used to give official status to a token list.
2850Before saying |freeze_text|, items are appended to the current token list,
2851and we know that the eventual number of this token list will be the current
2852value of |text_ptr|. But no list of that number really exists as yet,
2853because no ending point for the current list has been
2854stored in the |tok_start| array. After saying |freeze_text|, the
2855old current token list becomes legitimate, and its number is the current
2856value of |text_ptr-1| since |text_ptr| has been increased. The new
2857current token list is empty and ready to be appended to.
2858Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
2859too large, since it is assumed that this test was done beforehand.
2860
2861@d freeze_text *(++text_ptr)=tok_ptr
2862
2863@ Here's the |reduce| procedure used in our code for productions:
2864
2865@c
2866void
2867reduce(j,k,c,d,n)
2868scrap_pointer j;
2869eight_bits c;
2870short k, d, n;
2871{
2872 scrap_pointer i, i1; /* pointers into scrap memory */
2873 j->cat=c; j->trans=text_ptr;
2874 j->mathness=4*cur_mathness+init_mathness;
2875 freeze_text;
2876 if (k>1) {
2877 for (i=j+k, i1=j+1; i<=lo_ptr; i++, i1++) {
2878 i1->cat=i->cat; i1->trans=i->trans;
2879 i1->mathness=i->mathness;
2880 }
2881 lo_ptr=lo_ptr-k+1;
2882 }
2883 @<Change |pp| to $\max(|scrap_base|,|pp|+d)$@>;
2884 @<Print a snapshot of the scrap list if debugging @>;
2885 pp--; /* we next say |pp++| */
2886}
2887
2888@ @<Change |pp| to $\max...@>=
2889if (pp+d>=scrap_base) pp=pp+d;
2890else pp=scrap_base;
2891
2892@ Here's the |squash| procedure, which
2893takes advantage of the simplification that occurs when |k==1|.
2894
2895@c
2896void
2897squash(j,k,c,d,n)
2898scrap_pointer j;
2899eight_bits c;
2900short k, d, n;
2901{
2902 scrap_pointer i; /* pointers into scrap memory */
2903 if (k==1) {
2904 j->cat=c; @<Change |pp|...@>;
2905 @<Print a snapshot...@>;
2906 pp--; /* we next say |pp++| */
2907 return;
2908 }
2909 for (i=j; i<j+k; i++) big_app1(i);
2910 reduce(j,k,c,d,n);
2911}
2912
2913@ Here now is the code that applies productions as long as possible.
2914Before applying the production mechanism, we must make sure
2915it has good input (at least four scraps, the length of the lhs of the
2916longest rules), and that there is enough room in the memory arrays
2917to hold the appended tokens and texts. Here we use a very
2918conservative test: it's more important to make sure the program
2919will still work if we change the production rules (within reason)
2920than to squeeze the last bit of space from the memory arrays.
2921
2922@d safe_tok_incr 20
2923@d safe_text_incr 10
2924@d safe_scrap_incr 10
2925
2926@<Reduce the scraps using the productions until no more rules apply@>=
2927while (1) {
2928 @<Make sure the entries |pp| through |pp+3| of |cat| are defined@>;
2929 if (tok_ptr+safe_tok_incr>tok_mem_end) {
2930 if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
2931 overflow("token");
2932 }
2933 if (text_ptr+safe_text_incr>tok_start_end) {
2934 if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
2935 overflow("text");
2936 }
2937 if (pp>lo_ptr) break;
2938 init_mathness=cur_mathness=maybe_math;
2939 @<Match a production...@>;
2940}
2941
2942@ If we get to the end of the scrap list, category codes equal to zero are
2943stored, since zero does not match anything in a production.
2944
2945@<Make sure the entries...@>=
2946if (lo_ptr<pp+3) {
2947 while (hi_ptr<=scrap_ptr && lo_ptr!=pp+3) {
2948 (++lo_ptr)->cat=hi_ptr->cat; lo_ptr->mathness=(hi_ptr)->mathness;
2949 lo_ptr->trans=(hi_ptr++)->trans;
2950 }
2951 for (i=lo_ptr+1;i<=pp+3;i++) i->cat=0;
2952}
2953
2954@ If \.{CWEAVE} is being run in debugging mode, the production numbers and
2955current stack categories will be printed out when |tracing| is set to 2;
2956a sequence of two or more irreducible scraps will be printed out when
2957|tracing| is set to 1.
2958
2959@<Global...@>=
2960int tracing; /* can be used to show parsing details */
2961
2962@ @<Print a snapsh...@>=
2963{ scrap_pointer k; /* pointer into |scrap_info| */
2964 if (tracing==2) {
2965 printf("\n%d:",n);
2966 for (k=scrap_base; k<=lo_ptr; k++) {
2967 if (k==pp) putxchar('*'); else putxchar(' ');
2968 if (k->mathness %4 == yes_math) putchar('+');
2969 else if (k->mathness %4 == no_math) putchar('-');
2970 print_cat(k->cat);
2971 if (k->mathness /4 == yes_math) putchar('+');
2972 else if (k->mathness /4 == no_math) putchar('-');
2973 }
2974 if (hi_ptr<=scrap_ptr) printf("..."); /* indicate that more is coming */
2975 }
2976}
2977
2978@ The |translate| function assumes that scraps have been stored in
2979positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
2980applies productions as much as
2981possible. The result is a token list containing the translation of
2982the given sequence of scraps.
2983
2984After calling |translate|, we will have |text_ptr+3<=max_texts| and
2985|tok_ptr+6<=max_toks|, so it will be possible to create up to three token
2986lists with up to six tokens without checking for overflow. Before calling
2987|translate|, we should have |text_ptr<max_texts| and |scrap_ptr<max_scraps|,
2988since |translate| might add a new text and a new scrap before it checks
2989for overflow.
2990
2991@c
2992text_pointer
2993translate() /* converts a sequence of scraps */
2994{
2995 scrap_pointer i, /* index into |cat| */
2996 j; /* runs through final scraps */
2997 pp=scrap_base; lo_ptr=pp-1; hi_ptr=pp;
2998 @<If tracing, print an indication of where we are@>;
2999 @<Reduce the scraps...@>;
3000 @<Combine the irreducible scraps that remain@>;
3001}
3002
3003@ If the initial sequence of scraps does not reduce to a single scrap,
3004we concatenate the translations of all remaining scraps, separated by
3005blank spaces, with dollar signs surrounding the translations of scraps
3006where appropriate.
3007
3008@<Combine the irreducible...@>= {
3009 @<If semi-tracing, show the irreducible scraps@>;
3010 for (j=scrap_base; j<=lo_ptr; j++) {
3011 if (j!=scrap_base) app(' ');
3012 if (j->mathness % 4 == yes_math) app('$');
3013 app1(j);
3014 if (j->mathness / 4 == yes_math) app('$');
3015 if (tok_ptr+6>tok_mem_end) overflow("token");
3016 }
3017 freeze_text; return(text_ptr-1);
3018}
3019
3020@ @<If semi-tracing, show the irreducible scraps@>=
3021if (lo_ptr>scrap_base && tracing==1) {
3022 printf("\nIrreducible scrap sequence in section %d:",section_count);
3023@.Irreducible scrap sequence...@>
3024 mark_harmless;
3025 for (j=scrap_base; j<=lo_ptr; j++) {
3026 printf(" "); print_cat(j->cat);
3027 }
3028}
3029
3030@ @<If tracing,...@>=
3031if (tracing==2) {
3032 printf("\nTracing after l. %d:\n",cur_line); mark_harmless;
3033@.Tracing after...@>
3034 if (loc>buffer+50) {
3035 printf("...");
3036 term_write(loc-51,51);
3037 }
3038 else term_write(buffer,loc-buffer);
3039}
3040
3041@* Initializing the scraps.
3042If we are going to use the powerful production mechanism just developed, we
3043must get the scraps set up in the first place, given a \CEE/ text. A table
3044of the initial scraps corresponding to \CEE/ tokens appeared above in the
3045section on parsing; our goal now is to implement that table. We shall do this
3046by implementing a subroutine called |C_parse| that is analogous to the
3047|C_xref| routine used during phase one.
3048
3049Like |C_xref|, the |C_parse| procedure starts with the current
3050value of |next_control| and it uses the operation |next_control=get_next()|
3051repeatedly to read \CEE/ text until encountering the next `\.{\v}' or
3052`\.{/*}', or until |next_control>=format_code|. The scraps corresponding to
3053what it reads are appended into the |cat| and |trans| arrays, and |scrap_ptr|
3054is advanced.
3055
3056@c
3057void
3058C_parse(spec_ctrl) /* creates scraps from \CEE/ tokens */
3059 eight_bits spec_ctrl;
3060{
3061 int count; /* characters remaining before string break */
3062 while (next_control<format_code || next_control==spec_ctrl) {
3063 @<Append the scrap appropriate to |next_control|@>;
3064 next_control=get_next();
3065 if (next_control=='|' || next_control==begin_comment ||
3066 next_control==begin_short_comment) return;
3067 }
3068}
3069
3070@ The following macro is used to append a scrap whose tokens have just
3071been appended:
3072
3073@d app_scrap(c,b) {
3074 (++scrap_ptr)->cat=(c); scrap_ptr->trans=text_ptr;
3075 scrap_ptr->mathness=5*(b); /* no no, yes yes, or maybe maybe */
3076 freeze_text;
3077}
3078
3079@ @<Append the scr...@>=
3080@<Make sure that there is room for the new scraps, tokens, and texts@>;
3081switch (next_control) {
3082 case section_name:
3083 app(section_flag+(int)(cur_section-name_dir));
3084 app_scrap(section_scrap,maybe_math);
3085 app_scrap(exp,yes_math);@+break;
3086 case string: case constant: case verbatim: @<Append a string or constant@>;
3087 @+break;
3088 case identifier: app_cur_id(1);@+break;
3089 case TeX_string: @<Append a \TEX/ string, without forming a scrap@>;@+break;
3090 case '/': case '.':
3091 app(next_control); app_scrap(binop,yes_math);@+break;
3092 case '<': app_str("\\langle");@+app_scrap(prelangle,yes_math);@+break;
3093@.\\langle@>
3094 case '>': app_str("\\rangle");@+app_scrap(prerangle,yes_math);@+break;
3095@.\\rangle@>
3096 case '=': app_str("\\K"); app_scrap(binop,yes_math);@+break;
3097@.\\K@>
3098 case '|': app_str("\\OR"); app_scrap(binop,yes_math);@+break;
3099@.\\OR@>
3100 case '^': app_str("\\XOR"); app_scrap(binop,yes_math);@+break;
3101@.\\XOR@>
3102 case '%': app_str("\\MOD"); app_scrap(binop,yes_math);@+break;
3103@.\\MOD@>
3104 case '!': app_str("\\R"); app_scrap(unop,yes_math);@+break;
3105@.\\R@>
3106 case '~': app_str("\\CM"); app_scrap(unop,yes_math);@+break;
3107@.\\CM@>
3108 case '+': case '-': app(next_control); app_scrap(unorbinop,yes_math);@+break;
3109 case '*': app(next_control); app_scrap(raw_unorbin,yes_math);@+break;
3110 case '&': app_str("\\AND"); app_scrap(raw_unorbin,yes_math);@+break;
3111@.\\AND@>
3112 case '?': app_str("\\?"); app_scrap(question,yes_math);@+break;
3113@.\\?@>
3114 case '#': app_str("\\#"); app_scrap(unorbinop,yes_math);@+break;
3115@.\\\#@>
3116 case ignore: case xref_roman: case xref_wildcard:
3117 case xref_typewriter: case noop:@+break;
3118 case '(': case '[': app(next_control); app_scrap(lpar,maybe_math);@+break;
3119 case ')': case ']': app(next_control); app_scrap(raw_rpar,maybe_math);@+break;
3120 case '{': app_str("\\{"@q}@>); app_scrap(lbrace,yes_math);@+break;
3121@.\\\{@>@q}@>
3122 case '}': app_str(@q{@>"\\}"); app_scrap(rbrace,yes_math);@+break;
3123@q{@>@.\\\}@>
3124 case ',': app(','); app_scrap(comma,yes_math);@+break;
3125 case ';': app(';'); app_scrap(semi,maybe_math);@+break;
3126 case ':': app(':'); app_scrap(colon,maybe_math);@+break;@/
3127 @t\4@> @<Cases involving nonstandard characters@>@;
3128 case thin_space: app_str("\\,"); app_scrap(insert,maybe_math);@+break;
3129@.\\,@>
3130 case math_break: app(opt); app_str("0");
3131 app_scrap(insert,maybe_math);@+break;
3132 case line_break: app(force); app_scrap(insert,no_math);@+break;
3133 case left_preproc: app(force); app(preproc_line);
3134 app_str("\\#"); app_scrap(lproc,no_math);@+break;
3135@.\\\#@>
3136 case right_preproc: app(force); app_scrap(rproc,no_math);@+break;
3137 case big_line_break: app(big_force); app_scrap(insert,no_math);@+break;
3138 case no_line_break: app(big_cancel); app(noop); app(break_space);
3139 app(noop); app(big_cancel);
3140 app_scrap(insert,no_math);@+break;
3141 case pseudo_semi: app_scrap(semi,maybe_math);@+break;
3142 case macro_arg_open: app_scrap(begin_arg,maybe_math);@+break;
3143 case macro_arg_close: app_scrap(end_arg,maybe_math);@+break;
3144 case join: app_str("\\J"); app_scrap(insert,no_math);@+break;
3145@.\\J@>
3146 case output_defs_code: app(force); app_str("\\ATH"); app(force);
3147 app_scrap(insert,no_math);@+break;
3148@.\\ATH@>
3149 default: app(inserted); app(next_control);
3150 app_scrap(insert,maybe_math);@+break;
3151}
3152
3153@ @<Make sure that there is room for the new...@>=
3154if (scrap_ptr+safe_scrap_incr>scrap_info_end ||
3155 tok_ptr+safe_tok_incr>tok_mem_end @| ||
3156 text_ptr+safe_text_incr>tok_start_end) {
3157 if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
3158 if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
3159 if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
3160 overflow("scrap/token/text");
3161}
3162
3163@ Some nonstandard characters may have entered \.{CWEAVE} by means of
3164standard ones. They are converted to \TEX/ control sequences so that it is
3165possible to keep \.{CWEAVE} from outputting unusual |char| codes.
3166
3167@<Cases involving nonstandard...@>=
3168case not_eq: app_str("\\I");@+app_scrap(binop,yes_math);@+break;
3169@.\\I@>
3170case lt_eq: app_str("\\Z");@+app_scrap(binop,yes_math);@+break;
3171@.\\Z@>
3172case gt_eq: app_str("\\G");@+app_scrap(binop,yes_math);@+break;
3173@.\\G@>
3174case eq_eq: app_str("\\E");@+app_scrap(binop,yes_math);@+break;
3175@.\\E@>
3176case and_and: app_str("\\W");@+app_scrap(binop,yes_math);@+break;
3177@.\\W@>
3178case or_or: app_str("\\V");@+app_scrap(binop,yes_math);@+break;
3179@.\\V@>
3180case plus_plus: app_str("\\PP");@+app_scrap(unop,yes_math);@+break;
3181@.\\PP@>
3182case minus_minus: app_str("\\MM");@+app_scrap(unop,yes_math);@+break;
3183@.\\MM@>
3184case minus_gt: app_str("\\MG");@+app_scrap(binop,yes_math);@+break;
3185@.\\MG@>
3186case gt_gt: app_str("\\GG");@+app_scrap(binop,yes_math);@+break;
3187@.\\GG@>
3188case lt_lt: app_str("\\LL");@+app_scrap(binop,yes_math);@+break;
3189@.\\LL@>
3190case dot_dot_dot: app_str("\\,\\ldots\\,");@+app_scrap(exp,yes_math);@+break;
3191@.\\,@>
3192@.\\ldots@>
3193case colon_colon: app_str("\\DC");@+app_scrap(colcol,maybe_math);@+break;
3194@.\\DC@>
3195case period_ast: app_str("\\PA");@+app_scrap(binop,yes_math);@+break;
3196@.\\PA@>
3197case minus_gt_ast: app_str("\\MGA");@+app_scrap(binop,yes_math);@+break;
3198@.\\MGA@>
3199
3200@ The following code must use |app_tok| instead of |app| in order to
3201protect against overflow. Note that |tok_ptr+1<=max_toks| after |app_tok|
3202has been used, so another |app| is legitimate before testing again.
3203
3204Many of the special characters in a string must be prefixed by `\.\\' so that
3205\TEX/ will print them properly.
3206@^special string characters@>
3207
3208@<Append a string or...@>=
3209count= -1;
3210if (next_control==constant) app_str("\\T{"@q}@>);
3211@.\\T@>
3212else if (next_control==string) {
3213 count=20; app_str("\\.{"@q}@>);
3214}
3215@.\\.@>
3216else app_str("\\vb{"@q}@>);
3217@.\\vb@>
3218while (id_first<id_loc) {
3219 if (count==0) { /* insert a discretionary break in a long string */
3220 app_str(@q(@>@q{@>"}\\)\\.{"@q}@>); count=20;
3221@q(@>@.\\)@>
3222 }
3223@^high-bit character handling@>
3224 if((eight_bits)(*id_first)>0177) {
3225 app_tok(quoted_char);
3226 app_tok((eight_bits)(*id_first++));
3227 }
3228 else {
3229 switch (*id_first) {
3230 case ' ':case '\\':case '#':case '%':case '$':case '^':
3231 case '{': case '}': case '~': case '&': case '_': app('\\'); break;
3232@.\\\ @>
3233@.\\\\@>
3234@.\\\#@>
3235@.\\\%@>
3236@.\\\$@>
3237@.\\\^@>
3238@.\\\{@>@q}@>
3239@q{@>@.\\\}@>
3240@.\\\~@>
3241@.\\\&@>
3242@.\\_@> @q CWEAVE does quote an underscore! @>
3243 case '@@': if (*(id_first+1)=='@@') id_first++;
3244 else err_print("! Double @@ should be used in strings");
3245@.Double @@ should be used...@>
3246 }
3247 app_tok(*id_first++);
3248 }
3249 count--;
3250}
3251app(@q{@>'}');
3252app_scrap(exp,maybe_math);
3253
3254@ We do not make the \TEX/ string into a scrap, because there is no
3255telling what the user will be putting into it; instead we leave it
3256open, to be picked up by next scrap. If it comes at the end of a
3257section, it will be made into a scrap when |finish_C| is called.
3258
3259@<Append a \TEX/ string, without forming a scrap@>=
3260app_str("\\hbox{"@q}@>);
3261@^high-bit character handling@>
3262while (id_first<id_loc)
3263 if((eight_bits)(*id_first)>0177) {
3264 app_tok(quoted_char);
3265 app_tok((eight_bits)(*id_first++));
3266 }
3267 else {
3268 if (*id_first=='@@') id_first++;
3269 app_tok(*id_first++);
3270 }
3271app(@q{@>'}');
3272
3273@ The function |app_cur_id| appends the current identifier to the
3274token list; it also builds a new scrap if |scrapping==1|.
3275
3276@<Predec...@>=
3277void app_cur_id();
3278
3279@ @c
3280void
3281app_cur_id(scrapping)
3282boolean scrapping; /* are we making this into a scrap? */
3283{
3284 name_pointer p=id_lookup(id_first,id_loc,normal);
3285 if (p->ilk<=quoted) { /* not a reserved word */
3286 app(id_flag+(int)(p-name_dir));
3287 if (scrapping) app_scrap(exp,p->ilk>=custom? yes_math: maybe_math);
3288@.\\NULL@>
3289 } else {
3290 app(res_flag+(int)(p-name_dir));
3291 if (scrapping) app_scrap(p->ilk,maybe_math);
3292 }
3293}
3294
3295@ When the `\.{\v}' that introduces \CEE/ text is sensed, a call on
3296|C_translate| will return a pointer to the \TEX/ translation of
3297that text. If scraps exist in |scrap_info|, they are
3298unaffected by this translation process.
3299
3300@c
3301text_pointer
3302C_translate()
3303{
3304 text_pointer p; /* points to the translation */
3305 scrap_pointer save_base; /* holds original value of |scrap_base| */
3306 save_base=scrap_base; scrap_base=scrap_ptr+1;
3307 C_parse(section_name); /* get the scraps together */
3308 if (next_control!='|') err_print("! Missing '|' after C text");
3309@.Missing '|'...@>
3310 app_tok(cancel); app_scrap(insert,maybe_math);
3311 /* place a |cancel| token as a final ``comment'' */
3312 p=translate(); /* make the translation */
3313 if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
3314 scrap_ptr=scrap_base-1; scrap_base=save_base; /* scrap the scraps */
3315 return(p);
3316}
3317
3318@ The |outer_parse| routine is to |C_parse| as |outer_xref|
3319is to |C_xref|: it constructs a sequence of scraps for \CEE/ text
3320until |next_control>=format_code|. Thus, it takes care of embedded comments.
3321
3322@c
3323void
3324outer_parse() /* makes scraps from \CEE/ tokens and comments */
3325{
3326 int bal; /* brace level in comment */
3327 text_pointer p, q; /* partial comments */
3328 while (next_control<format_code)
3329 if (next_control!=begin_comment && next_control!=begin_short_comment)
3330 C_parse(ignore);
3331 else {
3332 boolean is_long_comment=(next_control==begin_comment);
3333 @<Make sure that there is room for the new...@>;
3334 app(cancel); app(inserted);
3335 if (is_long_comment) app_str("\\C{"@q}@>);
3336@.\\C@>
3337 else app_str("\\SHC{"@q}@>);
3338@.\\SHC@>
3339 bal=copy_comment(is_long_comment,1); next_control=ignore;
3340 while (bal>0) {
3341 p=text_ptr; freeze_text; q=C_translate();
3342 /* at this point we have |tok_ptr+6<=max_toks| */
3343 app(tok_flag+(int)(p-tok_start));
3344 app_str("\\PB{"); app(inner_tok_flag+(int)(q-tok_start)); app_tok('}');
3345@.\\PB@>
3346 if (next_control=='|') {
3347 bal=copy_comment(is_long_comment,bal);
3348 next_control=ignore;
3349 }
3350 else bal=0; /* an error has been reported */
3351 }
3352 app(force); app_scrap(insert,no_math);
3353 /* the full comment becomes a scrap */
3354 }
3355}
3356
3357@* Output of tokens.
3358So far our programs have only built up multi-layered token lists in
3359\.{CWEAVE}'s internal memory; we have to figure out how to get them into
3360the desired final form. The job of converting token lists to characters in
3361the \TEX/ output file is not difficult, although it is an implicitly
3362recursive process. Four main considerations had to be kept in mind when
3363this part of \.{CWEAVE} was designed. (a) There are two modes of output:
3364|outer| mode, which translates tokens like |force| into line-breaking
3365control sequences, and |inner| mode, which ignores them except that blank
3366spaces take the place of line breaks. (b) The |cancel| instruction applies
3367to adjacent token or tokens that are output, and this cuts across levels
3368of recursion since `|cancel|' occurs at the beginning or end of a token
3369list on one level. (c) The \TEX/ output file will be semi-readable if line
3370breaks are inserted after the result of tokens like |break_space| and
3371|force|. (d) The final line break should be suppressed, and there should
3372be no |force| token output immediately after `\.{\\Y\\B}'.
3373
3374@ The output process uses a stack to keep track of what is going on at
3375different ``levels'' as the token lists are being written out. Entries on
3376this stack have three parts:
3377
3378\yskip\hang |end_field| is the |tok_mem| location where the token list of a
3379particular level will end;
3380
3381\yskip\hang |tok_field| is the |tok_mem| location from which the next token
3382on a particular level will be read;
3383
3384\yskip\hang |mode_field| is the current mode, either |inner| or |outer|.
3385
3386\yskip\noindent The current values of these quantities are referred to
3387quite frequently, so they are stored in a separate place instead of in the
3388|stack| array. We call the current values |cur_end|, |cur_tok|, and
3389|cur_mode|.
3390
3391The global variable |stack_ptr| tells how many levels of output are
3392currently in progress. The end of output occurs when an |end_translation|
3393token is found, so the stack is never empty except when we first begin the
3394output process.
3395
3396@d inner 0 /* value of |mode| for \CEE/ texts within \TEX/ texts */
3397@d outer 1 /* value of |mode| for \CEE/ texts in sections */
3398
3399@<Typed...@>= typedef int mode;
3400typedef struct {
3401 token_pointer end_field; /* ending location of token list */
3402 token_pointer tok_field; /* present location within token list */
3403 boolean mode_field; /* interpretation of control tokens */
3404} output_state;
3405typedef output_state *stack_pointer;
3406
3407@ @d cur_end cur_state.end_field /* current ending location in |tok_mem| */
3408@d cur_tok cur_state.tok_field /* location of next output token in |tok_mem| */
3409@d cur_mode cur_state.mode_field /* current mode of interpretation */
3410@d init_stack stack_ptr=stack;cur_mode=outer /* initialize the stack */
3411
3412@<Global...@>=
3413output_state cur_state; /* |cur_end|, |cur_tok|, |cur_mode| */
3414output_state stack[stack_size]; /* info for non-current levels */
3415stack_pointer stack_ptr; /* first unused location in the output state stack */
3416stack_pointer stack_end=stack+stack_size-1; /* end of |stack| */
3417stack_pointer max_stack_ptr; /* largest value assumed by |stack_ptr| */
3418
3419@ @<Set init...@>=
3420max_stack_ptr=stack;
3421
3422@ To insert token-list |p| into the output, the |push_level| subroutine
3423is called; it saves the old level of output and gets a new one going.
3424The value of |cur_mode| is not changed.
3425
3426@c
3427void
3428push_level(p) /* suspends the current level */
3429text_pointer p;
3430{
3431 if (stack_ptr==stack_end) overflow("stack");
3432 if (stack_ptr>stack) { /* save current state */
3433 stack_ptr->end_field=cur_end;
3434 stack_ptr->tok_field=cur_tok;
3435 stack_ptr->mode_field=cur_mode;
3436 }
3437 stack_ptr++;
3438 if (stack_ptr>max_stack_ptr) max_stack_ptr=stack_ptr;
3439 cur_tok=*p; cur_end=*(p+1);
3440}
3441
3442@ Conversely, the |pop_level| routine restores the conditions that were in
3443force when the current level was begun. This subroutine will never be
3444called when |stack_ptr==1|.
3445
3446@c
3447void
3448pop_level()
3449{
3450 cur_end=(--stack_ptr)->end_field;
3451 cur_tok=stack_ptr->tok_field; cur_mode=stack_ptr->mode_field;
3452}
3453
3454@ The |get_output| function returns the next byte of output that is not a
3455reference to a token list. It returns the values |identifier| or |res_word|
3456or |section_code| if the next token is to be an identifier (typeset in
3457italics), a reserved word (typeset in boldface) or a section name (typeset
3458by a complex routine that might generate additional levels of output).
3459In these cases |cur_name| points to the identifier or section name in
3460question.
3461
3462@<Global...@>=
3463name_pointer cur_name;
3464
3465@ @d res_word 0201 /* returned by |get_output| for reserved words */
3466@d section_code 0200 /* returned by |get_output| for section names */
3467
3468@c
3469eight_bits
3470get_output() /* returns the next token of output */
3471{
3472 sixteen_bits a; /* current item read from |tok_mem| */
3473 restart: while (cur_tok==cur_end) pop_level();
3474 a=*(cur_tok++);
3475 if (a>=0400) {
3476 cur_name=a % id_flag + name_dir;
3477 switch (a / id_flag) {
3478 case 2: return(res_word); /* |a==res_flag+cur_name| */
3479 case 3: return(section_code); /* |a==section_flag+cur_name| */
3480 case 4: push_level(a % id_flag + tok_start); goto restart;
3481 /* |a==tok_flag+cur_name| */
3482 case 5: push_level(a % id_flag + tok_start); cur_mode=inner; goto restart;
3483 /* |a==inner_tok_flag+cur_name| */
3484 default: return(identifier); /* |a==id_flag+cur_name| */
3485 }
3486 }
3487 return(a);
3488}
3489
3490@ The real work associated with token output is done by |make_output|.
3491This procedure appends an |end_translation| token to the current token list,
3492and then it repeatedly calls |get_output| and feeds characters to the output
3493buffer until reaching the |end_translation| sentinel. It is possible for
3494|make_output| to be called recursively, since a section name may include
3495embedded \CEE/ text; however, the depth of recursion never exceeds one
3496level, since section names cannot be inside of section names.
3497
3498A procedure called |output_C| does the scanning, translation, and
3499output of \CEE/ text within `\pb' brackets, and this procedure uses
3500|make_output| to output the current token list. Thus, the recursive call
3501of |make_output| actually occurs when |make_output| calls |output_C|
3502while outputting the name of a section.
3503@^recursion@>
3504
3505The token list created from within `\pb' brackets is output as an argument
3506to \.{\\PB}. Although \.{cwebmac} ignores \.{\\PB}, other macro packages
3507might use it to localize the special meaning of the macros that mark up
3508program text.
3509
3510@c
3511void
3512output_C() /* outputs the current token list */
3513{
3514 token_pointer save_tok_ptr;
3515 text_pointer save_text_ptr;
3516 sixteen_bits save_next_control; /* values to be restored */
3517 text_pointer p; /* translation of the \CEE/ text */
3518 save_tok_ptr=tok_ptr; save_text_ptr=text_ptr;
3519 save_next_control=next_control; next_control=ignore; p=C_translate();
3520 app(inner_tok_flag+(int)(p-tok_start));
3521 out_str("\\PB{"); make_output(); out('}'); /* output the list */
3522@.\\PB@>
3523 if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
3524 if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
3525 text_ptr=save_text_ptr; tok_ptr=save_tok_ptr; /* forget the tokens */
3526 next_control=save_next_control; /* restore |next_control| to original state */
3527}
3528
3529@ Here is \.{CWEAVE}'s major output handler.
3530
3531@<Predecl...@>=
3532void make_output();
3533
3534@ @c
3535void
3536make_output() /* outputs the equivalents of tokens */
3537{
3538 eight_bits a, /* current output byte */
3539 b; /* next output byte */
3540 int c; /* count of |indent| and |outdent| tokens */
3541 char scratch[longest_name]; /* scratch area for section names */
3542 char *k, *k_limit; /* indices into |scratch| */
3543 char *j; /* index into |buffer| */
3544 char *p; /* index into |byte_mem| */
3545 char delim; /* first and last character of string being copied */
3546 char *save_loc, *save_limit; /* |loc| and |limit| to be restored */
3547 name_pointer cur_section_name; /* name of section being output */
3548 boolean save_mode; /* value of |cur_mode| before a sequence of breaks */
3549 app(end_translation); /* append a sentinel */
3550 freeze_text; push_level(text_ptr-1);
3551 while (1) {
3552 a=get_output();
3553 reswitch: switch(a) {
3554 case end_translation: return;
3555 case identifier: case res_word: @<Output an identifier@>; break;
3556 case section_code: @<Output a section name@>; break;
3557 case math_rel: out_str("\\MRL{"@q}@>);
3558@.\\MRL@>
3559 case noop: case inserted: break;
3560 case cancel: case big_cancel: c=0; b=a;
3561 while (1) {
3562 a=get_output();
3563 if (a==inserted) continue;
3564 if ((a<indent && !(b==big_cancel&&a==' ')) || a>big_force) break;
3565 if (a==indent) c++; else if (a==outdent) c--;
3566 else if (a==opt) a=get_output();
3567 }
3568 @<Output saved |indent| or |outdent| tokens@>;
3569 goto reswitch;
3570 case indent: case outdent: case opt: case backup: case break_space:
3571 case force: case big_force: case preproc_line: @<Output a control,
3572 look ahead in case of line breaks, possibly |goto reswitch|@>; break;
3573 case quoted_char: out(*(cur_tok++)); break;
3574 default: out(a); /* otherwise |a| is an ordinary character */
3575 }
3576 }
3577}
3578
3579@ An identifier of length one does not have to be enclosed in braces, and it
3580looks slightly better if set in a math-italic font instead of a (slightly
3581narrower) text-italic font. Thus we output `\.{\\\v}\.{a}' but
3582`\.{\\\\\{aa\}}'.
3583
3584@<Output an identifier@>=
3585out('\\');
3586if (a==identifier) {
3587 if (cur_name->ilk>=custom && cur_name->ilk<=quoted && !doing_format) {
3588 for (p=cur_name->byte_start;p<(cur_name+1)->byte_start;p++)
3589 out(isxalpha(*p)? 'x':*p);
3590 break;
3591 } else if (is_tiny(cur_name)) out('|')
3592@.\\|@>
3593 else { delim='.';
3594 for (p=cur_name->byte_start;p<(cur_name+1)->byte_start;p++)
3595 if (xislower(*p)) { /* not entirely uppercase */
3596 delim='\\'; break;
3597 }
3598 out(delim);
3599 }
3600@.\\\\@>
3601@.\\.@>
3602}
3603else out('&') /* |a==res_word| */
3604@.\\\&@>
3605if (is_tiny(cur_name)) {
3606 if (isxalpha((cur_name->byte_start)[0]))
3607 out('\\');
3608 out((cur_name->byte_start)[0]);
3609}
3610else out_name(cur_name);
3611
3612@ The current mode does not affect the behavior of \.{CWEAVE}'s output routine
3613except when we are outputting control tokens.
3614
3615@<Output a control...@>=
3616if (a<break_space || a==preproc_line) {
3617 if (cur_mode==outer) {
3618 out('\\'); out(a-cancel+'0');
3619@.\\1@>
3620@.\\2@>
3621@.\\3@>
3622@.\\4@>
3623@.\\8@>
3624 if (a==opt) {
3625 b=get_output(); /* |opt| is followed by a digit */
3626 if (b!='0' || force_lines==0) out(b)@;
3627 else out_str("{-1}"); /* |force_lines| encourages more \.{@@\v} breaks */
3628 }
3629 } else if (a==opt) b=get_output(); /* ignore digit following |opt| */
3630 }
3631else @<Look ahead for strongest line break, |goto reswitch|@>
3632
3633@ If several of the tokens |break_space|, |force|, |big_force| occur in a
3634row, possibly mixed with blank spaces (which are ignored),
3635the largest one is used. A line break also occurs in the output file,
3636except at the very end of the translation. The very first line break
3637is suppressed (i.e., a line break that follows `\.{\\Y\\B}').
3638
3639@<Look ahead for st...@>= {
3640 b=a; save_mode=cur_mode; c=0;
3641 while (1) {
3642 a=get_output();
3643 if (a==inserted) continue;
3644 if (a==cancel || a==big_cancel) {
3645 @<Output saved |indent| or |outdent| tokens@>;
3646 goto reswitch; /* |cancel| overrides everything */
3647 }
3648 if ((a!=' ' && a<indent) || a==backup || a>big_force) {
3649 if (save_mode==outer) {
3650 if (out_ptr>out_buf+3 && strncmp(out_ptr-3,"\\Y\\B",4)==0)
3651 goto reswitch;
3652 @<Output saved |indent| or |outdent| tokens@>;
3653 out('\\'); out(b-cancel+'0');
3654@.\\5@>
3655@.\\6@>
3656@.\\7@>
3657 if (a!=end_translation) finish_line();
3658 }
3659 else if (a!=end_translation && cur_mode==inner) out(' ');
3660 goto reswitch;
3661 }
3662 if (a==indent) c++;
3663 else if (a==outdent) c--;
3664 else if (a==opt) a=get_output();
3665 else if (a>b) b=a; /* if |a==' '| we have |a<b| */
3666 }
3667}
3668
3669@ @<Output saved...@>=
3670 for (;c>0;c--) out_str("\\1");
3671@.\\1@>
3672 for (;c<0;c++) out_str("\\2");
3673@.\\2@>
3674
3675@ The remaining part of |make_output| is somewhat more complicated. When we
3676output a section name, we may need to enter the parsing and translation
3677routines, since the name may contain \CEE/ code embedded in
3678\pb\ constructions. This \CEE/ code is placed at the end of the active
3679input buffer and the translation process uses the end of the active
3680|tok_mem| area.
3681
3682@<Output a section name@>= {
3683 out_str("\\X");
3684@.\\X@>
3685 cur_xref=(xref_pointer)cur_name->xref;
3686 if (cur_xref->num==file_flag) {an_output=1; cur_xref=cur_xref->xlink;}
3687 else an_output=0;
3688 if (cur_xref->num>=def_flag) {
3689 out_section(cur_xref->num-def_flag);
3690 if (phase==3) {
3691 cur_xref=cur_xref->xlink;
3692 while (cur_xref->num>=def_flag) {
3693 out_str(", ");
3694 out_section(cur_xref->num-def_flag);
3695 cur_xref=cur_xref->xlink;
3696 }
3697 }
3698 }
3699 else out('0'); /* output the section number, or zero if it was undefined */
3700 out(':');
3701 if (an_output) out_str("\\.{"@q}@>);
3702@.\\.@>
3703 @<Output the text of the section name@>;
3704 if (an_output) out_str(@q{@>" }");
3705 out_str("\\X");
3706}
3707
3708@ @<Output the text...@>=
3709sprint_section_name(scratch,cur_name);
3710k=scratch;
3711k_limit=scratch+strlen(scratch);
3712cur_section_name=cur_name;
3713while (k<k_limit) {
3714 b=*(k++);
3715 if (b=='@@') @<Skip next character, give error if not `\.{@@}'@>;
3716 if (an_output)
3717 switch (b) {
3718 case ' ':case '\\':case '#':case '%':case '$':case '^':
3719 case '{': case '}': case '~': case '&': case '_':
3720 out('\\'); /* falls through */
3721@.\\\ @>
3722@.\\\\@>
3723@.\\\#@>
3724@.\\\%@>
3725@.\\\$@>
3726@.\\\^@>
3727@.\\\{@>@q}@>
3728@q{@>@.\\\}@>
3729@.\\\~@>
3730@.\\\&@>
3731@.\\_@> @q CWEAVE does quote an underscore! @>
3732 default: out(b);
3733 }
3734 else if (b!='|') out(b)
3735 else {
3736 @<Copy the \CEE/ text into the |buffer| array@>;
3737 save_loc=loc; save_limit=limit; loc=limit+2; limit=j+1;
3738 *limit='|'; output_C();
3739 loc=save_loc; limit=save_limit;
3740 }
3741}
3742
3743@ @<Skip next char...@>=
3744if (*k++!='@@') {
3745 printf("\n! Illegal control code in section name: <");
3746@.Illegal control code...@>
3747 print_section_name(cur_section_name); printf("> "); mark_error;
3748}
3749
3750@ The \CEE/ text enclosed in \pb\ should not contain `\.{\v}' characters,
3751except within strings. We put a `\.{\v}' at the front of the buffer, so that an
3752error message that displays the whole buffer will look a little bit sensible.
3753The variable |delim| is zero outside of strings, otherwise it
3754equals the delimiter that began the string being copied.
3755
3756@<Copy the \CEE/ text into...@>=
3757j=limit+1; *j='|'; delim=0;
3758while (1) {
3759 if (k>=k_limit) {
3760 printf("\n! C text in section name didn't end: <");
3761@.C text...didn't end@>
3762 print_section_name(cur_section_name); printf("> "); mark_error; break;
3763 }
3764 b=*(k++);
3765 if (b=='@@' || (b=='\\' && delim!=0))
3766 @<Copy a quoted character into the buffer@>
3767 else {
3768 if (b=='\'' || b=='"')
3769 if (delim==0) delim=b;
3770 else if (delim==b) delim=0;
3771 if (b!='|' || delim!=0) {
3772 if (j>buffer+long_buf_size-3) overflow("buffer");
3773 *(++j)=b;
3774 }
3775 else break;
3776 }
3777}
3778
3779@ @<Copy a quoted char...@>= {
3780 if (j>buffer+long_buf_size-4) overflow("buffer");
3781 *(++j)=b; *(++j)=*(k++);
3782}
3783
3784@** Phase two processing.
3785We have assembled enough pieces of the puzzle in order to be ready to specify
3786the processing in \.{CWEAVE}'s main pass over the source file. Phase two
3787is analogous to phase one, except that more work is involved because we must
3788actually output the \TEX/ material instead of merely looking at the
3789\.{CWEB} specifications.
3790
3791@<Predecl...@>=
3792void phase_two();
3793
3794@ @c
3795void
3796phase_two() {
3797reset_input(); if (show_progress) printf("\nWriting the output file...");
3798@.Writing the output file...@>
3799section_count=0; format_visible=1; copy_limbo();
3800finish_line(); flush_buffer(out_buf,0,0); /* insert a blank line, it looks nice */
3801while (!input_has_ended) @<Translate the current section@>;
3802}
3803
3804@ The output file will contain the control sequence \.{\\Y} between non-null
3805sections of a section, e.g., between the \TEX/ and definition parts if both
3806are nonempty. This puts a little white space between the parts when they are
3807printed. However, we don't want \.{\\Y} to occur between two definitions
3808within a single section. The variables |out_line| or |out_ptr| will
3809change if a section is non-null, so the following macros `|save_position|'
3810and `|emit_space_if_needed|' are able to handle the situation:
3811
3812@d save_position save_line=out_line; save_place=out_ptr
3813@d emit_space_if_needed if (save_line!=out_line || save_place!=out_ptr)
3814 out_str("\\Y");
3815 space_checked=1
3816@.\\Y@>
3817
3818@<Global...@>=
3819int save_line; /* former value of |out_line| */
3820char *save_place; /* former value of |out_ptr| */
3821int sec_depth; /* the integer, if any, following \.{@@*} */
3822boolean space_checked; /* have we done |emit_space_if_needed|? */
3823boolean format_visible; /* should the next format declaration be output? */
3824boolean doing_format=0; /* are we outputting a format declaration? */
3825boolean group_found=0; /* has a starred section occurred? */
3826
3827@ @<Translate the current section@>= {
3828 section_count++;
3829 @<Output the code for the beginning of a new section@>;
3830 save_position;
3831 @<Translate the \TEX/ part of the current section@>;
3832 @<Translate the definition part of the current section@>;
3833 @<Translate the \CEE/ part of the current section@>;
3834 @<Show cross-references to this section@>;
3835 @<Output the code for the end of a section@>;
3836}
3837
3838@ Sections beginning with the \.{CWEB} control sequence `\.{@@\ }' start in the
3839output with the \TEX/ control sequence `\.{\\M}', followed by the section
3840number. Similarly, `\.{@@*}' sections lead to the control sequence `\.{\\N}'.
3841In this case there's an additional parameter, representing one plus the
3842specified depth, immediately after the \.{\\N}.
3843If the section has changed, we put \.{\\*} just after the section number.
3844
3845@<Output the code for the beginning...@>=
3846if (*(loc-1)!='*') out_str("\\M");
3847@.\\M@>
3848else {
3849 while (*loc == ' ') loc++;
3850 if (*loc=='*') { /* ``top'' level */
3851 sec_depth = -1;
3852 loc++;
3853 }
3854 else {
3855 for (sec_depth=0; xisdigit(*loc);loc++)
3856 sec_depth = sec_depth*10 + (*loc) -'0';
3857 }
3858 while (*loc == ' ') loc++; /* remove spaces before group title */
3859 group_found=1;
3860 out_str("\\N");
3861@.\\N@>
3862 {@+ char s[32];@+sprintf(s,"{%d}",sec_depth+1);@+out_str(s);@+}
3863 if (show_progress)
3864 printf("*%d",section_count); update_terminal; /* print a progress report */
3865}
3866out_str("{");out_section(section_count); out_str("}");
3867
3868@ In the \TEX/ part of a section, we simply copy the source text, except that
3869index entries are not copied and \CEE/ text within \pb\ is translated.
3870
3871@<Translate the \T...@>= do {
3872 next_control=copy_TeX();
3873 switch (next_control) {
3874 case '|': init_stack; output_C(); break;
3875 case '@@': out('@@'); break;
3876 case TeX_string: case noop:
3877 case xref_roman: case xref_wildcard: case xref_typewriter:
3878 case section_name: loc-=2; next_control=get_next(); /* skip to \.{@@>} */
3879 if (next_control==TeX_string)
3880 err_print("! TeX string should be in C text only"); break;
3881@.TeX string should be...@>
3882 case thin_space: case math_break: case ord:
3883 case line_break: case big_line_break: case no_line_break: case join:
3884 case pseudo_semi: case macro_arg_open: case macro_arg_close:
3885 case output_defs_code:
3886 err_print("! You can't do that in TeX text"); break;
3887@.You can't do that...@>
3888 }
3889} while (next_control<format_code);
3890
3891@ When we get to the following code we have |next_control>=format_code|, and
3892the token memory is in its initial empty state.
3893
3894@<Translate the d...@>=
3895space_checked=0;
3896while (next_control<=definition) { /* |format_code| or |definition| */
3897 init_stack;
3898 if (next_control==definition) @<Start a macro definition@>@;
3899 else @<Start a format definition@>;
3900 outer_parse(); finish_C(format_visible); format_visible=1;
3901 doing_format=0;
3902}
3903
3904@ The |finish_C| procedure outputs the translation of the current
3905scraps, preceded by the control sequence `\.{\\B}' and followed by the
3906control sequence `\.{\\par}'. It also restores the token and scrap
3907memories to their initial empty state.
3908
3909A |force| token is appended to the current scraps before translation
3910takes place, so that the translation will normally end with \.{\\6} or
3911\.{\\7} (the \TEX/ macros for |force| and |big_force|). This \.{\\6} or
3912\.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.
3913
3914@<Predecl...@>=
3915void finish_C();
3916
3917@ @c
3918void
3919finish_C(visible) /* finishes a definition or a \CEE/ part */
3920 boolean visible; /* nonzero if we should produce \TEX/ output */
3921{
3922 text_pointer p; /* translation of the scraps */
3923 if (visible) {
3924 out_str("\\B"); app_tok(force); app_scrap(insert,no_math);
3925 p=translate();
3926@.\\B@>
3927 app(tok_flag+(int)(p-tok_start)); make_output(); /* output the list */
3928 if (out_ptr>out_buf+1)
3929 if (*(out_ptr-1)=='\\')
3930@.\\6@>
3931@.\\7@>
3932@.\\Y@>
3933 if (*out_ptr=='6') out_ptr-=2;
3934 else if (*out_ptr=='7') *out_ptr='Y';
3935 out_str("\\par"); finish_line();
3936 }
3937 if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
3938 if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
3939 if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
3940 tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info;
3941 /* forget the tokens and the scraps */
3942}
3943
3944@ Keeping in line with the conventions of the \CEE/ preprocessor (and
3945otherwise contrary to the rules of \.{CWEB}) we distinguish here
3946between the case that `\.(' immediately follows an identifier and the
3947case that the two are separated by a space. In the latter case, and
3948if the identifier is not followed by `\.(' at all, the replacement
3949text starts immediately after the identifier. In the former case,
3950it starts after we scan the matching `\.)'.
3951
3952@<Start a macro...@>= {
3953 if (save_line!=out_line || save_place!=out_ptr) app(backup);
3954 if(!space_checked){emit_space_if_needed;save_position;}
3955 app_str("\\D"); /* this will produce `\&{define }' */
3956@.\\D@>
3957 if ((next_control=get_next())!=identifier)
3958 err_print("! Improper macro definition");
3959@.Improper macro definition@>
3960 else {
3961 app('$'); app_cur_id(0);
3962 if (*loc=='(')
3963 reswitch: switch (next_control=get_next()) {
3964 case '(': case ',': app(next_control); goto reswitch;
3965 case identifier: app_cur_id(0); goto reswitch;
3966 case ')': app(next_control); next_control=get_next(); break;
3967 default: err_print("! Improper macro definition"); break;
3968 }
3969 else next_control=get_next();
3970 app_str("$ "); app(break_space);
3971 app_scrap(dead,no_math); /* scrap won't take part in the parsing */
3972 }
3973}
3974
3975@ @<Start a format...@>= {
3976 doing_format=1;
3977 if(*(loc-1)=='s' || *(loc-1)=='S') format_visible=0;
3978 if(!space_checked){emit_space_if_needed;save_position;}
3979 app_str("\\F"); /* this will produce `\&{format }' */
3980@.\\F@>
3981 next_control=get_next();
3982 if (next_control==identifier) {
3983 app(id_flag+(int)(id_lookup(id_first, id_loc,normal)-name_dir));
3984 app(' ');
3985 app(break_space); /* this is syntactically separate from what follows */
3986 next_control=get_next();
3987 if (next_control==identifier) {
3988 app(id_flag+(int)(id_lookup(id_first, id_loc,normal)-name_dir));
3989 app_scrap(exp,maybe_math); app_scrap(semi,maybe_math);
3990 next_control=get_next();
3991 }
3992 }
3993 if (scrap_ptr!=scrap_info+2) err_print("! Improper format definition");
3994@.Improper format definition@>
3995}
3996
3997@ Finally, when the \TEX/ and definition parts have been treated, we have
3998|next_control>=begin_C|. We will make the global variable |this_section|
3999point to the current section name, if it has a name.
4000
4001@<Global...@>=
4002name_pointer this_section; /* the current section name, or zero */
4003
4004@ @<Translate the \CEE/...@>=
4005this_section=name_dir;
4006if (next_control<=section_name) {
4007 emit_space_if_needed; init_stack;
4008 if (next_control==begin_C) next_control=get_next();
4009 else {
4010 this_section=cur_section;
4011 @<Check that '=' or '==' follows this section name, and
4012 emit the scraps to start the section definition@>;
4013 }
4014 while (next_control<=section_name) {
4015 outer_parse();
4016 @<Emit the scrap for a section name if present@>;
4017 }
4018 finish_C(1);
4019}
4020
4021@ The title of the section and an $\E$ or $\mathrel+\E$ are made
4022into a scrap that should not take part in the parsing.
4023
4024@<Check that '='...@>=
4025do next_control=get_next();
4026 while (next_control=='+'); /* allow optional `\.{+=}' */
4027if (next_control!='=' && next_control!=eq_eq)
4028 err_print("! You need an = sign after the section name");
4029@.You need an = sign...@>
4030 else next_control=get_next();
4031if (out_ptr>out_buf+1 && *out_ptr=='Y' && *(out_ptr-1)=='\\') app(backup);
4032 /* the section name will be flush left */
4033@.\\Y@>
4034app(section_flag+(int)(this_section-name_dir));
4035cur_xref=(xref_pointer)this_section->xref;
4036if(cur_xref->num==file_flag) cur_xref=cur_xref->xlink;
4037app_str("${}");
4038if (cur_xref->num!=section_count+def_flag) {
4039 app_str("\\mathrel+"); /*section name is multiply defined*/
4040 this_section=name_dir; /*so we won't give cross-reference info here*/
4041}
4042app_str("\\E"); /* output an equivalence sign */
4043@.\\E@>
4044app_str("{}$");
4045app(force); app_scrap(dead,no_math);
4046 /* this forces a line break unless `\.{@@+}' follows */
4047
4048@ @<Emit the scrap...@>=
4049if (next_control<section_name) {
4050 err_print("! You can't do that in C text");
4051@.You can't do that...@>
4052 next_control=get_next();
4053}
4054else if (next_control==section_name) {
4055 app(section_flag+(int)(cur_section-name_dir));
4056 app_scrap(section_scrap,maybe_math);
4057 next_control=get_next();
4058}
4059
4060@ Cross references relating to a named section are given
4061after the section ends.
4062
4063@<Show cross...@>=
4064if (this_section>name_dir) {
4065 cur_xref=(xref_pointer)this_section->xref;
4066 if (cur_xref->num==file_flag){an_output=1;cur_xref=cur_xref->xlink;}
4067 else an_output=0;
4068 if (cur_xref->num>def_flag)
4069 cur_xref=cur_xref->xlink; /* bypass current section number */
4070 footnote(def_flag); footnote(cite_flag); footnote(0);
4071}
4072
4073@ The |footnote| procedure gives cross-reference information about
4074multiply defined section names (if the |flag| parameter is
4075|def_flag|), or about references to a section name
4076(if |flag==cite_flag|), or to its uses (if |flag==0|). It assumes that
4077|cur_xref| points to the first cross-reference entry of interest, and it
4078leaves |cur_xref| pointing to the first element not printed. Typical outputs:
4079`\.{\\A101.}'; `\.{\\Us 370\\ET1009.}';
4080`\.{\\As 8, 27\\*\\ETs64.}'.
4081
4082Note that the output of \.{CWEAVE} is not English-specific; users may
4083supply new definitions for the macros \.{\\A}, \.{\\As}, etc.
4084
4085@<Predecl...@>=
4086void footnote();
4087
4088@ @c
4089void
4090footnote(flag) /* outputs section cross-references */
4091sixteen_bits flag;
4092{
4093 xref_pointer q; /* cross-reference pointer variable */
4094 if (cur_xref->num<=flag) return;
4095 finish_line(); out('\\');
4096@.\\A@>
4097@.\\Q@>
4098@.\\U@>
4099 out(flag==0? 'U': flag==cite_flag? 'Q': 'A');
4100 @<Output all the section numbers on the reference list |cur_xref|@>;
4101 out('.');
4102}
4103
4104@ The following code distinguishes three cases, according as the number
4105of cross-references is one, two, or more than two. Variable |q| points
4106to the first cross-reference, and the last link is a zero.
4107
4108@<Output all the section numbers...@>=
4109q=cur_xref; if (q->xlink->num>flag) out('s'); /* plural */
4110while (1) {
4111 out_section(cur_xref->num-flag);
4112 cur_xref=cur_xref->xlink; /* point to the next cross-reference to output */
4113 if (cur_xref->num<=flag) break;
4114 if (cur_xref->xlink->num>flag) out_str(", "); /* not the last */
4115 else {out_str("\\ET"); /* the last */
4116@.\\ET@>
4117 if (cur_xref != q->xlink) out('s'); /* the last of more than two */
4118 }
4119}
4120
4121@ @<Output the code for the end of a section@>=
4122out_str("\\fi"); finish_line();
4123@.\\fi@>
4124flush_buffer(out_buf,0,0); /* insert a blank line, it looks nice */
4125
4126@** Phase three processing.
4127We are nearly finished! \.{CWEAVE}'s only remaining task is to write out the
4128index, after sorting the identifiers and index entries.
4129
4130If the user has set the |no_xref| flag (the |-x| option on the command line),
4131just finish off the page, omitting the index, section name list, and table of
4132contents.
4133
4134@<Predecl...@>=
4135void phase_three();
4136
4137@ @c
4138void
4139phase_three() {
4140if (no_xref) {
4141 finish_line();
4142 out_str("\\end");
4143@.\\end@>
4144 finish_line();
4145}
4146else {
4147 phase=3; if (show_progress) printf("\nWriting the index...");
4148@.Writing the index...@>
4149 finish_line();
4150 if ((idx_file=fopen(idx_file_name,"w"))==NULL)
4151 fatal("! Cannot open index file ",idx_file_name);
4152@.Cannot open index file@>
4153 if (change_exists) {
4154 @<Tell about changed sections@>; finish_line(); finish_line();
4155 }
4156 out_str("\\inx"); finish_line();
4157@.\\inx@>
4158 active_file=idx_file; /* change active file to the index file */
4159 @<Do the first pass of sorting@>;
4160 @<Sort and output the index@>;
4161 finish_line(); fclose(active_file); /* finished with |idx_file| */
4162 active_file=tex_file; /* switch back to |tex_file| for a tic */
4163 out_str("\\fin"); finish_line();
4164@.\\fin@>
4165 if ((scn_file=fopen(scn_file_name,"w"))==NULL)
4166 fatal("! Cannot open section file ",scn_file_name);
4167@.Cannot open section file@>
4168 active_file=scn_file; /* change active file to section listing file */
4169 @<Output all the section names@>;
4170 finish_line(); fclose(active_file); /* finished with |scn_file| */
4171 active_file=tex_file;
4172 if (group_found) out_str("\\con");@+else out_str("\\end");
4173@.\\con@>
4174@.\\end@>
4175 finish_line();
4176 fclose(active_file);
4177}
4178if (show_happiness) printf("\nDone.");
4179check_complete(); /* was all of the change file used? */
4180}
4181
4182@ Just before the index comes a list of all the changed sections, including
4183the index section itself.
4184
4185@<Global...@>=
4186sixteen_bits k_section; /* runs through the sections */
4187
4188@ @<Tell about changed sections@>= {
4189 /* remember that the index is already marked as changed */
4190 k_section=0;
4191 while (!changed_section[++k_section]);
4192 out_str("\\ch ");
4193@.\\ch@>
4194 out_section(k_section);
4195 while (k_section<section_count) {
4196 while (!changed_section[++k_section]);
4197 out_str(", "); out_section(k_section);
4198 }
4199 out('.');
4200}
4201
4202@ A left-to-right radix sorting method is used, since this makes it easy to
4203adjust the collating sequence and since the running time will be at worst
4204proportional to the total length of all entries in the index. We put the
4205identifiers into 102 different lists based on their first characters.
4206(Uppercase letters are put into the same list as the corresponding lowercase
4207letters, since we want to have `$t<\\{TeX}<\&{to}$'.) The
4208list for character |c| begins at location |bucket[c]| and continues through
4209the |blink| array.
4210
4211@<Global...@>=
4212name_pointer bucket[256];
4213name_pointer next_name; /* successor of |cur_name| when sorting */
4214name_pointer blink[max_names]; /* links in the buckets */
4215
4216@ To begin the sorting, we go through all the hash lists and put each entry
4217having a nonempty cross-reference list into the proper bucket.
4218
4219@<Do the first pass...@>= {
4220int c;
4221for (c=0; c<=255; c++) bucket[c]=NULL;
4222for (h=hash; h<=hash_end; h++) {
4223 next_name=*h;
4224 while (next_name) {
4225 cur_name=next_name; next_name=cur_name->link;
4226 if (cur_name->xref!=(char*)xmem) {
4227 c=(eight_bits)((cur_name->byte_start)[0]);
4228 if (xisupper(c)) c=tolower(c);
4229 blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
4230 }
4231 }
4232}
4233}
4234
4235@ During the sorting phase we shall use the |cat| and |trans| arrays from
4236\.{CWEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
4237represent a stack of identifier lists for all the index entries that have
4238not yet been output. The variable |sort_ptr| tells how many such lists are
4239present; the lists are output in reverse order (first |sort_ptr|, then
4240|sort_ptr-1|, etc.). The |j|th list starts at |head[j]|, and if the first
4241|k| characters of all entries on this list are known to be equal we have
4242|depth[j]==k|.
4243
4244@ @<Rest of |trans_plus| union@>=
4245name_pointer Head;
4246
4247@ @d depth cat /* reclaims memory that is no longer needed for parsing */
4248@d head trans_plus.Head /* ditto */
4249@f sort_pointer int
4250@d sort_pointer scrap_pointer /* ditto */
4251@d sort_ptr scrap_ptr /* ditto */
4252@d max_sorts max_scraps /* ditto */
4253
4254@<Global...@>=
4255eight_bits cur_depth; /* depth of current buckets */
4256char *cur_byte; /* index into |byte_mem| */
4257sixteen_bits cur_val; /* current cross-reference number */
4258sort_pointer max_sort_ptr; /* largest value of |sort_ptr| */
4259
4260@ @<Set init...@>=
4261max_sort_ptr=scrap_info;
4262
4263@ The desired alphabetic order is specified by the |collate| array; namely,
4264|collate[0]<collate[1]<@t$\cdots$@><collate[100]|.
4265
4266@<Global...@>=
4267eight_bits collate[102+128]; /* collation order */
4268@^high-bit character handling@>
4269
4270@ We use the order $\hbox{null}<\.\ <\hbox{other characters}<{}$\.\_${}<
4271\.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$ Warning: The collation mapping
4272needs to be changed if ASCII code is not being used.
4273@^ASCII code dependencies@>
4274@^high-bit character handling@>
4275
4276@<Set init...@>=
4277collate[0]=0; strcpy(collate+1," \1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\
4278\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\
4279!\42#$%&'()*+,-./:;<=>?@@[\\]^`{|}~_\
4280abcdefghijklmnopqrstuvwxyz0123456789\
4281\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\
4282\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\
4283\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\
4284\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\
4285\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\
4286\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\
4287\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\
4288\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\
4289");
4290
4291@ Procedure |unbucket| goes through the buckets and adds nonempty lists
4292to the stack, using the collating sequence specified in the |collate| array.
4293The parameter to |unbucket| tells the current depth in the buckets.
4294Any two sequences that agree in their first 255 character positions are
4295regarded as identical.
4296
4297@d infinity 255 /* $\infty$ (approximately) */
4298
4299@<Predecl...@>=
4300void unbucket();
4301
4302@ @c
4303void
4304unbucket(d) /* empties buckets having depth |d| */
4305eight_bits d;
4306{
4307 int c; /* index into |bucket|; cannot be a simple |char| because of sign
4308 comparison below*/
4309 for (c=100+128; c>= 0; c--) if (bucket[collate[c]]) {
4310@^high-bit character handling@>
4311 if (sort_ptr>=scrap_info_end) overflow("sorting");
4312 sort_ptr++;
4313 if (sort_ptr>max_sort_ptr) max_sort_ptr=sort_ptr;
4314 if (c==0) sort_ptr->depth=infinity;
4315 else sort_ptr->depth=d;
4316 sort_ptr->head=bucket[collate[c]]; bucket[collate[c]]=NULL;
4317 }
4318}
4319
4320@ @<Sort and output...@>=
4321sort_ptr=scrap_info; unbucket(1);
4322while (sort_ptr>scrap_info) {
4323 cur_depth=sort_ptr->depth;
4324 if (blink[sort_ptr->head-name_dir]==0 || cur_depth==infinity)
4325 @<Output index entries for the list at |sort_ptr|@>@;
4326 else @<Split the list at |sort_ptr| into further lists@>;
4327}
4328
4329@ @<Split the list...@>= {
4330 eight_bits c;
4331 next_name=sort_ptr->head;
4332 do {
4333 cur_name=next_name; next_name=blink[cur_name-name_dir];
4334 cur_byte=cur_name->byte_start+cur_depth;
4335 if (cur_byte==(cur_name+1)->byte_start) c=0; /* hit end of the name */
4336 else {
4337 c=(eight_bits) *cur_byte;
4338 if (xisupper(c)) c=tolower(c);
4339 }
4340 blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
4341 } while (next_name);
4342 --sort_ptr; unbucket(cur_depth+1);
4343}
4344
4345@ @<Output index...@>= {
4346 cur_name=sort_ptr->head;
4347 do {
4348 out_str("\\I");
4349@.\\I@>
4350 @<Output the name at |cur_name|@>;
4351 @<Output the cross-references at |cur_name|@>;
4352 cur_name=blink[cur_name-name_dir];
4353 } while (cur_name);
4354 --sort_ptr;
4355}
4356
4357@ @<Output the name...@>=
4358switch (cur_name->ilk) {
4359 case normal: if (is_tiny(cur_name)) out_str("\\|");
4360 else {char *j;
4361 for (j=cur_name->byte_start;j<(cur_name+1)->byte_start;j++)
4362 if (xislower(*j)) goto lowcase;
4363 out_str("\\."); break;
4364lowcase: out_str("\\\\");
4365 }
4366 break;
4367@.\\|@>
4368@.\\.@>
4369@.\\\\@>
4370 case roman: break;
4371 case wildcard: out_str("\\9"); break;
4372@.\\9@>
4373 case typewriter: out_str("\\."); break;
4374@.\\.@>
4375 case custom: case quoted: {char *j; out_str("$\\");
4376 for (j=cur_name->byte_start;j<(cur_name+1)->byte_start;j++)
4377 out(isxalpha(*j)? 'x' : *j);
4378 out('$');
4379 goto name_done;
4380 }
4381 default: out_str("\\&");
4382@.\\\&@>
4383}
4384out_name(cur_name);
4385name_done:
4386
4387@ Section numbers that are to be underlined are enclosed in
4388`\.{\\[}$\,\ldots\,$\.]'.
4389
4390@<Output the cross-references...@>=
4391@<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
4392do {
4393 out_str(", "); cur_val=cur_xref->num;
4394 if (cur_val<def_flag) out_section(cur_val);
4395 else {out_str("\\["); out_section(cur_val-def_flag); out(']');}
4396@.\\[@>
4397 cur_xref=cur_xref->xlink;
4398} while (cur_xref!=xmem);
4399out('.'); finish_line();
4400
4401@ List inversion is best thought of as popping elements off one stack and
4402pushing them onto another. In this case |cur_xref| will be the head of
4403the stack that we push things onto.
4404@<Global...@>=
4405xref_pointer next_xref, this_xref;
4406 /* pointer variables for rearranging a list */
4407
4408@ @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
4409this_xref=(xref_pointer)cur_name->xref; cur_xref=xmem;
4410do {
4411 next_xref=this_xref->xlink; this_xref->xlink=cur_xref;
4412 cur_xref=this_xref; this_xref=next_xref;
4413} while (this_xref!=xmem);
4414
4415@ The following recursive procedure walks through the tree of section names and
4416prints them.
4417@^recursion@>
4418
4419@<Predecl...@>=
4420void section_print();
4421
4422@ @c
4423void
4424section_print(p) /* print all section names in subtree |p| */
4425name_pointer p;
4426{
4427 if (p) {
4428 section_print(p->llink); out_str("\\I");
4429@.\\I@>
4430 tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info; init_stack;
4431 app(p-name_dir+section_flag); make_output();
4432 footnote(cite_flag);
4433 footnote(0); /* |cur_xref| was set by |make_output| */
4434 finish_line();@/
4435 section_print(p->rlink);
4436 }
4437}
4438
4439@ @<Output all the section names@>=section_print(root)
4440
4441@ Because on some systems the difference between two pointers is a |long|
4442rather than an |int|, we use \.{\%ld} to print these quantities.
4443
4444@c
4445void
4446print_stats() {
4447 printf("\nMemory usage statistics:\n");
4448@.Memory usage statistics:@>
4449 printf("%ld names (out of %ld)\n",
4450 (long)(name_ptr-name_dir),(long)max_names);
4451 printf("%ld cross-references (out of %ld)\n",
4452 (long)(xref_ptr-xmem),(long)max_refs);
4453 printf("%ld bytes (out of %ld)\n",
4454 (long)(byte_ptr-byte_mem),(long)max_bytes);
4455 printf("Parsing:\n");
4456 printf("%ld scraps (out of %ld)\n",
4457 (long)(max_scr_ptr-scrap_info),(long)max_scraps);
4458 printf("%ld texts (out of %ld)\n",
4459 (long)(max_text_ptr-tok_start),(long)max_texts);
4460 printf("%ld tokens (out of %ld)\n",
4461 (long)(max_tok_ptr-tok_mem),(long)max_toks);
4462 printf("%ld levels (out of %ld)\n",
4463 (long)(max_stack_ptr-stack),(long)stack_size);
4464 printf("Sorting:\n");
4465 printf("%ld levels (out of %ld)\n",
4466 (long)(max_sort_ptr-scrap_info),(long)max_scraps);
4467}
4468
4469@** Index.
4470If you have read and understood the code for Phase III above, you know what
4471is in this index and how it got here. All sections in which an identifier is
4472used are listed with that identifier, except that reserved words are
4473indexed only when they appear in format definitions, and the appearances
4474of identifiers in section names are not indexed. Underlined entries
4475correspond to where the identifier was declared. Error messages, control
4476sequences put into the output, and a few
4477other things like ``recursion'' are indexed here too.
cweb.1+98−0
@@ -0,0 +1,98 @@
1.TH CWEB 1L 6/15/92
2.SH NAME
3ctangle, cweave \- translate CWEB to C and/or TeX
4.SH SYNOPSIS
5.B ctangle
6[
7.B \-bhp
8] [
9.B \+s
10] webfile[.w] [changefile[.ch]] [outputfile[.c]]
11.br
12.B cweave
13[
14.B \-bfhpx
15] [
16.B \+s
17] webfile[.w] [changefile[.ch]] [outputfile[.tex]]
18
19.SH DESCRIPTION
20The
21.I ctangle
22program converts a CWEB
23source document into a C program that may be compiled in the usual way.
24The output file includes #line specifications so that debugging can be
25done in terms of the CWEB source file.
26.PP
27The
28.I cweave
29program converts the same CWEB file into a TeX file that may be
30formatted and printed in the usual way.
31It takes appropriate care of typographic details like page
32layout and the use of indentation, italics, boldface, etc., and it supplies
33extensive cross-index information that it gathers automatically.
34.PP
35CWEB allows you to prepare a single
36document containing all the information that is needed both to produce
37a compilable C program and to produce a well-formatted document
38describing the program in as much detail as the writer may desire. The
39user of CWEB ought to be familiar with TeX as well as C.
40.PP
41The command line should have one, two, or three names on it.
42The first is taken as the CWEB file (and .w is added if there is no
43extension). If that file cannot be opened, the extension .web is
44tried instead. (But .w is recommended, since .web usually implies Pascal.)
45If there is a second name, it is a change file (and .ch is added if there is
46no extension). The change file overrides parts of the WEB file,
47as described in the documentation. If there is a third name, it overrides
48the default name of the output file, which is ordinarily the same as
49the name of the input file (but on the current directory) with the
50extension .c or .tex.
51.PP
52Options in the command line may be either turned off with -
53(if they are on by default) or turned on with + (if they are off by
54default). In fact, the options are processed from left to right,
55so a sequence like -f +f corresponds to +f (which is the default).
56.PP
57The
58.B \-b
59option suppresses the banner line that normally appears on your terminal
60when ctangle or cweave begins. The
61.B \-h
62option suppresses the happy message that normally appears if the processing
63was successful. The
64.B \-p
65option suppresses progress reports (starred module numbers) as the processing
66takes place. If you say -bhp, you get nothing but error messages.
67.PP
68The \+s option prints statistics about memory usage at the end of a run
69(assuming that the programs have been compiled with the -DSTAT switch).
70.PP
71There are two other options applicable to
72.I cweave
73only:
74.B \-f
75means do not force a newline after every statement in the formatted output.
76.B \-x
77means omit the index and table of contents.
78.PP
79.SH FILES
80/usr/local/lib/tex/inputs/cwebmac.tex TeX macros used by cweave output.
81.br
82/usr/local/src/cweb/cwebman.tex The user manual.
83.br
84/usr/local/src/cweb/examples/wc.w An introductory example.
85.br
86/usr/local/lib/cweb Directory for cweb "include" files.
87.SH "SEE ALSO"
88.I Literate Programming
89by D.E. Knuth.
90.br
91.I Weaving a Program
92by Wayne Sewell
93.br
94tex(1), cc(1)
95.SH "AUTHORS"
96Don Knuth wrote WEB for TeX and Pascal. Silvio Levy designed and developed CWEB
97by adapting the WEB conventions to C and by recoding everything in CWEB.
98Knuth began using CWEB and made further refinements.
cweb.el+222−0
@@ -0,0 +1,222 @@
1;; This file contains extensions to GNU-Emacs, to wit:
2; (1) some WEB-oriented functions that are also of general use
3; (2) changes to the GNU-distributed TeX mode
4; (3) definitions of simple WEB and CWEB modes
5
6; To use: Put this in your EMACS-lisp library and say (load-library "cweb")
7; in your .emacs init file.
8
9; Contributed by Don Knuth, July 1990
10
11;; OK, here's part (1): some WEB-oriented functions whose main purpose is
12; to maintain a stack of module names that are "pending" as you are writing
13; a program. When you first think of a module that needs to be written later,
14; put it into the pending list (by typing CTL-Z instead of @> after the
15; name). Later you can say CTL-\ to retrieve a pending name (and if
16; you want to cycle through the pending names, ESC-y after CTL-\ will
17; do it, just as ESC-y works after a yank).
18; After you've said CTL-\, the current region is the name just removed from
19; the pending list. If you change your mind, you can put it back again by
20; saying ESC-\. If you had put it into the pending list by mistake, you
21; can get rid of it by using the normal CTL-W operation (kill-region).
22; The following code binds the new commands to CTL-Z, CTL-\, and ESC-\
23; in all modes. You may prefer other bindings, of course.
24; CTL-Z is normally "suspend emacs", but it is best not used when emacs
25; has its own window as it usually does nowadays; if you need the
26; old CTL-Z, you might rather bind it to CTL-X CTL-Z.
27; CTL-\ is normally undefined.
28; ESC-\ is normally "delete space", but ESC-space DEL does that easily too.
29
30(defvar pending-list nil
31 "List of strings (usually WEB module names) still pending.")
32
33(defun into-pending-list (beg end)
34 "Copy region into pending-list."
35 (interactive "r")
36 (indicate-region)
37 (setq pending-list (cons (buffer-substring beg end) pending-list)))
38
39(defun new-module-name-pending ()
40 "Insert @> to complete a module name, then put it into pending-list."
41 (interactive)
42 (insert "@>")
43 (push-mark)
44 (if (search-backward "@<" nil t)
45 (progn
46 (exchange-point-and-mark)
47 (into-pending-list (point) (mark))
48 )
49 (message "There's no @< to begin the module name!")))
50(global-set-key "\C-z" 'new-module-name-pending)
51
52(defun pop-pending-list (arg)
53 "Remove first element of pending-list and insert it as current region.
54With argument, put point at left; otherwise point will follow the insertion.
55Say \\[new-yank-pop] to replace this by another element of the list.
56Say \\[into-pending-list] to put it back in the list."
57 (interactive "*P")
58 (if (consp pending-list)
59 (progn
60 (push-mark (point))
61 (insert (car pending-list))
62 (setq pending-list (cdr pending-list))
63 (if arg
64 (exchange-point-and-mark)))
65 (message "Nothing is pending.")
66 (setq this-command nil)))
67(global-set-key "\C-\\" 'pop-pending-list)
68(global-set-key "\M-\\" 'into-pending-list)
69
70(defun new-yank-pop (arg)
71 "If previous command was \\[pop-pending-list], pop a different string;
72otherwise do an ordinary Meta-y."
73 (interactive "*p")
74 (if (eq last-command 'pop-pending-list)
75 (let (xch)
76 (setq xch (< (point) (mark)))
77 (setq pending-list (append pending-list
78 (list (buffer-substring (point) (mark)))))
79 (delete-region (point) (mark))
80 (setq this-command 'pop-pending-list)
81 (pop-pending-list xch))
82 (yank-pop arg)))
83(global-set-key "\M-y" 'new-yank-pop)
84
85(defun indicate-region ()
86 "Bounce cursor to mark and back again"
87 (let ((point-save (point)))
88 (unwind-protect
89 (progn (goto-char (mark))
90; The next two lines of code are controversial ---
91; they seem to be the best way to do a short wait and redraw the screen with
92; standard emacs primitives --- but the short wait is a "busy wait".
93; On a faster machine, it would be better to install the function
94; sit-for-millisecs found in sunfns.c (if not already installed)
95; and to say (sit-for-millisecs 100) instead.
96; On a slower machine, do the call-process only once.
97; On a still slower machine, (sit-for 1) is probably best.
98 (call-process "echo" nil nil t)
99 (call-process "echo" nil nil t))
100 (goto-char point-save))))
101
102; I prefer to change the standard copy-region command to the following,
103; which gives me visual feedback about what I've copied to the kill ring:
104(defun indicate-and-copy-region (beg end)
105 "Indicate current region, then copy it to the kill ring."
106 (interactive "r")(indicate-region)(copy-region-as-kill beg end))
107(global-set-key "\M-w" 'indicate-and-copy-region)
108
109; Here's another convenient command, bound to the usually unused ESC-".
110(defun ditto (arg)
111 "Copy ARG characters from the line above."
112 (interactive "*p")
113 (let (ch)
114 (while (> arg 0)
115 (setq temporary-goal-column (current-column))
116 (save-excursion
117 (previous-line 1)
118 (setq ch (following-char)))
119 (insert ch)
120 (setq arg (1- arg)))))
121(global-set-key "\M-\"" 'ditto)
122
123;; OK, here's part (2): Changes to TeX mode.
124; The WEB modes below are very much like TeX mode, but some improvements were
125; desirable in TeX mode:
126; I made newline act as it does in indented-text mode, since this
127; works nicely for both TeX and WEB (Pascal or C code).
128; I made RET check for unmatched delimiters if it ends a paragraph.
129; Otherwise TeX mode remains as it was before.
130
131(setq TeX-mode-map (make-sparse-keymap))
132(define-key TeX-mode-map "\C-c\C-k" 'TeX-kill-job)
133(define-key TeX-mode-map "\C-c\C-l" 'TeX-recenter-output-buffer)
134(define-key TeX-mode-map "\C-c\C-q" 'TeX-show-print-queue)
135(define-key TeX-mode-map "\C-c\C-p" 'TeX-print)
136(define-key TeX-mode-map "\"" 'TeX-insert-quote)
137(define-key TeX-mode-map "\e}" 'up-list)
138(define-key TeX-mode-map "\e{" 'TeX-insert-braces)
139(define-key TeX-mode-map "\C-c\C-r" 'TeX-region)
140(define-key TeX-mode-map "\C-c\C-b" 'TeX-buffer)
141(define-key TeX-mode-map "\C-c\C-f" 'TeX-close-LaTeX-block)
142(define-key TeX-mode-map "\r" 'TeX-newline)
143(define-key TeX-mode-map "\t" 'indent-relative)
144(setq TeX-mode-hook '(lambda ()
145 (make-local-variable 'indent-line-function)
146 (setq indent-line-function 'indent-relative-maybe)))
147
148(defun TeX-newline (arg)
149"If previous character is newline and no ARG, check for unbalanced braces
150and/or dollar signs in previous paragraph. If ARG is \\[universal-argument],
151do a single newline; otherwise do ordinary newline."
152 (interactive "*P")
153 (if (and (eq (preceding-char) ?\n) (not arg))
154 (TeX-check-paragraph)
155 (if (listp arg)
156 (newline)
157 (newline arg))))
158
159(defun TeX-check-paragraph ()
160"Insert a newline following a newline, breaking a paragraph for TeX.
161Check for mismatched delimiters in paragraph being terminated."
162 (interactive)
163 (if (TeX-validate-paragraph
164 (save-excursion
165 (search-backward "\n\n" nil 'move)
166 (point))
167 (point))
168 (insert ?\n)
169 (insert ?\n)
170 (error "Mismatched delimiters in that paragraph?")))
171
172;; and now, part (3): WEB and CWEB modes.
173; These are like plain TeX mode except that the automatic conversion of
174; " to `` or '' is disabled. (Personally I never liked that feature anyway,
175; since it's easy to get used to typing `` and ''. In WEB modes, the
176; feature soon becomes intolerable, unless you never use string constants!)
177; Another thing distinguishing WEB mode from TeX is ESC-p and ESC-n, to
178; move to previous or next module. These keys are usually unbound, except
179; when processing email.
180
181(defun forward-module (arg)
182"Advance past next WEB module beginning; with ARG, repeat ARG times."
183 (interactive "p")
184 (move-to-module arg))
185(defun backward-module (arg)
186"Advance to previous WEB module beginning; with ARG, repeat ARG times."
187 (interactive "p")
188 (move-to-module (- arg)))
189(defun move-to-module (arg)
190 (while (> arg 0)
191 (re-search-forward "@ \\|@\\*\\|@\n")
192 (setq arg (1- arg)))
193 (while (< arg 0)
194 (re-search-backward "@ \\|@\\*\\|@\n")
195 (setq arg (1+ arg))))
196
197(defun web-mode ()
198 "Major mode like TeX mode plus \\[forward-module] and \\[backward-module]
199for relative module movement. The automatic \" feature is disabled."
200 (interactive)
201 (plain-tex-mode)
202 (local-set-key "\M-n" 'forward-module)
203 (local-set-key "\M-p" 'backward-module)
204 (local-set-key "\"" 'self-insert-command)
205 (setq mode-name "WEB")
206 (setq major-mode 'web-mode)
207 (run-hooks 'web-mode-hook))
208(setq auto-mode-alist (cons '("\\.web$" . web-mode) auto-mode-alist))
209
210(defun cweb-mode ()
211 "Major mode like TeX mode plus \\[forward-module] and \\[backward-module]
212for relative module movement. The automatic \" feature is disabled."
213 (interactive)
214 (plain-tex-mode)
215 (local-set-key "\M-n" 'forward-module)
216 (local-set-key "\M-p" 'backward-module)
217 (local-set-key "\"" 'self-insert-command)
218 (setq mode-name "CWEB")
219 (setq major-mode 'cweb-mode)
220 (run-hooks 'cweb-mode-hook))
221(setq auto-mode-alist (cons '("\\.w$" . cweb-mode) auto-mode-alist))
222(setq auto-mode-alist (cons '("\\.ch$" . cweb-mode) auto-mode-alist))
cwebmac.tex+331−0
@@ -0,0 +1,331 @@
1% standard macros for CWEB listings (in addition to plain.tex)
2% Version 3.0 --- June 1993
3\ifx\documentstyle\undefined\else\endinput\fi % LaTeX will use other macros
4\xdef\fmtversion{\fmtversion+CWEB3.0}
5
6\let\:=\. % preserve a way to get the dot accent
7 % (all other accents will still work as usual)
8
9\parskip 0pt % no stretch between paragraphs
10\parindent 1em % for paragraphs and for the first line of C text
11
12\font\ninerm=cmr9
13\let\mc=\ninerm % medium caps
14\def\CEE/{{\mc C\spacefactor1000}}
15\def\UNIX/{{\mc U\kern-.05emNIX\spacefactor1000}}
16\def\TEX/{\TeX}
17\def\CPLUSPLUS/{{\mc C\PP\spacefactor1000}}
18\def\Cee{\CEE/} % for backward compatibility
19\def\9#1{}
20\font\eightrm=cmr8
21\let\sc=\eightrm % small caps (NOT a caps-and-small-caps font)
22\let\mainfont=\tenrm
23\let\cmntfont\tenrm
24%\font\tenss=cmss10 \let\cmntfont\tenss % alternative comment font
25\font\titlefont=cmr7 scaled\magstep4 % title on the contents page
26\font\ttitlefont=cmtt10 scaled\magstep2 % typewriter type in title
27\font\tentex=cmtex10 % TeX extended character set (used in strings)
28\fontdimen7\tentex=0pt % no double space after sentences
29
30\def\\#1{\leavevmode\hbox{\it#1\/\kern.05em}} % italic type for identifiers
31\def\|#1{\leavevmode\hbox{$#1$}} % one-letter identifiers look better this way
32\def\&#1{\leavevmode\hbox{\bf
33 \def\_{\kern.04em\vbox{\hrule width.3em height .6pt}\kern.08em}%
34 #1\/\kern.05em}} % boldface type for reserved words
35\def\.#1{\leavevmode\hbox{\tentex % typewriter type for strings
36 \let\\=\BS % backslash in a string
37 \let\{=\LB % left brace in a string
38 \let\}=\RB % right brace in a string
39 \let\~=\TL % tilde in a string
40 \let\ =\SP % space in a string
41 \let\_=\UL % underline in a string
42 \let\&=\AM % ampersand in a string
43 \let\^=\CF % circumflex in a string
44 #1\kern.05em}}
45\def\){\discretionary{\hbox{\tentex\BS}}{}{}}
46\def\AT{@} % at sign for control text (not needed in versions >= 2.9)
47\def\ATL{\par\noindent\bgroup\catcode`\_=12 \postATL} % print @l in limbo
48\def\postATL#1 #2 {\bf letter \\{\uppercase{\char"#1}}
49 tangles as \tentex "#2"\egroup\par}
50\def\noATL#1 #2 {}
51\def\noatl{\let\ATL=\noATL} % suppress output from @l
52\def\ATH{\X\kern-.5em:Preprocessor definitions\X}
53\let\PB=\relax % hook for program brackets |...| in TeX part or section name
54
55\chardef\AM=`\& % ampersand character in a string
56\chardef\BS=`\\ % backslash in a string
57\chardef\LB=`\{ % left brace in a string
58\chardef\RB=`\} % right brace in a string
59\def\SP{{\tt\char`\ }} % (visible) space in a string
60\chardef\TL=`\~ % tilde in a string
61\chardef\UL=`\_ % underline character in a string
62\chardef\CF=`\^ % circumflex character in a string
63
64\newbox\PPbox % symbol for ++
65\setbox\PPbox=\hbox{\kern.5pt\raise1pt\hbox{\sevenrm+\kern-1pt+}\kern.5pt}
66\def\PP{\copy\PPbox}
67\newbox\MMbox \setbox\MMbox=\hbox{\kern.5pt\raise1pt\hbox{\sevensy\char0
68 \kern-1pt\char0}\kern.5pt}
69\def\MM{\copy\MMbox}
70\newbox\MGbox % symbol for ->
71\setbox\MGbox=\hbox{\kern-2pt\lower3pt\hbox{\teni\char'176}\kern1pt}
72\def\MG{\copy\MGbox}
73\def\MRL#1{\mathrel{\let\K==#1}}
74%\def\MRL#1{\KK#1}\def\KK#1#2{\buildrel\;#1\over{#2}}
75\let\GG=\gg
76\let\LL=\ll
77\let\NULL=\Lambda
78\mathchardef\AND="2026 % bitwise and; also \& (unary operator)
79\let\OR=\mid % bitwise or
80\let\XOR=\oplus % bitwise exclusive or
81\def\CM{{\sim}} % bitwise complement
82\newbox\MODbox \setbox\MODbox=\hbox{\eightrm\%}
83\def\MOD{\mathbin{\copy\MODbox}}
84\def\DC{\kern.1em{::}\kern.1em} % symbol for ::
85\def\PA{\mathbin{.*}} % symbol for .*
86\def\MGA{\mathbin{\MG*}} % symbol for ->*
87\def\this{\&{this}}
88
89\newbox\bak \setbox\bak=\hbox to -1em{} % backspace one em
90\newbox\bakk\setbox\bakk=\hbox to -2em{} % backspace two ems
91
92\newcount\ind % current indentation in ems
93\def\1{\global\advance\ind by1\hangindent\ind em} % indent one more notch
94\def\2{\global\advance\ind by-1} % indent one less notch
95\def\3#1{\hfil\penalty#10\hfilneg} % optional break within a statement
96\def\4{\copy\bak} % backspace one notch
97\def\5{\hfil\penalty-1\hfilneg\kern2.5em\copy\bakk\ignorespaces}% optional break
98\def\6{\ifmmode\else\par % forced break
99 \hangindent\ind em\noindent\kern\ind em\copy\bakk\ignorespaces\fi}
100\def\7{\Y\6} % forced break and a little extra space
101\def\8{\hskip-\ind em\hskip 2em} % no indentation
102
103\newcount\gdepth % depth of current major group, plus one
104\newcount\secpagedepth
105\secpagedepth=3 % page breaks will occur for depths -1, 0, and 1
106\newtoks\gtitle % title of current major group
107\newskip\intersecskip \intersecskip=12pt minus 3pt % space between sections
108\let\yskip=\smallskip
109\def\?{\mathrel?}
110\def\note#1#2.{\Y\noindent{\hangindent2em\baselineskip10pt\eightrm#1~#2.\par}}
111\def\lapstar{\rlap{*}}
112\def\stsec{\rightskip=0pt % get out of C mode (cf. \B)
113 \sfcode`;=1500 \pretolerance 200 \hyphenpenalty 50 \exhyphenpenalty 50
114 \noindent{\let\*=\lapstar\bf\secstar.\quad}}
115\let\startsection=\stsec
116\def\defin#1{\global\advance\ind by 2 \1\&{#1 } } % begin `define' or `format'
117\def\A{\note{See also section}} % xref for doubly defined section name
118\def\As{\note{See also sections}} % xref for multiply defined section name
119\def\B{\rightskip=0pt plus 100pt minus 10pt % go into C mode
120 \sfcode`;=3000
121 \pretolerance 10000
122 \hyphenpenalty 9999 % so strings can be broken (discretionary \ is inserted)
123 \exhyphenpenalty 10000
124 \global\ind=2 \1\ \unskip}
125\def\C#1{\5\5\quad$/\ast\,${\cmntfont #1}$\,\ast/$}
126\let\SHC\C % "// short comments" treated like "/* ordinary comments */"
127%\def\C#1{\5\5\quad$\triangleright\,${\cmntfont#1}$\,\triangleleft$}
128%\def\SHC#1{\5\5\quad$\diamond\,${\cmntfont#1}}
129\def\D{\defin{\#define}} % macro definition
130\let\E=\equiv % equivalence sign
131\def\ET{ and~} % conjunction between two section numbers
132\def\ETs{, and~} % conjunction between the last two of several section numbers
133\def\F{\defin{format}} % format definition
134\let\G=\ge % greater than or equal sign
135% \H is long Hungarian umlaut accent
136\let\I=\ne % unequal sign
137\def\J{\.{@\&}} % TANGLE's join operation
138\let\K== % assignment operator
139%\let\K=\leftarrow % "honest" alternative to standard assignment operator
140% \L is Polish letter suppressed-L
141\outer\def\M#1{\MN{#1}\ifon\vfil\penalty-100\vfilneg % beginning of section
142 \vskip\intersecskip\startsection\ignorespaces}
143\outer\def\N#1#2#3.{\gdepth=#1\gtitle={#3}\MN{#2}% beginning of starred section
144 \ifon\ifnum#1<\secpagedepth \vfil\eject % force page break if depth is small
145 \else\vfil\penalty-100\vfilneg\vskip\intersecskip\fi\fi
146 \message{*\secno} % progress report
147 \edef\next{\write\cont{\ZZ{#3}{#1}{\secno}% write to contents file
148 {\noexpand\the\pageno}}}\next % \ZZ{title}{depth}{sec}{page}
149 \ifon\startsection{\bf#3.\quad}\ignorespaces}
150\def\MN#1{\par % common code for \M, \N
151 {\xdef\secstar{#1}\let\*=\empty\xdef\secno{#1}}% remove \* from section name
152 \ifx\secno\secstar \onmaybe \else\ontrue \fi
153 \mark{{{\tensy x}\secno}{\the\gdepth}{\the\gtitle}}}
154% each \mark is {section reference or null}{depth plus 1}{group title}
155% \O is Scandinavian letter O-with-slash
156% \P is paragraph sign
157\def\Q{\note{This code is cited in section}} % xref for mention of a section
158\def\Qs{\note{This code is cited in sections}} % xref for mentions of a section
159\let\R=\lnot % logical not
160% \S is section sign
161\def\T#1{\leavevmode % octal, hex or decimal constant
162 \hbox{$\def\?{\kern.2em}%
163 \def\$##1{\egroup_{\,\rm##1}\bgroup}% suffix to constant
164 \def\_{\cdot 10^{\aftergroup}}% power of ten (via dirty trick)
165 \let\~=\oct \let\^=\hex {#1}$}}
166\def\U{\note{This code is used in section}} % xref for use of a section
167\def\Us{\note{This code is used in sections}} % xref for uses of a section
168\let\V=\lor % logical or
169\let\W=\land % logical and
170\def\X#1:#2\X{\ifmmode\gdef\XX{\null$\null}\else\gdef\XX{}\fi % section name
171 \XX$\langle\,${#2\eightrm\kern.5em#1}$\,\rangle$\XX}
172\def\Y{\par\yskip}
173\let\Z=\le
174\let\ZZ=\let % now you can \write the control sequence \ZZ
175\let\*=*
176
177%\def\oct{\hbox{\rm\char'23\kern-.2em\it\aftergroup\?\aftergroup}} % WEB style
178%\def\hex{\hbox{\rm\char"7D\tt\aftergroup}} % WEB style
179\def\oct{\hbox{$^\circ$\kern-.1em\it\aftergroup\?\aftergroup}}% CWEB style
180\def\hex{\hbox{$^{\scriptscriptstyle\#}$\tt\aftergroup}} % CWEB style
181\def\vb#1{\leavevmode\hbox{\kern2pt\vrule\vtop{\vbox{\hrule
182 \hbox{\strut\kern2pt\.{#1}\kern2pt}}
183 \hrule}\vrule\kern2pt}} % verbatim string
184
185\def\onmaybe{\let\ifon=\maybe} \let\maybe=\iftrue
186\newif\ifon \newif\iftitle \newif\ifpagesaved
187
188\def\lheader{\mainfont\the\pageno\eightrm\qquad\grouptitle\hfill\title\qquad
189 \mainfont\topsecno} % top line on left-hand pages
190\def\rheader{\mainfont\topsecno\eightrm\qquad\title\hfill\grouptitle
191 \qquad\mainfont\the\pageno} % top line on right-hand pages
192\def\grouptitle{\let\i=I\let\j=J\uppercase\expandafter{\expandafter
193 \takethree\topmark}}
194\def\topsecno{\expandafter\takeone\topmark}
195\def\takeone#1#2#3{#1}
196\def\taketwo#1#2#3{#2}
197\def\takethree#1#2#3{#3}
198\def\nullsec{\eightrm\kern-2em} % the \kern-2em cancels \qquad in headers
199
200\let\page=\pagebody \raggedbottom
201% \def\page{\box255 }\normalbottom % faster, but loses plain TeX footnotes
202\def\normaloutput#1#2#3{\shipout\vbox{
203 \ifodd\pageno\hoffset=\pageshift\fi
204 \vbox to\fullpageheight{
205 \iftitle\global\titlefalse
206 \else\hbox to\pagewidth{\vbox to10pt{}\ifodd\pageno #3\else#2\fi}\fi
207 \vfill#1}} % parameter #1 is the page itself
208 \global\advance\pageno by1}
209
210\gtitle={\.{CWEB} output} % this running head is reset by starred sections
211\mark{\noexpand\nullsec0{\the\gtitle}}
212\def\title{\expandafter\uppercase\expandafter{\jobname}}
213\def\topofcontents{\centerline{\titlefont\title}\vskip.7in
214 \vfill} % this material will start the table of contents page
215\def\botofcontents{\vfill
216 \centerline{\covernote}} % this material will end the table of contents page
217\def\covernote{}
218\def\contentspagenumber{0} % default page number for table of contents
219\newdimen\pagewidth \pagewidth=6.5in % the width of each page
220\newdimen\pageheight \pageheight=8.7in % the height of each page
221\newdimen\fullpageheight \fullpageheight=9in % page height including headlines
222\newdimen\pageshift \pageshift=0in % shift righthand pages wrt lefthand ones
223\def\magnify#1{\mag=#1\pagewidth=6.5truein\pageheight=8.7truein
224 \fullpageheight=9truein\setpage}
225\def\setpage{\hsize\pagewidth\vsize\pageheight} % use after changing page size
226\def\contentsfile{\jobname.toc} % file that gets table of contents info
227\def\readcontents{\input \contentsfile}
228\def\readindex{\input \jobname.idx}
229\def\readsections{\input \jobname.scn}
230
231\newwrite\cont
232\output{\setbox0=\page % the first page is garbage
233 \openout\cont=\contentsfile
234 \write\cont{\catcode `\noexpand\@=11\relax} % \makeatletter
235 \global\output{\normaloutput\page\lheader\rheader}}
236\setpage
237\vbox to \vsize{} % the first \topmark won't be null
238
239\def\ch{\note{The following sections were changed by the change file:}
240 \let\*=\relax}
241\newbox\sbox % saved box preceding the index
242\newbox\lbox % lefthand column in the index
243\def\inx{\par\vskip6pt plus 1fil % we are beginning the index
244 \def\page{\box255 } \normalbottom
245 \write\cont{} % ensure that the contents file isn't empty
246 \write\cont{\catcode `\noexpand\@=12\relax} % \makeatother
247 \closeout\cont % the contents information has been fully gathered
248 \output{\ifpagesaved\normaloutput{\box\sbox}\lheader\rheader\fi
249 \global\setbox\sbox=\page \global\pagesavedtrue}
250 \pagesavedfalse \eject % eject the page-so-far and predecessors
251 \setbox\sbox\vbox{\unvbox\sbox} % take it out of its box
252 \vsize=\pageheight \advance\vsize by -\ht\sbox % the remaining height
253 \hsize=.5\pagewidth \advance\hsize by -10pt
254 % column width for the index (20pt between cols)
255 \parfillskip 0pt plus .6\hsize % try to avoid almost empty lines
256 \def\lr{L} % this tells whether the left or right column is next
257 \output{\if L\lr\global\setbox\lbox=\page \gdef\lr{R}
258 \else\normaloutput{\vbox to\pageheight{\box\sbox\vss
259 \hbox to\pagewidth{\box\lbox\hfil\page}}}\lheader\rheader
260 \global\vsize\pageheight\gdef\lr{L}\global\pagesavedfalse\fi}
261 \message{Index:}
262 \parskip 0pt plus .5pt
263 \outer\def\I##1, {\par\hangindent2em\noindent##1:\kern1em} % index entry
264 \def\[##1]{$\underline{##1}$} % underlined index item
265 \rm \rightskip0pt plus 2.5em \tolerance 10000 \let\*=\lapstar
266 \hyphenpenalty 10000 \parindent0pt
267 \readindex}
268\def\fin{\par\vfill\eject % this is done when we are ending the index
269 \ifpagesaved\null\vfill\eject\fi % output a null index column
270 \if L\lr\else\null\vfill\eject\fi % finish the current page
271 \parfillskip 0pt plus 1fil
272 \def\grouptitle{NAMES OF THE SECTIONS}
273 \let\topsecno=\nullsec
274 \message{Section names:}
275 \output={\normaloutput\page\lheader\rheader}
276 \setpage
277 \def\note##1##2.{\quad{\eightrm##1~##2.}}
278 \def\Q{\note{Cited in section}} % crossref for mention of a section
279 \def\Qs{\note{Cited in sections}} % crossref for mentions of a section
280 \def\U{\note{Used in section}} % crossref for use of a section
281 \def\Us{\note{Used in sections}} % crossref for uses of a section
282 \def\I{\par\hangindent 2em}\let\*=*
283 \readsections}
284\def\con{\par\vfill\eject % finish the section names
285% \ifodd\pageno\else\titletrue\null\vfill\eject\fi % for duplex printers
286 \rightskip 0pt \hyphenpenalty 50 \tolerance 200
287 \setpage \output={\normaloutput\page\lheader\rheader}
288 \titletrue % prepare to output the table of contents
289 \pageno=\contentspagenumber
290 \def\grouptitle{TABLE OF CONTENTS}
291 \message{Table of contents:}
292 \topofcontents
293 \line{\hfil Section\hbox to3em{\hss Page}}
294 \let\ZZ=\contentsline
295 \readcontents\relax % read the contents info
296 \botofcontents \end} % print the contents page(s) and terminate
297\def\contentsline#1#2#3#4{\ifnum#2=0 \smallbreak\fi
298 \line{\consetup{#2}#1
299 \rm\leaders\hbox to .5em{.\hfil}\hfil\ #3\hbox to3em{\hss#4}}}
300\def\consetup#1{\ifcase#1 \bf % depth -1 (@**)
301 \or % depth 0 (@*)
302 \or \hskip2em % depth 1 (@*1)
303 \or \hskip4em % depth 2 (@*2)
304 \or \hskip6em % depth 3 (@*3)
305 \or \hskip8em % depth 4 (@*4)
306 \or \hskip10em % depth 5 (@*5)
307 \else \hskip12em \fi} % depth 6 or more
308\def\noinx{\let\inx=\end} % no indexes or table of contents
309\def\nosecs{\let\FIN=\fin \def\fin{\let\parfillskip=\end \FIN}}
310 % no index of section names or table of contents
311\def\nocon{\let\con=\end} % no table of contents
312\def\today{\ifcase\month\or
313 January\or February\or March\or April\or May\or June\or
314 July\or August\or September\or October\or November\or December\fi
315 \space\number\day, \number\year}
316\newcount\twodigits
317\def\hours{\twodigits=\time \divide\twodigits by 60 \printtwodigits
318 \multiply\twodigits by-60 \advance\twodigits by\time :\printtwodigits}
319\def\gobbleone1{}
320\def\printtwodigits{\advance\twodigits100
321 \expandafter\gobbleone\number\twodigits
322 \advance\twodigits-100 }
323\def\TeX{{\ifmmode\it\fi
324 \leavevmode\hbox{T\kern-.1667em\lower.424ex\hbox{E}\hskip-.125em X}}}
325\def\,{\relax\ifmmode\mskip\thinmuskip\else\thinspace\fi}
326\def\datethis{\def\startsection{\leftline{\sc\today\ at \hours}\bigskip
327 \let\startsection=\stsec\stsec}}
328 % say `\datethis' in limbo, to get your listing timestamped before section 1
329\def\datecontentspage{%
330 \def\topofcontents{\leftline{\sc\today\ at \hours}\bigskip
331 \centerline{\titlefont\title}\vfill}} % timestamps the contents page
cwebman.tex+1610−0
@@ -0,0 +1,1610 @@
1% This file generates the user manual; TeX it, don't read it!
2
3\def\tangref{3} % where the main explanation of CTANGLing is given
4\input cwebmac
5\def\page{\box255 } \normalbottom
6\parskip 0pt plus 1pt
7\def\RA{\char'31 } % right arrow
8\def\hang{\hangindent 4em\ignorespaces}
9\font\eightrm=cmr8
10\font\ninerm=cmr9
11\font\ninett=cmtt9
12\font\eighttt=cmtt8
13\font\twelvett=cmtt12
14\font\quoterm=cmssq8
15\font\quoteit=cmssqi8
16\font\authorfont=cmr12
17\font\sectionfont=cmbx12
18
19\def\pb{\.{|...|}}
20\def\v{\.{\char'174}} % vertical (|) in typewriter font
21\def\lpile{\def\cr{\hfill\endline}\matrix} % I only use \lpile by itself
22\abovedisplayskip=.5\abovedisplayskip
23\belowdisplayskip=.5\belowdisplayskip
24\abovedisplayshortskip=.5\abovedisplayshortskip
25\belowdisplayshortskip=.5\belowdisplayshortskip
26\advance\baselineskip by -.5pt
27\advance\pageheight by \baselineskip % the manual just got a bit longer
28\advance\fullpageheight by \baselineskip
29\setpage
30
31\outer\def\section #1.{\penalty-500\bigskip
32 \centerline{\sectionfont\def\.##1{{\twelvett##1}} #1}\nobreak\vskip 6pt
33 \everypar{\hskip-\parindent\everypar{}}}
34
35\def\lheader{\mainfont\the\pageno\hfill\sc\runninghead\hfill}
36\def\rheader{\hfill\sc\runninghead\hfill\mainfont\the\pageno}
37\def\runninghead{{\tentt CWEB} USER MANUAL (VERSION 3.0)}
38
39% This verbatim mode assumes that ! marks are !! in the text being copied.
40\def\verbatim{\begingroup
41 \def\do##1{\catcode`##1=12 } \dospecials
42 \parskip 0pt \parindent 0pt \let\!=!
43 \catcode`\ =13 \catcode`\^^M=13
44 \tt \catcode`\!=0 \verbatimdefs \verbatimgobble}
45{\catcode`\^^M=13{\catcode`\ =13\gdef\verbatimdefs{\def^^M{\ \par}\let =\ }} %
46 \gdef\verbatimgobble#1^^M{}}
47
48\null\vfill
49\centerline{\titlefont The {\ttitlefont CWEB} System of
50 Structured Documentation}
51\vskip 18pt\centerline{(Version 3.0)}
52\vskip 24pt
53\centerline{\authorfont Donald E. Knuth and Silvio Levy}
54\vfill
55
56\noindent
57\TeX\ is a trademark of the American Mathematical Society.
58
59\bigskip\noindent
60The printed form of this manual is copyright \copyright\ 1994
61 by Addison-Wesley Publishing Company, Inc. All rights reserved.
62\smallskip\noindent
63The electronic form is copyright \copyright\ 1987, 1990, 1993
64 by Silvio Levy and Donald E. Knuth.
65
66\bigskip\noindent
67Permission is granted to make and distribute verbatim copies of the
68electronic form of this document provided that the electronic copyright
69notice and this permission notice are preserved on all copies.
70
71\smallskip\noindent
72Permission is granted to copy and distribute modified versions of the
73electronic form of this document under the conditions for verbatim copying,
74provided that the entire resulting derived work is distributed under the terms
75of a permission notice identical to this one.
76
77\smallskip\noindent
78Individuals may make copies of the documentation from the electronic files
79for their own personal use.
80
81\pageno=0 \titletrue\eject
82
83\titletrue
84\centerline{\titlefont The {\ttitlefont CWEB} System of
85 Structured Documentation}
86
87\vskip 15pt plus 3pt minus 3pt
88\centerline{\authorfont Donald E. Knuth and Silvio Levy}
89
90\vskip 24pt plus 3pt minus 3pt
91\noindent
92This document describes a version of Don Knuth's \.{WEB} system,
93adapted to \CEE/ by Silvio Levy. Since its creation in 1987, \.{CWEB}
94has been revised and enhanced in various ways, by both Knuth and Levy.
95We now believe that its evolution is near an end; however, bug
96reports, suggestions and comments are still welcome, and
97should be sent to Levy (\.{levy@geom.umn.edu}).
98
99Readers who are familiar with Knuth's memo ``The \.{WEB} System of Structured
100Documentation'' will be able
101to skim this material rapidly, because \.{CWEB} and \.{WEB} share
102the same philosophy and (essentially) the same syntax. In some respects
103\.{CWEB} is a simplification
104of \.{WEB}: for example, \.{CWEB} does not need \.{WEB}'s features
105for macro definition and string handling, because \CEE/ and its
106preprocessor already take care of macros and strings. Similarly, the \.{WEB}
107conventions of denoting octal and hexadecimal constants by \.{@'77}
108and \.{@"3f} are replaced by \CEE/'s conventions \.{077} and
109\.{0x3f}. All other features of \.{WEB} have been
110retained, and new features have been added.
111
112We thank all who contributed suggestions and criticism to
113the development of \.{CWEB}. We are especially grateful to Steve
114Avery, Nelson Beebe, Hans-Hermann Bode, Klaus Guntermann, Norman Ramsey and
115Joachim Schnitter, who contributed code, and to Cameron Smith, who
116made many suggestions improving the manual. Ramsey has made
117literate programming accessible to users of yet other languages by means of
118his \.{SPIDER} system [see {\sl Communications of the ACM\/ \bf32} (1989),
1191051--1055]. Bode adapted \.{CWEB} so that it works for \CPLUSPLUS/ as
120well, so in the text below you can read \CPLUSPLUS/ for \CEE/ if you so desire.
121
122\section Introduction.
123The philosophy behind \.{CWEB} is
124that programmers who want to provide the best
125possible documentation for their programs need two things
126simultaneously: a language like \TEX/ for formatting, and a language like
127\CEE/ for programming. Neither type of language can provide the
128best documentation by itself. But when both are appropriately combined, we
129obtain a system that is much more useful than either language separately.
130
131The structure of a software program may be thought of as a ``web'' that is
132made up of many interconnected pieces. To document such a program, we want
133to explain each individual part of the web and how it relates to its
134neighbors. The typographic tools provided by \TEX/ give us an opportunity
135to explain the local structure of each part by making that structure
136visible, and the programming tools provided by \CEE/ make it possible
137for us to specify the algorithms formally and unambiguously. By combining
138the two, we can develop a style of programming that maximizes our ability
139to perceive the structure of a complex piece of software, and at the same
140time the documented programs can be mechanically translated into a working
141software system that matches the documentation.
142
143The \.{CWEB} system consists of two programs named \.{CWEAVE} and \.{CTANGLE}.
144When writing a \.{CWEB} program the user keeps the
145\CEE/ code and the documentation in the same file, called the \.{CWEB}
146file and generally named \.{something.w}. The command
147`\.{cweave something}' creates an output file \.{something.tex}, which
148can then be fed to \TEX/, yielding a ``pretty printed'' version of
149\.{something.w} that correctly handles
150typographic details like page layout and the use of indentation,
151italics, boldface, and mathematical symbols. The typeset output also
152includes extensive cross-index
153information that is gathered automatically. Similarly, if you run the
154command `\.{ctangle something}' you will get a \CEE/ file \.{something.c},
155with can then be compiled to yield executable code.
156
157Besides providing a documentation tool, \.{CWEB} enhances the \CEE/
158language by providing the
159ability to permute pieces of the program text, so that a large system can
160be understood entirely in terms of small sections and their local
161interrelationships. The \.{CTANGLE} program is so named because it takes a
162given web and moves the sections from their web structure into the order
163required by \CEE/; the advantage of programming in \.{CWEB} is that the
164algorithms can be expressed in ``untangled'' form, with each section
165explained separately. The \.{CWEAVE} program is so named because it takes
166a given web and intertwines the \TEX/ and \CEE/ portions contained in
167each section, then it knits the whole fabric into a structured document.
168(Get it? Wow.) Perhaps there is some deep connection here with the fact
169that the German word for ``weave'' is ``{\it web\/}'', and the
170corresponding Latin imperative is ``{\it texe\/}''!
171
172A user of \.{CWEB} should be fairly familiar with the \CEE/
173programming language. A minimal amount of acquaintance with \TEX/ is also
174desirable, but in fact it can be acquired as one uses \.{CWEB}, since
175straight text can be typeset in \TEX/ with virtually no knowledge of
176that language. To someone familiar with both \CEE/ and \TEX/ the amount of
177effort necessary to learn the commands of \.{CWEB} is small.
178
179\section Overview.
180Two kinds of material go into \.{CWEB} files: \TEX/ text and \CEE/ text.
181A programmer writing in \.{CWEB} should be thinking both of the
182documentation and of the \CEE/ program being created;
183i.e., the programmer should be instinctively aware of the different
184actions that \.{CWEAVE} and \.{CTANGLE} will perform on the \.{CWEB} file.
185\TEX/ text is essentially copied without change by \.{CWEAVE}, and it is
186entirely deleted by \.{CTANGLE}; the \TEX/ text is ``pure
187documentation.'' \CEE/ text, on the other hand, is formatted by
188\.{CWEAVE} and it is shuffled around by \.{CTANGLE}, according to rules that
189will become clear later. For now the important point to keep in mind is
190that there are two kinds of text. Writing \.{CWEB} programs is something
191like writing \TEX/ documents, but with an additional ``\CEE/ mode''
192that is added to \TEX/'s horizontal mode, vertical mode, and math mode.
193
194A \.{CWEB} file is built up from units called {\sl sections\/} that are more
195or less self-contained. Each section has three parts:
196
197\yskip\item{$\bullet$} A \TEX/ part, containing explanatory material about what
198is going on in the section.
199
200\item{$\bullet$} A middle part, containing macro definitions that serve as
201abbreviations for \CEE/ constructions that would be less comprehensible
202if written out in full each time. They are turned by \.{CTANGLE} into
203preprocessor macro definitions.
204
205\item{$\bullet$} A \CEE/ part, containing a piece of the program that
206\.{CTANGLE} will produce. This \CEE/ code should ideally be about a
207dozen lines long, so that it is easily comprehensible as a unit and so
208that its structure is readily perceived.
209
210\yskip\noindent The three parts of each section must appear in this order;
211i.e., the \TEX/ commentary must come first, then the middle part, and
212finally the \CEE/ code. Any of the parts may be empty.
213
214A section begins with either of the symbols `\.{@\ }' or `\.{@*}', where
215`\.{\ }' denotes a blank space. A section ends
216at the beginning of the next section (i.e., at the next
217`\.{@\ }' or `\.{@*}'), or at the end of the file, whichever comes first.
218The \.{CWEB} file may also contain material that is not part of any section
219at all, namely the text (if any) that occurs before the first section.
220Such text is said to be ``in limbo''; it is ignored by \.{CTANGLE}
221and copied essentially verbatim by \.{CWEAVE}, so its function is to
222provide any additional formatting instructions that may be desired in the
223\TEX/ output. Indeed, it is customary to begin a \.{CWEB} file with
224\TEX/ code in limbo that loads special fonts, defines special macros,
225changes the page sizes, and/or produces a title page.
226
227Sections are numbered consecutively, starting with 1. These numbers appear
228at the beginning of each section of the \TEX/ documentation output by
229\.{CWEAVE}, and they appear
230as bracketed comments at the beginning and end of the code generated by that
231section in the \CEE/ program output by \.{CTANGLE}.
232
233\section Section Names.
234Fortunately, you never mention these numbers yourself when you are writing
235in \.{CWEB}. You just say `\.{@\ }' or `\.{@*}' at the beginning of each
236new section, and the numbers are supplied automatically by \.{CWEAVE} and
237\.{CTANGLE}. As far as you are concerned, a section has a
238{\sl name\/} instead of a number; its name is specified by writing
239`\.{@<}' followed by \TEX/ text followed by `\.{@>}'. When \.{CWEAVE}
240outputs a section name, it replaces the `\.{@<}' and `\.{@>}' by
241angle brackets and inserts the section number in small type. Thus, when you
242read the output of \.{CWEAVE} it is easy to locate any section that is
243referred to in another section.
244
245For expository purposes, a section name should be a good description of the
246contents of that section; i.e., it should stand for the abstraction
247represented by the section. Then the section can be ``plugged into'' one or
248more other sections in such a way
249that unimportant details of its inner workings
250are suppressed. A section name therefore ought to be long enough to convey
251the necessary meaning.
252
253Unfortunately, it is laborious to type
254such long names over and over again, and it is also difficult to specify a
255long name twice in exactly the same way so that \.{CWEAVE} and \.{CTANGLE}
256will be able to match the names to the sections. To ameliorate this situation,
257\.{CWEAVE} and \.{CTANGLE} let you abbreviate a section name, so long as
258the full name appears somewhere in the \.{CWEB} file; you can type simply
259`\.{@<$\alpha$...@>}', where $\alpha$ is any string that is a prefix of
260exactly one section name appearing in the file. For example, `\.{@<Clear
261the arrays@>}' can be abbreviated to `\.{@<Clear...@>}' if no other section
262name begins with the five letters `\.{Clear}'. Elsewhere
263you might use the abbreviation `\.{@<Clear t...@>}', and so on.
264
265Section names must otherwise match character for character, except
266that consecutive characters of white space (spaces, tab marks, newlines, and/or
267form feeds) are treated as equivalent to a single space, and such spaces are
268deleted at the beginning and end of the name. Thus, `\.{@< Clear { }the
269arrays @>}' will also match the name in the previous example.
270Spaces following the ellipsis in abbreviations are ignored as well, but
271not those before, so that `\.{@<Clear t ...@>}' would not match
272`\.{@<Clear the arrays@>}'.
273
274\section What \.{CTANGLE} Does.
275We have said that a section begins with `\.{@\ }' or `\.{@*}', but we
276didn't say how it gets divided up into a \TEX/ part, a middle part,
277and a \CEE/ part. The middle part begins with the first appearance of
278`\.{@d}' or `\.{@f}' in the section, and the \CEE/ part begins with
279the first appearance of `\.{@c}' or `\.{@<section name@>=}'. In the
280latter case you are saying, in effect, that the section name stands
281for the \CEE/ text that follows. Alternatively, if the \CEE/ part
282begins with `\.{@c}' instead of a section name, the current section is
283said to be {\sl unnamed}.
284
285The construct `\.{@<section name@>}' can appear
286any number of times in the \CEE/ part of a section:
287subsequent appearances indicate that the named section is being
288``used'' rather than ``defined'', that is, that the
289\CEE/ code for the named section, presumably defined elsewhere, should be
290spliced in at this point in the \CEE/ program. Indeed,
291the main idea of \.{CTANGLE} is to make a \CEE/ program out of
292individual sections, named and unnamed. The exact way in which this is done
293is this: First all the macro definitions
294indicated by `\.{@d}' are turned into \CEE/ preprocessor macro definitions
295and copied at the beginning.
296Then the \CEE/ parts of unnamed sections are copied down,
297in order; this constitutes the first-order
298approximation to the text of the program. (There should be at least
299one unnamed section, otherwise there will be no program.) Then all section
300names that appear in the first-order approximation are replaced by the \CEE/
301parts of the corresponding sections, and this substitution process
302continues until no section names remain. All comments are removed, because
303the \CEE/ program is intended only for the eyes of the \CEE/ compiler.
304
305If the same name has been given to more than one section, the \CEE/ text
306for that name is obtained by putting together all of the \CEE/ parts in
307the corresponding sections. This feature is useful, for example, in a
308section named `Global variables', since one can then
309declare global variables in whatever sections those variables are
310introduced. When several sections have the same name, \.{CWEAVE} assigns the
311first section number as the number corresponding to that name, and it
312inserts a note at the bottom of that section telling the reader to `See
313also sections so-and-so'; this footnote gives the numbers of all the other
314sections having the same name as the present one. The \CEE/ text
315corresponding to a section is usually formatted by \.{CWEAVE} so that the
316output has an equivalence sign in place of the equals sign in the \.{CWEB}
317file; i.e., the output says `$\langle\,$section
318name$\,\rangle\equiv\null$\CEE/ text'. However, in the case of the second
319and subsequent appearances of a section with the same name, this `$\equiv$'
320sign is replaced by `$\mathrel+\equiv$', as an indication that the
321following \CEE/ text is being appended to the \CEE/ text of another section.
322
323As \.{CTANGLE} enters and leaves sections, it inserts preprocessor
324\.{\#line} commands into the \CEE/ output file. This means that
325when the compiler gives you error messages, or when you debug your program,
326the messages refer to line numbers in the \.{CWEB} file, and not in the
327\CEE/ file. In most cases you can therefore
328forget about the \CEE/ file altogether.
329
330\section What \.{CWEAVE} Does.
331The general idea of \.{CWEAVE} is to make a \.{.tex} file from the \.{CWEB}
332file in the following way: The first line of the \.{.tex} file
333tells \TEX/ to input a file with macros that
334define \.{CWEB}'s documentation conventions. The next lines of the file
335will be copied from whatever \TEX/ text is in limbo before the first
336section. Then comes the output for each section in turn, possibly
337interspersed with end-of-page marks. Finally, \.{CWEAVE} will generate a
338cross-reference index that lists each section number in which each \CEE/
339identifier appears, and it will also generate an alphabetized list
340of the section names, as well as a table of contents that
341shows the page and section numbers for each ``starred'' section.
342
343What is a ``starred'' section, you ask? A section that begins with `\.{@*}'
344instead of `\.{@\ }' is slightly special in that it denotes a new major
345group of sections. The `\.{@*}' should be followed by the title of this
346group, followed by a period. Such sections will always start on a new page
347in the \TEX/ output, and the group title will appear as a running headline
348on all subsequent pages until the next starred section. The title will also
349appear in the table of contents, and in boldface type at the beginning of
350its section. Caution: Do not use \TEX/ control sequences in such titles,
351unless you know that the \.{cwebmac} macros will do the right thing with
352them. The reason is that these titles are converted to uppercase when
353they appear as running heads, and they are converted to boldface when they
354appear at the beginning of their sections, and they are also written out to
355a table-of-contents file used for temporary storage while \TEX/ is
356working; whatever control sequences you use must be meaningful in all
357three of these modes.
358
359The \TEX/ output produced by \.{CWEAVE} for each section consists of
360the following: First comes the section number (e.g., `\.{\\M123.}'
361at the beginning of section 123, except that `\.{\\N}' appears in place of
362`\.{\\M}' at the beginning of a starred section). Then comes the
363\TEX/ part of the section, copied almost verbatim except as noted
364below. Then comes the middle part and the \CEE/ part, formatted
365so that there will be a little extra space between them if both are
366nonempty. The middle and \CEE/ parts are obtained by inserting
367a bunch of funny-looking \TEX/ macros into the \CEE/ program; these
368macros handle typographic details about fonts and proper math spacing,
369as well as line breaks and indentation.
370
371\section C Code in \TEX/ Text and Vice Versa.
372When you are typing \TEX/ text, you will probably want to make frequent
373reference to variables and other quantities in your \CEE/ code, and you
374will want those variables to have the same typographic treatment
375when they appear in your text as when they appear in your
376program. Therefore the \.{CWEB} language allows you to get the effect of
377\CEE/ editing within \TEX/ text, if you place `\.|' marks before and
378after the \CEE/ material. For example, suppose you want to say something
379like this:
380$$\hbox{ If \\{pa} is declared as `\&{int} ${}{*}\\{pa}$',
381the assignment $\\{pa}\K{\AND}\|a[\T{0}]$ makes \\{pa}
382point to the zeroth element of \|a.}$$
383The \TEX/ text would look like this in your \.{CWEB} file:
384$$\lpile{\.{If |pa| is declared as `|int *pa|', the}\cr
385\.{assignment |pa=\&a[0]| makes |pa| point
386to the zeroth element of |a|.}\cr}$$
387And \.{CWEAVE} translates this into something you are glad you didn't have
388to type:
389$$\lpile{\.{If \\\\\{pa\} is declared as
390 `\\\&\{int\} \$\{\}\{*\}\\\\\{pa\}\$',}\cr
391\.{the assignment \$\\\\\{pa\}\\K\{\\AND\}\\|a[\\T\{0\}]\$}\cr
392\.{makes \\\\\{pa\} point to the zeroth element of \\|a.}\cr}$$
393Incidentally, the cross-reference index that \.{CWEAVE} would make, in
394the presence of a comment like this, would include
395the current section number as one of the index entries for \\{pa},
396even though \\{pa} might not appear in the \CEE/ part of
397this section. Thus, the index covers references to identifiers in
398the explanatory comments as well as in the program itself; you will
399soon learn to appreciate this feature. However, the identifiers
400\&{int} and \|a\ would not be indexed,
401because \.{CWEAVE} does not make index entries for reserved words or
402single-letter identifiers. Such identifiers are felt to be so ubiquitous
403that it would be pointless to mention every place where they occur.
404
405Although a section begins with \TEX/ text and ends with \CEE/ text, we
406have noted that the dividing line isn't sharp, since \CEE/ text can be
407included in \TEX/ text if it is enclosed in `\pb'. Conversely, \TEX/ text
408appears frequently within \CEE/ text, because everything in
409comments (i.e., between \.{/*} and \.{*/}) is treated as \TEX/ text.
410Likewise, the text of a section name consists of \TEX/ text, but
411the construct \.{@<section name@>} as a whole is is expected to be found
412in \CEE/ text; thus, one typically goes back and forth
413between the \CEE/ and \TEX/ environments in a natural way, as in these
414examples:
415$$
416\displaylines{
417\hbox{\.{if} \.{(x==0)} \.{@<Empty} \.{the} \.{|buffer|} \.{array@>}} \cr
418\hbox{\.{...} \.{using} \.{the} \.{algorithm}
419\.{in} \.{|@<Empty} \.{the} \.{|buffer|} \.{array@>|.}} }
420$$
421The first of these excerpts
422would be found in the \CEE/ part of a section, into which the code
423from the section
424named ``Empty the \\{buffer} array'' is being spliced. The second excerpt
425would be found in the \TEX/ part of the section, and the named section
426is being ``cited'', rather than defined or used.
427(Note the `\pb' surrounding the section name in this case.)
428
429\section Macros.
430The control code \.{@d} followed by
431$$\\{identifier}\.{ }\hbox{\CEE/ text}\qquad\hbox{or by}\qquad
432\\{identifier}\.(\\{par}_1,\ldots,\\{par}_n\.{) }\hbox{\CEE/ text}$$
433(where there is no blank between the
434\\{identifier} and the parentheses in the second case) is
435transformed by \.{CTANGLE} into a preprocessor command, starting with
436\.{\#define}, which is printed at the top of the \CEE/ output file
437as explained earlier.
438
439A `\.{@d}' macro definition can go on for several lines, and the
440newlines don't have to be protected by backslashes, since \.{CTANGLE}
441itself inserts the backslashes. If
442for any reason you need a \.{\#define} command at a specific spot in
443your \CEE/ file, you can treat it as \CEE/ code, instead of as a
444\.{CWEB} macro; but then you do have to protect newlines yourself.
445
446\section Strings and constants.
447If you want a string to appear in the \CEE/ file, delimited by pairs of
448\.' or \." marks as usual, you can type it exactly so in the \.{CWEB} file,
449except that the character `\.@' should be typed `\.{@@}' (it becomes a
450control code, the only one that can appear in strings; see below).
451Strings should end on the same line as they begin, unless there's a
452backslash at the end of lines within them.
453
454\TEX/ and \CEE/ have different ways to refer to octal and hex constants,
455because \TEX/ is oriented to technical writing while \CEE/ is oriented to
456computer processing. In \TEX/ you
457make a constant octal or hexadecimal by prepending \.' or \.",
458respectively, to it; in \CEE/ the constant should be preceded by \.0
459or \.{0x}. In \.{CWEB} it seems reasonable to let each convention hold
460in its respective realm; so in \CEE/ text you get $40_8$ by typing
461`\.{040}', which \.{CTANGLE} faithfully copies into the \CEE/ file (for
462the compiler's benefit) and which \.{CWEAVE} prints as $\T{\~40}$.
463Similarly, \.{CWEAVE} prints the hexadecimal \CEE/ constant `\.{0x20}'
464as \T{\^20}. The use of italic font for octal digits and typewriter font
465for hexadecimal digits makes the meaning of such constants clearer in
466a document. For consistency, then, you
467should type `\.{|040|}' or `\.{|0x20|}'
468in the \TEX/ part of the section.
469
470\section Control codes.
471A \.{CWEB} {\sl control code\/}
472is a two-character combination of which the first is `\.@'.
473We've already seen the meaning of several control codes; it's time to
474list them more methodically.
475
476In the following list,
477the letters in brackets after a control code indicate in what contexts that
478code is allowed. $L$ indicates that the code is allowed in limbo; $T$
479(for \TEX/), $M$ (for middle) and $C$ mean that the code is allowed in
480each of the three parts of a section, at top level---that is, outside
481such constructs as `\pb' and section names. An arrow $\to$ means
482that the control code terminates the present part of the \.{CWEB}
483file, and inaugurates the part indicated by the letter following the
484arrow. Thus $[LTMC\to T]$ next to \.{@\ } indicates that this control
485code can occur in limbo, or in any of the three parts of a section, and
486that it starts the (possibly empty) \TEX/ part of the following
487section.
488
489Two other abbreviations can occur in these brackets: The letter $r$ stands for
490{\it restricted context}, that is, material inside \CEE/ comments, section
491names, \CEE/ strings and control texts (defined below); the letter
492$c$ stands for {\it inner \CEE/ context}, that is, \CEE/ material
493inside `\pb' (including `\pb's inside comments, but not those
494occurring in other restricted contexts). An asterisk $*$ following
495the brackets means
496that the context from this control code to the matching \.{@>} is
497restricted.
498
499Control codes involving letters are case-insensitive: thus \.{@d} and
500\.{@D} are equivalent. Only the lowercase versions are mentioned
501specifically below.
502
503\gdef\@#1[#2] {\penalty-50\yskip\hangindent 2em\noindent\.{@#1\unskip
504 \spacefactor1000{ }}$[#2]$\quad}
505\def\more{\hangindent 2em \hangafter0}
506\def\subsec{\penalty-300\medskip\noindent}
507
508\@@ [LTMCrc] A double \.@ denotes the single character `\.@'. This is
509the only control code that is legal everywhere.
510Note that you must use this convention if you are giving an internet
511email address in a \.{CWEB} file (e.g., \.{levy@@geom.umn.edu}).
512
513\subsec
514Here are the codes that introduce the \TEX/ part of a section.
515
516\@\ [LTMC\to T] This denotes the beginning of a new (unstarred)
517section. A tab mark or form feed or
518end-of-line character is equivalent to a space when it follows an \.@
519sign (and in most other cases).
520
521\@* [LTMC\to T] This denotes the beginning of a new starred
522section, i.e., a section that begins a new major group. The title of the new
523group should appear after the \.{@*}, followed by a period. As explained
524above, \TEX/ control sequences should be avoided in such titles unless
525they are quite simple. When \.{CWEAVE} and \.{CTANGLE} read a \.{@*}, they
526print an asterisk on the terminal
527followed by the current section number, so that the user
528can see some indication of progress. The very first section should be starred.
529
530\more You can specify the ``depth'' of a starred section by typing \.* or a
531decimal number after the \.{@*}; this indicates the relative ranking
532of the current group of sections in the program hierarchy. Top-level
533portions of the program, introduced by \.{@**}, get their names typeset
534in boldface type in the table of contents; they are said to have
535depth~$-1$. Otherwise the depth is a nonnegative number, which governs
536the amount of indentation on the contents page. Such indentation helps
537clarify the structure of a long program. The depth is assumed to be 0
538if it is not specified explicitly; when your program is short, you
539might as well leave all depths zero. A starred section always begins
540a new page in the output, unless the depth is greater than~1.
541
542\subsec
543The middle part of each section consists of any number of
544macro definitions (beginning with \.{@d}) and format definitions (beginning
545with \.{@f} or \.{@s}), intermixed in any order.
546
547\@d [TM\to M] Macro definitions begin with \.{@d}, followed by
548an identifier and optional parameters and \CEE/ text as explained earlier.
549
550\@f [TM\to M] Format definitions begin with \.{@f}; they cause
551\.{CWEAVE} to treat identifiers in a special way when they appear in
552\CEE/ text. The general form of a format definition is `\.{@f} \|l
553\|r', followed by an optional comment enclosed between
554\.{/*} and \.{*/}, where \|l and \|r
555are identifiers; \.{CWEAVE} will subsequently treat identifier \|l as it
556currently treats \|r. This feature allows a \.{CWEB} programmer to invent
557new reserved words and/or to unreserve some of \CEE/'s reserved
558identifiers. If \|r is the special identifier `\\{TeX}', identifier \|l
559will be formatted as a \TEX/ control sequence; for example,
560`\.{@f foo TeX}' in the \.{CWEB} file will cause identifier \\{foo} to
561be output as \.{\\foo} by \.{CWEAVE}. The programmer should define
562\.{\\foo} to have whatever custom format is desired, assuming \TEX/
563math mode. (Each underline
564character is converted to \.{x} when making the \TEX/ control sequence;
565thus \\{foo\_bar} becomes \.{\\fooxbar}. Other characters, including digits,
566are left untranslated, so \TEX/ will consider them as macro parameters,
567not as part of the control sequence itself. For example,
568$$\.{\\def\\x\#1\{x\_\{\#1\}\} @f x1 TeX @f x2 TeX}$$
569will format \.{x1} and \.{x2} not as \\{x1} and \\{x2} but as $x_1$ and $x_2$.
570
571\more \.{CWEAVE} knows that identifiers being
572defined with a \&{typedef} should become reserved words; thus you
573don't need format definitions very often.
574
575\@s [TM\to M;\;L] Same as \.{@f}, but \.{CWEAVE} does not show the format
576definition in the output, and the optional \CEE/ comment is not
577allowed. This is used mostly in \.{@i} files.
578
579\subsec
580Next come the codes that govern the \CEE/ part of a section.
581
582\@{c @p} [TM\to C] The \CEE/ part of an unnamed section begins with \.{@c}
583(or with \.{@p} for ``program''; both control codes do the same thing).
584This causes \.{CTANGLE} to append the following \CEE/ code
585to the first-order program text, as explained on page~\tangref.
586Note that \.{CWEAVE} does not print a `\.{@c}' in the \TEX/
587output, so if you are creating a \.{CWEB} file based on a \TEX/-printed
588\.{CWEB} documentation you have to remember to insert \.{@c} in the
589appropriate places of the unnamed sections.
590
591\@< [TM\to C;\; C;\; c] $*$ This control code introduces a
592section name (or unambiguous prefix, as discussed above), which
593consists of \TEX/ text and extends to the matching \.{@>}.
594The whole construct \.{@<...@>} is conceptually a \CEE/ element.
595The behavior is different depending on the context:
596
597\more A \.{@<} appearing in contexts $T$ and $M$ attaches the
598following section name to the current section, and inaugurates the
599\CEE/ part of the section. The closing \.{@>} should be followed by
600\.{=} or \.{+=}.
601
602\more
603In context $C$, \.{@<} indicates that the named
604section is being used---its \CEE/ definition is spliced in by
605\.{CTANGLE}, as explained on page~\tangref.
606As an error-detection measure,
607\.{CTANGLE} and \.{CWEAVE} complain if such a section name is followed
608by \.=, because most likely this is meant as the definition of a new
609section, and so should be preceded by \.{@\ }. If you really want to
610say $\langle\,$foo$\,\rangle=\\{bar}$, where $\langle\,$foo$\,\rangle$
611is being used and not defined, put a newline before the \.=.
612
613\more
614Finally, in inner \CEE/ context (that is, within `\pb' in the \TEX/ part
615of a section or in a comment), \.{@<...@>}
616means that the named section is being
617cited. Such an occurrence is ignored by \.{CTANGLE}. Note that
618even here we think of the section name as being a \CEE/ element, hence the \pb.
619
620\@( [TM\to C;\;C;\;c] $*$ A section name can begin with \.{@(}.
621Everything works just as for \.{@<}, except that the \CEE/ code
622of the section named \.{@(foo@>} is written by \.{CTANGLE}
623to file \.{foo}. In this way you can get multiple-file output from
624a single \.{CWEB} file. (The \.{@d} definitions are not output
625to such files, only to the master \.{.c} file.) One use of this feature
626is to produce header files for other program modules that will be loaded
627with the present one. Another use is to produce a test routine that
628goes with your program. By keeping the sources for a program and its
629header and test routine together, you are more likely to keep
630all three consistent with each other. Notice that the output of a named
631section can be incorporated in several different output files, because
632you can mention \.{@<foo@>} in both \.{@(bar1@>} and \.{@(bar2@>}.
633
634\@h [Cc] Causes \.{CTANGLE}
635to insert at the current spot the \.{\#define} statements
636from the middle parts of all sections,
637and {\it not\/} to write them at the beginning of the \CEE/ file.
638Useful when you want the macro definitions to come after the include files,
639say. (Ignored by \.{CTANGLE} inside `\pb'.)
640
641\subsec
642The next several control codes introduce ``control
643texts'', which end with the next `\.{@>}'. The closing `\.{@>}' must be on
644the same line of the \.{CWEB} file as the line where the control text began.
645The context from each of these control codes to the matching \.{@>} is
646restricted.
647
648\@\^ [TMCc] $*$ The control text that follows, up to the next
649`\.{@>}', will be entered into the index together with the identifiers of
650the \CEE/ program; this text will appear in roman type. For example, to
651put the phrase ``system dependencies'' into the index that is output by
652\.{CWEAVE}, type
653`\.{@\^system dependencies@>}' in each section
654that you want to index as system dependent.
655
656\@. [TMCc] $*$ The control text that follows will be entered into the index
657in \.{typewriter} \.{type}.
658
659\@: [TMCc] $*$ The control text that follows will be entered into the index
660in a format controlled by the \TEX/ macro `\.{\\9}', which you
661should define as desired.
662
663\@t [MCc] $*$ The control text that follows will
664be put into a \TEX/ \.{\\hbox} and formatted along with the neighboring
665\CEE/ program. This text is ignored by \.{CTANGLE}, but it can be used
666for various purposes within \.{CWEAVE}. For example, you can make comments
667that mix \CEE/ and classical mathematics, as in `$\\{size}<2^{15}$', by
668typing `\.{|size < @t\$2\^\{15\}\$@>|}'.
669
670\@= [MCc] $*$ The control text that follows will
671be passed verbatim to the \CEE/ program.
672
673\@q [LTMCc] $*$ The control text that follows will
674be totally ignored---it's a comment for readers of the \.{CWEB} file only.
675A file intended to be included in
676limbo, with \.{@i}, can identify itself with \.{@q} comments.
677Another use is to balance unbalanced parentheses in C strings,
678so that your text editor's parenthesis matcher doesn't go into a tailspin.
679
680\@! [TMCc] $*$
681The section number in an index entry will be underlined if `\.{@!}'
682immediately precedes the identifier or control text being indexed. This
683convention is used to distinguish the sections where an identifier is
684defined, or where it is explained in some special way, from the sections
685where it is used. A~reserved word or an identifier of length one will not
686be indexed except for underlined entries. An `\.{@!}' is implicitly inserted
687by \.{CWEAVE} when an identifier is being defined or declared in \CEE/
688code; for example, the definition
689$$\hbox{\&{int} \\{array}[\\{max\_dim}], \\{count}${}=\\{old\_count};$}$$
690makes the names \\{array} and \\{count} get an underlined entry in the
691index. Statement labels, function definitions like
692$\\{main}(\\{argc},\39\\{argv})$, and \&{typedef} definitions also
693imply underlining. A traditional-style
694function definition (without prototyping) doesn't define its arguments;
695the arguments will, however, be defined
696(i.e., their index entries will be underlined) if their types are
697declared before the body of the function in the usual way
698(e.g., `\.{int}~\\{argc}; \.{char}~${**}\\{argv}$; $\{\,\ldots\,\}$').
699
700\subsec
701We now turn to control codes that affect only the operation of
702\.{CTANGLE}.
703
704\@' [MCc] This control code is dangerous because it has quite different
705meanings in \.{CWEB} and the original \.{WEB}. In \.{CWEB} it produces the
706decimal constant corresponding to the ASCII code for a string of length~1
707(e.g., \.{@'a'} is \.{CTANGLE}d into \.{97} and \.{@'\\t'} into
708\.9). You might want to use this if you need to work in ASCII on a
709non-ASCII machine; but in most cases the \CEE/ conventions of
710\.{<ctype.h>} are adequate for character-set-independent programming.
711
712\@\& [MCc] The \.{@\&} operation causes whatever is on its left to be
713adjacent to whatever is on its right, in the \CEE/ output. No spaces or
714line breaks will separate these two items.
715
716\@l [L] \.{CWEB} programmers have the option of using any 8-bit character
717code from the often-forbidden range 128--255 within \TEX/ text; such
718characters are also permitted in strings and even in identifiers of the
719\CEE/ program.
720Under various extensions of the basic
721ASCII standard, the higher 8-bit codes correspond
722to accented letters, letters from non-Latin alphabets,
723and so on. When such characters occur in identifiers, \.{CTANGLE} must replace
724them by standard ASCII alphanumeric characters or
725\.{\_}, in order to generate legal \CEE/ code. It does this by means
726of a transliteration table, which by default associates the string
727\.{Xab} to the character with ASCII code \T{\^}$ab$ (where $a$ and $b$ are
728hexadecimal digits, and $a\ge8$). By placing the
729construction \.{@l\ ab\ newstring} in limbo, you are telling
730\.{CTANGLE} to replace this character by \.{newstring} instead.
731For example, the ISO Latin-1 code for the letter `\"u' is \T{\^FC}
732(or \.{'\char`\\374'}),
733and \.{CTANGLE} will normally change this code to the
734three-character sequence \.{XFC} if it
735appears in an identifier. If you say \.{@l} \.{fc} \.{ue}, the code will
736be transliterated into \.{ue} instead.
737
738\more
739\.{CWEAVE} passes 8-bit characters straight through to \TEX/ without
740transliteration; therefore \TEX/ must be prepared to receive them.
741If you are formatting all your nonstandard identifiers as ``custom''
742control sequences, you should
743make \TEX/ treat all their characters as letters. Otherwise you should either
744make your 8-bit codes ``active'' in \TEX/, or load fonts that
745contain the special characters you need in the correct positions.
746(The font selected by \TEX/ control sequence \.{\\it} is used for
747identifiers.)
748Look for special macro packages designed for \.{CWEB} users in your language;
749or, if you are brave, write one yourself.
750
751\subsec
752The next eight control codes (namely `\.{@,}', `\.{@/}', `\.{@|}', `\.{@\#}',
753`\.{@+}', `\.{@;}', `\.{@[}', and `\.{@]}') have no effect on the \CEE/
754program output by \.{CTANGLE}; they merely help to improve the readability
755of the \TEX/-formatted \CEE/ that is output by \.{CWEAVE}, in unusual
756circumstances. \.{CWEAVE}'s built-in formatting method is fairly good
757when dealing with syntactically correct \CEE/ text, but
758it is incapable of handling all possible cases, because it must deal with
759fragments of text involving macros and section names; these fragments do
760not necessarily obey \CEE/'s syntax. Although \.{CWEB} allows you to
761override the automatic formatting, your best strategy is not to worry
762about such things until you have seen what \.{CWEAVE} produces automatically,
763since you will probably need to make only a few corrections when you are
764touching up your documentation.
765
766\@, [MCc] This control code inserts a thin space in \.{CWEAVE}'s output.
767Sometimes you need this extra space if you are using
768macros in an unusual way, e.g., if two identifiers are adjacent.
769
770\@/ [MC] This control code causes a line break to occur within a \CEE/
771program formatted by \.{CWEAVE}. Line breaks
772are chosen automatically by \TEX/ according to a scheme that works 99\%\
773of the time, but sometimes you will prefer to force a line break so that
774the program is segmented according to logical rather than visual
775criteria.
776
777\@| [MC] This control code specifies an optional line break in the midst of
778an expression. For example, if you have
779a long expression on the right-hand side of an assignment
780statement, you can use `\.{@|}' to specify breakpoints more logical than
781the ones that \TEX/ might choose on visual grounds.
782
783\@\# [MC] This control code forces a line break, like \.{@/} does,
784and it also causes a little extra white space to appear between the lines at
785this break. You might use it, for example,
786between groups of macro definitions that are logically separate but within
787the same section. \.{CWEB} automatically inserts this extra space
788between functions, between external declarations and functions, and
789between declarations and statements within a function.
790
791\@+ [MC] This control code cancels a line break that might otherwise be
792inserted by \.{CWEAVE}, e.g., before the word `\&{else}', if you want to
793put a short if--else construction on a single line.
794If you say `\.{\{@+}' at the beginning of a compound statement
795that is the body of a function, the first declaration or
796statement of the function will appear on the same line as the
797left brace, and it will be indented by the same amount as the
798second declaration or statement on the next line.
799
800\@; [MC] This control code is treated like a semicolon, for formatting
801purposes, except that it is invisible. You can use it, for example, after
802a section name or macro when the \CEE/ text represented by that section or macro
803is a compound statement or ends
804with a semicolon. Consider constructions like
805$$\lpile{\.{if (condition) macro @;}\cr
806\.{else break;}\cr}$$
807where \\{macro} is defined to be a compound statement (enclosed in braces).
808This is a well-known infelicity of \CEE/ syntax.
809
810\@{[} [MC] See \.{@]}.
811
812\@] [MC] Place \.{@[...@]} brackets around program text that \.{CWEAVE} is
813supposed to format as an expression, if it doesn't already do so. (This
814occasionally applies to unusual macro arguments.) Also
815insert `\.{@[@]}' between a simple type name and a left parenthesis
816when declaring a pointer to a function, as in
817$$\.{int @[@] (*f)();}$$
818otherwise \.{CWEAVE} will confuse the first part of that declaration with
819the \CPLUSPLUS/ expression `\&{int}($*f$)'.
820
821\subsec
822The remaining control codes govern the input that \.{CWEB} sees.
823
824\@{x @y @z}[\\{change\_file}]
825\.{CWEAVE} and \.{CTANGLE} are designed to work with two input files,
826called \\{web\_file} and \\{change\_file}, where \\{change\_file} contains
827data that overrides selected portions of \\{web\_file}. The resulting merged
828text is actually what has been called the \.{CWEB} file elsewhere in this
829report.
830
831\more Here's how it works: The change file consists of zero or more ``changes,''
832where a change has the form `\.{@x}$\langle$old lines$\rangle$\.{@y}$\langle$%
833new lines$\rangle$\.{@z}'. The special control codes \.{@x}, \.{@y}, \.{@z},
834which are allowed only in change files, must appear at the beginning of a line;
835the remainder of such a line is ignored.
836The $\langle$old lines$\rangle$ represent material that exactly matches
837consecutive lines of the \\{web\_file}; the $\langle$new lines$\rangle$
838represent zero or more lines that are supposed to replace the old. Whenever
839the first ``old line'' of a change is found to match a line in the
840\\{web\_file}, all the other lines in that change must match too.
841
842\more Between changes, before the first change, and after the last change,
843the change file can have any number of lines that do not begin with
844`\.{@x}', `\.{@y}', or~`\.{@z}'. Such lines are bypassed and not used for
845matching purposes.
846
847\more This dual-input feature is useful when working with a master \.{CWEB}
848file that has been received from elsewhere (e.g., \.{tangle.w} or
849\.{weave.w} or \.{tex.web}), when changes are desirable to customize the
850program for your local computer system. You will be able to debug your
851system-dependent changes without clobbering the master web file; and once
852your changes are working, you will be able to incorporate them readily
853into new releases of the master web file that you might receive from time
854to time.
855
856\@i [\\{web\_file}]
857Furthermore the \\{web\_file} itself can be a combination of
858several files. When either \.{CWEAVE} or \.{CTANGLE} is reading a file and
859encounters the control code \.{@i} at the beginning of a line, it
860interrupts normal reading and start looking at the file named after the
861\.{@i}, much as the \CEE/ preprocessor does when it encounters an \.{\#include}
862line. After the included file has been entirely read, the program
863goes back to the next line
864of the original file. The file name following \.{@i} can be
865surrounded by \." characters, but such delimiters are
866optional. Include files can nest.
867
868\more
869Change files can have lines starting with \.{@i}. In this way
870you can replace one included file with another. Conceptually, the
871replacement mechanism described above does its work first, and
872its output is then checked for \.{@i} lines. If \.{@i} \.{foo}
873occurs between \.{@y} and \.{@z} in a change file, individual lines
874of file \.{foo} and files it includes are not changeable; but changes
875can be made to lines from files that were included by unchanged input.
876
877\more On UNIX systems (and others that support environment variables),
878if the environment variable \.{CWEBINPUTS} is set, or if the compiler flag
879of the same name was defined at compile time,
880\.{CWEB} will look for include files in the directory thus named, if
881it cannot find them in the current directory.
882
883\section Additional features and caveats.
884
8851. In certain installations of \.{CWEB} that
886{\def\\#1#2{`{\tentex\char'#1#2}'}%
887have an extended character set, the characters
888\\13, \\01, \\31, \\32, \\34, \\35,
889\\36, \\37, \\04, \\20, and \\21}
890can be typed as abbreviations for `\.{++}', `\.{--}', `\.{->}',
891`\.{!=}', `\.{<=}', `\.{>=}', `\.{==}', `\.{\v\v}', `\.{\&\&}',
892`\.{<<}', and `\.{>>}',
893respectively.
894
8952. If you have an extended character set, you can use it with only minimal
896restrictions, as discussed under the rules for \.{@l} above. But you should
897stick to standard ASCII characters if you want to write programs that will
898be useful to all the poor souls out there who don't have extended
899character sets.
900
9013. The \TEX/ file output by \.{CWEAVE} is broken into lines having at most
90280 characters each. When
903\TEX/ text is being copied, the existing line breaks are copied as well.
904If you aren't doing anything too tricky, \.{CWEAVE} will recognize when
905a \TEX/ comment is being split across two or more lines, and it will
906append `\.\%' to the beginning of such continued comments.
907
9084. \CEE/ text is translated by a ``bottom up'' procedure that
909identifies each token as a ``part of speech'' and combines parts of speech
910into larger and larger phrases as much as possible according to a special
911grammar that is explained in the documentation of \.{CWEAVE}. It is easy to
912learn the translation scheme for simple constructions like single
913identifiers and short expressions, just by looking at a few examples of
914what \.{CWEAVE} does, but the general mechanism is somewhat complex because
915it must handle much more than \CEE/ itself. Furthermore the output
916contains embedded codes that cause \TEX/ to indent and break lines as
917necessary, depending on the fonts used and the desired page width. For
918best results it is wise to avoid enclosing long \CEE/ texts in \pb, since the
919indentation and line breaking codes are omitted when the \pb\ text is
920translated from \CEE/ to \TEX/. Stick to simple expressions or
921statements. If a \CEE/ preprocessor command is enclosed in \pb,
922the \.\# that introduces it must be at the beginning of a line,
923or \.{CWEAVE} won't print it correctly.
924
9255. Comments are not permitted in \pb\ text. After a `\.|'
926signals the change from \TEX/ text to \CEE/ text, the next `\.|' that is
927not part of a string or control text or section name ends the \CEE/ text.
928
9296. A comment must have properly nested occurrences of left and right
930braces, otherwise \.{CWEAVE} will complain. But it
931does try to balance the braces, so that \TEX/ won't foul up too much.
932
9337. When you're debugging a program and decide to omit some of your
934\CEE/ code, do NOT simply ``comment it out.'' Such comments are not
935in the spirit of \.{CWEB} documentation; they will appear to readers
936as if they were explanations of the uncommented-out instructions.
937Furthermore, comments of a program must be valid \TEX/ text; hence
938\.{CWEAVE} will get confused if you enclose \CEE/ statements in
939\.{/*...*/} instead of in \.{/*|...|*/}. If you must comment out
940\CEE/ code, you can surround it with preprocessor commands
941like \.{\#if 0==1} and \.{\#endif}.
942
9438. The \.{@f} feature allows you to define one identifier to act like
944another, and these format definitions are carried out sequentially.
945In general, a given identifier has only one printed format
946throughout the entire document, and this format is used even before
947the \.{@f} that defines it. The reason is that \.{CWEAVE} operates in two
948passes; it processes \.{@f}'s and cross-references on the first pass and
949it does the output on the second. (However, identifiers that
950implicitly get a boldface format, thanks to a \.{typedef} declaration,
951don't obey this rule: they are printed differently before and after
952the relevant \.{typedef}. This is unfortunate, but hard to fix. You can
953get around the restriction by using \.{@s}, before or after the \.{typedef}.)
954
9559. Sometimes it is desirable to insert spacing into formatted \CEE/ code that
956is more general than the thin space provided by `\.{@,}'. The \.{@t} feature
957can be used for this purpose; e.g., `\.{@t\\hskip 1in@>}' will
958leave one inch of blank space. Furthermore, `\.{@t\\4@>}' can be
959used to backspace by one unit of indentation, since the control sequence
960\.{\\4} is defined in \.{cwebmac} to be such a backspace. (This
961control sequence is used, for example, at the beginning of lines that
962contain labeled statements, so that the label will stick out a little at
963the left.) You can also use `\.{@t\}\\3\{-5@>}' to force a break
964in the middle of an expression.
965
96610. Don't use a change file to change just part of a macro call that
967extends over more than one line; change the whole call or nothing.
968Otherwise \.{CTANGLE} will insert \.{\#line} directives that confuse
969the \CEE/ preprocessor.
970
971\section Running the programs.
972The \UNIX/ command line for \.{CTANGLE} is
973$$\.{ctangle [options] web\_file[.w] [\{change\_file[.ch]|-\} [out\_file]]}$$
974and the same conventions apply to \.{CWEAVE}. If `\.-' or no change file is
975specified, the change file is null. The extensions \.{.w} and \.{.ch}
976are appended only if the given file names contain no dot. If the
977web file defined in this way cannot be found, the extension \.{.web}
978will be tried. For example, `\.{cweave} \.{cob}' will try to read
979\.{cob.w}; failing that, it will try \.{cob.web} before giving up.
980If no output file name is specified, the name of the \CEE/ file output by
981\.{CTANGLE} is obtained by appending the extension \.{.c};
982the name of the \TEX/ file output by \.{CWEAVE} gets the extension \.{.tex}.
983Index files output by \.{CWEAVE} replace \.{.tex} by \.{.idx} and \.{.scn}.
984
985Programmers who like terseness might choose to set up their
986 operating shell so that `\.{wv}' expands to
987`\.{cweave -bhp}'; this will suppress most terminal output from \.{CWEAVE}
988except for error messages.
989
990Options are introduced either by a \.- sign, to turn an option off,
991or by a \.+ sign to turn one on. For example, `\.{-fb}' turns off
992options \.f and \.b; `\.{+s}' turns on option \.s. Options can be
993specified before the file names, after the file names, or both. The following
994options are currently implemented:
995
996\yskip
997\def\option#1 {\textindent{\.#1}\hangindent2\parindent}
998
999\option b Print a banner line at the beginning of execution. (On
1000by default.)
1001
1002\option f Force line breaks after each \CEE/ statement formatted
1003by \.{CWEAVE}. (On by default; \.{-f} saves paper but looks less \CEE/-like
1004to some people.) (Has no effect on \.{CTANGLE}.)
1005
1006\option h Print a happy message at the conclusion of a successful
1007run. (On by default.)
1008
1009\option p Give progress reports as the program runs. (On by default.)
1010
1011\option s Show statistics about memory usage after the program
1012runs to completion. (Off by default.)
1013If you
1014have large \.{CWEB} files or sections, you may need to see
1015how close you come to exceeding the capacity of \.{CTANGLE} and/or \.{CWEAVE}.
1016
1017\option x Include indexes and a table of contents in the \TEX/ file
1018output by \.{CWEAVE}. (On by default.) (Has no effect on \.{CTANGLE}.)
1019
1020\section Further details about formatting.
1021You may not like the way \.{CWEAVE} handles certain
1022situations. If you're desperate, you can customize \.{CWEAVE}
1023by changing its grammar. This means changing the source code,
1024a task that you might find amusing. A table of grammar rules
1025appears in the \.{CWEAVE} source listing, and you can make a separate
1026copy of that table by copying the file \.{prod.w} found in the \.{CWEB}
1027sources and saying `\.{cweave}~\.{-x}~\.{prod}', followed by
1028`\.{tex}~\.{prod}'.
1029
1030You can see exactly
1031how \.{CWEAVE} is parsing your \CEE/ code by preceding
1032it with the line `\.{@ @c @2}'. (The control code `\.{@2}'
1033turns on a ``peeping'' mode, and `\.{@0}' turns it off.)
1034For example, if you run \.{CWEAVE} on the file
1035\medskip
1036\begingroup
1037\verbatim
1038@ @c @2
1039main (argc,argv)
1040char **argv;
1041{ for (;argc>0;argc--) printf("%s\n",argv[argc-1]); }
1042!endgroup
1043\endgroup
1044\medskip\noindent
1045you get the following gibberish on your screen:
1046\medskip
1047\begingroup
1048\verbatim
1049[...]
10504:*exp ( +exp+ )...
105111:*exp +exp+ int...
10525:*+exp+ int +unorbinop+...
1053[...]
105460: +fn_decl+*+{+ -stmt- +}-
105555:*+fn_decl+ -stmt-
105652:*+function-
1057[...]
1058!endgroup
1059\endgroup
1060\medskip
1061The first line says that grammar rule 4 has just been applied, and \.{CWEAVE}
1062currently has in its memory a sequence of chunks of \TEX/ code (called
1063``scraps'') that are respectively
1064of type \\{exp} (for expression), open-parenthesis,
1065\\{exp} again, close-parenthesis, and further scraps that haven't yet
1066been considered by the parser. (The \.+ and \.- signs stipulate that
1067\TEX/ should be in or out of math mode at the scrap boundaries. The \.* shows
1068the parser's current position.)
1069Then rule 11 is applied, and
1070the sequence $(\,exp\,)$ becomes an \\{exp} and so on. In the
1071end the whole \CEE/ text has become one big scrap of type \\{function}.
1072
1073Sometimes things don't work as smoothly, and you get a bunch of
1074lines lumped together. This means that \.{CWEAVE} could not
1075digest something in your \CEE/ code. For instance, suppose
1076`\.{@<Argument definitions@>}' had appeared instead of
1077`\.{char **argv;}' in the program above. Then \.{CWEAVE} would have
1078been somewhat mystified, since it thinks that section names
1079are just \\{exp}s. Thus it would tell \TEX/ to format
1080`\X2:Argument declarations\X' on the same line as
1081`$\\{main}(\\{argc},\39\\{argv}{}$)'.
1082In this case you should help \.{CWEAVE} by putting `\.{@/}' after
1083`\.{main(argc,argv)}'.
1084
1085\.{CWEAVE} automatically inserts a bit of extra space between declarations
1086and the first apparent statement of a block, unless you turn off the
1087feature globally by running with the \.{-o} option. One way to defeat this
1088spacing locally is
1089$$\vbox{\halign{#\hfil\cr
1090\.{int x;@+@t\}\\6\{@>}\cr
1091\.{@<Other locals@>@;@\#}\cr}}$$
1092the `\.{@\#}' will put extra space after `$\langle\,$Other locals$\,\rangle$'.
1093
1094\section Appendices.
1095
1096As an example of a real program written in \.{CWEB}, Appendix~A
1097contains an excerpt from the \.{CWEB} program itself. The reader who
1098examines the listings in this appendix carefully will get a good
1099feeling for the basic ideas of \.{CWEB}.
1100
1101Appendix B is the file that sets \TEX/ up to accept
1102the output of \.{CWEAVE}, and Appendix~C discusses how to use some of those
1103macros to vary the output formats.
1104
1105A ``long'' version of this manual, which can be produced from the \.{CWEB}
1106sources via the \UNIX/ command \.{make} \.{fullmanual}, also contains
1107appendices D, E, and~F, which exhibit the complete source code for
1108\.{CTANGLE} and \.{CWEAVE}.
1109
1110\vfil\eject\titletrue
1111
1112\def\runninghead{APPENDIX A --- {\tentt CWEB} FILE FORMAT}
1113\section Appendix A: Excerpts from a \.{CWEB} Program.
1114
1115This appendix consists
1116of four listings. The first shows the \.{CWEB} input that
1117generated sections 12--15 of the file \.{common.w}, which contains
1118routines common to \.{CWEAVE} and \.{CTANGLE}.
1119Note that some of the lines are indented to show the program structure;
1120the indentation is ignored by \.{CWEAVE} and \.{CTANGLE}, but users find
1121that \.{CWEB} files are quite readable if they have some such indentation.
1122
1123The second and third listings
1124show corresponding parts
1125of the \CEE/ code output by \.{CTANGLE} and of
1126the corresponding \TEX/ code output by \.{CWEAVE}, when run on \.{common.w}.
1127The fourth listing shows how that output looks when printed out.
1128
1129\vskip 6pt
1130\begingroup \def\tt{\eighttt} \baselineskip9pt
1131\verbatim
1132@ Procedure |prime_the_change_buffer|
1133sets |change_buffer| in preparation for the next matching operation.
1134Since blank lines in the change file are not used for matching, we have
1135|(change_limit==change_buffer && !!changing)| if and only if
1136the change file is exhausted. This procedure is called only when
1137|changing| is 1; hence error messages will be reported correctly.
1138
1139@c
1140void
1141prime_the_change_buffer()
1142{
1143 change_limit=change_buffer; /* this value is used if the change file ends */
1144 @<Skip over comment lines in the change file; |return| if end of file@>;
1145 @<Skip to the next nonblank line; |return| if end of file@>;
1146 @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
1147}
1148
1149@ While looking for a line that begins with \.{@@x} in the change file, we
1150allow lines that begin with \.{@@}, as long as they don't begin with \.{@@y},
1151\.{@@z} or \.{@@i} (which would probably mean that the change file is fouled up).
1152
1153@<Skip over comment lines in the change file...@>=
1154while(1) {
1155 change_line++;
1156 if (!!input_ln(change_file)) return;
1157 if (limit<buffer+2) continue;
1158 if (buffer[0]!!='@@') continue;
1159 if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
1160 if (buffer[1]=='x') break;
1161 if (buffer[1]=='y' || buffer[1]=='z' || buffer[1]=='i') {
1162 loc=buffer+2;
1163 err_print("!! Missing @@x in change file");
1164@.Missing @@x...@>
1165 }
1166}
1167
1168@ Here we are looking at lines following the \.{@@x}.
1169
1170@<Skip to the next nonblank line...@>=
1171do {
1172 change_line++;
1173 if (!!input_ln(change_file)) {
1174 err_print("!! Change file ended after @@x");
1175@.Change file ended...@>
1176 return;
1177 }
1178} while (limit==buffer);
1179
1180@ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
1181{
1182 change_limit=change_buffer-buffer+limit;
1183 strncpy(change_buffer,buffer,limit-buffer+1);
1184}
1185
1186!endgroup
1187\endgroup
1188\vfill\eject
1189
1190\def\runninghead{APPENDIX A --- TRANSLATION BY {\tentt CTANGLE}}
1191
1192Here's the portion of the \CEE/ code generated by \.{CTANGLE} that corresponds
1193to the source on the preceding page. Notice that sections~13, 14 and~15
1194have been tangled into section~12.
1195
1196\vskip6pt
1197\begingroup \def\tt{\eighttt} \baselineskip9pt
1198\verbatim
1199/*:9*//*12:*/
1200#line 247 "common.w"
1201
1202void
1203prime_the_change_buffer()
1204{
1205change_limit= change_buffer;
1206/*13:*/
1207#line 261 "common.w"
1208
1209while(1){
1210change_line++;
1211if(!!input_ln(change_file))return;
1212if(limit<buffer+2)continue;
1213if(buffer[0]!!='@')continue;
1214if(xisupper(buffer[1]))buffer[1]= tolower(buffer[1]);
1215if(buffer[1]=='x')break;
1216if(buffer[1]=='y'||buffer[1]=='z'||buffer[1]=='i'){
1217loc= buffer+2;
1218err_print("!! Missing @x in change file");
1219
1220}
1221}
1222
1223/*:13*/
1224#line 252 "common.w"
1225;
1226/*14:*/
1227#line 278 "common.w"
1228
1229do{
1230change_line++;
1231if(!!input_ln(change_file)){
1232err_print("!! Change file ended after @x");
1233
1234return;
1235}
1236}while(limit==buffer);
1237
1238/*:14*/
1239#line 253 "common.w"
1240;
1241/*15:*/
1242#line 288 "common.w"
1243
1244{
1245change_limit= change_buffer-buffer+limit;
1246strncpy(change_buffer,buffer,limit-buffer+1);
1247}
1248
1249/*:15*/
1250#line 254 "common.w"
1251;
1252}
1253
1254/*:12*//*16:*/
1255!endgroup
1256\endgroup
1257\vfill\eject
1258
1259\def\runninghead{APPENDIX A --- TRANSLATION BY {\tentt CWEAVE}}
1260
1261Here is the corresponding excerpt from \.{common.tex}.
1262
1263\vskip6pt
1264\begingroup \def\tt{\eighttt} \baselineskip9pt
1265\verbatim
1266\M{12}Procedure \PB{\\{prime\_the\_change\_buffer}}
1267sets \PB{\\{change\_buffer}} in preparation for the next matching operation.
1268Since blank lines in the change file are not used for matching, we have
1269\PB{$(\\{change\_limit}\E\\{change\_buffer}\W\R\\{changing})$} if and only if
1270the change file is exhausted. This procedure is called only when
1271\PB{\\{changing}} is 1; hence error messages will be reported correctly.
1272!vskip-.5!baselineskip
1273\Y\B\&{void} \\{prime\_the\_change\_buffer}(\,)\1\1\2\2\6
1274${}\{{}$\1\6
1275${}\\{change\_limit}\K\\{change\_buffer}{}$;\C{ this value is used if the
1276change file ends }\6
1277\X13:Skip over comment lines in the change file; \PB{\&{return}} if end of file%
1278\X;\6
1279\X14:Skip to the next nonblank line; \PB{\&{return}} if end of file\X;\6
1280\X15:Move \PB{\\{buffer}} and \PB{\\{limit}} to \PB{\\{change\_buffer}} and %
1281\PB{\\{change\_limit}}\X;\6
1282\4${}\}{}$\2\par
1283\fi
1284!vskip-.5!baselineskip
1285\M{13}While looking for a line that begins with \.{@x} in the change file, we
1286allow lines that begin with \.{@}, as long as they don't begin with \.{@y},
1287\.{@z} or \.{@i} (which would probably mean that the change file is fouled up).
1288!vskip-.5!baselineskip
1289\Y\B\4\X13:Skip over comment lines in the change file; \PB{\&{return}} if end
1290of file\X${}\E{}$\6
1291\&{while} (\T{1})\5
1292${}\{{}$\1\6
1293${}\\{change\_line}\PP;{}$\6
1294\&{if} ${}(\R\\{input\_ln}(\\{change\_file})){}$\1\5
1295\&{return};\2\6
1296\&{if} ${}(\\{limit}<\\{buffer}+\T{2}){}$\1\5
1297\&{continue};\2\6
1298\&{if} ${}(\\{buffer}[\T{0}]\I\.{'@'}){}$\1\5
1299\&{continue};\2\6
1300\&{if} (\\{xisupper}(\\{buffer}[\T{1}]))\1\5
1301${}\\{buffer}[\T{1}]\K\\{tolower}(\\{buffer}[\T{1}]);{}$\2\6
1302\&{if} ${}(\\{buffer}[\T{1}]\E\.{'x'}){}$\1\5
1303\&{break};\2\6
1304\&{if} ${}(\\{buffer}[\T{1}]\E\.{'y'}\V\\{buffer}[\T{1}]\E\.{'z'}\V\\{buffer}[%
1305\T{1}]\E\.{'i'}){}$\5
1306${}\{{}$\1\6
1307${}\\{loc}\K\\{buffer}+\T{2};{}$\6
1308\\{err\_print}(\.{"!!\ Missing\ @x\ in\ cha}\)\.{nge\ file"});\6
1309\4${}\}{}$\2\6
1310\4${}\}{}$\2\par
1311\U12.\fi
1312!vskip-.5!baselineskip
1313\M{14}Here we are looking at lines following the \.{@x}.
1314!vskip-.5!baselineskip
1315\Y\B\4\X14:Skip to the next nonblank line; \PB{\&{return}} if end of file\X${}%
1316\E{}$\6
1317\&{do}\5
1318${}\{{}$\1\6
1319${}\\{change\_line}\PP;{}$\6
1320\&{if} ${}(\R\\{input\_ln}(\\{change\_file})){}$\5
1321${}\{{}$\1\6
1322\\{err\_print}(\.{"!!\ Change\ file\ ended}\)\.{\ after\ @x"});\6
1323\&{return};\6
1324\4${}\}{}$\2\6
1325\4${}\}{}$\2\5
1326\&{while} ${}(\\{limit}\E\\{buffer}){}$;\par
1327\U12.\fi
1328!vskip-.5!baselineskip
1329\M{15}\B\X15:Move \PB{\\{buffer}} and \PB{\\{limit}} to \PB{\\{change\_buffer}}
1330and \PB{\\{change\_limit}}\X${}\E{}$\6
1331${}\{{}$\1\6
1332${}\\{change\_limit}\K\\{change\_buffer}-\\{buffer}+\\{limit};{}$\6
1333${}\\{strncpy}(\\{change\_buffer},\39\\{buffer},\39\\{limit}-\\{buffer}+%
1334\T{1});{}$\6
1335\4${}\}{}$\2\par
1336\Us12\ET16.\fi
1337!endgroup
1338\endgroup
1339\vfil\eject
1340
1341\def\runninghead{APPENDIX A --- FINAL DOCUMENT}
1342
1343And here's what the same excerpt looks like when typeset.
1344
1345\M{12}Procedure \PB{\\{prime\_the\_change\_buffer}}
1346sets \PB{\\{change\_buffer}} in preparation for the next matching operation.
1347Since blank lines in the change file are not used for matching, we have
1348\PB{$(\\{change\_limit}\E\\{change\_buffer}\W\R\\{changing})$} if and only if
1349the change file is exhausted. This procedure is called only when
1350\PB{\\{changing}} is 1; hence error messages will be reported correctly.
1351
1352\Y\B\&{void} \\{prime\_the\_change\_buffer}(\,)\1\1\2\2\6
1353${}\{{}$\1\6
1354${}\\{change\_limit}\K\\{change\_buffer}{}$;\C{ this value is used if the
1355change file ends }\6
1356\X13:Skip over comment lines in the change file; \PB{\&{return}} if end of file%
1357\X;\6
1358\X14:Skip to the next nonblank line; \PB{\&{return}} if end of file\X;\6
1359\X15:Move \PB{\\{buffer}} and \PB{\\{limit}} to \PB{\\{change\_buffer}} and %
1360\PB{\\{change\_limit}}\X;\6
1361\4${}\}{}$\2\par
1362\fi
1363
1364\M{13}While looking for a line that begins with \.{@x} in the change file, we
1365allow lines that begin with \.{@}, as long as they don't begin with \.{@y},
1366\.{@z} or \.{@i} (which would probably mean that the change file is fouled up).
1367
1368\Y\B\4\X13:Skip over comment lines in the change file; \PB{\&{return}} if end
1369of file\X${}\E{}$\6
1370\&{while} (\T{1})\5
1371${}\{{}$\1\6
1372${}\\{change\_line}\PP;{}$\6
1373\&{if} ${}(\R\\{input\_ln}(\\{change\_file})){}$\1\5
1374\&{return};\2\6
1375\&{if} ${}(\\{limit}<\\{buffer}+\T{2}){}$\1\5
1376\&{continue};\2\6
1377\&{if} ${}(\\{buffer}[\T{0}]\I\.{'@'}){}$\1\5
1378\&{continue};\2\6
1379\&{if} (\\{xisupper}(\\{buffer}[\T{1}]))\1\5
1380${}\\{buffer}[\T{1}]\K\\{tolower}(\\{buffer}[\T{1}]);{}$\2\6
1381\&{if} ${}(\\{buffer}[\T{1}]\E\.{'x'}){}$\1\5
1382\&{break};\2\6
1383\&{if} ${}(\\{buffer}[\T{1}]\E\.{'y'}\V\\{buffer}[\T{1}]\E\.{'z'}\V\\{buffer}[%
1384\T{1}]\E\.{'i'}){}$\5
1385${}\{{}$\1\6
1386${}\\{loc}\K\\{buffer}+\T{2};{}$\6
1387\\{err\_print}(\.{"!\ Missing\ @x\ in\ cha}\)\.{nge\ file"});\6
1388\4${}\}{}$\2\6
1389\4${}\}{}$\2\par
1390\U12.\fi
1391
1392\M{14}Here we are looking at lines following the \.{@x}.
1393
1394\Y\B\4\X14:Skip to the next nonblank line; \PB{\&{return}} if end of file\X${}%
1395\E{}$\6
1396\&{do}\5
1397${}\{{}$\1\6
1398${}\\{change\_line}\PP;{}$\6
1399\&{if} ${}(\R\\{input\_ln}(\\{change\_file})){}$\5
1400${}\{{}$\1\6
1401\\{err\_print}(\.{"!\ Change\ file\ ended}\)\.{\ after\ @x"});\6
1402\&{return};\6
1403\4${}\}{}$\2\6
1404\4${}\}{}$\2\5
1405\&{while} ${}(\\{limit}\E\\{buffer}){}$;\par
1406\U12.\fi
1407
1408\M{15}\B\X15:Move \PB{\\{buffer}} and \PB{\\{limit}} to \PB{\\{change\_buffer}}
1409and \PB{\\{change\_limit}}\X${}\E{}$\6
1410${}\{{}$\1\6
1411${}\\{change\_limit}\K\\{change\_buffer}-\\{buffer}+\\{limit};{}$\6
1412${}\\{strncpy}(\\{change\_buffer},\39\\{buffer},\39\\{limit}-\\{buffer}+%
1413\T{1});{}$\6
1414\4${}\}{}$\2\par
1415\Us12\ET16.\fi
1416
1417\vfil\eject\titletrue
1418\rightskip=0pt % get out of C mode (cf. \B)
1419\sfcode`;=1500 \pretolerance 200 \hyphenpenalty 50 \exhyphenpenalty 50
1420
1421\def\runninghead{APPENDIX B --- MACROS FOR FORMATTING}
1422\section Appendix B: The \.{cwebmac.tex} file.
1423This is the file that extends ``plain \TEX/'' format in order to support the
1424features needed by the output of \.{CWEAVE}.
1425
1426\vskip6pt
1427\begingroup \def\tt{\eighttt} \baselineskip9pt
1428\def\printmacs{\input cwebmac}
1429\verbatim
1430!printmacs
1431!endgroup
1432\endgroup
1433\vfill\eject
1434
1435\def\runninghead{APPENDIX C --- NOTES ON FORMATTING}
1436\section Appendix C: How to use \.{CWEB} macros.
1437The macros in \.{cwebmac} make it possible to produce a variety of formats
1438without editing the output of \.{CWEAVE}, and the purpose of this appendix
1439is to explain some of the possibilities.
1440
1441\def\point#1.{\yskip\indent#1.\quad\ignorespaces}
1442
1443\point 1. Four fonts have been declared in addition to the standard fonts of
1444\.{PLAIN} format: You can say `\.{\{\\mc UNIX\}}' to get {\mc UNIX} in
1445medium-size caps; you can say `\.{\{\\sc STUFF\}}' to get {\sc STUFF}
1446in small caps; and you can select the largish fonts \.{\\titlefont}
1447and \.{\\ttitlefont} in the title of your document, where \.{\\ttitlefont}
1448is a typewriter style of type. There are macros \.{\\UNIX/} and \.{\\CEE/}
1449to refer to \UNIX/ and \CEE/ with medium-size caps.
1450
1451\point 2. When you mention an identifier in \TEX/ text, you normally call
1452it `\.{|identifier|}'. But you can also say `\.{\\\\\{identifier\}}'. The
1453output will look the same in both cases, but the second alternative
1454doesn't put \\{identifier} into the index, since
1455it bypasses \.{CWEAVE}'s translation from \CEE/ mode. In the second
1456case you have to put a backslash before each underline character
1457in the identifier.
1458
1459\point 3. To get typewriter-like type, as when referring to `\.{CWEB}', you
1460can use the `\.{\\.}' macro (e.g., `\.{\\.\{CWEB\}}'). In the argument to
1461this macro you should insert an additional backslash before the symbols
1462listed as `special string characters' in the index to \.{CWEAVE}, i.e.,
1463before backslashes and dollar signs and the like.
1464A `\.{\\\ }' here will result in the visible space symbol; to get an
1465invisible space following a control sequence you can say `\.{\{\ \}}'.
1466If the string is long, you can break it up into substrings that
1467are separated by `\.{\\)}'\,; the latter gives a discretionary backslash
1468if \TEX/ has to break a line here.
1469
1470\point 4. The three control sequences \.{\\pagewidth}, \.{\\pageheight},
1471and \.{\\fullpageheight} can be redefined in the limbo section at the
1472beginning of your \.{CWEB} file, to change the dimensions of each page.
1473The default settings
1474$$\lpile{\.{\\pagewidth=6.5in}\cr
1475 \.{\\pageheight=8.7in}\cr
1476 \.{\\fullpageheight=9in}\cr}$$
1477were used to prepare this manual; \.{\\fullpageheight} is
1478\.{\\pageheight} plus room for the additional heading and page numbers at
1479the top of each page. If you change any of these quantities, you should
1480call the macro \.{\\setpage} immediately after making the change.
1481
1482\point 5. The \.{\\pageshift} macro defines an amount by which right-hand
1483pages (i.e., odd-numbered pages) are shifted right with respect to
1484left-hand (even-numbered) ones. By adjusting this amount you may be
1485able to get two-sided output in which the page numbers line up on
1486opposite sides of each sheet.
1487
1488\point 6. The \.{\\title} macro will appear at the top of each page
1489in small caps; it is the job name unless redefined.
1490
1491\point 7. The first page usually is assigned page
1492number 1. To start on page 16, with contents
1493on page 15, say this: `\.{\\def\\contentspagenumber\{15\}}
1494\.{\\pageno=\\contentspagenumber} \.{\\advance\\pageno by 1}'.
1495
1496\point 8. The macro \.{\\iftitle} will suppress the header line if it is
1497defined by `\.{\\titletrue}'. The normal value is \.{\\titlefalse}
1498except for the table of contents; thus, the contents
1499page is usually unnumbered.
1500
1501Two macros are provided to give flexibility to the table of
1502contents: \.{\\topofcontents} is invoked just before the contents
1503info is read, and \.{\\botofcontents} is invoked just after.
1504Here's a typical definition:
1505$$\lpile{\.{\\def\\topofcontents\{\\null\\vfill}\cr
1506 \.{ { }\\titlefalse \% include headline on the contents page}\cr
1507 \.{ { }\\def\\rheader\{\\mainfont The \{\\tt CWEAVE\}{ }processor\\hfil\}}\cr
1508 \.{ { }\\centerline\{\\titlefont The \{\\ttitlefont CWEAVE\}{ }processor\}}\cr
1509 \.{ { }\\vskip 15pt \\centerline\{(Version 3.0)\}{ }\\vfill\}}\cr}$$
1510Redefining \.{\\rheader}, which is the headline for right-hand pages,
1511suffices in this case to put the desired information at the top of the
1512contents page.
1513
1514\point 9. Data for the table of contents is written to a file that
1515is read after the indexes have been \TEX/ed; there's one line of data
1516for every starred section. The file \.{common.toc} might look like this:
1517$$\lpile{\.{\\ZZ \{Introduction\}\{0\}\{1\}\{23\}}\cr
1518 \.{\\ZZ \{The character set\}\{2\}\{5\}\{24\}}\cr}$$
1519and so on. The \.{\\topofcontents} macro could
1520redefine \.{\\ZZ} so that the information appears in any desired format.
1521
1522\point 10. Sometimes it is necessary or desirable to divide the output of
1523\.{CWEAVE} into subfiles that can be processed separately. For example,
1524the listing of \TEX/ runs to more than 500 pages, and that is enough to
1525exceed the capacity of many printing devices and/or their software.
1526When an extremely large job isn't cut into smaller pieces, the entire
1527process might be spoiled by a single error of some sort, making it
1528necessary to start everything over.
1529
1530Here's a safe way to break a woven file into three parts:
1531Say the pieces are $\alpha$,
1532$\beta$, and $\gamma$, where each piece begins with a starred section.
1533All macros should be defined in the opening limbo section of $\alpha$,
1534and copies of this \TEX/ code should be placed at the
1535beginning of $\beta$ and of $\gamma$. In order to process the parts
1536separately, we need to take care of two things: The starting page
1537numbers of $\beta$ and $\gamma$ need to be set up properly, and
1538the table of contents data from all three runs needs to be
1539accumulated.
1540
1541The \.{cwebmac} macros include two control sequences \.{\\contentsfile} and
1542\.{\\readcontents} that facilitate the necessary processing. We include
1543`\.{\\def\\contentsfile\{cont1\}}' in the limbo section of $\alpha$, and
1544we include `\.{\\def\\contentsfile\{cont2\}}' in the limbo section of
1545$\beta$; this causes \TEX/ to write the contents data for $\alpha$ and $\beta$
1546into \.{cont1.tex} and \.{cont2.tex}. Now in $\gamma$ we say
1547$$\.{\\def\\readcontents\{\\input cont1 \\input cont2
1548 \\input \\contentsfile\}}\,;$$
1549this brings in the data from all three pieces, in the proper order.
1550
1551However, we still need to solve the page-numbering problem. One way to
1552do it is to include the following in the limbo material for $\beta$:
1553$$\lpile{\.{\\message\{Please type the last page number of part 1: \}}\cr
1554 \.{\\read -1 to \\temp \\pageno=\\temp \\advance\\pageno by 1}\cr}$$
1555Then you simply provide the necessary data when \TEX/ requests
1556it; a similar construction is used at the beginning of $\gamma$.
1557
1558This method can, of course, be used to divide a woven file into
1559any number of pieces.
1560
1561\point 11. Sometimes it is nice to include things in the index that are
1562typeset in a special way. For example, we might want to have an
1563index entry for `\TeX'. \.{CWEAVE} provides two simple ways to
1564typeset an index entry (unless the entry is an identifier or a reserved word):
1565`\.{@\^}' gives roman type, and `\.{@.}' gives typewriter type.
1566But if we try to typeset `\TeX' in roman type by saying, e.g.,
1567`\.{@\^\\TeX@>}', the backslash character gets in the way,
1568and this entry wouldn't appear in the index with the T's.
1569
1570The solution is to use the `\.{@:}' feature, declaring a macro that
1571simply removes a sort key as follows:
1572$$\.{\\def\\9\#1\{\}}$$
1573Now you can say, e.g., `\.{@:TeX\}\{\\TeX@>}' in your \.{CWEB} file; \.{CWEAVE}
1574puts it into the index alphabetically, based on the sort key, and
1575produces the macro call `\.{\\9\{TeX\}\{\\TeX\}}' which will ensure that
1576the sort key isn't printed.
1577
1578A similar idea can be used to insert hidden material into section
1579names so that they are alphabetized in whatever way you might wish.
1580Some people call these tricks ``special refinements''; others call
1581them ``kludges''.
1582
1583\point 12. The control sequence \.{\\secno} is set to the number of the
1584section being typeset.
1585
1586\point 13. If you want to list only the sections that have changed,
1587together with the index, put the command `\.{\\let\\maybe=\\iffalse}' in
1588the limbo section before the first section of your \.{CWEB} file. It's
1589customary to make this the first change in your change file.
1590
1591\point 14. To get output in languages other than English, redefine the
1592macros \.{\\A}, \.{\\ET}, \.{\\Q}, \.{\\U},
1593\.{\\ch}, \.{\\fin}, and \.{\\con}. \.{CWEAVE} itself need not be changed.
1594
1595\point 15. Some output can be selectively suppressed with the macros
1596\.{\\noatl}, \.{\\noinx}, \.{\\nosecs}, \.{\\nocon}.
1597
1598\point 16. All accents and special text symbols of plain \TEX/ format
1599will work in \.{CWEB} documents just as they are described in
1600Chapter~9 of {\sl The \TEX/book}, with one exception.
1601The dot accent (normally \.{\\.}) must be typed \.{\\:} instead.
1602
1603\point 17. Several commented-out lines in \.{cwebmac.tex} are suggestions
1604that users may wish to adopt. For example, one such line inserts a blank page
1605if you have a duplex printer. Appendices D, E, and F of the complete
1606version of this manual are printed using a commented-out option that
1607substitutes `$\gets$' for `$=$' in the program listings. Looking at those
1608appendices might help you decide which format you like better.
1609
1610\vfill\end
examples/Makefile+57−0
@@ -0,0 +1,57 @@
1#
2# generic Makefile to use when you've got CWEB
3# (add it to, or add to it, whatever you like)
4#
5#======================================================================
6
7CFLAGS = -g
8MLIB = -lm
9RM = /bin/rm -f
10WFILES = extex.w treeprint.w wc.w wmerge.w wordtest.w oemacs.w
11
12#======================================================================
13
14.SUFFIXES: .tex .dvi .w
15
16.w.tex:
17 cweave $*
18
19.tex.dvi:
20 tex $<
21
22.w.dvi:
23 make $*.tex
24 make $*.dvi
25
26.w.c:
27 ctangle $*
28
29.w.o:
30 make $*.c
31 make $*.o
32
33.c.o:
34 cc $(CFLAGS) -c $*.c
35
36.w:
37 make $*.c
38 cc $(CFLAGS) $*.c -o $*
39
40#======================================================================
41
42all: $(WFILES: .w=) excweb
43
44excweb: extex
45 ln extex excweb
46
47oemacs: oemacs.c
48 cc $(CFLAGS) -I/usr/openwin/include oemacs.c \
49 -o oemacs -lxview -lolgx -lX11
50
51doc: $(WFILES:.w=.dvi)
52
53clean:
54 $(RM) *~ \#~ .\#* *.o *.log *.dvi *.toc core a.out
55
56clobber: clean
57 $(RM) $(WFILES:.w=) $(WFILES:.w=.c) $(WFILES:.w=.tex)
examples/README+55−0
@@ -0,0 +1,55 @@
1This directory contains several files for programs that are tutorial
2and/or useful. If you are new to CWEB, read "wc.w" first; it's a
3typical example of CWEB applied to system programming.
4
5The Makefile on this directory is a generic way to build applications
6written in CWEB. Say, for example, "make wc" to get an executable
7program "wc" from wc.w. Say "make wc.dvi" to get a printable listing
8of its documentation. The program "wc" is a slight improvement over
9UNIX's standard word-count utility. (Try it, for example, with "wc *".)
10
11The treeprint program, by Norman Ramsey, generates tree-structured
12representations of file hierarchies. To use it, say "make treeprint.run"
13and then
14 find dir -type p -print | sort | treeprint
15(on a UNIX system), where dir is a directory with interesting subdirectories.
16
17The wmerge program, by Silvio Levy, produces a single CWEB file from a
18given CWEB file and a change file. It expands any "web include" (@i)
19specifications in the original CWEB file. To use it, say "make wmerge.run"
20and then, e.g., "wmerge foo.w bar.ch > foobar.w". Both CTANGLE and
21CWEAVE already accept change files, so you need not merge anything yourself
22in normal day-to-day operations; but wmerge can be useful in connection with
23the spelling checker described below.
24
25If you intend to read the source code of CTANGLE and CWEAVE, you may
26well wish to read wmerge.w first, or the hardcopy version obtained from
27"make wmerge.dvi"; it is similar but much simpler.
28
29The extex and wordtest programs, by Don Knuth, are useful spellcheckers.
30After "make extex.run" say also "ln extex excweb"; this gives
31you two filter programs, extex and excweb, that remove extraneous
32material from TeX and CWEB source files, respectively. To use them,
33you can say for example
34 cat foo.w | excweb | spell
35(or replace "cat foo.w" with "wmerge foo.w bar.ch"). A similar pipeline
36for TeX files would be
37 cat foo.tex | extex | spell
38Even better is to replace "spell" by "wordtest /usr/local/lib/dict/words",
39if you have a suitable dictionary. One such dictionary in the public domain
40can be found in directory ~ftp/pub/dict at labrea.stanford.edu, available
41via anonymous ftp. To make your own dictionary from given ones,
42 cat dict1 dict2 dict3 dict4 | wordtest > words
43is quick and effective. See the documentation of wordtest for more info.
44
45A file kspell.el that provides an emacs user interface to extex+excweb+wordtest
46also appears in this directory. (Somebody should write ELWEB...)
47
48The files xview_types.w and xlib_types.w are examples of @i (include) files
49that can be used when writing XView programs. They are based on the header
50files in OpenWindows Version 3.0.
51
52An example XView application appears in Knuth's program oemacs.w, which
53he uses for heavy emacsing. It's not very portable, but if you have
54OpenWindows3 and a Sun Type-4 keyboard you may like it as much as he does.
55(It replaces "emacstool".) The file oemacs.el goes with it.
examples/extex.w+362−0
@@ -0,0 +1,362 @@
1\datethis
2@* Introduction. This program is a simple filter that inputs \TEX/ or \.{CWEB}
3files and outputs its best guess at the ``words'' they contain. The word
4list can then be passed to a spelling check routine such as {\tt wordtest}.
5
6If this program is invoked with the name `{\tt excweb}', it will apply
7special rules based on the syntax of \.{CWEB} files. Otherwise it will
8use only the \TEX/ conventions. (Note that \UNIX/'s {\tt ln} command
9allows a program to be invoked with more than one name although it
10appears only once in the computer's memory.)
11
12The \TEX/ conventions adopted here say that words are what remain
13after you remove nonletters, control sequences,
14comments triggered by \.\% marks, and material enclosed
15within \.{\$...\$} or \.{\$\$...\$\$}. However, an apostrophe within
16a word will be retained. The plain \TEX/ control
17sequences for accented characters and special text characters, namely
18$$\vbox{\halign{&\.{\\#}\hfil\qquad\cr
19'&`&\relax\^&"&\relax\~&=&.&u&v\cr
20H&t&c&d&b&oe&OE&ae&AE\cr
21aa&AA&o&O&l&L&ss&i&j\cr}}$$
22will also be retained, so that users can treat them as parts of words.
23A blank space
24following any of the alphabetic control sequences in this list will be carried
25along too. If any of these control sequences is followed by \.\{, everything
26up to the next \.\} will also be retained. Thus, for example, the
27construction `\.{m\\=\{\\i\}n\\u\ us}' will be considered a single word,
28in spite of the control sequences and the space between the two u's.
29
30The \.{CWEB} conventions are essentially the same as the \TEX/ conventions,
31in the \TEX/ parts of a \.{CWEB} file. The \CEE/ parts of the file
32are blanked out.
33
34No attempt is made to reach a high level of artificial intelligence,
35which would be able to truly understand the input file. Tricky users can
36 confuse us. But we claim that devious tricks are their problem, not ours.
37
38@ So here goes. The main idea is to keep a one-character lookahead
39buffer, called |c|, which is set to zero when the character has been
40processed. A giant switch to various cases, depending on the value of~|c|,
41keeps everything moving.
42
43If you don't like |goto| statements, don't read this. (And don't read
44any other programs that simulate finite-state automata.)
45
46@c
47#include <stdio.h>
48#include <ctype.h>
49extern void exit(); /* system routine that terminates execution */
50@#
51@<Global variables@>@;
52@<Procedures@>@;
53@#
54int main(argc,argv)
55 int argc; /* the number of arguments (should be 1, but this isn't checked) */
56 char *argv[]; /* the arguments (|*argv| is the program name) */
57{
58 @<Local variables@>;
59 if (strcmp(*argv,"excweb")==0) {
60 web=1;
61 @<Adjust tables for \.{CWEB} mode@>;
62 } else web=0;
63 comment=skipping=c=0;
64 main_cycle: if (c) goto big_switch;
65 restart: c=get();
66 big_switch: switch(c) {
67 @<Special cases of the giant switch where we don't just discard |c|@>@;
68 case EOF: exit(0);
69 default: goto restart;
70 }
71 @<Labeled code segments, which exit by explicit |goto|@>;
72}
73
74@ @<Global variables@>=
75int c; /* one-character look-see buffer */
76
77@ @<Local variables@>=
78int web; /* are we looking for \.{CWEB} constructs? */
79int comment; /* are we inside a \CEE/ comment in a \.{CWEB} document? */
80int skipping; /* are we skipping \CEE/ code in a \.{CWEB} document? */
81int save_skipping; /* value of |skipping| outside current \CEE/ mode */
82register int cc; /* temporary buffer */
83
84@* Simple cases.
85Let's do some of the easiest things first, in order to get the hang of
86this program. Several special characters will cause us to ignore everything
87until the first appearance of something else.
88
89@d discard_to(x) {@+while (get()!=x) ;@+}
90
91@<Special cases...@>=
92case '%': discard_to('\n');@+goto restart;
93case '$': c=getchar();
94 if (c!='$') discard_to('$')@;
95 else { /* after \.{\$\$} we discard everything to the next \.{\$\$} */
96 do discard_to('$')@;
97 while (getchar()!='$');
98 }
99 goto restart;
100
101@ The `|get|' procedure in the code above is like \Cee's standard
102`|getchar|', except that it immediately terminates execution at the end of
103the input file. Otherwise malformed input files could lead to
104infinite loops.
105
106@<Procedures@>=
107int get()
108{@+register int x;
109 x=getchar();
110 if (x==EOF) exit(0);
111 return x;
112}
113
114@ More complex behavior is handled by jumping out of the |switch| statement
115to one of the routines following it. None of the cases say |break|, so
116the code following the switch statement is accessible only via |goto|.
117
118@<Special cases...@>=
119case 'a': case 'A':
120case 'b': case 'B':
121case 'c': case 'C':
122case 'd': case 'D':
123case 'e': case 'E':
124case 'f': case 'F':
125case 'g': case 'G':
126case 'h': case 'H':
127case 'i': case 'I':
128case 'j': case 'J':
129case 'k': case 'K':
130case 'l': case 'L':
131case 'm': case 'M':
132case 'n': case 'N':
133case 'o': case 'O':
134case 'p': case 'P':
135case 'q': case 'Q':
136case 'r': case 'R':
137case 's': case 'S':
138case 't': case 'T':
139case 'u': case 'U':
140case 'v': case 'V':
141case 'w': case 'W':
142case 'x': case 'X':
143case 'y': case 'Y':
144case 'z': case 'Z':
145goto out_word;
146
147@ When letters appear in |stdin|, we pass them immediately through to |stdout|
148with little further ado.
149An apostrophe is rejected unless it is immediately followed by a letter.
150
151@<Labeled code...@>=
152out_word: putchar(c);
153continue_word: c=getchar();
154checkout_word:
155if (isalpha(c)) goto out_word;
156if (c=='\'') {
157 c=getchar();
158 if (isalpha(c)) {
159 putchar('\'');@+goto out_word;
160 }
161 goto end_word;
162}
163if (c=='\\' && controlseq()) goto control_seq_in_word;
164end_word: putchar('\n');
165 goto main_cycle;
166
167@* Control sequences. The |controlseq()| function is the only
168delicate part of this program. After a backslash has been scanned,
169|controlseq| looks to see if the next characters define one of the
170special plain \TEX/ macros listed above. If so, the control sequence
171and its immediately following argument (if any) are output and
172|controlseq| returns a nonzero value. If not, nothing is output and
173|controlseq| returns zero. In both cases the value of |c| will be
174nonzero if and only if |controlseq| has had to look ahead at a
175character it decided not to process.
176
177@ @<Labeled code...@>=
178control_seq_in_word: if (!c) goto continue_word;
179goto checkout_word;
180
181@ @<Special cases...@>=
182case '\\': if (controlseq()) goto control_seq_in_word;
183goto main_cycle;
184
185@ @<Procedures@>=
186int controlseq()
187{
188 int l; /* number of letters in the control sequence */
189 char a,b; /* the first two characters after `\.\\' */
190 l=0;
191 a=c=getchar();
192 while (isalpha(c)) {
193 l++;
194 c=getchar();
195 if (l==1) b=c;
196 }
197 if (l==0) c=getchar();
198 @<Check for special plain \TEX/ control sequences;
199 output them and |return 1| if found@>;
200 return 0;
201}
202
203@ @d pair(x,y) (a==x && b==y)
204
205@<Check for special...@>=
206if ((a>='"' && a<='~' && ptab[a-'"']==l) ||
207 (l==2 && (pair('a','e') || pair('A','E')@|
208 || pair('o','e') || pair('O','E')@|
209 || pair('a','a') || pair('A','A') || pair('s','s')))) {
210 putchar('\\');
211 putchar(a);
212 if (l==2) putchar(b);
213 if (l && c==' ') {
214 putchar(' '); /* optional space after alphabetic control sequence */
215 c=getchar();
216 }
217 if (c=='{') {
218 do@+{putchar(c);
219 c=get();
220 }@+while (c!='}'); /* optional argument after special control sequence */
221 putchar(c);
222 c=0;
223 }
224 return 1;
225}
226
227@ The |ptab| entries for nonletters are 0 when the control sequence is
228special, otherwise~1; the conventions for letters are reversed.
229
230@<Global...@>=
231char ptab[]={0,1,1,1,1,0, /* \.{\\"} and \.{\\'} */
232 1,1,1,1,1,1,0,1, /* \.{\\.} */
233 1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1, /* \.{\\=} */
234 1,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1, /* \.{\\H}, \.{\\L}, \.{\\O} */
235 0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1, /* \.{\\\^} */
236 0,0,1,1,1,0,0,0, /* \.{\\`}, \.{\\b}, \.{\\c}, \.{\\d} */
237 0,1,1,0,1,0,0,1, /* \.{\\i}, \.{\\j}, \.{\\l}, \.{\\o} */
238 0,0,0,0,1,1,1,0, /* \.{\\t}, \.{\\u}, \.{\\v} */
239 0,0,0,1,1,1,0}; /* \.{\\\~} */
240
241@ In \.{CWEB} the \TEX/ control sequence `\.{\\.}' denotes the typewriter
242font used for strings, not the dot-over accent. We must modify
243|ptab| to reflect this unfortunate (but too-late-too-change) design decision.
244
245@<Adjust tables for \.{CWEB} mode@>=
246ptab[12]=1;
247
248@* CWEB considerations.
249We're finished now with all that would be needed if we only wanted to
250handle \TEX/. For \.{CWEB} a bit more should be done.
251
252The \.{CWEB} escape character is \.{@@}, and the character following
253it tells us what mode we should enter. In \TEX/ mode we should not
254only do what we normally do for \TEX/ files, we should also ignore
255material delimited by \.{\char"7C...\char"7C}, being careful to recognize when
256|'|'| is part of a string (as it just was). And we should stop \TEX/
257mode if we scan \.{*/} while in a \CEE/ comment.
258
259@<Special cases...@>=
260case '@@': if (web) goto do_web;
261 goto restart;
262case '|': if (web>1) {
263 save_skipping=skipping;
264 goto skip_C_prime;
265 }
266 goto restart;
267case '*': if (!comment) goto restart;
268 c=getchar();
269 if (c=='/') {
270 comment=0;
271 goto skip_C;
272 }
273 goto big_switch;
274
275@ The characters that follow \.@@ in a \.{CWEB} file can be classified into
276a few types that have distinct implications for {\tt excweb}.
277
278@d nop 0 /* control code that doesn't matter to us */
279@d start_section 1 /* control code that begins a \.{CWEB} section */
280@d start_C 2 /* control code that begins \CEE/ code */
281@d start_name 3 /* control code that begins a section name */
282@d start_index 4 /* control code for \.{CWEB} index entry */
283@d start_insert 5 /* control code for \CEE/ material ended by `\.{@@>}' */
284@d end_item 6 /* `\.{@@>}' */
285@d ignore_line 7 /* `\.{@@i}' or `\.{@@l}' */
286
287@<Global...@>=
288char wtab[]={start_section,nop,nop,nop,nop,nop,nop,nop, /* \.{\ !"\#\$\%\&'} */
289 start_name,nop,start_section,nop,nop,nop,start_index,nop, /* \.{()*+,-./} */
290 nop,nop,nop,nop,nop,nop,nop,nop, /* \.{01234567} */
291 nop,nop,start_index,nop,start_name,start_insert,end_item,nop,
292 /* \.{89:;<=>?} */
293 nop,nop,nop,start_C,start_C,nop,start_C,nop, /* \.{@@ABCDEFG} */
294 nop,ignore_line,nop,nop,ignore_line,nop,nop,nop, /* \.{HIJKLMNO} */
295 start_C,start_insert,nop,start_C,start_insert,nop,nop,nop, /* \.{PQRSTUVW} */
296 nop,nop,nop,nop,nop,nop,start_index,nop, /* \.{XYZ[\\]\^\_} */
297 nop,nop,nop,start_C,start_C,nop,start_C,nop, /* \.{`abcdefg} */
298 nop,ignore_line,nop,nop,ignore_line,nop,nop,nop, /* \.{hijklmno} */
299 start_C,start_insert,nop,start_C,start_insert}; /* \.{pqrst} */
300
301@ We do not leave \TEX/ mode until the first \.{WEB} section has begun.
302
303@<Labeled code...@>=
304do_web: c=getchar();
305 if (c<' ' || c>'t') goto restart;
306 switch(wtab[c-' ']){
307 case nop: case start_index: goto restart;
308 case start_section: web++; /* out of ``limbo'' */
309 comment=skipping=0;@+goto restart;
310 case start_C: if (web>1) goto skip_C;
311 goto restart;
312 case start_name: case start_insert: if (web>1) skipping=1;
313 goto restart;
314 case end_item: if (skipping) goto skip_C;
315 goto restart;
316 case ignore_line: discard_to('\n');
317 goto restart;
318 }
319
320@ The final piece of program we need is a sub-automaton to pass over
321the \CEE/ parts of a \.{CWEB} document. The main subtlety here is that
322we don't want to get out of synch while scanning over a supposed
323string constant or verbatim insert.
324
325@<Labeled code...@>=
326skip_C: save_skipping=2;
327skip_C_prime: skipping=1;
328 while (1) {
329 c=get();
330 C_switch: switch(c) {
331 case '/': c=get();
332 if (c!='*') goto C_switch;
333 comment=1; /* fall through to the next case, returning to \TEX/ mode */
334 case '|': if (save_skipping==2) continue; /* |'|'| as \CEE/ operator */
335 skipping=save_skipping;@+goto restart; /* |'|'| as \.{CWEB} delimiter */
336 case '@@': c=getchar();
337 inner_switch: if (c<' ' || c>'t') continue;
338 switch(wtab[c-' ']) {
339 case nop: case start_C: case end_item: continue;
340 case start_section: web++;
341 comment=skipping=0;@+goto restart;
342 case start_name: case start_index: goto restart;
343 case start_insert: do@+discard_to('@@')@;@+while ((c=getchar())=='@@');
344 goto inner_switch; /* now |c| should equal |'>'| */
345 case ignore_line: discard_to('\n');
346 continue;
347 }
348 case '\'': case '"':
349 while ((cc=get())!=c && cc!='\n')
350 if (cc=='\\') getchar();
351 else if (cc=='@@') {
352 cc=getchar();
353 if (cc!='@@') { /* syntax error, we try to recover */
354 c=cc; goto inner_switch;
355 }
356 };
357 continue; /* \.{CWEB} strings do not extend past one line */
358 default: continue;
359 }
360 }
361
362@* Index.
examples/kspell.el+223−0
@@ -0,0 +1,223 @@
1;; Alternative spelling enterface for Emacs, contributed by Don Knuth
2;; (Uses the wordtest and extex programs, which are
3;; supplied as examples with the CWEB distribution,
4;; available by anonymous ftp from labrea.stanford.edu)
5
6;; Based in part on "spell.el" from GNU Emacs; redistributed under
7;; the terms of the GNU General Public License; NO WARRANTY implied.
8
9;; To install this, using the default directories defined below,
10;; install wordtest and extex in /usr/local/bin, then say
11;; "ln /usr/local/bin/extex /usr/local/bin/excweb", then install
12;; a suitable dictionary in /usr/local/lib/dict/words; one such
13;; dictionary can be found in ~ftp/pub/dict/words at labrea.stanford.edu.
14;; Also create an empty file called .words in your home directory.
15;; Finally, add (load-library "kspell") to your .emacs file, or
16;; include such a line in site-init.el if kspell is to be use by everybody.
17;; If you get a message like "Checking spelling of buffer...not correct"
18;; and nothing else, the probable cause is that the wordtest program
19;; could not open /usr/local/lib/dict/words or ~/.words for reading.
20
21(provide 'kspell)
22
23(defvar wordtest-command "wordtest" ;; maybe "/usr/local/bin/wordtest" better?
24 "*Command to run the wordtest program; can include command-line options.")
25
26;; "wordtest [options] [dictionaries] <infile >outfile" outputs all
27;; lines of infile that don't appear in the dictionaries. The options
28;; can define arbitrary character code mappings of 8-bit characters.
29;; The default mapping takes a-z into A-Z, otherwise is ASCII.
30
31(defvar wordtest-filter "extex" ;; maybe "/usr/local/bin/extex" is better?
32 "*Command to run the filter needed by wordtest.")
33(make-variable-buffer-local 'wordtest-filter)
34
35;; The extex filter extracts words from its input and outputs them on
36;; separate lines as required by wordtest. It removes TeX control
37;; sequences except those used to make accents and special characters.
38;; There's a companion filter excweb that also removes C code from CWEBs.
39(setq cweb-mode-hook '(lambda () (setq wordtest-filter "excweb")))
40
41(defvar wordtest-system-dictionary "/usr/local/lib/dict/words"
42 "*Sorted dictionary containing all \"correct\" words,
43including all variant forms obtained by prefix and suffix transformations.")
44;; The standard UNIX dictionary /usr/dict/words is NOT satisfactory.
45
46(defvar wordtest-personal-dictionary "~/.words"
47 "*Default dictionary to supplement the words in the system dictionary.
48If nil, no supplementary dictionary will be used.
49This dictionary must be in alphabetic order as defined by wordtest.
50Inserting any word with the + option to kspell-region will sort the file.")
51(make-variable-buffer-local 'wordtest-personal-dictionary)
52
53(defun set-personal-dictionary (filename)
54 "Defines the supplementary personal dictionary for kspell to use in the
55current buffer, overriding the default value of wordtest-personal-dictionary."
56 (interactive "FPersonal dictionary file name: ")
57 (setq wordtest-personal-dictionary filename))
58
59(defun unset-personal-dictionary ()
60 "Tells kspell not to use personal spelling dictionary with current buffer."
61 (interactive)
62 (setq wordtest-personal-dictionary nil))
63
64(defun insert-into-personal-dictionary (word)
65 "Put WORD into user's dictionary and sort that dictionary."
66 (interactive "sword: ")
67 (let ((xword (concat word "\n")))
68 (if (null wordtest-personal-dictionary)
69 (setq wordtest-personal-dictionary
70 (read-string "Personal dictionary file name: " "~/.words")))
71 (set-buffer (find-file-noselect wordtest-personal-dictionary))
72 (goto-char (point-min))
73 (insert xword)
74 (call-process-region (point-min) (point-max) shell-file-name
75 t t nil "-c" wordtest-command)
76 (search-backward xword (point-min) 1) ;; in case the user is watching
77 (while (not (bolp)) (search-backward xword (point-min) 1))
78 (save-buffer)))
79
80(defun kspell-buffer ()
81 "Check spelling of every word in the buffer.
82For each incorrect word, you are asked for the correct spelling
83and then put into a query-replace to fix some or all occurrences.
84
85If you do not want to change a word, just give the same word
86as its \"incorrect\" spelling; then the query replace is skipped.
87Words are given in lowercase, but they will be Capitalized when
88replacing Capitalized words, ALL_CAPS when replacing ALL_CAPS words.
89If you type ? after a replacement, your correction will first be
90looked up in the dictionary, and the query-replace will occur
91only if the replacement is found. If you type + after a replacement,
92your replacement will be inserted into the current personal dictionary.
93
94You can leave the minibuffer to do some other editing and then come
95back again to the query-replace loop by typing \\[other-window]."
96 (interactive)
97 (save-excursion (kspell-region (point-min) (point-max) "buffer")))
98
99(defun kspell-word ()
100 "Check spelling of the word at or before point.
101If it is not correct, ask user for the correct spelling and
102query-replace the entire buffer to substitute it as with kspell-buffer."
103 (interactive)
104 (let (beg end wordtest-filter)
105 (save-excursion
106 (if (not (looking-at "\\<"))
107 (forward-word -1))
108 (setq beg (point))
109 (forward-word 1)
110 (setq end (point))
111 (kspell-region beg end (buffer-substring beg end)))))
112
113(defun kspell-region (start end &optional description)
114 "Like kspell-buffer but checks only words in the current region.
115Used in a program, applies from START to END.
116DESCRIPTION is an optional string naming the unit being checked:
117for example, \"buffer\"."
118 (interactive "r")
119 (let (correct
120 (filter wordtest-filter)
121 (buf (get-buffer-create " *kspell*")) ;; hidden by list-buffers
122 (dicts wordtest-system-dictionary))
123 (if wordtest-personal-dictionary
124 (setq dicts (concat dicts " " wordtest-personal-dictionary)))
125 (save-excursion
126 (save-excursion
127 (set-buffer buf)
128 (widen)
129 (erase-buffer))
130 (message "Checking spelling of %s..." (or description "region"))
131 (if (and (null filter)
132 (< end (point-max))
133 (= ?\n (char-after end)))
134 (call-process-region start (1+ end) shell-file-name
135 nil buf nil "-c"
136 (concat wordtest-command " " dicts))
137 (let ((oldbuf (current-buffer)))
138 (save-excursion
139 (set-buffer buf)
140 (insert-buffer-substring oldbuf start end)
141 (or (bolp) (insert ?\n))
142 (if filter
143 (call-process-region (point-min) (point-max) shell-file-name
144 t t nil "-c" filter))
145 (call-process-region (point-min) (point-max) shell-file-name
146 t t nil "-c"
147 (concat wordtest-command " " dicts)))))
148 (setq correct (save-excursion (set-buffer buf) (= (buffer-size) 0)))
149 (message "Checking spelling of %s...%scorrect"
150 (or description "region")
151 (if correct "" "not "))
152 (if correct t
153 (let (word newword qtext lastchar
154 (case-fold-search t)
155 (case-replace t))
156 (while (save-excursion
157 (set-buffer buf)
158 (> (buffer-size) 0))
159 (save-excursion
160 (set-buffer buf)
161 (goto-char (point-min))
162 (setq word (downcase
163 (buffer-substring (point)
164 (progn (end-of-line) (point)))))
165 (forward-char 1) ;; pass the newline
166 (delete-region (point-min) (point))
167 (setq qtext (concat "\\b" (regexp-quote word) "\\b")))
168 (goto-char (point-min))
169 (setq lastchar nil)
170 (if (re-search-forward qtext nil t)
171 (while (null lastchar)
172 (setq newword
173 (read-string
174 (concat "edit a replacement for `" word "': ")
175 word))
176 (if (null newword) (setq lastchar 0)
177 (setq lastchar (string-to-char (substring newword -1)))
178 (if (memq lastchar '(?? ?+))
179 (setq newword (substring newword 0 -1))))
180 (cond ((= lastchar ??)
181 (cond ((or (string= word newword) (string= "" newword))
182 (describe-function 'kspell-buffer)
183 (setq lastchar nil))
184 ((not (kspelt-right newword))
185 (setq lastchar nil))))
186 ((= lastchar ?+)
187 (save-excursion
188 (insert-into-personal-dictionary newword))))
189 (cond ((string= word newword))
190 ((null lastchar))
191 (t
192 (goto-char (point-min))
193 (if (or (equal word newword) (null lastchar)) t
194 (query-replace-regexp qtext newword))))))))))))
195
196(defun kspelt-right (word)
197 "T if WORD is in the system dictionary or user's personal dictionary."
198 (let ((buf (get-buffer-create " *temp*"))
199 (pdict wordtest-personal-dictionary))
200 (message "Checking spelling of %s..." word)
201 (save-excursion
202 (set-buffer buf)
203 (widen)
204 (erase-buffer)
205 (insert word "\n")
206 (if pdict
207 (call-process-region (point-min) (point-max) shell-file-name
208 t t nil "-c"
209 (concat wordtest-command " "
210 wordtest-system-dictionary " "
211 pdict))
212 (call-process-region (point-min) (point-max) shell-file-name
213 t t nil "-c"
214 (concat wordtest-command " "
215 wordtest-system-dictionary)))
216 (= 0 (buffer-size)))))
217
218(defun kspell-string (string)
219 "Check spelling of string supplied as argument."
220 (interactive "sSpell string: ")
221 (message "%s is %scorrect" string
222 (if (kspelt-right string) "" "in")))
223
examples/oemacs.el+176−0
@@ -0,0 +1,176 @@
1;; macros to go with oemacs
2
3; suntool-map is the map for "\C-x*", the oemacs prefix for function keys
4; commented-out lines agree with the settings in $(EMACS)/lisp/term/sun.el
5
6(setq suntool-map-hooks '( ; not your usual hook list
7; (define-key suntool-map "al" 'keyboard-quit) ; Stop
8; (define-key suntool-map "bl" 'redraw-display) ; Again L2
9; (define-key suntool-map "b\M-l" 'repeat-complex-command); M-Again = C-X ESC
10; (define-key repeat-complex-command-map "\C-x*b\M-l"
11; 'previous-complex-command) ; M-Again M-Again...
12 (define-key suntool-map "bL" 'rerun-prev-command) ; AGAIN (no confirm)
13; (define-key suntool-map "b\M-L" 'rerun-prev-command) ; M-AGAIN
14; (define-key suntool-map "cl" 'buffer-menu) ; Props
15; (define-key suntool-map "dl" 'undo) ; Undo
16; (define-key suntool-map "el" 'ignore-key) ; Front
17; (define-key suntool-map "fl" 'sun-select-region) ; Copy
18; (define-key suntool-map "f," 'copy-region-as-kill) ; C-Copy
19; (define-key suntool-map "gl" 'ignore-key) ; Open
20; (define-key suntool-map "hl" 'sun-yank-selection) ; Paste
21; (define-key suntool-map "h," 'yank) ; C-Paste
22; (define-key suntool-map "il" 'research-forward) ; Find (with default)
23; (define-key suntool-map "i\M-l" 'research-backward) ; M-Find
24; (define-key suntool-map "iL" 'isearch-forward-regexp) ; FIND (incremental)
25; (define-key suntool-map "i\M-L" 'isearch-backward-regexp); M-FIND
26; (define-key suntool-map "i," 're-search-forward) ; C-Find (ordinary)
27; (define-key suntool-map "i\M-," 're-search-backward) ; C-M-Find
28 (define-key suntool-map "jl" 'sun-cut-region) ; Cut
29 (define-key suntool-map "j," 'kill-region-and-unmark) ; C-Cut
30 (define-key suntool-map "jL" 'pop-the-mark) ; CUT
31; (define-key suntool-map "j\M-l" 'exchange-point-and-mark); M-Cut
32
33 (define-key suntool-map "at" 'bury-buffer) ; F1
34; (define-key suntool-map "bt" 'toggle-selective-display) ; F2
35; (define-key suntool-map "ct" 'scroll-down-in-place) ; F3
36; (define-key suntool-map "cT" '(lambda(n) (interactive "p") (scroll-down n)))
37; (define-key suntool-map "dt" 'scroll-up-in-place) ; F4
38; (define-key suntool-map "dT" '(lambda(n) (interactive "p") (scroll-up n)))
39 (define-key suntool-map "et" 'jumpup) ; F5
40; (define-key suntool-map "ft" 'shrink-window) ; F6
41; (define-key suntool-map "fT" 'shrink-window-horizontally) ; Shift-F6
42; (define-key suntool-map "gt" 'enlarge-window) ; F7
43; (define-key suntool-map "gT" 'enlarge-window-horizontally) ; Shift-F7
44 (define-key suntool-map "ht" 'tags-search) ; F8
45 (define-key suntool-map "it" 'tags-query-replace) ; F9
46 (define-key suntool-map "jt" 'narrow-to-region) ; F10
47 (define-key suntool-map "j\M-t" 'narrow-to-page) ; M-F10
48 (define-key suntool-map "kt" 'quick-revert-buffer) ; F11
49 (define-key suntool-map "k\M-t" 'quick-revert-other-buffer) ; M-F11
50 (define-key suntool-map "lt" 'goto-line) ; F12
51 (define-key suntool-map "l\M-t" 'goto-line) ; M-F12
52
53 (define-key suntool-map "ar" 'redraw-display) ; Pause, R1
54 (define-key suntool-map "br" 'call-secondlast-kbd-macro) ; PrSc, R2
55 (define-key suntool-map "cr" 'ignore-key) ; Scroll Lock Break, R3
56 (define-key suntool-map "dr" 'unbound-key) ; KP=, R4
57 (define-key suntool-map "d\M-r" 'bind-last-kbd-macro-to-KP=) ; M-KP=, M-R4
58 (define-key suntool-map "er" 'unbound-key) ; KP/, R5
59 (define-key suntool-map "e\M-r" 'bind-last-kbd-macro-to-KP/) ; M-KP/, M-R5
60 (define-key suntool-map "fr" 'unbound-key) ; KP*, R6
61 (define-key suntool-map "f\M-r" 'bind-last-kbd-macro-to-KP*) ; M-KP*, M-R6
62; (define-key suntool-map "gr" 'beginning-of-buffer) ; Home, R7
63
64; (define-key suntool-map "hr" 'previous-line) ; Up, R8
65; (define-key suntool-map "ir" 'scroll-down) ; PgUp, R9
66; (define-key suntool-map "iR" 'backward-page) ; Shift-PGUP
67; (define-key suntool-map "jr" 'backward-char) ; Lft, R10
68 (define-key suntool-map "kr" "\C-u\C-l") ; KP5, R11
69; (define-key suntool-map "lr" 'forward-char) ; Rt, R12
70; (define-key suntool-map "mr" 'end-of-buffer) ; End, R13
71; (define-key suntool-map "nr" 'next-line) ; Dn, R14
72; (define-key suntool-map "or" 'scroll-up) ; PgDn, R15
73; (define-key suntool-map "oR" 'forward-page) ; Shift-PGUP
74
75 (define-key suntool-map "ab" 'apropos) ; Help
76 (define-key suntool-map "a\M-b" 'mouse-help) ; M-Help
77 (define-key suntool-map "aB" 'describe-bindings) ; HELP
78 (define-key suntool-map "a\M-B" 'describe-mouse-bindings); M-HELP
79 (define-key suntool-map "a\"" 'command-apropos) ; C-Help
80 (define-key suntool-map "a\C-B" 'apropos) ; C-HELP
81 (define-key suntool-map "a\M-\C-B" 'help-for-dummies) ; M-C-HELP
82 (define-key suntool-map "bb" 'ignore-key) ; Alt
83 (define-key suntool-map "cb" 'ignore-key) ; AltGraph
84 (define-key suntool-map "db" 'auto-fill-mode) ; Keypad Ins
85 (define-key suntool-map "eb" 'overwrite-mode) ; Keypad Del
86 (define-key suntool-map "fb" 'call-last-kbd-macro) ; Keypad Enter
87 (define-key suntool-map "gb" 'forward-paragraph) ; Keypad +
88 (define-key suntool-map "hb" 'backward-paragraph) ; Keypad -
89 ))
90
91
92; redefinition of emacs functions
93(defun end-of-buffer ()
94 "Move point to the end of the buffer; leave a mark at previous position.
95Scroll so that point is at the bottom of the window, if possible."
96 (interactive)
97 (push-mark)
98 (goto-char (point-max))
99 (recenter -1))
100
101; new functions
102(defun jumpup ()
103 "Scroll so that point is at the top of the window."
104 (interactive)(recenter 0))
105
106(defun quick-revert-buffer ()
107 "Revert the buffer without asking for confirmation."
108 (interactive)
109 (revert-buffer t t))
110
111(defun quick-revert-other-buffer (n)
112 "Revert the Nth other buffer without asking for confirmation."
113 (interactive "p")
114 (other-window n)
115 (revert-buffer t t)
116 (other-window (- n)))
117
118(defun bind-last-kbd-macro-to-KP= ()
119 "Assign the last keyboard macro to the = key on the numeric keypad."
120 (interactive)
121 (define-key suntool-map "dr" last-kbd-macro))
122
123(defun bind-last-kbd-macro-to-KP/ ()
124 "Assign the last keyboard macro to the / key on the numeric keypad."
125 (interactive)
126 (define-key suntool-map "er" last-kbd-macro))
127
128(defun bind-last-kbd-macro-to-KP* ()
129 "Assign the last keyboard macro to the * key on the numeric keypad."
130 (interactive)
131 (define-key suntool-map "fr" last-kbd-macro))
132
133(defvar secondlast-kbd-macro nil)
134(defun pre-end-kbd-macro ()
135 "Preserve last-kbd-macro as secondlast-kbd-macro, then end-kbd-macro."
136 (interactive)
137 (setq secondlast-kbd-macro last-kbd-macro)
138 (end-kbd-macro))
139(substitute-key-definition 'end-kbd-macro 'pre-end-kbd-macro global-map)
140(substitute-key-definition 'end-kbd-macro 'pre-end-kbd-macro esc-map)
141(substitute-key-definition 'end-kbd-macro 'pre-end-kbd-macro ctl-x-map)
142
143(defun call-secondlast-kbd-macro (n)
144 "Like call-last-kbd-macro, but uses the macro defined before that."
145 (interactive "p")
146 (let ((last-kbd-macro secondlast-kbd-macro))
147 (call-last-kbd-macro n)))
148
149; The turn-numlock-on/off commands are created automatically by oemacs
150; when the NumLock light changes state.
151(defun turn-numlock-on () ; numlock is always off when oemacs starts
152 "Bind keys in keypad area to numeric interpretations."
153 (interactive)
154 (setq hb-binding (lookup-key suntool-map "hb"))
155 (setq gb-binding (lookup-key suntool-map "gb"))
156 (setq fb-binding (lookup-key suntool-map "fb"))
157 (setq eb-binding (lookup-key suntool-map "eb"))
158 (setq db-binding (lookup-key suntool-map "db"))
159 (define-key suntool-map "hb" "-")
160 (define-key suntool-map "gb" "+")
161 (define-key suntool-map "fb" "\C-j")
162 (define-key suntool-map "eb" ".")
163 (define-key suntool-map "db" "0"))
164(defun turn-numlock-off ()
165 "Rebind keys in keypad area to function-key interpretations."
166 (interactive)
167 (define-key suntool-map "hb" hb-binding)
168 (define-key suntool-map "gb" gb-binding)
169 (define-key suntool-map "fb" fb-binding)
170 (define-key suntool-map "eb" eb-binding)
171 (define-key suntool-map "db" db-binding))
172(defvar hb-binding nil)
173(defvar gb-binding nil)
174(defvar fb-binding nil)
175(defvar eb-binding nil)
176(defvar db-binding nil)
examples/oemacs.w+896−0
@@ -0,0 +1,896 @@
1\datethis
2@i xview_types.w
3
4@* Introduction.
5This program provides an interface between the GNU Emacs editor and the
6OpenWindows environment, using the XView toolkit for interactive graphics.
7It is based on \.{emacstool}, a SunView interface written by Jeff Peck
8of Sun Microsystems in 1986 and adapted by him in 1988 to \.{xvetool},
9an early XView interface. The present code, by Don Knuth, is designed to work
10with OpenWindows Version~3 as distributed in 1992, using a Sun Type~4
11keyboard.
12
13GNU Emacs is a highly portable and versatile program, which does most
14of the hard work involved in editing files. Our job is simply twofold:
15To get \.{emacs} started in an appropriate window, and to transmit
16keyboard and mouse events as sequences of characters that \.{emacs}
17can happily consume. These simple tasks do, however, require us to
18get a lot of fussy details right. In fact, this program could not have been
19written without a good deal more knowledge about XView than can be found
20in the manuals. Fortunately Jeff Peck works for Sun, and his
21inside knowledge has provided the necessary clues. (All complaints below
22about the XView documentation are based on the reference manuals and
23programming manuals available from Sun and from O'Reilly \AM\ Associates, in
24the summer of 1992. Let us hope that such problems will not persist;
25computer programming should be fun, but some of the code below was
26written only after a bitter struggle!)
27
28The command-line arguments to \.{oemacs} are either standard XView
29arguments, which specify the font and the size and position of the window,
30the icon, the colors, etc.; or they are standard arguments of \.{emacs},
31which typically specify the file to be edited and a position in that file.
32If I decide later to make certain things in \.{oemacs} less hardwired,
33I will look for options in the X resource database instead of on the
34command line.
35
36An important note about using \.{xmodmap} to change the behavior of
37certain keys appears below. It makes \.{emacs} more powerful, unless you
38have other good uses for those keys. (See the entry for \.{xmodmap}
39in the index.)
40
41Before using \.{oemacs}, you must compile \.{emacs} with the
42\.{sunfns} module (which the \.{Makefile} will do for you if you've
43configured it correctly), and you should include the lines
44$$\vbox{\halign{\.{#}\hfil\cr
45(load-library "sun-mouse")\cr
46(load-library "sun-fns")\cr}}$$
47in Emacs's file \.{lisp/site-init.el}.
48
49Caution: This program was developed and tested with Peck's improved
50versions of sun-mouse and sun-fns; these are available from
51\.{peck@@sun.com} if not yet part of the GNU distribution.
52
53@ We follow the traditional structure of XView applications. The |exit|
54statement at the end is important, because \.{oemacs} can be invoked by
55the \.{system} command in \TEX/ (when the user has typed \.e in response
56to an error message); without |exit(0)|, \TEX/ would complain of trouble
57executing this program, although we would simply be terminating the program
58without returning any particular value.
59
60@c
61@<Include header files@>@;
62@#
63Frame frame; /* the base frame where we will live */
64@<Global variables@>@; /* additional globals besides |frame| */
65@#
66@<Event-handling procedures@>@;
67@#
68main(argc,argv)
69 int argc;@+char *argv[]; /* typical \UNIX/ setup */
70{
71 @<Special initialization@>;
72 @<Install the components and controls of |frame|@>;
73 xv_main_loop(frame);
74 exit(0);
75}
76
77@ Including the header file \.{<xview/xview.h>} also causes other
78basic header files like \.{<xview/frame.h>}, \.{<xview/icon.h>}, etc.,
79to be loaded. We must call the \CEE/ compiler with the flag
80\.{-I\$(OPENWINHOME)/include} so that the \CEE/ preprocessor will
81find the OpenWindows header files.
82
83Some \UNIX/ systems define string functions in \.{<string.h>}, some in
84\.{<strings.h>}; the Sun documentation calls for \.{<string.h>}. My
85experiments indicate that Sun's compiler and loader work perfectly
86well with string functions even when no header files are given, so the
87programmer doesn't really have to remember the right name. Similarly,
88\.{<stdio.h>} isn't really needed with Sun's \CEE/, unless certain macros
89are used. I'll include \.{<string.h>} and \.{<stdio.h>} anyway, in the
90spirit of being obedient to the stated rules.
91
92@<Include...@>=
93#include <string.h>
94#include <stdio.h>
95#include <xview/xview.h>
96
97@* The icon and frame.
98First we attach an icon that will appear if the user closes the \.{oemacs}
99window later.
100
101There are two reasons for doing this first. One is that we might as well
102begin with an easy task, in order to get warmed up. The other is that
103if we specify the icon {\it after\/} creating the frame, we will unconditionally
104override an icon that the user may have specified with the \.{-WI}
105option on the command line. (This is one of the little things a
106programmer has to turn by trial and error, since the XView documentation
107leaves much unsaid.)
108
109The colors used in the icon will be inherited from the frame, so they will
110be reversed if the user asks for reverse video. I~prefer to have the icon
111always in black on a yellow background, so I'm making the color explicit.
112(I hope this will work on monochrome displays; it works fine on my
113grayscale monitor.)
114
115@<Create a frame with the gnu icon@>=
116{@+Server_image icon_image=(Server_image)xv_create(NULL,SERVER_IMAGE,@|
117 XV_WIDTH,64,XV_HEIGHT,64,SERVER_IMAGE_BITS,icon_bits,NULL);
118 Server_image mask_image=(Server_image)xv_create(NULL,SERVER_IMAGE,@|
119 XV_WIDTH,64,XV_HEIGHT,64,SERVER_IMAGE_BITS,mask_bits,NULL);
120 Cms cms=(Cms)xv_create(NULL,CMS,CMS_SIZE,2,@|
121 CMS_NAMED_COLORS,"yellow","black",NULL,NULL);
122 Icon icon=(Icon)xv_create(NULL,ICON,@|
123 ICON_IMAGE,icon_image,ICON_MASK_IMAGE,mask_image,@|
124 WIN_CMS,cms,NULL);
125 frame=xv_create(NULL,FRAME,FRAME_ICON,icon,NULL);
126}
127
128@ @<Include...@>=
129#include <xview/cms.h>
130
131@ If the user hasn't specified a label with the \.{-Wl} option, we turn off
132the header line at the top of the frame. That gives us a chance to see
133two more lines of the file \.{emacs} is editing. However, we add a
134label of our own; it will show up in the virtual window manager display.
135
136@<Remove the frame header, unless the user has specifically requested it@>=
137if (xv_get(frame,XV_LABEL)==NULL) /* no label specified */
138 xv_set(frame,FRAME_SHOW_HEADER,FALSE,XV_LABEL,"OEMACS",NULL);
139
140@ The following icon and mask are derived from the ``what's gnu'' image on the
141back cover of the GNU Emacs manual. (This accounts for my black-on-yellow
142preference.)
143
144@<Global...@>=
145unsigned short icon_bits[]={@|
146 0x0000, 0x0000, 0x0000, 0x1E00,
147 0x0000, 0x0000, 0x0000, 0x0900,@|
148 0x001E, 0x0000, 0x0000, 0x0880,
149 0x0064, 0x0000, 0x0000, 0x0440,@|
150 0x0088, 0x0000, 0x0000, 0x0420,
151 0x0110, 0x0000, 0x0000, 0x0210,@|
152 0x0220, 0x0000, 0x0000, 0x0210,
153 0x0420, 0x0FCF, 0x01C0, 0x0108,@|
154 0x0840, 0x1030, 0x8620, 0x0088,
155 0x1080, 0x00C0, 0x5810, 0x0084,@|
156 0x1080, 0x1F00, 0x2008, 0x0044,
157 0x2100, 0xE200, 0x1004, 0x0044,@|
158 0x4103, 0x0400, 0x0002, 0x0042,
159 0x4204, 0x080E, 0x0001, 0x0042,@|
160 0x8200, 0x7830, 0x0020, 0x8082,
161 0x8203, 0x9040, 0x0018, 0x4102,@|
162 0x8204, 0x2080, 0x07C6, 0x3E04,
163 0x8108, 0x410C, 0x0021, 0x8004,@|
164 0x8080, 0x8210, 0x03D0, 0x6008,
165 0x4041, 0x0420, 0x0008, 0x1810,@|
166 0x403E, 0x0820, 0x0FFC, 0x0620,
167 0x2000, 0x1040, 0x0002, 0x01C0,@|
168 0x1000, 0x608C, 0x0FFF, 0x0060,
169 0x0801, 0x8110, 0x0080, 0x8118,@|
170 0x0406, 0x0220, 0x1FFF, 0x66E0,
171 0x0238, 0x044F, 0x0000, 0xD800,@|
172 0x01C0, 0x0890, 0x8FFF, 0x4000,
173 0x0300, 0x10A6, 0x4041, 0x6000,@|
174 0x1C00, 0x2026, 0x4FFF, 0x6000,
175 0x60CC, 0x4026, 0x4001, 0x6000,@|
176 0x1F33, 0x8010, 0x8FFF, 0x4000,
177 0x0012, 0x000F, 0x0040, 0xC000,@|
178 0x0022, 0x4000, 0x07FF, 0x4000,
179 0x0024, 0x4000, 0x0000, 0x2000,@|
180 0x0024, 0x4818, 0x8FFF, 0xE000,
181 0x0024, 0x4907, 0x0040, 0x2000,@|
182 0x0044, 0x4900, 0x1FFF, 0xE000,
183 0x0044, 0x4900, 0x0000, 0x2000,@|
184 0x0044, 0x4900, 0x07FF, 0xE000,
185 0x0044, 0x4880, 0x0020, 0x2000,@|
186 0x0044, 0x4880, 0x07FF, 0xE000,
187 0x0044, 0x4840, 0x0000, 0x2000,@|
188 0x0044, 0x2A20, 0x07FF, 0xE000,
189 0x0044, 0x2410, 0x0020, 0x2000,@|
190 0x0042, 0x2448, 0x0FFF, 0xE000,
191 0x0042, 0x2948, 0x0000, 0x2000,@|
192 0x0041, 0x1144, 0x07FF, 0xA000,
193 0x0041, 0x1144, 0x2010, 0x1000,@|
194 0x0021, 0x1126, 0x20FA, 0x1000,
195 0x0024, 0x8925, 0x2600, 0x1000,@|
196 0x0014, 0x8924, 0xA138, 0x7000,
197 0x0016, 0x88A4, 0x9090, 0x6000,@|
198 0x000A, 0x44A4, 0x4880, 0xA000,
199 0x0002, 0x44A2, 0x4401, 0x2000,@|
200 0x0003, 0x4492, 0x2001, 0x4000,
201 0x0001, 0x2451, 0x3002, 0x8000,@|
202 0x0000, 0xA251, 0x1E05, 0x0000,
203 0x0000, 0x2248, 0xA1F9, 0x8000,@|
204 0x0000, 0x1648, 0x9002, 0x8000,
205 0x0000, 0x1A28, 0x4C02, 0x8000,@|
206 0x0000, 0x1220, 0x43FC, 0x8000,
207 0x0000, 0x0120, 0x2000, 0x8000,@|
208 0x0000, 0x0120, 0x2003, 0x0000,
209 0x0000, 0x0150, 0x1FFC, 0x0000
210};
211unsigned short mask_bits[]={@|
212 0x0000, 0x0000, 0x0000, 0x1E00,
213 0x0000, 0x0000, 0x0000, 0x0F00,@|
214 0x001E, 0x0000, 0x0000, 0x0F80,
215 0x007C, 0x0000, 0x0000, 0x07C0,@|
216 0x00F8, 0x0000, 0x0000, 0x07E0,
217 0x01F0, 0x0000, 0x0000, 0x03F0,@|
218 0x03E0, 0x0000, 0x0000, 0x03F0,
219 0x07E0, 0x0FCF, 0x01C0, 0x01F8,@|
220 0x0FC0, 0x103F, 0x87F0, 0x00F8,
221 0x1F80, 0x00FF, 0xDFF0, 0x00FC,@|
222 0x1F80, 0x1FFF, 0xFFF8, 0x007C,
223 0x3F00, 0xE3FF, 0xFFFC, 0x007C,@|
224 0x7F03, 0x07FF, 0xFFFE, 0x007E,
225 0x7E04, 0x0FFF, 0xFFFF, 0x007E,@|
226 0xFE00, 0x7FFF, 0xFFFF, 0x80FE,
227 0xFE03, 0x9FFF, 0xFFFF, 0xC1FE,@|
228 0xFE04, 0x3FFF, 0xFFFF, 0xFFFC,
229 0xFF08, 0x7FFF, 0xFFFF, 0xFFFC,@|
230 0xFF80, 0xFFFF, 0xFFFF, 0xFFF8,
231 0x7FC1, 0xFFFF, 0xFFFF, 0xFFF0,@|
232 0x7FFF, 0xFFFF, 0xFFFF, 0xFFE0,
233 0x3FFF, 0xFFFF, 0xFFFF, 0xFFC0,@|
234 0x1FFF, 0xFFFF, 0xFFFF, 0xFFE0,
235 0x0FFF, 0xFFFF, 0xFFFF, 0xFFF8,@|
236 0x07FF, 0xFFFF, 0xFFFF, 0xFEE0,
237 0x03FF, 0xFFFF, 0xFFFF, 0xF800,@|
238 0x01FF, 0xFFFF, 0xFFFF, 0xE000,
239 0x03FF, 0xFFFF, 0xFFFF, 0xE000,@|
240 0x1FFF, 0xFFFF, 0xFFFF, 0xE000,
241 0x7FFF, 0xFFFF, 0xFFFF, 0xE000,@|
242 0x1F7F, 0xFFFF, 0xFFFF, 0xC000,
243 0x001F, 0xFFFF, 0xFFFF, 0xC000,@|
244 0x003F, 0xFFFF, 0xFFFF, 0xC000,
245 0x003F, 0xFFFF, 0xFFFF, 0xE000,@|
246 0x003F, 0xFFFF, 0xFFFF, 0xE000,
247 0x003F, 0xFFFF, 0xFFFF, 0xE000,@|
248 0x007F, 0xFFFF, 0xFFFF, 0xE000,
249 0x007F, 0xFFFF, 0xFFFF, 0xE000,@|
250 0x007F, 0xFFFF, 0xFFFF, 0xE000,
251 0x007F, 0xFFFF, 0xFFFF, 0xE000,@|
252 0x007F, 0xFFFF, 0xFFFF, 0xE000,
253 0x007F, 0xFFFF, 0xFFFF, 0xE000,@|
254 0x007F, 0xFFFF, 0xFFFF, 0xE000,
255 0x007F, 0xFFFF, 0xFFFF, 0xE000,@|
256 0x007F, 0xFFFF, 0xFFFF, 0xE000,
257 0x007F, 0xFFFF, 0xFFFF, 0xE000,@|
258 0x007F, 0xFFFF, 0xFFFF, 0xE000,
259 0x007F, 0xFFFF, 0xFFFF, 0xF000,@|
260 0x003F, 0xFFFF, 0xFFFF, 0xF000,
261 0x003F, 0xFFFF, 0xFFFF, 0xF000,@|
262 0x001F, 0xFFFF, 0xFFFF, 0xF000,
263 0x001F, 0xFFFF, 0xFFFF, 0xE000,@|
264 0x000B, 0xFFFF, 0xFFFF, 0xE000,
265 0x0003, 0xFFFF, 0xFFFF, 0xE000,@|
266 0x0003, 0xFFFF, 0xFFFF, 0xC000,
267 0x0001, 0xFFFF, 0xFFFF, 0x8000,@|
268 0x0000, 0xBFF1, 0xFFFF, 0x0000,
269 0x0000, 0x3FF8, 0xFFFF, 0x8000,@|
270 0x0000, 0x1FF8, 0xFFFF, 0x8000,
271 0x0000, 0x1FF8, 0x7FFF, 0x8000,@|
272 0x0000, 0x13E0, 0x7FFF, 0x8000,
273 0x0000, 0x01E0, 0x3FFF, 0x8000,@|
274 0x0000, 0x01E0, 0x3FFF, 0x0000,
275 0x0000, 0x0150, 0x1FFC, 0x0000
276};
277
278@* Emulating a terminal.
279We will run \.{emacs} in a ``tty subwindow,'' named after the teletype
280terminals of ancient yore.
281
282The |argv| array will be a command line that invokes
283\.{emacs} with all arguments not removed by |xv_init|, i.e., all arguments
284that remain after generic XView arguments have been removed.
285
286We have to say |WIN_IS_CLIENT_PANE|, otherwise fonts specified on the
287command line will be ignored. (This cryptic instruction is mentioned briefly
288in the XView reference manual, but not in the XView programming manual;
289I~would never have discovered it without Jeff Peck's help.)
290
291We also have to set |TTY_QUIT_ON_CHILD_DEATH| to |TRUE|. Otherwise when
292\.{emacs} exits (via control-X, control-C) there still will be a terminal
293window (into which we can type but not access the shell).
294
295Before starting \.{emacs} we set the environment variable
296\.{TERM} equal to \.{sun}.
297This will tell \.{emacs} to initialize itself with the
298programs in its source file \.{lisp/term/sun.el}, where special
299adaptations for Sun-style terminals have been recorded.
300
301@<Put a tty subwindow into the frame@>=
302argv[0]="emacs";
303putenv("TERM=sun");
304tty=(Tty)xv_create(frame,TTY,WIN_IS_CLIENT_PANE,@|
305 TTY_QUIT_ON_CHILD_DEATH,TRUE,@|
306 TTY_ARGV,argv,NULL);
307
308@ @<Global...@>=
309Tty tty;
310
311@ @<Include...@>=
312#include <xview/tty.h>
313
314@ The XView manual doesn't tell us that tty subwindows have a view part
315and a pseudo-terminal part. (The manual does mention briefly that text
316subwindows have views---at the beginning of section 6.3, and indirectly in
317one of the examples in the chapter on color.)
318
319The view window of an emulated tty will receive keyboard and
320mouse events. We need to know its ``handle,'' because we want to
321modify XView's default interpretation of many of those events.
322
323For example, we want to grab the keyboard focus (i.e., to begin receiving
324keyboard input) as soon as the user moves the mouse into the \.{emacs}
325window. The normal OpenLook default requires a user to click in the window
326first, but that is inefficient in a production book-writing environment.
327Us \.{emacs} users would rather type than point.
328
329A secret incantation makes the view window accessible. Dear reader,
330would you have guessed how to do this, from reading the manuals only,
331without looking at Jeff Peck's code? Be honest now.
332
333We don't have to enable the notification of other kinds of events;
334tty subwindows already do that.
335
336@<Prepare to be notified when the mouse enters the window@>=
337window=(Xv_window)xv_get(tty,OPENWIN_NTH_VIEW,0);
338xv_set(window,WIN_CONSUME_EVENT,LOC_WINENTER,NULL);
339
340@ @<Global...@>=
341Xv_window window; /* the view window of |tty| */
342
343@ If the user has specified reverse video with the \.{-rv} option,
344we will reverse black and white in the mouse cursor. This will make it
345more visible against a black background.
346
347Changing the cursor is another undocumented reason why we need to know
348about the tty's view window; nothing changes if we try to attach
349the new cursor to |frame| or to |tty| instead of to |window|.
350
351@<Change the cursor, to avoid black-on-black@>=
352if (rv) {Xv_singlecolor white,black;
353 Xv_cursor cursor;
354 white.red=white.green=white.blue=255;
355 black.red=black.green=black.blue=0;
356 cursor=(Xv_cursor)xv_create(NULL,CURSOR,@|
357 CURSOR_SRC_CHAR,OLC_BASIC_PTR,CURSOR_MASK_CHAR,OLC_BASIC_MASK_PTR,@|
358 CURSOR_FOREGROUND_COLOR,&white,CURSOR_BACKGROUND_COLOR,&black,NULL);
359 xv_set(window,WIN_CURSOR,cursor,NULL);
360}
361
362@ @<Include...@>=
363#include <xview/cursor.h> /* we're using the cursor package */
364
365@ What is the variable |rv| that was tested in the code above? Good question.
366We have to scan for \.{-rv} before |xv_init| looks at the command arguments.
367
368@<Scan the command line, setting |rv| nonzero if \.{-rv} is present@>=
369rv=0;
370{@+int k=argc;
371 while (--k>0) if (strcmp(argv[k],"-rv")==0 ||
372 strcmp(argv[k],"-reverse")==0) rv=1;
373}
374
375@ @<Global...@>=
376int rv;
377
378@ We need to know the height and width of characters in the font, in order
379to convert mouse positions into coordinates that \.{emacs} will like.
380If the user has specified a font explicitly, the font will presumably have
381a fixed width for all characters; we can learn the relevant dimensions
382by calling |xv_get|. But if the user has not specified a font, the
383situation is trickier; |xv_get| will report the width of the default
384{\it non\/}-fixed-width font, and this will probably differ from the width of
385the actual fixed-width font the tty subwindow will choose.
386
387Curiously, if we call |xv_find(NULL,FONT,FONT_FAMILY,
388FONT_FAMILY_DEFAULT_FIXEDWIDTH,NULL)| {\it before\/} calling |xv_init|,
389without even doing anything with the result returned by |xv_find|,
390|xv_init| will not install any fonts specified on the command line.
391The trick we used for icons---installing the default gnu icon on the first
392call to |xv_create|---will therefore fail.
393
394Thus, we have to work around two distinct bugs in XView. The solution
395is to discover the effects of the user's command line after |xv_init|
396has acted and the frame has been set up; we can determine by brute force what
397font will go into the tty window. The program below works correctly
398even if the command line specifies \.{-scale} \.{large}, say, instead of
399specifying a new font explicitly by something like \.{-font} \.{9x15}.
400
401While we are cataloguing peculiarities of XView, we might as well mention
402that the default character dimensions of the default font (Lucida) are
403reported to be $8\times13$ in the 12-point (medium) size, $8\times15$ in the
40414-point (large) size, and $12\times20$ in the 19-point (extralarge) size.
405The actual character dimensions in the window come, however, from the
406default fixed-width font (Lucida typewriter), and they are $7\times13$,
407$9\times15$, and $11\times23$ in the same three sizes. No logical progression
408is evident in either the variable-width or the fixed-width dimensions,
409although Lucida is a ``scalable font family.''
410
411@<Compute the height and width of characters in the font@>=
412{
413 Xv_font font=(Xv_font)xv_get(frame,XV_FONT);
414 Xv_font dfont=(Xv_font)xv_find(NULL,FONT,FONT_FAMILY,
415 FONT_FAMILY_DEFAULT,NULL);
416 if (strcmp((char*)xv_get(font,FONT_NAME),
417 (char*)xv_get(dfont,FONT_NAME))==0) {
418 /* the user didn't specify a new font by name */
419 dfont=(Xv_font)xv_find(NULL,FONT,FONT_FAMILY,
420 FONT_FAMILY_DEFAULT_FIXEDWIDTH,NULL);
421 /* this one will be used by the tty window */
422 } else dfont=font;
423 char_width=(int)xv_get(dfont,FONT_DEFAULT_CHAR_WIDTH);
424 char_height=(int)xv_get(dfont,FONT_DEFAULT_CHAR_HEIGHT);
425}
426
427@ @<Global...@>=
428int char_width, char_height; /* character dimensions in the font */
429
430@ @<Include...@>=
431#include <xview/font.h> /* header for the font package */
432
433@ OK, we've figured out how to install a tty subwindow with the right
434event mask and the right cursor, and how to calculate the sizes of the
435characters it will contain. All that remains is for us to do these
436operations in the proper order, and to specify a filter routine that
437will monitor and edit all communications between the keyboard and the
438Emacs processor in the window.
439
440The new ingredient is the filter specification. We tell the XView
441notifier to call |filter| when a window event occurs, instead of
442letting it call the tty subroutine event handler directly. The parameter
443|NOTIFY_SAFE| implies that the window's event handler is
444part of XView, not an alien routine.
445
446@<Install the components...@>=
447@<Scan the command line, setting |rv| nonzero if \.{-rv} is present@>;
448xv_init(XV_INIT_ARGC_PTR_ARGV,&argc,argv,NULL);
449 /* start XViewing; strip and remember the OpenWin arguments */
450@<Create a frame with the gnu icon@>;
451@<Remove the frame header...@>;
452@<Put a tty subwindow into the frame@>;
453@<Prepare to be notified when the mouse enters the window@>;
454@<Change the cursor, to avoid black-on-black@>;
455@<Compute the height and width of characters in the font@>;
456notify_interpose_event_func(window,filter,NOTIFY_SAFE);
457
458@* Keyboard events.
459The job of an interposed filter function is to look at an event and
460either process it ourselves or pass it through (possibly modified)
461to its normal recipient. In the first case we return the code
462value |NOTIFY_DONE|, since we aren't reporting any errors;
463in the second case we call the normal event handler and return the value
464it returns to us.
465
466An XView event is a data structure that has been partially
467interpreted by the XView routines, which add semantic sugar to
468the complex union type of X~Window events. We need not look
469too far inside an event structure to do the things that concern us.
470
471And what is our job? We are looking for three different kinds of events:
472
473\smallskip
474\itemitem{(1)} When the mouse enters the window,
475we want to grab the keyboard focus.
476
477\itemitem{(2)} When a mouse button goes up or down, and we have the keyboard
478focus, we want to send a coded sequence of characters to \.{emacs}.
479
480\itemitem{(3)} When a key goes down, and we have the keyboard focus, we
481want to send an appropriate sequence of characters to \.{emacs}.
482
483\itemitem{(4)} When the status of the Num Lock indicator light changes, we
484will send emacs the command {\tt turn-numlock-on} or {\tt turn-numlock-off},
485for reasons described below.
486
487\smallskip\noindent Other events, like instructions to repaint or
488resize the window, will be passed through without change to the tty window.
489
490@<Event-handling...@>=
491Notify_value filter(window,event,arg,type)
492 Xv_window window; /* the ``client'' on whom we interposed */
493 Event *event; /* the data we are filtering */
494 Notify_arg arg; /* optional communication parameter between clients */
495 Notify_event_type type; /* |NOTIFY_SAFE| or |NOTIFY_IMMEDIATE| */
496{@+register int id=event_id(event);
497#ifdef DEBUG
498 printf("event %d%s, action %d, shift %x, mouse(%d,%d)\n",
499 event_id(event),event_is_up(event)?"UP":"DOWN",event->action,
500 event_shiftmask(event),event_x(event),event_y(event));
501#endif
502 @<Update the Num Lock status@>;
503 if (id==LOC_WINENTER) @<Grab the keyboard focus and return@>;
504 if (event_is_button(event)) @<Translate a mouse event and return@>;
505 if (event_is_up(event)) return NOTIFY_DONE; /* key has been released */
506 @<Translate a function key into a special escape sequence@>;
507 @<Sanitize a keypress event so that unusual semantic actions are removed@>;
508 return notify_next_event_func(window,event,arg,type); /* pass it through */
509}
510
511@ It's easy to take charge of the keyboard and mouse, as soon as the mouse
512enters our territory.
513
514@<Grab...@>=
515{
516 win_set_kbd_focus(window,xv_get(window,XV_XID));
517 return NOTIFY_DONE;
518}
519
520@ If the event is not related to mouse buttons or special function keys,
521we want to pass it on unchanged, unless its |event_id| is less than 128.
522In that case, it represents a character code, and we want to nuke any
523semantic ``keyboard acceleration'' actions it might have been assigned
524by OpenWindows.
525
526We also make the Meta key add 128 here. An undocumented macro
527called |event_set_id|, found in \.{<xview/win\_input.h>},
528clears the |action| code as desired.
529
530@<Sanitize...@>=
531if (id<128)
532 if (event_meta_is_down(event)) event_set_id(event,id+128);
533 else event_set_action(event,ACTION_NULL_EVENT);
534
535@* Function keys.
536The Sun Type 4 keyboard has lots of keys, and these can be bound to lots
537of useful functions when we are \.{emacs}ing to the max. Besides the
538letters and punctuation marks of a normal typewriter, there are ten
539``left'' function keys, L1--L10; twelve ``top'' function keys, F1--F12;
540fifteen ``right'' function keys, R1--R15; and eight additional keys
541labeled Help, Alt, AltGraph, Ins, Del, Enter, $+$, $-$, which we will
542pretend have been labeled B1--B8.
543
544The L5 key, also known as Front, is controlled by the Open Look
545window manager; it makes a window rise above any that might overlap it,
546or shoves the window underneath in case it already was on top.
547
548The L7 key, aka Open, is likewise preempted by the
549window manager. It closes a frame to an icon, or opens an icon.
550
551The window manager traps the R2 key and calls it the ``language'' key;
552but I have no use for that feature. So I have remapped R2 to the comparatively
553useless character $3\over4$, and I will translate it back to R2 below. (The
554\.{xmodmap} program allows users to reassign the interpretation of key codes.)
555I could have recovered the L5 and L7 keys in the same way, but I like
556their functions as they stand. (L5 and L7 still come through if a
557Shift, Control, and/or Meta key is down.)
558
559I can never remember the difference between Delete and BackSpace, so I
560have mapped them both into control-?, ASCII code 127.
561
562There are two Shift keys, one at the left and one at the right, which
563are best kept indistinguishable from each other. Similarly, the left
564and right Meta keys (`\.{\char27}') are essentially identical. There's a
565Control key too. These three types of modifier keys generate keypress
566events, but we ignore them; the only thing that matters to us is whether
567they are currently up or down, when other keys are pressed.
568
569\font\ttit=cmitt10
570There also are three special keys that do not generate events, so we
571never see them. The CapsLock key toggles the Caps Lock light and
572changes lowercase letters to uppercase when the light is on. The
573NumLock key toggles the Num Lock light and changes the interpretation
574of R4--R15 and B4--B8 when that light is on. The Compose key turns the
575Compose light on until you type two characters, then it produces a
576special symbol if those two characters match a pattern. For example,
577when Compose is followed by either \.{a"} or \.{"a} you get the 8-bit
578ISO code for {\tt \"a}; when Compose is followed by either \.{th} or
579\.{ht} you get the Icelandic thorn; when it's followed by \.{??} you get {\tt
580?`}; \.{c/} and \.{L-} give \rlap{\./}\.c and {\ttit\char`\$}
581and so on. (A list of all composition patterns
582appears in \.{<X11/Suncompose.h>}, but not in any of the manuals
583I've seen.) The light goes off after two characters have been
584typed, or if your first character is not composable, or if
585you hit Compose again prematurely. If no proper two-character pattern
586was specified, only ``up'' events (key releases) are transmitted, and
587nothing will pass through to \.{emacs}.
588
589One other feature is worth noting: The key between F12 and Delete
590produces a backslash `\.\\', or a vertical line `\.{\char125}' when
591shifted. Everybody knows that, but even more is true. If you hold the
592AltGraph key down and press this key, it turns out that you get the
593broken-bar character `{\tt\hbox to1em{\hss\vbox{\hrule width 1pt height
5943pt\vskip1.5pt\hrule height2pt depth1pt}\hss}}'. This is the only key that the
595engineers chose to endow with three different graphic symbols.
596
597A few other anomalies occur; for example, AltGraph-R1 gives ASCII null,
598while AltGraph does not affect R4. But I didn't discover any additional
599combinations that are either useful or harmful.
600
601Once upon a time the Caps Lock key might have affected the |event_shiftmask|
602field of an event, but it has no effect now. The shiftmask is always an
603even number, contrary to the implications of \.{<xview/win\_input.h>}.
604
605@ The function keys will be translated into a four-character code.
606First comes control-X; then an asterisk; then a letter, \.{a}--\.{o}
607for function numbers 1--15, respectively; and then another letter,
608identifying left, right, top, or bottom. The final letter is
609ordinarily `\.l', `\.r', `\.t', or `\.b', respectively. But it is `\.L', `\.R',
610`\.T', or `\.B' if a Shift key is down. Furthermore the Control key
611subtracts 64 from the ASCII code, so you get `\.,', `\.2', `\.4', or
612`\."' with Control and no Shift. With both Control and Shift you get
613\.{\\C-L}, \.{\\C-R}, \.{\\C-T}, \.{\\C-B}. A Meta key adds another 128
614to the code. Thus, each function key leads to eight possibilities.
615
616For example, if F4 is pressed when Control and Shift are down, but not
617Meta, the four-letter code is \.{\\C-X*d\\C-T}. The user could type
618that sequence of four characters and get the same effect.
619
620Shifted function keys sometimes have a nice mnemonic significance.
621For example, key R14, also labeled PgDn, is usually bound to the Emacs
622operation `\.{scroll-up}', which moves the window down [sic] by one
623screenful; we can then bind Shift-R14 to \.{forward-page}, which advances
624down to the next page boundary. In \.{cweb-mode}, the next page boundary
625is the next \.{@@*}, beginning a major part of the program. Similarly,
626it's convenient to bind B7, the keypad `\.+' key, to \.{forward-paragraph}.
627Then in \.{cweb-mode}, Shift-B7 goes to the next module (the next
628\.{@@\ } or \.{@@*}).
629
630A Composed character will be preceded by \.{\\C-Q}, the Emacs `quote'
631character, to distinguish it from a character that was generated with the
632Meta key down. This also applies to the broken-bar character, which
633will incidentally be preceded by AltGraph, which is B3; you'll probably
634want to bind B3 to a no-op if broken bars are important to you.
635
636@ This program assumes that several key codes have been rebound from
637their normal values. Namely, the commands
638$$\vbox{\halign{\.{#}\hfil\cr
639keysym R2 = threequarters\cr
640keysym KP\_Subtract = onehalf\cr
641keysym KP\_Add = onequarter\cr
642keysym KP\_Enter = threesuperior\cr
643keysym KP\_Decimal = twosuperior\cr
644keysym KP\_0 = onesuperior\cr}}$$
645should be executed by \.{xmodmap}, preferably in the user's \.{.xinitrc} file.
646This makes the keys act as $3\over4$, $1\over2$, $1\over4$, $^3$, $^2$, and
647$^1$, respectively. The corresponding 8-bit codes are respectively
648190, 189, 188, 179, 178, 185. (By the way, can anybody explain why the ISO
649LATIN-1 code has $^0$, $^2$, and $^3$ in the positions of meta-0, meta-2,
650and meta-3, while $^1$ is in the position of meta-9?)
651@.xmodmap@>
652
653We haven't actually bound the keys this way to use them in editing.
654We did it to provide linguistically unimportant codes that OpenWindows
655wouldn't mess up; its normal conventions make those valuable keys
656unusable for editing, except as duplicates for other existing keys.
657
658We send \.{turn-numlock-on/off} commands so that \.{emacs} can keep in
659synch with the keyboard state. Namely, it will rebind the function
660keys B4--B8 to their numeric-keypad equivalents while the Num Lock light is on.
661
662On the other hand, our remapping does make the Num Lock
663feature useless in other (non-Emacs) applications. If you don't
664rebind the keys as stated, you lose the functionality of R2 and B4--B8,
665but \.{oemacs} will still work.
666
667The Help key is another special case. We don't want to remap it,
668because it gives useful help information with other OpenWindows
669applications. If Help is pressed without the shift or control key,
670the |event_id| is zero and the |event_action| is |ACTION_HELP|.
671Control-Help is similar, but with |ACTION_TEXT_HELP|. Shift-Help is
672more complicated; it invokes `helpopen: starting new Viewer', after
673generating an event that has |event_action=WIN_VISIBILITY_NOTIFY|. The
674program below considers the Help key B1 to be characterized by any
675event with |event_id=0| and either |event_action!=0| or
676|event_shiftmask!=CTRLMASK|.
677
678@<Translate a function key into a special escape sequence@>=
679{@+register int bank='b'; /* |'l'|, |'r'|, |'t'|, or |'b'| */
680 register int n; /* function key serial number, |1<=n<=15| */
681 if (id>=KEY_LEFT(1)) @<Translate an ordinary function key@>@;
682 else if (id>=256) @<Look for Alt or AltGraph@>@;
683 else if (id>=128)
684 @<Translate a special function key or composed character@>@;
685 else if (id>0 ||
686 (event_action(event)==0 && event_shiftmask(event)==CTRLMASK))
687 goto non_function;
688 else n=1; /* Help key */
689emit_function_key:@<Emit the code for a function key and |return|@>;
690non_function:;
691}
692
693@ I'm assuming here that the event id codes occur in the order left, right,
694top, bottom, and that no higher event codes exist.
695
696@<Translate an ordinary function key@>=
697{
698 if (id<KEY_RIGHT(1)) { /* on the left bank */
699 bank='l';@+n=id-KEY_LEFT(0);
700 } else if (id<KEY_TOP(1)) { /* on the right bank */
701 bank='r';@+n=id-KEY_RIGHT(0);
702 } else if (id<KEY_BOTTOM(1)) {
703 bank='t';@+n=id-KEY_TOP(0);
704 } else n=id-KEY_BOTTOM(0);
705 goto emit_function_key;
706}
707
708@ The event codes examined here appear in \.{<xview/win\_event.h>}
709but not in the XView reference manual.
710
711@<Look for Alt or AltGraph@>=
712if (id==SHIFT_ALT) {
713 n=2;@+goto emit_function_key;
714} else if (id==SHIFT_ALTG) {
715 n=3;@+goto emit_function_key;
716} else goto non_function;
717
718@ The |ttysw_input| routine sends text to a tty's view window.
719The second parameter is a string, not necessarily terminated by
720|'\0'| or anything else; the third parameter is the string length.
721
722@<Emit the code for a function key and |return|@>=
723{
724 if (event_shift_is_down(event)) bank-=32;
725 if (event_ctrl_is_down(event)) bank-=64;
726 if (event_meta_is_down(event)) bank+=128;
727 buf[2]=n+'a'-1;
728 buf[3]=bank;
729 ttysw_input(window,buf,4);
730 return NOTIFY_DONE;
731}
732
733@ @<Global...@>=
734char buf[]="\030*??\021"; /* |030| and |021| give control-X, control-Q */
735
736@ @<Translate a special function key or composed character@>=
737switch (id) {
738case 190: bank='r';@+n=2;@+goto emit_function_key;
739case 189: n=8;@+goto emit_function_key;
740case 188: n=7;@+goto emit_function_key;
741case 179: n=6;@+goto emit_function_key;
742case 178: n=5;@+goto emit_function_key;
743case 185: n=4;@+goto emit_function_key;
744default: buf[5]=id; /* composed character or broken-bar */
745 ttysw_input(window,buf+4,2);
746 return NOTIFY_DONE;
747}
748
749@* The NumLock key.
750The global variable |num_lock_state| will be 0 if the Num Lock indicator
751light is off, 1 if it is on. Whenever an event occurs, we check to see
752if |num_lock_state| should change; if so, we change it and send an
753appropriate command to \.{emacs}.
754
755To read the state of the keyboard LED indicator lights, we need an I/O
756control command called the |KIOCGLED| ioctl, described on the
757man page for \.{kb(4m)}.
758
759@<Global...@>=
760int num_lock_state;
761char turnon[]="\370turn-numlock-on\r", turnoff[]="\370turn-numlock-off\r";
762int keyboard; /* file descriptor of \.{/dev/kbd} */
763
764@ @<Include...@>=
765#include <sys/file.h> /* definition of |O_RDWR| for |open| */
766#include <sundev/kbio.h> /* definition of |KIOCGLED| for |ioctl| */
767
768@ @d LED_NUM_LOCK 0x1 /* the official definition is in \.{<server/sunevq.h>},
769 but that header file includes huge gobs of other stuff */
770
771@<Update the Num Lock status@>=
772{@+char leds; /* binary encoding of LED lights */
773 ioctl(keyboard,KIOCGLED,&leds);
774 if ((leds&LED_NUM_LOCK)!=num_lock_state) {
775 num_lock_state=leds&LED_NUM_LOCK;
776 if (num_lock_state) ttysw_input(window,turnon,17);
777 else ttysw_input(window,turnoff,18);
778 }
779}
780
781@ Any ordinary user can apparently open the keyboard as a file. I would
782have tried read-only access if read-write had failed; but read-write access
783gives a sense of power even though I won't be writing anything.
784
785@<Special initialization@>=
786keyboard=open("/dev/kbd",O_RDWR);
787if (keyboard<0) {
788 fprintf(stderr,"%s: Can't open /dev/kbd!\n",argv[0]);
789 exit(1);
790}
791
792@* Mouse events.
793When a mouse button is pressed or released, we send \.{emacs} the
794codes control-X and ASCII null, followed by a parenthesized list
795of four numbers and carriage-return.
796For example, as I was typing this paragraph, I
797clicked the left mouse button on the screen just for fun; \.{emacs}
798received the characters
799$$\.{\\030\\0(1 18 28 9999)\\r\\030\\0(129 18 28 141)\\r}$$
800as a result (according to `\.{view-lossage}'). I would have received
801the same response if I had typed these characters myself, instead
802of clicking the mouse.
803
804The first of the four numbers identifies the mouse button itself
805as the code number 1, 2, or 4 (for left, middle, right), plus 8 if
806a Shift key is down, plus 16 if the Control key is down, plus 32
807if a Meta key is down, plus 128 if the mouse key is being released
808instead of pressed.
809
810The second number is the row number in the frame, the top row being
811considered row~0.
812
813The third number is the column number in the frame, the left column being
814considered column~0.
815
816The fourth number is the elapsed time between this mouse event and the
817previous one, in milliseconds. If the elapsed time was 10 seconds or
818more, 9999 is substituted.
819
820Macros inside \.{emacs} can use the second and third numbers to
821position the cursor. The fourth number can be used to determine if the
822user is ``double clicking'' or using ``chords.'' Examples of such
823macros appear in the Emacs source file \.{lisp/sun-mouse.el}.
824
825Incidentally, the ASCII null character in mouse sequence makes us happy that
826the string parameter to |ttysw_input| is not null-terminated.
827
828@<Translate a mouse event...@>=
829{@+register int button_code,elapsed_time;
830 button_code=(id==MS_LEFT? 1: id==MS_MIDDLE? 2: 4);
831 if (event_shift_is_down(event)) button_code += 8;
832 if (event_ctrl_is_down(event)) button_code += 16;
833 if (event_meta_is_down(event)) button_code += 32;
834 if (event_is_up(event)) button_code += 128;
835 @<Compute the time elapsed since the previous mouse event@>;
836 sprintf(mouse_buf+2,"(%d %d %d %d)\r",button_code,@|
837 event_x(event)/char_width, event_y(event)/char_height,@|
838 elapsed_time);
839 ttysw_input(window,mouse_buf,12+strlen(mouse_buf+12)); /* length is at least 12 */
840 return NOTIFY_DONE;
841}
842
843@ @<Global...@>=
844char mouse_buf[24]="\030";
845
846@ XView's event structure includes |event_time(event)|, which has
847type |struct timeval|; this data type is declared in \.{<sys/time.h>},
848which is one of the files included automatically as a result of
849including \.{<xview/xview.h>}.
850A |timeval| structure consists of two |long| integers, |tv_sec| and |tv_usec|,
851denoting clock time in seconds and microseconds, respectively.
852
853@<Compute the time...@>=
854{@+struct timeval now; /* current time */
855 long delta_sec, delta_usec; /* difference between current and
856 previous time */
857 now=event_time(event);
858 delta_sec=now.tv_sec-prev_mouse_time.tv_sec;
859 delta_usec=now.tv_usec-prev_mouse_time.tv_usec;
860 if (delta_usec<0) delta_usec+=1000000,delta_sec--;
861 if (delta_sec>=10) elapsed_time=9999; /* infinity (or close enough) */
862 else elapsed_time=(delta_sec*1000)+(delta_usec/1000);
863 prev_mouse_time=now;
864}
865
866@ @<Global...@>=
867struct timeval prev_mouse_time;
868
869@* Remaining problems. There's a terribly unfortunate bug in the
870present implementation of XView, causing characters of tty subwindows
871to be badly painted at crucial times; the rightmost column of pixels
872in a character is often clobbered. If I could figure out how to
873generate repaint events for the tty subwindow, I might build a mechanism
874into \.{oemacs} that does this after the keyboard has been idle for 10
875seconds, say. This would blink the screen; maybe I'll get used to that,
876or maybe I'll prefer to refresh the window manually by binding
877\.{redraw-display} to the L2 and R1 keys. In any case a lot of screen
878refreshing is necessary at the moment, alas.
879
880(Note added later: I doubt if I'll get used to blinking, and the present
881method of manual refresh is tolerable so I won't pursue the 10-second
882timer idea. I have meanwhile noticed a procedure |wmgr_refreshwindow(window)|
883mentioned in \.{<xview/wmgr.h>}; it will presumably refresh any
884given window.
885
886Another bug, much less serious, occurs when the window is resized.
887If the window gets smaller, \.{emacs} isn't told to correct its
888assumptions; so it puts information in strange places or offscreen.
889(Internally, emacs uses the \.{TIOCGWINSZ} or \.{TIOCSWINSZ} ioctl,
890described in the man page for \.{termio}.)
891You can work around this by first making the window very small, then
892making it large.
893
894@* Index.
895
896
examples/treeprint.w+247−0
@@ -0,0 +1,247 @@
1\def\covernote{Copyright 1987 Norman Ramsey -- Princeton University}
2
3\def\vbar{\.{|}}
4@*Directory Trees.
5Our object is to print out a directory hierarchy in some pleasant way.
6The program takes output from {\tt find * -type d -print \vbar\ sort}
7@^system dependencies@>
8and produces a nicer-looking listing.
9More precisely, our input, which is the output of {\tt find} followed
10by {\tt sort}, is a list of fully qualified directory names (parent
11and child separated by slashes |'/'|); everything has already been
12sorted nicely into lexicographic order.
13
14The {\tt treeprint} routine takes one option, |"-p"|, which tells it
15to use the printer's line-drawing set, rather than the terminal's.
16
17@c
18@<Global definitions@>@;
19@<Global include files@>@;
20@<Global declarations@>@;
21
22@#
23main(argc, argv)
24 int argc;
25 char **argv;
26{
27@<|main| variable declarations@>;
28@<Search for options and set special characters on |"-p"|@>;
29@<Read output from find and enter into tree@>;
30@<Write tree on standard output@>@;
31exit(0);
32}
33
34@
35We make all the siblings of a directory a linked list off of its left child,
36and the offspring a linked list off the right side.
37Data are just directory names.
38@d sibling left
39@d child right
40
41@<Global decl...@>=
42typedef struct tnode {
43 struct tnode *left, *right;
44 char *data;
45} TNODE;
46@ @<|main| variable...@>=
47struct tnode *root;
48
49
50
51@*Input.
52Reading the tree is simple---we read one line at a time, and call on the
53recursive |add_tree| procedure.
54
55@c
56read_tree (fp, rootptr)
57 FILE *fp;
58 struct tnode **rootptr;
59{
60 char buf[255], *p;
61
62 while ((fgets(buf, 255, fp))!=NULL) {
63 @<If |buf| contains a newline, make it end there@>;
64 add_tree(rootptr, buf);
65 }
66 }
67@ @<Global include...@>=#include <stdio.h>
68
69@ Depending what system you're on, you may or may not get a newline in |buf|.
70@<If |buf| contains a newline...@>=
71 p=buf; while (*p!='\0'&&*p!='\n') p++;
72@^system dependencies@>
73 *p='\0';
74
75@
76To add a string, we split off the first part of the name and insert it into
77the sibling list. We then do the rest of the string as a child of the new node.
78
79@c
80add_tree(rootptr, p)
81 struct tnode **rootptr;
82 char *p;
83{
84 char *s;
85 int slashed;
86
87 if (*p=='\0') return;
88
89@<Break up the string so |p| is the first word,
90 |s| points at null-begun remainder,
91 and |slashed| tells whether |*s=='/'| on entry@>;
92
93 if (*rootptr==NULL) {
94@<Allocate new node to hold string of size |strlen(p)|@>;
95 strcpy((*rootptr)->data,p);
96 }
97 if (strcmp((*rootptr)->data,p)==0) {
98 if (slashed) ++s;
99 add_tree(&((*rootptr)->child),s);
100 }
101 else {
102 if (slashed) *s='/';
103 add_tree(&((*rootptr)->sibling),p);
104 }
105 }
106
107@ We perform some nonsense to cut off the string |p| so that |p| just
108holds the first word of a multiword name. Variable |s| points at what
109was either the end of |p| or a slash delimiting names. In either case
110|*s| is made |'\0'|. Later, depending on whether we want to pass the
111whole string or the last piece, we will restore the slash or advance
112|s| one character to the right.
113
114@<Break up...@>=
115 for (s=p;*s!='\0'&&*s!='/';) s++;
116 if (*s=='/') {
117 slashed=1;
118 *s='\0';
119 } else slashed=0;
120
121@ Node allocation is perfectly standard \dots
122@<Allocate new node...@>=
123 *rootptr=(struct tnode *) malloc (sizeof(struct tnode));
124 (*rootptr)->left = (*rootptr)->right = NULL;
125 (*rootptr)->data = malloc (strlen(p)+1);
126
127@
128@<Global decl...@>= char *malloc();
129
130@ In this simple implementation, we just read from standard input.
131@<Read...@>= read_tree(stdin,&root);
132
133@*Output.
134We begin by defining some lines, tees, and corners.
135The |s| stands for screen and the |p| for printer.
136You will have to change this for your line-drawing set.
137@^system dependencies@>
138
139@<Global definitions@>=
140#define svert '|'
141#define shoriz '-'
142#define scross '+'
143#define scorner '\\' /* lower left corner */
144
145#define pvert '|'
146#define phoriz '-'
147#define pcross '+'
148#define pcorner '\\' /* lower left corner */
149
150@ The default is to use the terminal's line drawing set.
151@<Global declarations@>=
152char vert=svert;
153char horiz=shoriz;
154char cross=scross;
155char corner=scorner;
156
157@ With option |"-p"| use the printer character set.
158@<Search for options...@>=
159while (--argc>0) {
160 if (**++argv=='-') {
161 switch (*++(*argv)) {
162 case 'p':
163 vert=pvert;
164 horiz=phoriz;
165 cross=pcross;
166 corner=pcorner;
167 break;
168 default:
169 fprintf(stderr,"treeprint: bad option -%c\n",**argv);
170 break;
171 }
172 }
173}
174
175@ We play games with a character stack to figure out when to put in vertical
176bars.
177A vertical bar connects every sibling with its successor, but the last sibling
178in a list is followed by blanks, not by vertical bars. The state of
179bar-ness or space-ness for each preceding sibling is recorded in the
180|indent_string| variable, one character (bar or blank) per sibling.
181
182@<Global decl...@>=
183char indent_string[100]="";
184
185@ Children get printed
186before siblings.
187We don't bother trying to bring children up to the same line as their parents,
188because the \UNIX/ filenames are so long.
189
190We define a predicate telling us when a sibling is the last in a series.
191@d is_last(S) (S->sibling==NULL)
192
193@c
194print_node(fp, indent_string, node)
195 FILE *fp;
196 char *indent_string;
197 struct tnode *node;
198{
199 char string[255];
200 int i;
201 char *p, *is;
202
203 if (node==NULL) {
204 }
205 else {
206 *string='\0';
207 for (i=strlen(indent_string); i>0; i--)
208 strcat(string,@, " | ");
209 strcat(string,@t\ \ @> " +--");
210@<Replace chars in |string| with chars from
211 line-drawing set and from |indent_string|@>;
212 fprintf(fp,"%s%s\n",string,node->data);
213
214@#
215 /* Add vertical bar or space for this sibling (claim |*is=='\0'|) */
216 *is++ = (is_last(node) ? ' ' : vert);
217 *is=='\0';
218
219 print_node(fp, indent_string, node->child); /* extended |indent_string| */
220 *--is='\0';
221 print_node(fp, indent_string, node->sibling); /* original |indent_string| */
222 }
223
224}
225@ For simplicity, we originally wrote connecting lines with |'|'|, |'+'|, and
226|'-'|.
227Now we replace those characters with appropriate characters from the
228line-drawing set.
229We take the early vertical bars and replace them with characters from
230|indent_string|, and we replace the other characters appropriately.
231We are sure to put a |corner|, not a |cross|, on the last sibling in
232a group.
233@<Replace chars...@>=
234 is=indent_string;
235 for (p=string; *p!='\0'; p++) switch(*p) {
236 case '|': *p=*is++; break;
237 case '+': *p=(is_last(node) ? corner : cross); break;
238 case '-': *p=horiz; break;
239 default: break;
240 }
241
242
243@ For this simple implementation, we just write on standard output.
244
245@<Write...@>= print_node(stdout, indent_string, root);
246
247@*Index.
examples/wc.w+239−0
@@ -0,0 +1,239 @@
1% wc: An example of CWEB by Silvio Levy and Donald E. Knuth
2
3\nocon % omit table of contents
4\datethis % print date on listing
5\def\SPARC{SPARC\-\kern.1em station}
6
7@* An example of {\tt CWEB}. This example, based on a program by
8Klaus Guntermann and Joachim Schrod [{\sl TUGboat\/ \bf7} (1986),
9135--137] presents the ``word count'' program from \UNIX/, rewritten in
10\.{CWEB} to demonstrate literate programming in \CEE/. The level of
11detail in this document is intentionally high, for didactic purposes;
12many of the things spelled out here don't need to be explained in
13other programs.
14
15The purpose of \.{wc} is to count lines, words, and/or characters in a
16list of files. The number of lines in a file is the number of newline
17characters it contains. The number of characters is the file length in bytes.
18A ``word'' is a maximal sequence of consecutive characters other than
19newline, space, or tab, containing at least one visible ASCII code.
20(We assume that the standard ASCII code is in use.)
21
22@ Most \.{CWEB} programs share a common structure. It's probably a
23good idea to state the overall structure explicitly at the outset,
24even though the various parts could all be introduced in unnamed
25sections of the code if we wanted to add them piecemeal.
26
27Here, then, is an overview of the file \.{wc.c} that is defined
28by this \.{CWEB} program \.{wc.w}:
29
30@c
31@<Header files to include@>@/
32@<Global variables@>@/
33@<Functions@>@/
34@<The main program@>
35
36@ We must include the standard I/O definitions, since we want to send
37formatted output to |stdout| and |stderr|.
38
39@<Header files...@>=
40#include <stdio.h>
41
42@ The |status| variable will tell the operating system if the run was
43successful or not, and |prog_name| is used in case there's an error message to
44be printed.
45
46@d OK 0 /* |status| code for successful run */
47@d usage_error 1 /* |status| code for improper syntax */
48@d cannot_open_file 2 /* |status| code for file access error */
49
50@<Global variables@>=
51int status=OK; /* exit status of command, initially |OK| */
52char *prog_name; /* who we are */
53
54@ Now we come to the general layout of the |main| function.
55
56@<The main...@>=
57main (argc,argv)
58 int argc; /* the number of arguments on the \UNIX/ command line */
59 char **argv; /* the arguments themselves, an array of strings */
60{
61 @<Variables local to |main|@>@;
62 prog_name=argv[0];
63 @<Set up option selection@>;
64 @<Process all the files@>;
65 @<Print the grand totals if there were multiple files @>;
66 exit(status);
67}
68
69@ If the first argument begins with a `\.{-}', the user is choosing
70the desired counts and specifying the order in which they should be
71displayed. Each selection is given by the initial character
72(lines, words, or characters). For example, `\.{-cl}' would cause
73just the number of characters and the number of lines to be printed,
74in that order.
75
76We do not process this string now; we simply remember where it is.
77 It will be used to control the formatting at output time.
78
79@<Var...@>=
80int file_count; /* how many files there are */
81char *which; /* which counts to print */
82
83@ @<Set up o...@>=
84which="lwc"; /* if no option is given, print all three values */
85if (argc>1 && *argv[1] == '-') { which=argv[1]+1; argc--; argv++; }
86file_count=argc-1;
87
88@ Now we scan the remaining arguments and try to open a file, if
89possible. The file is processed and its statistics are given.
90We use a |do|~\dots~|while| loop because we should read from the
91standard input if no file name is given.
92
93@<Process...@>=
94argc--;
95do@+{
96 @<If a file is given, try to open |*(++argv)|; |continue| if unsuccessful@>;
97 @<Initialize pointers and counters@>;
98 @<Scan file@>;
99 @<Write statistics for file@>;
100 @<Close file@>;
101 @<Update grand totals@>; /* even if there is only one file */
102}@+while (--argc>0);
103
104@ Here's the code to open the file. A special trick allows us to
105handle input from |stdin| when no name is given.
106Recall that the file descriptor to |stdin| is~0; that's what we
107use as the default initial value.
108
109@<Variabl...@>=
110int fd=0; /* file descriptor, initialized to |stdin| */
111
112@ @d READ_ONLY 0 /* read access code for system |open| routine */
113
114@<If a file...@>=
115if (file_count>0 && (fd=open(*(++argv),READ_ONLY))<0) {
116 fprintf (stderr, "%s: cannot open file %s\n", prog_name, *argv);
117@.cannot open file@>
118 status|=cannot_open_file;
119 file_count--;
120 continue;
121}
122
123@ @<Close file@>=
124close(fd);
125
126@ We will do some homemade buffering in order to speed things up: Characters
127will be read into the |buffer| array before we process them.
128To do this we set up appropriate pointers and counters.
129
130@d buf_size BUFSIZ /* \.{stdio.h}'s |BUFSIZ| is chosen for efficiency*/
131
132@<Var...@>=
133char buffer[buf_size]; /* we read the input into this array */
134register char *ptr; /* the first unprocessed character in |buffer| */
135register char *buf_end; /* the first unused position in |buffer| */
136register int c; /* current character, or number of characters just read */
137int in_word; /* are we within a word? */
138long word_count, line_count, char_count; /* number of words, lines,
139 and characters found in the file so far */
140
141@ @<Init...@>=
142ptr=buf_end=buffer; line_count=word_count=char_count=0; in_word=0;
143
144@ The grand totals must be initialized to zero at the beginning of the
145program. If we made these variables local to |main|, we would have to
146do this initialization explicitly; however, \CEE/'s globals are automatically
147zeroed. (Or rather, ``statically zeroed.'') (Get it?)
148@^Joke@>
149
150@<Global var...@>=
151long tot_word_count, tot_line_count, tot_char_count;
152 /* total number of words, lines, and chars */
153
154@ The present section, which does the counting that is \.{wc}'s {\it raison
155d'\^etre}, was actually one of the simplest to write. We look at each
156character and change state if it begins or ends a word.
157
158@<Scan...@>=
159while (1) {
160 @<Fill |buffer| if it is empty; |break| at end of file@>;
161 c=*ptr++;
162 if (c>' ' && c<0177) { /* visible ASCII codes */
163 if (!in_word) {word_count++; in_word=1;}
164 continue;
165 }
166 if (c=='\n') line_count++;
167 else if (c!=' ' && c!='\t') continue;
168 in_word=0; /* |c| is newline, space, or tab */
169}
170
171@ Buffered I/O allows us to count the number of characters almost for free.
172
173@<Fill |buff...@>=
174if (ptr>=buf_end) {
175 ptr=buffer; c=read(fd,ptr,buf_size);
176 if (c<=0) break;
177 char_count+=c; buf_end=buffer+c;
178}
179
180@ It's convenient to output the statistics by defining a new function
181|wc_print|; then the same function can be used for the totals.
182Additionally we must decide here if we know the name of the file
183we have processed or if it was just |stdin|.
184
185@<Write...@>=
186wc_print(which, char_count, word_count, line_count);
187if (file_count) printf (" %s\n", *argv); /* not |stdin| */
188else printf ("\n"); /* |stdin| */
189
190@ @<Upda...@>=
191tot_line_count+=line_count;
192tot_word_count+=word_count;
193tot_char_count+=char_count;
194
195@ We might as well improve a bit on \UNIX/'s \.{wc} by displaying the
196number of files too.
197
198@<Print the...@>=
199if (file_count>1) {
200 wc_print(which, tot_char_count, tot_word_count, tot_line_count);
201 printf(" total in %d files\n",file_count);
202}
203
204@ Here now is the function that prints the values according to the
205specified options. The calling routine is supposed to supply a
206newline. If an invalid option character is found we inform
207the user about proper usage of the command. Counts are printed in
2088-digit fields so that they will line up in columns.
209
210@d print_count(n) printf("%8ld",n)
211
212@<Fun...@>=
213wc_print(which, char_count, word_count, line_count)
214char *which; /* which counts to print */
215long char_count, word_count, line_count; /* given totals */
216{
217 while (*which)
218 switch (*which++) {
219 case 'l': print_count(line_count); break;
220 case 'w': print_count(word_count); break;
221 case 'c': print_count(char_count); break;
222 default: if ((status & usage_error)==0) {
223 fprintf (stderr, "\nUsage: %s [-lwc] [filename ...]\n", prog_name);
224@.Usage: ...@>
225 status|=usage_error;
226 }
227 }
228}
229
230@ Incidentally, a test of this program against the system \.{wc}
231command on a \SPARC\ showed that the ``official'' \.{wc} was slightly
232slower. Furthermore, although that \.{wc} gave an appropriate error
233message for the options `\.{-abc}', it made no complaints about the
234options `\.{-labc}'! Dare we suggest that the system routine might have been
235better if its programmer had used a more literate approach?
236
237@* Index.
238Here is a list of the identifiers used, and where they appear. Underlined
239entries indicate the place of definition. Error messages are also shown.
examples/wmerg-pc.ch+21−0
@@ -0,0 +1,21 @@
1Change file for wmerge, for MSDOS and Borland C++ 3.1.
2To compile the C file: bcc -w-pro wmerge.c
3
4(This file contributed by Barry Schwartz, trashman@crud.mn.org, 28 Jun 94.)
5
6@x Section 19.
7 cur_file_name[l]='/'; /* \UNIX/ pathname separator */
8@y
9 cur_file_name[l]='/'; /* A valid {\mc MSDOS} pathname separator */
10@z
11
12
13@x Section 33.
14 if (*s=='.') dot_pos=s++;
15 else if (*s=='/') dot_pos=NULL,name_pos=++s;
16 else s++;
17@y
18 if (*s=='.') dot_pos=s++;
19 else if (*s==':' || *s=='\\' || *s=='/') dot_pos=NULL,name_pos=++s;
20 else s++;
21@z
examples/wmerge.w+709−0
@@ -0,0 +1,709 @@
1\def\9#1{} % this hack is explained in CWEB manual Appendix F11
2
3@* Introduction. This file contains the program \.{wmerge},
4which takes two or more files and merges them according
5to the conventions of \.{CWEB}. Namely, it takes an ordinary \.{.w}
6file and and optional \.{.ch} file and sends the corresponding
7\.{.w}-style file to standard output (or to a named file),
8expanding all ``includes''
9that might be specified by \.{@@i} in the original \.{.w} file.
10(A more precise description appears in the section on ``command line
11arguments'' below.)
12
13@c
14#include <stdio.h>
15#include <stdlib.h> /* declaration of |getenv| */
16#include <ctype.h> /* definition of |isalpha|, |isdigit| and so on */
17@<Definitions@>@;
18@<Predeclarations of functions@>@;
19@<Functions@>@;
20main (ac,av)
21int ac; char **av;
22{
23 argc=ac; argv=av;
24 @<Set the default options@>;
25 @<Scan arguments and open output file@>;
26 reset_input();
27 while (get_line())
28 put_line();
29 fflush(out_file);
30 check_complete();
31 fflush(out_file);
32 return wrap_up();
33}
34
35@ @<Definitions@>=
36typedef short boolean;
37typedef unsigned char eight_bits;
38typedef char ASCII; /* type of characters inside \.{WEB} */
39
40@ We predeclare some standard string-handling functions here instead of
41including their system header files, because the names of the header files
42are not as standard as the names of the functions. (There's confusion
43between \.{<string.h>} and \.{<strings.h>}.)
44
45@<Predecl...@>=
46extern int strlen(); /* length of string */
47extern char* strcpy(); /* copy one string to another */
48extern int strncmp(); /* compare up to $n$ string characters */
49extern char* strncpy(); /* copy up to $n$ string characters */
50
51@ @<Predec...@>=
52
53@ The lowest level of input to the \.{WEB} programs
54is performed by |input_ln|, which must be told which file to read from.
55The return value of |input_ln| is 1 if the read is successful and 0 if
56not (generally this means the file has ended).
57The characters of the next line of the file
58are copied into the |buffer| array,
59and the global variable |limit| is set to the first unoccupied position.
60Trailing blanks are ignored. The value of |limit| must be strictly less
61than |buf_size|, so that |buffer[buf_size-1]| is never filled.
62
63Some of the routines use the fact that it is safe to refer to
64|*(limit+2)| without overstepping the bounds of the array.
65
66@d buf_size 100
67
68@<Definitions...@>=
69ASCII buffer[buf_size]; /* where each line of input goes */
70ASCII *buffer_end=buffer+buf_size-2; /* end of |buffer| */
71ASCII *limit; /* points to the last character in the buffer */
72ASCII *loc; /* points to the next character to be read from the buffer */
73
74@ In the unlikely event that your standard I/O library does not
75support |feof|, |getc| and |ungetc|, you may have to change things here.
76@^system dependencies@>
77
78Incidentally, here's a curious fact about \.{CWEB} for those of you
79who are reading this file as an example of \.{CWEB} programming.
80The file \.{stdio.h} includes a typedef for
81the identifier |FILE|, which is not, strictly speaking, part of \CEE/.
82It turns out \.{CWEAVE} knows that |FILE| is a reserved word (after all,
83|FILE| is almost as common as |int|); indeed, \.{CWEAVE} knows all
84the types of the ISO standard \CEE/ library. But
85if you're using other types like {\bf caddr\_t},
86@:caddr_t}{\bf caddr_t@>
87which is defined in \.{/usr/include/sys/types.h}, you should let
88\.{WEAVE} know that this is a type, either by including the \.{.h} file
89at \.{WEB} time (saying \.{@@i /usr/include/sys/types.h}), or by
90using \.{WEB}'s format command (saying \.{@@f caddr\_t int}). Either of
91these will make {\bf caddr\_t} be treated in the same way as |int|.
92
93@<Func...@>=
94input_ln(fp) /* copies a line into |buffer| or returns 0 */
95FILE *fp; /* what file to read from */
96{
97 register int c=EOF; /* character read; initialized so some compilers won't complain */
98 register char *k; /* where next character goes */
99 if (feof(fp)) return(0); /* we have hit end-of-file */
100 limit = k = buffer; /* beginning of buffer */
101 while (k<=buffer_end && (c=getc(fp)) != EOF && c!='\n')
102 if ((*(k++) = c) != ' ') limit = k;
103 if (k>buffer_end)
104 if ((c=getc(fp))!=EOF && c!='\n') {
105 ungetc(c,fp); loc=buffer; err_print("! Input line too long");
106@.Input line too long@>
107 }
108 if (c==EOF && limit==buffer) return(0); /* there was nothing after
109 the last newline */
110 return(1);
111}
112
113@ Now comes the problem of deciding which file to read from next.
114Recall that the actual text that \.{CWEB} should process comes from two
115streams: a |web_file|, which can contain possibly nested include
116commands \.{@@i}, and a |change_file|, which might also contain
117includes. The |web_file| together with the currently open include
118files form a stack |file|, whose names are stored in a parallel stack
119|file_name|. The boolean |changing| tells whether or not we're reading
120from the |change_file|.
121
122The line number of each open file is also kept for error reporting.
123
124@f line x /* make |line| an unreserved word */
125@d max_include_depth 10 /* maximum number of source files open
126 simultaneously, not counting the change file */
127@d max_file_name_length 60
128@d cur_file file[include_depth] /* current file */
129@d cur_file_name file_name[include_depth] /* current file name */
130@d cur_line line[include_depth] /* number of current line in current file */
131@d web_file file[0] /* main source file */
132@d web_file_name file_name[0] /* main source file name */
133
134@<Definitions...@>=
135int include_depth; /* current level of nesting */
136FILE *file[max_include_depth]; /* stack of non-change files */
137FILE *change_file; /* change file */
138char file_name[max_include_depth][max_file_name_length];
139 /* stack of non-change file names */
140char change_file_name[max_file_name_length]; /* name of change file */
141char alt_web_file_name[max_file_name_length]; /* alternate name to try */
142int line[max_include_depth]; /* number of current line in the stacked files */
143int change_line; /* number of current line in change file */
144int change_depth; /* where \.{@@y} originated during a change */
145boolean input_has_ended; /* if there is no more input */
146boolean changing; /* if the current line is from |change_file| */
147boolean web_file_open=0; /* if the web file is being read */
148
149@ When |changing=0|, the next line of |change_file| is kept in
150|change_buffer|, for purposes of comparison with the next
151line of |cur_file|. After the change file has been completely input, we
152set |change_limit=change_buffer|,
153so that no further matches will be made.
154
155Here's a shorthand expression for inequality between the two lines:
156
157@d lines_dont_match (change_limit-change_buffer != limit-buffer ||
158 strncmp(buffer, change_buffer, limit-buffer))
159
160@<Def...@>=
161char change_buffer[buf_size]; /* next line of |change_file| */
162char *change_limit; /* points to the last character in |change_buffer| */
163
164@ Procedure |prime_the_change_buffer| sets |change_buffer| in
165preparation for the next matching operation. Since blank lines in the change
166file are not used for matching, we have
167|(change_limit==change_buffer && !changing)| if and only if
168the change file is exhausted. This procedure is called only when
169|changing| is 1; hence error messages will be reported correctly.
170
171@<Func...@>=
172void
173prime_the_change_buffer()
174{
175 change_limit=change_buffer; /* this value is used if the change file ends */
176 @<Skip over comment lines in the change file; |return| if end of file@>;
177 @<Skip to the next nonblank line; |return| if end of file@>;
178 @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
179}
180
181@ While looking for a line that begins with \.{@@x} in the change file, we
182allow lines that begin with \.{@@}, as long as they don't begin with \.{@@y},
183\.{@@z} or \.{@@i} (which would probably mean that the change file is fouled up).
184
185@<Skip over comment lines in the change file...@>=
186while(1) {
187 change_line++;
188 if (!input_ln(change_file)) return;
189 if (limit<buffer+2) continue;
190 if (buffer[0]!='@@') continue;
191 if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
192 if (buffer[1]=='x') break;
193 if (buffer[1]=='y' || buffer[1]=='z' || buffer[1]=='i') {
194 loc=buffer+2;
195 err_print("! Missing @@x in change file");
196@.Missing @@x...@>
197 }
198}
199
200@ Here we are looking at lines following the \.{@@x}.
201
202@<Skip to the next nonblank line...@>=
203do {
204 change_line++;
205 if (!input_ln(change_file)) {
206 err_print("! Change file ended after @@x");
207@.Change file ended...@>
208 return;
209 }
210} while (limit==buffer);
211
212@ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
213{
214 change_limit=change_buffer-buffer+limit;
215 strncpy(change_buffer,buffer,limit-buffer+1);
216}
217
218@ The following procedure is used to see if the next change entry should
219go into effect; it is called only when |changing| is 0.
220The idea is to test whether or not the current
221contents of |buffer| matches the current contents of |change_buffer|.
222If not, there's nothing more to do; but if so, a change is called for:
223All of the text down to the \.{@@y} is supposed to match. An error
224message is issued if any discrepancy is found. Then the procedure
225prepares to read the next line from |change_file|.
226
227This procedure is called only when |buffer<limit|, i.e., when the
228current line is nonempty.
229
230@<Func...@>=
231void
232check_change() /* switches to |change_file| if the buffers match */
233{
234 int n=0; /* the number of discrepancies found */
235 if (lines_dont_match) return;
236 while (1) {
237 changing=1; change_line++;
238 if (!input_ln(change_file)) {
239 err_print("! Change file ended before @@y");
240@.Change file ended...@>
241 change_limit=change_buffer; changing=0;
242 return;
243 }
244 if (limit>buffer+1 && buffer[0]=='@@') {
245 if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
246 @<If the current line starts with \.{@@y},
247 report any discrepancies and |return|@>;
248 }
249 @<Move |buffer| and |limit|...@>;
250 changing=0; cur_line++;
251 while (!input_ln(cur_file)) { /* pop the stack or quit */
252 if (include_depth==0) {
253 err_print("! CWEB file ended during a change");
254@.CWEB file ended...@>
255 input_has_ended=1; return;
256 }
257 include_depth--; cur_line++;
258 }
259 if (lines_dont_match) n++;
260 }
261}
262
263@ @<If the current line starts with \.{@@y}...@>=
264if (buffer[1]=='x' || buffer[1]=='z') {
265 loc=buffer+2; err_print("! Where is the matching @@y?");
266@.Where is the match...@>
267 }
268else if (buffer[1]=='y') {
269 if (n>0) {
270 loc=buffer+2;
271 fprintf(stderr,"\n! Hmm... %d ",n);
272 err_print("of the preceding lines failed to match");
273@.Hmm... n of the preceding...@>
274 }
275 change_depth=include_depth;
276 return;
277}
278
279@ The |reset_input| procedure gets the program ready to read the
280user's \.{WEB} input.
281
282@<Func...@>=
283void
284reset_input()
285{
286 limit=buffer; loc=buffer+1; buffer[0]=' ';
287 @<Open input files@>;
288 include_depth=0; cur_line=0; change_line=0;
289 change_depth=include_depth;
290 changing=1; prime_the_change_buffer(); changing=!changing;
291 limit=buffer; loc=buffer+1; buffer[0]=' '; input_has_ended=0;
292}
293
294@ The following code opens the input files.
295@^system dependencies@>
296
297@<Open input files@>=
298if ((web_file=fopen(web_file_name,"r"))==NULL) {
299 strcpy(web_file_name,alt_web_file_name);
300 if ((web_file=fopen(web_file_name,"r"))==NULL)
301 fatal("! Cannot open input file ", web_file_name);
302}
303@.Cannot open input file@>
304@.Cannot open change file@>
305web_file_open=1;
306if ((change_file=fopen(change_file_name,"r"))==NULL)
307 fatal("! Cannot open change file ", change_file_name);
308
309@ The |get_line| procedure is called when |loc>limit|; it puts the next
310line of merged input into the buffer and updates the other variables
311appropriately. A space is placed at the right end of the line.
312This procedure returns |!input_has_ended| because we often want to
313check the value of that variable after calling the procedure.
314
315@<Fun...@>=
316get_line() /* inputs the next line */
317{
318 restart:
319 if (changing && include_depth==change_depth)
320 @<Read from |change_file| and maybe turn off |changing|@>;
321 if (! changing || include_depth>change_depth) {
322 @<Read from |cur_file| and maybe turn on |changing|@>;
323 if (changing && include_depth==change_depth) goto restart;
324 }
325 loc=buffer; *limit=' ';
326 if (*buffer=='@@' && (*(buffer+1)=='i' || *(buffer+1)=='I')) {
327 loc=buffer+2;
328 while (loc<=limit && (*loc==' '||*loc=='\t'||*loc=='"')) loc++;
329 if (loc>=limit) {
330 err_print("! Include file name not given");
331@.Include file name ...@>
332 goto restart;
333 }
334 if (include_depth>=max_include_depth-1) {
335 err_print("! Too many nested includes");
336@.Too many nested includes@>
337 goto restart;
338 }
339 include_depth++; /* push input stack */
340 @<Try to open include file, abort push if unsuccessful, go to |restart|@>;
341 }
342 return (!input_has_ended);
343}
344
345void put_line()
346{
347 char *ptr=buffer;
348 while (ptr<limit) putc(*ptr++,out_file);
349 putc('\n',out_file);
350}
351
352@ When an \.{@@i} line is found in the |cur_file|, we must temporarily
353stop reading it and start reading from the named include file. The
354\.{@@i} line should give a complete file name with or without
355double quotes.
356If the environment variable \.{CWEBINPUTS} is set, or if the compiler flag
357of the same name was defined at compile time,
358\.{CWEB} will look for include files in the directory thus named, if
359it cannot find them in the current directory.
360(Colon-separated paths are not supported.)
361The remainder of the \.{@@i} line after the file name is ignored.
362
363@d too_long() {include_depth--;
364 err_print("! Include file name too long"); goto restart;}
365
366@ @<Try to open...@>= {
367 char temp_file_name[max_file_name_length];
368 char *cur_file_name_end=cur_file_name+max_file_name_length-1;
369 char *k=cur_file_name, *kk;
370 int l; /* length of file name */
371
372 while (*loc!=' '&&*loc!='\t'&&*loc!='"'&&k<=cur_file_name_end) *k++=*loc++;
373 if (k>cur_file_name_end) too_long();
374@.Include file name ...@>
375 *k='\0';
376 if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
377 cur_line=0;
378 goto restart; /* success */
379 }
380 kk=getenv("CWEBINPUTS");
381 if (kk!=NULL) {
382 if ((l=strlen(kk))>max_file_name_length-2) too_long();
383 strcpy(temp_file_name,kk);
384 }
385 else {
386#ifdef CWEBINPUTS
387 if ((l=strlen(CWEBINPUTS))>max_file_name_length-2) too_long();
388 strcpy(temp_file_name,CWEBINPUTS);
389#else
390 l=0;
391#endif /* |CWEBINPUTS| */
392 }
393 if (l>0) {
394 if (k+l+2>=cur_file_name_end) too_long();
395@.Include file name ...@>
396 for (; k>= cur_file_name; k--) *(k+l+1)=*k;
397 strcpy(cur_file_name,temp_file_name);
398 cur_file_name[l]='/'; /* \UNIX/ pathname separator */
399 if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
400 cur_line=0;
401 goto restart; /* success */
402 }
403 }
404 include_depth--; err_print("! Cannot open include file"); goto restart;
405}
406
407@ @<Read from |cur_file|...@>= {
408 cur_line++;
409 while (!input_ln(cur_file)) { /* pop the stack or quit */
410 if (include_depth==0) {input_has_ended=1; break;}
411 else {
412 fclose(cur_file); include_depth--;
413 if (changing && include_depth==change_depth) break;
414 cur_line++;
415 }
416 }
417 if (!changing && !input_has_ended)
418 if (limit-buffer==change_limit-change_buffer)
419 if (buffer[0]==change_buffer[0])
420 if (change_limit>change_buffer) check_change();
421}
422
423@ @<Read from |change_file|...@>= {
424 change_line++;
425 if (!input_ln(change_file)) {
426 err_print("! Change file ended without @@z");
427@.Change file ended...@>
428 buffer[0]='@@'; buffer[1]='z'; limit=buffer+2;
429 }
430 if (limit>buffer) { /* check if the change has ended */
431 *limit=' ';
432 if (buffer[0]=='@@') {
433 if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
434 if (buffer[1]=='x' || buffer[1]=='y') {
435 loc=buffer+2;
436 err_print("! Where is the matching @@z?");
437@.Where is the match...@>
438 }
439 else if (buffer[1]=='z') {
440 prime_the_change_buffer(); changing=!changing;
441 }
442 }
443 }
444}
445
446@ At the end of the program, we will tell the user if the change file
447had a line that didn't match any relevant line in |web_file|.
448
449@<Funct...@>=
450void
451check_complete(){
452 if (change_limit!=change_buffer) { /* |changing| is 0 */
453 strncpy(buffer,change_buffer,change_limit-change_buffer+1);
454 limit=buffer+(int)(change_limit-change_buffer);
455 changing=1; change_depth=include_depth; loc=buffer;
456 err_print("! Change file entry did not match");
457 @.Change file entry did not match@>
458 }
459}
460
461@* Reporting errors to the user.
462A global variable called |history| will contain one of four values
463at the end of every run: |spotless| means that no unusual messages were
464printed; |harmless_message| means that a message of possible interest
465was printed but no serious errors were detected; |error_message| means that
466at least one error was found; |fatal_message| means that the program
467terminated abnormally. The value of |history| does not influence the
468behavior of the program; it is simply computed for the convenience
469of systems that might want to use such information.
470
471@d spotless 0 /* |history| value for normal jobs */
472@d harmless_message 1 /* |history| value when non-serious info was printed */
473@d error_message 2 /* |history| value when an error was noted */
474@d fatal_message 3 /* |history| value when we had to stop prematurely */
475@d mark_harmless {if (history==spotless) history=harmless_message;}
476@d mark_error history=error_message
477
478@<Definit...@>=
479int history=spotless; /* indicates how bad this run was */
480
481@ The command `|err_print("! Error message")|' will report a syntax error to
482the user, by printing the error message at the beginning of a new line and
483then giving an indication of where the error was spotted in the source file.
484Note that no period follows the error message, since the error routine
485will automatically supply a period. A newline is automatically supplied
486if the string begins with |"|"|.
487
488The actual error indications are provided by a procedure called |error|.
489
490@<Predecl...@>=
491void err_print();
492
493@
494@<Functions...@>=
495void
496err_print(s) /* prints `\..' and location of error message */
497char *s;
498{
499 char *k,*l; /* pointers into |buffer| */
500 fprintf(stderr,*s=='!'? "\n%s" : "%s",s);
501 if(web_file_open) @<Print error location based on input buffer@>;
502 update_terminal; mark_error;
503}
504
505@ The error locations can be indicated by using the global variables
506|loc|, |cur_line|, |cur_file_name| and |changing|,
507which tell respectively the first
508unlooked-at position in |buffer|, the current line number, the current
509file, and whether the current line is from |change_file| or |cur_file|.
510This routine should be modified on systems whose standard text editor
511has special line-numbering conventions.
512@^system dependencies@>
513
514@<Print error location based on input buffer@>=
515{if (changing && include_depth==change_depth)
516 printf(". (l. %d of change file)\n", change_line);
517else if (include_depth==0) fprintf(stderr,". (l. %d)\n", cur_line);
518 else fprintf(stderr,". (l. %d of include file %s)\n", cur_line, cur_file_name);
519l= (loc>=limit? limit: loc);
520if (l>buffer) {
521 for (k=buffer; k<l; k++)
522 if (*k=='\t') putc(' ',stderr);
523 else putc(*k,stderr); /* print the characters already read */
524 putchar('\n');
525 for (k=buffer; k<l; k++) putc(' ',stderr); /* space out the next line */
526}
527for (k=l; k<limit; k++) putc(*k,stderr); /* print the part not yet read */
528 putc('\n',stderr);
529}
530
531@ When no recovery from some error has been provided, we have to wrap
532up and quit as graciously as possible. This is done by calling the
533function |wrap_up| at the end of the code.
534
535@d fatal(s,t) {
536 fprintf(stderr,s); err_print(t);
537 history=fatal_message; exit(wrap_up());
538}
539
540@ Some implementations may wish to pass the |history| value to the
541operating system so that it can be used to govern whether or not other
542programs are started. Here, for instance, we pass the operating system
543a status of 0 if and only if only harmless messages were printed.
544@^system dependencies@>
545
546@<Func...@>=
547wrap_up() {
548 @<Print the job |history|@>;
549 if (history > harmless_message) return(1);
550 else return(0);
551}
552
553@ @<Print the job |history|@>=
554switch (history) {
555case spotless: if (show_happiness) fprintf(stderr,"(No errors were found.)\n"); break;
556case harmless_message:
557 fprintf(stderr,"(Did you see the warning message above?)\n"); break;
558case error_message:
559 fprintf(stderr,"(Pardon me, but I think I spotted something wrong.)\n"); break;
560case fatal_message: fprintf(stderr,"(That was a fatal error, my friend.)\n");
561} /* there are no other cases */
562
563@* Command line arguments.
564The user calls \.{wmerge} with arguments on the command line.
565These are either file names or flags to be turned off (beginning with |"-"|)
566or flags to be turned on (beginning with |"+"|.
567The following globals are for communicating the user's desires to the rest
568of the program. The various file name variables contain strings with
569the names of those files. Most of the 128 flags are undefined but available
570for future extensions.
571
572@d show_banner flags['b'] /* should the banner line be printed? */
573@d show_happiness flags['h'] /* should lack of errors be announced? */
574
575@<Defin...@>=
576int argc; /* copy of |ac| parameter to |main| */
577char **argv; /* copy of |av| parameter to |main| */
578char out_file_name[max_file_name_length]; /* name of |out_file| */
579boolean flags[128]; /* an option for each 7-bit code */
580
581@ The |flags| will be initially 1.
582
583@<Set the default options@>=
584show_banner=show_happiness=1;
585
586@ We now must look at the command line arguments and set the file names
587accordingly. At least one file name must be present: the \.{WEB}
588file. It may have an extension, or it may omit it to get |'.w'|
589added.
590
591If there is another file name present among the arguments, it is the
592change file, again either with an extension or without one to get |'.ch'|
593An omitted change file argument means that |'/dev/null'| should be used,
594when no changes are desired.
595@^system dependencies@>
596
597If there's a third file name, it will be the output file.
598
599@<Pred...@>=
600void scan_args();
601
602@
603@<Function...@>=
604void
605scan_args()
606{
607 char *dot_pos; /* position of |'.'| in the argument */
608 char *name_pos; /* file name beginning, sans directory */
609 register char *s; /* register for scanning strings */
610 boolean found_web=0,found_change=0,found_out=0;
611 /* have these names have been seen? */
612 boolean flag_change;
613
614 while (--argc > 0) {
615 if (**(++argv)=='-' || **argv=='+') @<Handle flag argument@>@;
616 else {
617 s=name_pos=*argv;@+dot_pos=NULL;
618 while (*s) {
619 if (*s=='.') dot_pos=s++;
620 else if (*s=='/') dot_pos=NULL,name_pos=++s;
621 else s++;
622 }
623 if (!found_web) @<Make |web_file_name|@>@;
624 else if (!found_change) @<Make |change_file_name| from |fname|@>@;
625 else if (!found_out) @<Override output file name@>@;
626 else @<Print usage error message and quit@>;
627 }
628 }
629 if (!found_web) @<Print usage error message and quit@>;
630 if (!found_change) strcpy(change_file_name,"/dev/null");
631}
632
633@ We use all of |*argv| for the |web_file_name| if there is a |'.'| in it,
634otherwise we add |".w"|. If this file can't be opened, we prepare an
635|alt_web_file_name| by adding |"web"| after the dot.
636The other file names come from adding other things
637after the dot. We must check that there is enough room in
638|web_file_name| and the other arrays for the argument.
639
640@<Make |web_file_name|...@>=
641{
642 if (s-*argv > max_file_name_length-5)
643 @<Complain about argument length@>;
644 if (dot_pos==NULL)
645 sprintf(web_file_name,"%s.w",*argv);
646 else {
647 strcpy(web_file_name,*argv);
648 *dot_pos=0; /* string now ends where the dot was */
649 }
650 sprintf(alt_web_file_name,"%s.web",*argv);
651 *out_file_name='\0'; /* this will print to stdout */
652 found_web=1;
653}
654
655@ @<Make |change_file_name|...@>=
656{
657 if (s-*argv > max_file_name_length-4)
658 @<Complain about argument length@>;
659 if (dot_pos==NULL)
660 sprintf(change_file_name,"%s.ch",*argv);
661 else strcpy(change_file_name,*argv);
662 found_change=1;
663}
664
665@ @<Override...@>=
666{
667 if (s-*argv > max_file_name_length-5)
668 @<Complain about argument length@>;
669 if (dot_pos==NULL) sprintf(out_file_name,"%s.out",*argv);
670 else strcpy(out_file_name,*argv);
671 found_out=1;
672}
673
674@ @<Handle flag...@>=
675{
676 if (**argv=='-') flag_change=0;
677 else flag_change=1;
678 for(dot_pos=*argv+1;*dot_pos>'\0';dot_pos++)
679 flags[*dot_pos]=flag_change;
680}
681
682@ @<Print usage error message and quit@>=
683{
684 fatal("! Usage: wmerge webfile[.w] [changefile[.ch] [outfile[.out]]]\n","")@;
685}
686
687@ @<Complain about arg...@>= fatal("! Filename too long\n", *argv);
688
689@* Output. Here is the code that opens the output file:
690@^system dependencies@>
691
692@<Defin...@>=
693FILE *out_file; /* where output goes */
694
695@ @<Scan arguments and open output file@>=
696scan_args();
697if (out_file_name[0]=='\0') out_file=stdout;
698else if ((out_file=fopen(out_file_name,"w"))==NULL)
699 fatal("! Cannot open output file ", out_file_name);
700@.Cannot open output file@>
701
702@ The |update_terminal| procedure is called when we want
703to make sure that everything we have output to the terminal so far has
704actually left the computer's internal buffers and been sent.
705@^system dependencies@>
706
707@d update_terminal fflush(stderr) /* empty the terminal output buffer */
708
709@* Index.
examples/wordtest.w+539−0
@@ -0,0 +1,539 @@
1\datethis
2@* Introduction. This program is a simple filter that sorts and outputs all
3lines of input that do not appear in a given set of sorted files. It is called
4{\tt wordtest} because each line of input is considered to be a `word' and
5each of the sorted files is considered to be a 'dictionary'. Words are
6output when they don't appear in any given dictionary.
7
8The character set and alphabetic order are flexible. Every 8-bit
9character is mapped into an integer called its {\it ord}. A character
10is called a {\it null\/} if its ord is zero; such characters are
11discarded from the input. A character is called a {\it break\/} if
12its ord is negative; such characters break the input into so-called words.
13Otherwise a character's ord is positive, and the character is called a
14{\it letter}. One letter precedes another in alphabetic order if and only
15if it has a smaller ord. Two letters are considered identical, for
16purposes of sorting, if their ords are the same.
17
18The null character |'\n'| must have ord~0; thus, it must remain null.
19Otherwise the ord mapping is arbitrary. If the user doesn't specify
20any special mapping, the default ord table simply maps every 8-bit
21character code into itself, considering characters to be unsigned char
22values in the range 0--255, except that ASCII codes {\tt a-z} are
23mapped into the corresponding codes for {\tt A-Z}, and newline is a
24break character. Optional command-line arguments, described below, can
25change this default mapping to any other desired scheme.
26
27A word is any nonempty sequence of letters that is immediately preceded
28and followed by break characters, when nulls are ignored. Technically
29speaking, we pretend that a break character is present at the beginning of a
30file but not at the end; thus, all letters following the final break character
31of a file are ignored, if any such letters are present. Two words are
32{\it equivalent\/} to each other if their letters have the same sequence
33of ord values. If two or more words of the input are equivalent, only
34the first will be output, and it will be output only if it is not
35equivalent to any word in the given dictionary files. Words in each
36dictionary are assumed to be in lexicographic order and to contain no
37nulls. Words in the output file will satisfy these conditions; therefore
38{\tt wordtest} can be used to generate and update the dictionaries it needs.
39Notice that if no dictionaries are given, {\tt wordtest} will act as a
40sorting routine that simply discards nulls and duplicate lines.
41
42@ The \UNIX/ command line `{\tt wordtest} {\tt [options]} {\tt [dictionaries]}'
43is interpreted by executing option commands from left to right and then by
44regarding any remaining arguments as the names of dictionary files.
45
46Most of the option commands are designed to specify the |ord| table.
47Initially |ord[c]=c| for each unsigned char code~|c|. The command
48$$\line{\hskip5em\tt-b\it string\hfil}$$
49makes every character in the string a break character. If the string is
50empty, {\tt-b} makes every nonnull character a break (i.e., it sets
51|ord[c]=-1| for |1<=c<=255|). The command
52$$\line{\hskip5em\tt-n\it string\hfil}$$
53makes every character in the string a null character. If the string is
54empty, {\tt-n} makes every character null. The command
55$$\line{\hskip5em\tt-a\it string\hfil}$$
56sets the ord of the $k$th element of the string equal to $\delta+k$,
57where $\delta$ is an offset value (normally zero). The command
58$$\line{\hskip5em\tt-d\it offset\hfil}$$
59sets the value of $\delta$; the offset should be a decimal integer between
600 and 255.
61
62There is also an option that has no effect on the |ord| table:
63$$\line{\hskip5em\tt-m\it length\hfil}$$
64defines the length of the longest word. If any word of a file has
65more than this many characters, a break is artificially inserted
66so that a word of this maximum length is obtained. The default value is 50.
67The maximum legal value is 1000.
68
69If the given options do not specify at least one break character,
70{\tt wordtest} applies the option commands
71$$\vbox{\line{\hskip5em\.{-b"\\}\hfil}
72\line{\.{" -d64 -a"abcdefghijklmnopqrstuvwxyz"}\hfil}}$$
73which generate the default mapping mentioned above (unless other ords were
74changed).
75
76The program is designed to run fastest when there are at most two
77dictionary files (usually one large system dictionary and another
78personalized one), although it places no limit on the actual number of
79dictionaries that can be mentioned on the command line. Users who want
80to specify a multitude of dictionaries should ask themselves why they
81wouldn't prefer to merge their dictionaries together first (using
82{\tt wordtest}).
83
84@d MAX_LENGTH_DEFAULT 50
85@d MAX_LENGTH_LIMIT 1000
86
87@ The general organization of {\tt wordtest} is typical of applications
88written in \CEE/, and its approach is quite simple. If any errors are
89detected, an indication of the error is sent to the |stderr| file and
90a nonzero value is returned.
91
92@p
93#include <stdio.h>
94@#
95@<Typedefs@>@;
96int main(argc,argv)
97 int argc; /* the number of command-line arguments */
98 char *argv[]; /* the arguments themselves */
99{
100 @<Local variables@>;
101 @<Scan the command line arguments@>;
102 @<Sort the input into memory@>;
103 @<Output all input words that aren't in dictionaries@>;
104 return 0;
105}
106
107@ @<Typedefs@>=
108typedef unsigned char byte; /* our bytes will range from 0 to 255 */
109
110@ @<Local variables@>=
111int targc; /* temporary modifications to |argc| */
112byte **targv; /* pointer to the current argument of interest */
113unsigned delta; /* the offset used in the \.{-a} and \.{-d} options */
114unsigned max_length=MAX_LENGTH_DEFAULT; /* longest allowable word */
115byte breakchar; /* break character to use in the output */
116int ord[256]; /* table of ord values */
117register int c; /* an all-purpose index */
118register byte *u,*v; /* pointer to current string characters */
119
120@ We try to use newline as the output break character, if possible.
121
122@<Scan the command line arguments@>=
123for (c=0;c<256;c++) ord[c]=c;
124delta=0;
125targc=argc-1;@+targv=(byte**)argv+1;
126while (targc && **targv=='-') {
127 @<Execute the option command |targv|@>;
128 targc--;@+targv++;
129}
130if (ord['\n']<0) breakchar='\n';
131else {
132 breakchar='\0';
133 for (c=255;c;c--) if (ord[c]<0) breakchar=c;
134 if (!breakchar) @<Set up the default ords@>;
135}
136@<Allocate data structures for a total of |targc| files@>;
137for (;targc;targc--,targv++) @<Open the dictionary file named |*targv|@>;
138
139@ @<Execute the option...@>=
140switch((*targv)[1]) {
141case 'a': for (c=delta,u=*targv+2;*u;u++) ord[*u]=++c;@+break;
142case 'b': if ((*targv)[2]) for (u=*targv+2;*u;u++) ord[*u]=-1;
143 else for (c=1;c<256;c++) ord[c]=-1;
144 break;
145case 'n': if ((*targv)[2]) for (u=*targv+2;*u;u++) ord[*u]=0;
146 else for (c=1;c<256;c++) ord[c]=0;
147 break;
148case 'd': if (sscanf((char*)*targv+2,"%u",&delta)==1 && delta<256) break;
149 goto print_usage;
150case 'm': if (sscanf((char*)*targv+2,"%u",&max_length)==1 &
151 max_length<=MAX_LENGTH_LIMIT) break;
152 goto print_usage;
153default: print_usage: fprintf(stderr,
154 "Usage: %s {-{{a|b|n}string|{d|m}number}}* dictionaryname*\n",*argv);
155 return-1;
156}
157
158@ @<Set up the default ords@>=
159{
160 ord['\n']=-1; /* newline is break character */
161 breakchar='\n';
162 for (c=1;c<=26;c++) ord['a'-1+c]='A'-1+c;
163}
164
165@*Treaps. The most interesting part of this program is its sorting algorithm,
166which is based on the ``treap'' data structure of Aragon and Seidel
167[{\sl 30th IEEE Symposium on Foundations of Computer Science\/} (1989),
168540--546].
169@^Aragon, Cecilia Rodriguez@>@^Seidel, Raimund@>
170A treap is a binary tree whose nodes have two key fields. The primary
171key, which in our application is a word from the input, obeys
172tree-search order: All descendants of the left child of node~$p$ have
173a primary key that is less than the primary key of~$p$, and all descendants
174of its right child have a primary key that is greater. The secondary key,
175which in our application is a unique pseudorandom integer attached to
176each input word, obeys heap order: The secondary key of~$p$'s children
177is greater than $p$'s own secondary key.
178
179A given set of nodes with distinct primary keys and distinct secondary
180keys can be made into a treap in exactly one way. This unique treap
181can be obtained, for example, by using ordinary tree insertion with
182respect to primary keys while inserting nodes in order of their
183secondary keys. It follows that, if the secondary keys are random,
184the binary tree will almost always be quite well balanced.
185
186We will compute secondary keys as unsigned long integers, assigning
187the key $(cn)\bmod 2^{32}$ to the $n$th node, where $c$ is an odd
188number. This will guarantee that the secondary keys are distinct.
189By choosing $c$ close to $2^{32}/\phi$, where $\phi$ is the golden
190ratio $(1+\sqrt5\,)/2$, we also spread the values out in a fashion that
191is unlikely to match any existing order in the data.
192
193@d PHICLONE 2654435769 /* $\approx 2^{32}/\phi$ */
194
195@<Typedefs@>=
196typedef struct node_struct {
197 struct node_struct *left,*right; /* children */
198 byte *keyword; /* primary key */
199 unsigned long rank; /* secondary key */
200} node; /* node of a treap */
201
202@ We want to be able to compare two strings rapidly with respect to
203lexicographic order, as defined by the |ord| table. This can be done
204if one string is delimited by |'\0'| as usual, while the other is
205delimited by a break character. Then we are sure to have an unequal
206comparison, and the inner loop is fast.
207
208Here is a routine that checks to see if a word is already present in the
209treap. The word is assumed to be in |buffer|, terminated by |breakchar|.
210The words in the treap are terminated by nulls. The
211treap is accessed by means of |root|, a pointer to its root node.
212
213@<Search for |buffer| in the treap; |goto found| if it's there@>=
214{@+register node *p=root;
215 while (p) {
216 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
217 if (*v=='\0' && *u==breakchar) goto found;
218 if (ord[*u]<ord[*v]) p=p->left;
219 else p=p->right;
220 }
221}
222
223@ We don't need to insert nodes into the treap as often as we need to
224look words up, so we don't mind repeating the comparisons already made
225when we discover that insertion is necessary. (Actually a more comprehensive
226study of this tradeoff ought to be done. But not today; I am trying
227here to keep the program short and sweet.)
228
229The insertion algorithm proceeds just as the lookup algorithm until
230we come to a node whose rank is larger than the rank of the node
231to be inserted. We insert the new node in its place, then split the
232old node and its descendants into two subtrees that will become the
233left and right subtrees of the new node.
234
235@<Insert the |buffer| word into the treap@>=
236{@+register node *p,**q,**qq,*r;
237 current_rank += PHICLONE; /* unsigned addition mod $2^{32}$ */
238 p=root;@+q=&root;
239 while (p) {
240 if (p->rank>current_rank) break; /* end of the first phase */
241 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
242 if (ord[*u]<ord[*v]) q=&(p->left), p=*q;
243 else q=&(p->right), p=*q;
244 }
245 @<Set |r| to the address of a new node, and move |buffer| into it@>;
246 r->rank=current_rank;
247 *q=r; /* link the new node into the tree */
248 @<Split subtree |p| and attach it below node |r|@>;
249}
250
251@ @<Local...@>=
252unsigned long current_rank=0; /* pseudorandom number */
253
254@ At this point |p| may already be empty. If not, we can hook its
255parts together easily. (A formal proof is a bit tricky, but the computer
256doesn't slow down like people do when they get to a conceptually harder
257part of an algorithm.)
258
259@<Split subtree |p| and attach it below node |r|@>=
260q=&(r->left);@+qq=&(r->right); /* slots to fill in as we split the subtree */
261while (p) {
262 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
263 if (ord[*u]<ord[*v]) {
264 *qq=p;
265 qq=&(p->left);
266 p=*qq;
267 } else {
268 *q=p;
269 q=&(p->right);
270 p=*q;
271 }
272}
273*q=*qq=NULL;
274
275@ We allocate node memory dynamically, in blocks of 100 nodes at a time.
276We also allocate string memory dynamically, 1000 characters at once
277(in addition to space for the current string).
278The variable |l| will be set to the length of the word in |buffer|.
279
280@d NODES_PER_BLOCK 100
281@d CHARS_PER_BLOCK 1000
282@d out_of_mem(x) {@+fprintf(stderr,"%s: Memory exhausted!\n",*argv);
283 return x;@+}
284
285@<Set |r| to the address of a new node, and move |buffer| into it@>=
286if (next_node==bad_node) {
287 next_node=(node*)calloc(NODES_PER_BLOCK,sizeof(node));
288 if (next_node==NULL) out_of_mem(-2);
289 bad_node=next_node+NODES_PER_BLOCK;
290}
291r=next_node++;
292@<Move |buffer| to a new place in the string memory, and make
293 |r->keyword| point to it@>;
294
295@ @<Move |buffer| to a new place...@>=
296if (next_string+l+1>=bad_string) {@+int block_size=CHARS_PER_BLOCK+l+1;
297 next_string=(byte*)malloc(block_size);
298 if (next_string==NULL) out_of_mem(-3);
299 bad_string=next_string+block_size;
300}
301r->keyword=next_string;
302for (u=buffer,v=next_string;ord[*u]>0;u++,v++) *v=*u;
303*v='\0';
304next_string=v+1;
305
306@ We had better define the variables we've been assuming in these
307storage allocation routines.
308
309@<Local variables@>=
310node *next_node=NULL, *bad_node=NULL;
311byte *next_string=NULL, *bad_string=NULL;
312node *root=NULL;
313byte *buffer;
314int l; /* length of current string in |buffer| */
315
316@ The mechanisms for sorting the input words are now all in place.
317We merely need to invoke them at the right times.
318
319@<Sort the input into memory@>=
320buffer=(byte*)malloc(max_length+1);
321if (buffer==NULL) out_of_mem(-5);
322while (1) {
323 @<Set |buffer| to the next word from |stdin|; |goto done| if file ends@>;
324 if (l) {
325 @<Search for |buffer| in the treap; |goto found| if it's there@>;
326 @<Insert the |buffer| word into the treap@>;
327 found:;
328 }
329}
330done:;
331
332@ @<Set |buffer| to the next word from |stdin|...@>=
333u=buffer;@+l=0;
334while (l<max_length) {
335 c=getchar();
336 if (c==EOF) {
337 if (ferror(stdin)) {
338 fprintf(stderr,"%s: File read error on standard input!\n",*argv);
339 return -6;
340 }
341 goto done; /* end of file; the current word, if any, is discarded */
342 }
343 if (ord[c]<=0) {
344 if (ord[c]<0) break;
345 } else {
346 *u++=(byte)c;
347 l++;
348 }
349}
350*u=breakchar;
351
352@ At the end we want to traverse the treap in symmetric order, so that
353we see its words in alphabetic order. We might as well destroy the
354treap structure as we do this. During this phase, |root| will point
355to a stack of nodes that remain to be visited (followed by traversal
356of their right subtrees).
357
358@<Output all input words that aren't in dictionaries@>=
359if (root!=NULL) {@+register node *p,*q;
360 p=root;
361 root=NULL;
362 while (1) {
363 while (p->left!=NULL) {
364 q=p->left;
365 p->left=root; /* |left| links are now used for the stack */
366 root=p;
367 p=q;
368 }
369visit: @<Output |p->keyword|, if it's not in the dictionaries@>;
370 if (p->right==NULL) {
371 if (root==NULL) break; /* the stack is empty, we're done */
372 p=root;
373 root=root->left; /* pop the stack */
374 goto visit;
375 } else p=p->right;
376 }
377}
378
379@* The dictionaries. So now all we have to do is provide a mechanism
380for reading the words in the dictionaries. The dictionaries are sorted,
381and by now the input words have been sorted too.
382So we need only scan through the
383dictionaries once; we'll try to zoom through as quickly as possible.
384
385First we need data structures. There will be an array of pointers to filenodes,
386for all dictionary files currently open. Each filenode will contain
387a buffer of size |BUFSIZ+1| for raw input bytes not yet scanned,
388as well as a buffer of size |MAX_LENGTH_LIMIT+1| for the current word
389being considered.
390
391@<Typedefs@>=
392typedef struct filenode_struct {
393 struct filenode_struct *link; /* pointer to next open file */
394 FILE *dfile; /* dictionary file */
395 byte buf[BUFSIZ+1], curword[MAX_LENGTH_LIMIT+1];
396 byte *pos; /* current position in |buf| */
397 byte *limit; /* end of input bytes in |buf| */
398 byte *endword; /* the first break character in |curword| */
399} filenode;
400
401@ @<Allocate data structures...@>=
402if (targc) {
403 curfile=(filenode*)calloc(targc,sizeof(filenode));
404 if (curfile==NULL) out_of_mem(-7);
405 for (f=curfile;f<curfile+targc-1;f++) f->link=f+1;
406 f->link=curfile; /* circular linking */
407} else curfile=NULL;
408
409@ @<Local...@>=
410filenode *curfile; /* current filenode of interest */
411filenode *f; /* temporary register for filenode list processing */
412
413@ @<Open the dictionary file named |*targv|@>=
414{
415 curfile->dfile=fopen((char*)*targv,"r");
416 if (curfile->dfile==NULL) {
417 fprintf(stderr,"%s: Can't open dictionary file %s!\n",*argv,(char*)*targv);
418 return -8;
419 }
420 curfile->pos=curfile->limit=curfile->buf; /* |buf| is empty */
421 curfile->buf[0]='\0';
422 curfile->endword=curfile->curword; /* |curword| is empty too */
423 curfile->curword[0]=breakchar;
424 curfile=curfile->link; /* move to next filenode */
425}
426
427@ We will implicitly merge the dictionaries together by using a brute force
428scheme that works fine when there are only a few of them. Namely,
429|curfile| will point to a file having the currently smallest
430current word. To get to the next word of the merge, we advance to the
431next word in that file, comparing it with the current words of the
432other files to see if |curfile| should switch to one of them.
433When we get to the end of a file, its filenode simply leaves the circular
434list. Eventually the list will be empty, and we will set |curfile| to
435|NULL|; we will then have seen all the dictionary words in order.
436
437@ @<Output |p->keyword|, if it's not in the dictionaries@>=
438while (curfile!=NULL) {
439 for (u=p->keyword,v=curfile->curword;ord[*u]==ord[*v];u++,v++) ;
440 if (*u=='\0' && *v==breakchar) goto word_done;
441 /* we found it in the dictionary */
442 if (ord[*u]<ord[*v]) break; /* we didn't find it */
443 @<Advance to the next dictionary word@>;
444}
445@<Print |p->keyword| and |breakchar| on |stdout|@>@;
446word_done:;
447
448@ @<Print |p->keyword| and |breakchar| on |stdout|@>=
449for (u=p->keyword;*u;u++) putchar(*u);
450putchar(breakchar);
451
452@ @<Advance...@>=
453@<Read a new word into |curfile->curword|, as fast as you can@>;
454@<Adjust |curfile|, if necessary, to point to a file with minimal
455 |curword|@>;
456
457@ The dictionaries are supposed to be in order, and they shouldn't
458contain nulls. But if they fail to meet these criteria, we don't want
459{\tt wordtest} to crash; it should just run more slowly and/or more
460peculiarly.
461
462The logic of the code here removes null characters, at the cost of speed.
463If the dictionary contains words out of order, say $\alpha>\beta$ where
464$\alpha$ precedes $\beta$ in the file, the effect will be as if $\beta$
465were not present. (In particular, if the dictionary would happen to have a null
466word because of a break character inserted by our |max_length| logic,
467that null word would cause no harm, because a null word is always less than
468any nonnull word.)
469
470A null character always appears in |curfile->limit|.
471
472@<Read a new word into |curfile->curword|...@>=
473v=curfile->curword;
474l=max_length; /* here |l| represents max characters to put in |curword| */
475while (1) {@+register byte *w=curfile->limit;
476 u=curfile->pos;
477 if (u+l>=w)
478 while (ord[*u]>0) *v++=*u++; /* this is the inner loop */
479 else {
480 w=u+l;
481 c=*w;
482 *w='\0'; /* temporarily store a null to avoid overlong string */
483 while (ord[*u]>0) *v++=*u++; /* this too is the inner loop */
484 *w=c; /* restore the damaged byte */
485 }
486 if (ord[*u]<0) {
487 curfile->pos=u+1; /* good, we found the next break character */
488 break;
489 }
490 l-=u-curfile->pos;
491 if (l==0) { /* |max_length| reached */
492 curfile->pos=u;
493 break;
494 }
495 if (u==w) { /* we're at |curfile->limit| */
496 @<Refill |curfile->buf|; or remove the current file from the
497 circular list and |goto update_done|, if it has ended@>;
498 } else curfile->pos=u+1; /* bypass a null character in the dictionary */
499}
500curfile->endword=v;
501*v=breakchar;
502update_done:;
503
504@ @<Refill |curfile->buf|...@>=
505if (ferror(curfile->dfile)) {
506 fprintf(stderr,"%s: File read error on dictionary file!\n",*argv);
507 return -9;
508}
509if (feof(curfile->dfile)) {
510 f=curfile->link;
511 if (f==curfile) curfile=NULL; /* the last dictionary file has ended */
512 else {
513 while (f->link!=curfile) f=f->link;
514 f->link=curfile->link; /* remove a filenode from the circular list */
515 curfile=f; /* and point to one of the remaining filenodes */
516 }
517 goto update_done;
518}
519curfile->limit=curfile->buf+fread(curfile->buf,1,BUFSIZ,curfile->dfile);
520*curfile->limit='\0';
521curfile->pos=curfile->buf;
522
523@ @<Adjust |curfile|, if necessary...@>=
524if (curfile!=NULL) {@+filenode *sentinel=curfile;
525 for (f=curfile->link;f!=sentinel;f=f->link)
526 @<Change |curfile| to |f| if |f->curword<curfile->curword|@>;
527}
528
529@ @<Change |curfile| to |f| if |f->curword<curfile->curword|@>=
530{
531 *f->endword='\0';
532 for (u=f->curword,v=curfile->curword;ord[*u]==ord[*v];u++,v++) ;
533 if (ord[*u]<ord[*v]) curfile=f;
534 *f->endword=breakchar;
535}
536
537@* Index. Here is a list of the identifiers used by {\tt wordtest},
538showing the sections in which they appear, underlined at points
539of definition.
examples/xlib_types.w+92−0
@@ -0,0 +1,92 @@
1@q This file tells CWEAVE to treat X11/Xlib types as reserved words. @>
2
3@s XExtData int
4@s XExtCodes int
5@s _XExtension int
6@s XPixmapFormatValues int
7@s XGCValues int
8@s GC int
9@s Visual int
10@s Depth int
11@s Screen int
12@s ScreenFormat int
13@s XSetWindowAttributes int
14@s XWindowAttributes int
15@s XHostAddress int
16@s XImage int
17@s XWindowChanges int
18@s XColor int
19@s XSegment int
20@s XPoint int
21@s XRectangle int
22@s XArc int
23@s XKeyboardControl int
24@s XKeyboardState int
25@s XTimeCoord int
26@s XModifierKeymap int
27@s Display int
28@s XKeyEvent int
29@s XKeyPressedEvent int
30@s XKeyReleasedEvent int
31@s XButtonEvent int
32@s XButtonPressedEvent int
33@s XButtonReleasedEvent int
34@s XMotionEvent int
35@s XPointerMovedEvent int
36@s XCrossingEvent int
37@s XEnterWindowEvent int
38@s XLeaveWindowEvent int
39@s XFocusChangeEvent int
40@s XFocusInEvent int
41@s XFocusOutEvent int
42@s XKeymapEvent int
43@s XExposeEvent int
44@s XGraphicsExposeEvent int
45@s XNoExposeEvent int
46@s XVisibilityEvent int
47@s XCreateWindowEvent int
48@s XDestroyWindowEvent int
49@s XUnmapEvent int
50@s XMapEvent int
51@s XMapRequestEvent int
52@s XReparentEvent int
53@s XConfigureEvent int
54@s XGravityEvent int
55@s XResizeRequestEvent int
56@s XConfigureRequestEvent int
57@s XCirculateEvent int
58@s XCirculateRequestEvent int
59@s XPropertyEvent int
60@s XSelectionClearEvent int
61@s XSelectionRequestEvent int
62@s XSelectionEvent int
63@s XColormapEvent int
64@s XClientMessageEvent int
65@s XMappingEvent int
66@s XErrorEvent int
67@s XAnyEvent int
68@s XEvent int
69@s _XQEvent int
70@s XCharStruct int
71@s XFontProp int
72@s XFontStruct int
73@s XTextItem int
74@s XChar2b int
75@s XTextItem16 int
76@s XEDataObject int
77@s XErrorHandler int
78@s XIOErrorHandler int
79@s XID int
80@s Window int
81@s Drawable int
82@s Font int
83@s Pixmap int
84@s Cursor int
85@s Colormap int
86@s GContext int
87@s KeySym int
88@s Mask int
89@s Atom int
90@s VisualID int
91@s Time int
92@s KeyCode int
examples/xview_types.w+274−0
@@ -0,0 +1,274 @@
1@q This file tells CWEAVE to treat XView types as reserved words. @>
2
3@s Attr_attribute int
4@s Attr_avlist int
5@s Attr_base_cardinality int
6@s Attr_base_type int
7@s Attr_cu_type int
8@s Attr_generic int
9@s Attr_list_ptr_type int
10@s Attr_list_type int
11@s Attr_pkg int
12@s Attr_union int
13@s Canvas int
14@s Canvas_attribute int
15@s Canvas_paint_attribute int
16@s Canvas_paint_window int
17@s Canvas_view int
18@s Canvas_view_attribute int
19@s Cms int
20@s Cms_attribute int
21@s Cms_type int
22@s Cursor_attribute int
23@s Cursor_drag_state int
24@s Cursor_drag_type int
25@s Defaults_pairs int
26@s Destroy_status int
27@s Dnd int
28@s DndDragType int
29@s Dnd_attribute int
30@s Drag_drop int
31@s Drawable_attr int
32@s Drawable_attribute int
33@s Drop_site_item int
34@s Enumerator int
35@s Error_attr int
36@s Error_attribute int
37@s Error_layer int
38@s Error_severity int
39@s Event int
40@s Firm_event int
41@s Font_attribute int
42@s Font_string_dims int
43@s Font_type int
44@s Frame int
45@s Frame_accelerator int
46@s Frame_attribute int
47@s Frame_cmd int
48@s Frame_cmd_pin_state int
49@s Frame_focus_direction int
50@s Frame_help int
51@s Frame_props int
52@s Fullscreen int
53@s Fullscreen_attr int
54@s Fullscreen_attribute int
55@s Fullscreen_grab_mode int
56@s Icon int
57@s Icon_attribute int
58@s Inputmask int
59@s Kbd_cmds_value int
60@s Menu int
61@s Menu_attribute int
62@s Menu_class int
63@s Menu_feedback int
64@s Menu_generate int
65@s Menu_item int
66@s Notice_attribute int
67@s Notify_arg int
68@s Notify_client int
69@s Notify_copy int
70@s Notify_dump_type int
71@s Notify_error int
72@s Notify_event int
73@s Notify_event_type int
74@s Notify_func int
75@s Notify_release int
76@s Notify_signal_mode int
77@s Notify_value int
78@s Openwin int
79@s Openwin_attribute int
80@s Openwin_split_direction int
81@s Panel int
82@s Panel_abbrev_menu_button_item int
83@s Panel_attr int
84@s Panel_attribute int
85@s Panel_attribute_value int
86@s Panel_button_item int
87@s Panel_choice_item int
88@s Panel_drop_target_item int
89@s Panel_gauge_item int
90@s Panel_item int
91@s Panel_item_type int
92@s Panel_list_item int
93@s Panel_list_mode int
94@s Panel_list_op int
95@s Panel_message_item int
96@s Panel_multiline_text_item int
97@s Panel_numeric_text_item int
98@s Panel_ops int
99@s Panel_paint_window int
100@s Panel_setting int
101@s Panel_slider_item int
102@s Panel_status int
103@s Panel_text_item int
104@s Panel_view int
105@s Pixwin int
106@s Pw_pixel_cache int
107@s Rect int
108@s Rectlist int
109@s Rectnode int
110@s Screen_attr int
111@s Screen_attribute int
112@s Scroll_motion int
113@s Scrollable_panel int
114@s Scrollbar int
115@s Scrollbar_attr int
116@s Scrollbar_attribute int
117@s Scrollbar_motion int
118@s Scrollbar_setting int
119@s Sel_cmpat_info int
120@s Sel_prop_info int
121@s Selection int
122@s Selection_attr int
123@s Selection_attribute int
124@s Selection_item int
125@s Selection_owner int
126@s Selection_requestor int
127@s Seln_access int
128@s Seln_attribute int
129@s Seln_client int
130@s Seln_file_info int
131@s Seln_function int
132@s Seln_function_buffer int
133@s Seln_functions_state int
134@s Seln_holder int
135@s Seln_holders_all int
136@s Seln_inform_args int
137@s Seln_level int
138@s Seln_rank int
139@s Seln_replier_data int
140@s Seln_request int
141@s Seln_requester int
142@s Seln_response int
143@s Seln_result int
144@s Seln_state int
145@s Server_attr int
146@s Server_attribute int
147@s Server_image int
148@s Server_image_attribute int
149@s Termsw int
150@s Termsw_attribute int
151@s Termsw_mode int
152@s Termsw_view int
153@s Text int
154@s Textsw int
155@s Textsw_action int
156@s Textsw_attribute int
157@s Textsw_enum int
158@s Textsw_expand_status int
159@s Textsw_filter_attribute int
160@s Textsw_filter_command int
161@s Textsw_index int
162@s Textsw_mark int
163@s Textsw_menu_cmd int
164@s Textsw_opaque int
165@s Textsw_status int
166@s Textsw_view int
167@s Tty int
168@s Tty_attribute int
169@s Tty_view int
170@s Ttysubwindow int
171@s Vuid_addr_probe int
172@s Vuid_device int
173@s WM_Direction int
174@s Win_enum_node int
175@s Win_enum_result int
176@s Win_tree_layer int
177@s Window_attr int
178@s Window_attribute int
179@s Window_handle int
180@s Window_input_event int
181@s Window_layout_op int
182@s Window_rescale_rect_obj int
183@s Window_rescale_state int
184@s Window_type int
185@s Ws_scale int
186@s Ws_scale_list int
187@s Xv_Color_info int
188@s Xv_Cursor int
189@s Xv_Drawable int
190@s Xv_Font int
191@s Xv_Notice int
192@s Xv_Screen int
193@s Xv_Server int
194@s Xv_Window int
195@s Xv_attr int
196@s Xv_attribute int
197@s Xv_base int
198@s Xv_canvas int
199@s Xv_canvas_pw int
200@s Xv_canvas_view int
201@s Xv_cms_struct int
202@s Xv_cmsdata int
203@s Xv_cursor int
204@s Xv_cursor_struct int
205@s Xv_dnd_struct int
206@s Xv_drag_drop int
207@s Xv_drawable int
208@s Xv_drawable_struct int
209@s Xv_drop_site int
210@s Xv_drop_site_struct int
211@s Xv_embedding int
212@s Xv_focus_rank int
213@s Xv_font int
214@s Xv_font_struct int
215@s Xv_frame_base int
216@s Xv_frame_class int
217@s Xv_frame_cmd int
218@s Xv_frame_help int
219@s Xv_frame_props int
220@s Xv_fullscreen int
221@s Xv_generic_attr int
222@s Xv_generic_attribute int
223@s Xv_generic_struct int
224@s Xv_icon int
225@s Xv_icon_header_info int
226@s Xv_item int
227@s Xv_menu int
228@s Xv_menu_item int
229@s Xv_Notice int
230@s Xv_notice int
231@s Xv_notice_struct int
232@s Xv_object int
233@s Xv_opaque int
234@s Xv_openwin int
235@s Xv_panel int
236@s Xv_panel_ambtn int
237@s Xv_panel_button int
238@s Xv_panel_choice int
239@s Xv_panel_drop int
240@s Xv_panel_extension_item int
241@s Xv_panel_gauge int
242@s Xv_panel_list int
243@s Xv_panel_message int
244@s Xv_panel_multiline_text int
245@s Xv_panel_num_text int
246@s Xv_panel_or_item int
247@s Xv_panel_slider int
248@s Xv_panel_text int
249@s Xv_panel_view int
250@s Xv_pkg int
251@s Xv_Screen int
252@s Xv_screen int
253@s Xv_screen_struct int
254@s Xv_scrollbar int
255@s Xv_sel int
256@s Xv_sel_item int
257@s Xv_sel_owner int
258@s Xv_sel_requestor int
259@s Xv_Server int
260@s Xv_server int
261@s Xv_server_image int
262@s Xv_server_struct int
263@s Xv_singlecolor int
264@s Xv_termsw int
265@s Xv_termsw_view int
266@s Xv_textsw int
267@s Xv_textsw_view int
268@s Xv_tty int
269@s Xv_tty_view int
270@s Xv_window int
271@s Xv_window_struct int
272@s Xv_xrectlist int
273@s icon_header_handle int
274@s icon_header_object int
makefile.bs+60−0
@@ -0,0 +1,60 @@
1# Makefile for CTANGLE and CWEAVE, pc/big versions, using
2# Borland C++ 3.1 and Borland Make.
3#
4# (This file contributed by Barry Schwartz, trashman@crud.mn.org,
5# 24 Jul 94.)
6
7
8
9CC = bcc
10
11# Redundant Load Suppression (-Z) is turned off, because it seems to
12# break the code. Likewise for Copy Propagation (-Op). (These
13# optimizations don't seem to cause any problems in common.w, but
14# better safe than sorry--compile everything with them turned off.)
15OPT = -O2-p -Z-
16
17# Compile with symbols. That way you'll be able to use the debugger if
18# you run into trouble. You can always use tdstrip later, to remove the
19# symbols.
20DEBUG = -v
21
22LCFLAGS = -mc -Ff=5000 -d -w-pro $(DEBUG)
23CFLAGS = $(LCFLAGS) $(OPT)
24COMPILE = $(CC) $(CFLAGS)
25
26LINK = $(CC) $(LCFLAGS) -e
27
28
29
30# Where to find an "old" version of ctangle, for bootstrapping. The first
31# time you make ctangle, you may have to edit the distributed ctangle.c
32# and/or common.c by hand to reduce the size of one or more arrays.
33# This will give you a functional ctangle.exe, which you can use to bootstrap
34# the "real" ctangle.exe.
35CTANGLE = ctangle
36
37
38
39
40all default: ctangle.exe cweave.exe
41
42
43ctangle.exe: ctangle.obj common.obj
44 $(LINK)$* $**
45
46cweave.exe: cweave.obj common.obj
47 $(LINK)$* $**
48
49
50common.obj: common.w comm-bs.ch
51 $(CTANGLE) common.w comm-bs.ch
52 $(COMPILE) -c common.c
53
54ctangle.obj: ctangle.w common.h ctang-bs.ch
55 $(CTANGLE) ctangle.w ctang-bs.ch
56 $(COMPILE) -c ctangle.c
57
58cweave.obj: cweave.w common.h cweav-bs.ch
59 $(CTANGLE) cweave.w cweav-bs.ch
60 $(COMPILE) -c cweave.c
prod.w+265−0
@@ -0,0 +1,265 @@
1% This file is part of CWEB.
2% This program by Silvio Levy and Donald E. Knuth
3% is based on a program by Knuth.
4% It is distributed WITHOUT ANY WARRANTY, express or implied.
5% Version 3.0 --- June 1993
6%
7@
8\def\v{\char'174}
9\mathchardef\RA="3221 % right arrow
10\mathchardef\BA="3224 % double arrow
11Here is a table of all the productions. Each production that
12combines two or more consecutive scraps implicitly inserts a {\tt \$}
13where necessary, that is, between scraps whose abutting boundaries
14have different |mathness|. In this way we never get double {\tt\$\$}.
15
16A translation is provided when the resulting scrap is not merely a
17juxtaposition of the scraps it comes from. An asterisk$^*$ next to a scrap
18means that its first identifier gets an underlined entry in the index,
19via the function |make_underlined|. Two asterisks$^{**}$ means that both
20|make_underlined| and |make_reserved| are called; that is, the
21identifier's ilk becomes |raw_int|. A dagger \dag\ before the
22production number refers to the notes at the end of this section,
23which deal with various exceptional cases.
24
25We use \\{in}, \\{out}, \\{back} and
26\\{bsp} as shorthands for |indent|, |outdent|, |backup| and
27|break_space|, respectively.
28
29\begingroup \lineskip=4pt
30\def\alt #1 #2
31{$\displaystyle\Bigl\{\!\matrix{\strut\hbox{#1}\cr
32 \strut\hbox{#2}\cr}\!\Bigr\}$ }
33\def\altt #1 #2 #3
34{$\displaystyle\Biggl\{\!\matrix{\strut\hbox{#1}\cr\hbox{#2}\cr
35 \strut\hbox{#3}\cr}\!\Biggr\}$ }
36\def\malt #1 #2
37{$\displaystyle\matrix{\strut\hbox{#1}\hfill\cr\strut\hbox{#2}\hfill\cr}$}
38\def\maltt #1 #2 #3
39{$\displaystyle\matrix{\strut\hbox{#1}\hfill\cr\hbox{#2}\hfill\cr
40 \strut\hbox{#3}\hfill\cr}$}
41\yskip\newcount\prodno\prodno=0
42\newdimen\midcol \midcol=2.5in
43\def\theprodno{\number\prodno \global\advance\prodno by1\enspace}
44\def\+#1&#2&#3&#4\cr{\def\next{#1}%
45 \line{\hbox to 2em{\hss
46 \ifx\next\empty\theprodno\else\next\fi}\strut
47 \ignorespaces#2\hfil\hbox to\midcol{$\RA$
48 \ignorespaces#3\hfil}\quad \hbox to1.45in{\ignorespaces#4\hfil}}}
49\+\relax & LHS & RHS \hfill Translation & Example\cr
50\yskip
51\+& \altt\\{any} {\\{any} \\{any}} {\\{any} \\{any} \\{any}}
52|insert| & \altt\\{any} {\\{any} \\{any}} {\\{any} \\{any} \\{any}}
53& stmt; \ /$\ast\,$comment$\,*$/\cr
54\+& |exp| \altt|lbrace| |int_like| |decl|
55 & |fn_decl| \altt|lbrace| |int_like| |decl|
56 \hfill $F=E^*\,|in|\,|in|$ & \malt {\\{main}()$\{$}
57 {\\{main}$(\\{ac},\\{av})$ \&{int} \\{ac};} \cr
58\+& |exp| |unop| & |exp| & |x++|\cr
59\+& |exp| \alt |binop| |unorbinop| |exp| & |exp| & \malt {|x/y|} {|x+y|} \cr
60\+& |exp| |comma| |exp| & |exp| \hfill $EC\,|opt|9\,E$& |f(x,y)|\cr
61\+& |exp| \alt |exp| |cast| & |exp| & |time()|\cr
62\+& |exp| |semi| & |stmt| & |x=0;|\cr
63\+& |exp| |colon| & |tag| \hfill $E^*C$ & |found:|\cr
64\+& |exp| |base| |int_like| |comma| & |base| \hfill $B\.\ IC$\,|opt|9
65 & \&D : \&C,\cr
66\+& |exp| |base| |int_like| |lbrace| & |exp| |lbrace| \hfill
67 $E=E\.\ B\.\ I$ & \&D : \&C $\{$\cr
68\+& |exp| |rbrace| & |stmt| |rbrace| & end of \&{enum} list\cr
69\+& |lpar| \alt |exp| |unorbinop| |rpar| & |exp| & \malt{|(x)|} {|(*)|} \cr
70\+& |lpar| |rpar| & |exp| \hfill $L\.{\\,}R$ & functions, declarations\cr
71\+& |lpar| \alt |decl_head| |int_like| |rpar| & |cast| & |(char*)|\cr
72\+& |lpar| \altt |decl_head| |int_like| |exp| |comma| & |lpar| \hfill
73 L\,\altt $D$ $I$ $E$ C\,|opt|9 & |(int,|\cr
74\+& |lpar| \alt |stmt| |decl| & |lpar| \hfill \alt {$LS\.\ $} {$LD\.\ $} &
75 \alt {|(k=5;|} {|(int k=5;|} \cr
76\+& |question| |exp| |colon| & |binop| & |?x:|\cr
77\+& |unop| \alt |exp| |int_like| & \alt |exp| |int_like| &
78 \malt |!x| |~|\&C \cr
79\+& |unorbinop| \alt|exp| |int_like| & \alt|exp| |int_like| \hfill
80 $\.\{U\.\}E$ & |*x|\cr
81\+& |unorbinop| |binop| & |binop| \hfill $|math_rel|\,U\.\{B\.\}\.\}$ & |*=|\cr
82\+& |binop| |binop| & |binop| \hfill
83 $|math_rel|\,\.\{B_1\.\}\.\{B_2\.\}\.\}$ & |>>=|\cr
84\+& |cast| |exp| & |exp| \hfill $C\.\ E$ & |(double)x|\cr
85\+& |cast| |semi| & |exp| |semi| & |(int);|\cr
86\+& |sizeof_like| |cast| & |exp| & |sizeof (double)|\cr
87\+& |sizeof_like| |exp| & |exp| \hfill $S\.\ E$ & |sizeof x|\cr
88\+& |int_like| \alt|int_like| |struct_like| &
89 \alt|int_like| |struct_like| \hfill $I\.\ $\alt $I$ $S$
90 \unskip& |extern char|\cr
91\+& |int_like| |exp| \alt|raw_int| |struct_like| &
92 |int_like| \alt|int_like| |struct_like| & |extern "Ada" int|\cr
93\+& |int_like| \altt|exp| |unorbinop| |semi| & |decl_head|
94 \altt|exp| |unorbinop| |semi| \hfill
95 $D=I$\altt{\.\ } {\.\ } {} \unskip & |int x|\cr
96\+& |int_like| |colon| & |decl_head| |colon| \hfill $D=I\.\ $ & |unsigned:|\cr
97\+& |int_like| |prelangle| & |int_like| |langle| & \&C$\langle$\cr
98\+& |int_like| |colcol| \alt |exp| |int_like| & \alt |exp| |int_like| &
99 \malt {\&C\DC$x$} {\&C\DC\&B} \cr
100\+& |int_like| |cast| |lbrace| & |fn_decl| |lbrace| \hfill $IC\,|in|\,|in|$&
101 \&C$\langle\&{void}\ast\rangle\{$\cr
102\+& |int_like| |cast| & |int_like| & \&C$\langle\&{class}\ \&T\rangle$\cr
103\+& |decl_head| |comma| & |decl_head| \hfill $DC\.\ $ & |int x,|\cr
104\+& |decl_head| |unorbinop| & |decl_head| \hfill $D\.\{U\.\}$ & |int *|\cr
105\+\dag\theprodno& |decl_head| |exp| & |decl_head| \hfill $DE^*$ & |int x|\cr
106\+& |decl_head| \alt|binop| |colon| |exp| \altt|comma| |semi| |rpar| &
107 |decl_head| \altt|comma| |semi| |rpar| \hfill
108 $D=D$\alt $B$ $C$ \unskip$E$ & \maltt initialization {fields or}
109 {default argument} \cr
110\+& |decl_head| |cast| & |decl_head| & |int f(int)|\cr
111\+\dag\theprodno& |decl_head| \altt|int_like| |lbrace| |decl| & |fn_decl|
112 \altt|int_like| |lbrace| |decl| \hfill $F=D\,|in|\,|in|$
113 & |long time () {|\cr
114\+& |decl_head| |semi| & |decl| & |int n;|\cr
115\+& |decl| |decl| & |decl| \hfill $D\,|force|\,D$ & |int n;double x;|\cr
116\+& |decl| \alt|stmt| |function| & \alt|stmt| |function|
117 \hfill $D\,|big_force|\,$\alt $S$ $F$ \unskip& \&{extern} $n$;
118 \\{main} ()|{}|\cr
119\+\dag\theprodno& |typedef_like| |decl_head| \alt|exp| |int_like| &
120 |typedef_like| |decl_head| \hfill $D=D$\alt $E^{**}$ $I^{**}$ \unskip &
121 \&{typedef} \&{char} \&{ch};\cr
122\+& |typedef_like| |decl_head| |semi| & |decl| \hfill $T\.\ D$ &
123 \&{typedef} \&{int} $\&x,\&y$;\cr
124\+& |struct_like| |lbrace| & |struct_head| \hfill $S\.\ L$ & |struct {|\cr
125\+& |struct_like| \alt|exp| |int_like| |semi| & |decl_head|
126 \hfill $S\.\ $\alt $E^{**}$ $I^{**}$ & \&{struct} \&{forward};\cr
127\+& |struct_like| \alt|exp| |int_like| |lbrace| & |struct_head| \hfill
128 $S\.\ $\alt $E^{**}$ $I^{**}$ \unskip $\.\ L$ &
129 \&{struct} \&{name\_info} $\{$\cr
130\+& |struct_like| \alt|exp| |int_like| |colon| &
131 |struct_like| \alt|exp| |int_like| |base| & |class| \&C :\cr
132\+\dag\theprodno& |struct_like| \alt|exp| |int_like| & |int_like|
133 \hfill $S\.\ $\alt$E$ $I$ & \&{struct} \&{name\_info} $z$;\cr
134\+& |struct_head| \altt|decl| |stmt| |function| |rbrace| & |int_like|\hfill
135 $S\,\\{in}\,|force|\,D\,\\{out}\,|force|\,R$ &
136 |struct {| declaration |}|\cr
137\+& |struct_head| |rbrace| & |int_like|\hfill $S\.{\\,}R$ & |class C{}|\cr
138\+& |fn_decl| |decl| & |fn_decl| \hfill $F\,|force|\,D$
139 & $f(z)$ \&{double} $z$; \cr
140\+& |fn_decl| |stmt| & |function| \hfill $F\,|out|\,|out|\,|force|\,S$
141 & \\{main}() {\dots}\cr
142\+& |function| \altt|stmt| |decl| |function| & \altt |stmt| |decl| |function|
143 \hfill $F\,|big_force|\,$\altt $S$ $D$ $F$ & outer block\cr
144\+& |lbrace| |rbrace| & |stmt| \hfill $L\.{\\,}R$ & empty statement\cr
145\advance\midcol35pt
146\+& |lbrace| \altt|stmt| |decl| |function| |rbrace| & |stmt| \hfill
147 $|force|\,L\,\\{in}\,|force|\,S\,
148 |force|\,\\{back}\,R\,\\{out}\,|force|$ & compound statement\cr
149\advance\midcol-20pt
150\+& |lbrace| |exp| [|comma|] |rbrace| & |exp| & initializer\cr
151\+& |if_like| |exp| & |if_clause| \hfill $I\.{\ }E$ & |if (z)|\cr
152\+& |for_like| |exp| & |else_like| \hfill $F\.{\ }E$ & |while (1)|\cr
153\+& |else_like| |lbrace| & |else_head| |lbrace| & \&{else} $\{$\cr
154\+& |else_like| |stmt| & |stmt| \hfill
155 $|force|\,E\,\\{in}\,\\{bsp}\,S\,\\{out}\,|force|$ & |else x=0;|\cr
156\+& |else_head| \alt|stmt| |exp| & |stmt| \hfill
157 $|force|\,E\,\\{bsp}\,|noop|\,|cancel|\,S\,\\{bsp}$ & |else{x=0;}|\cr
158\+& |if_clause| |lbrace| & |if_head| |lbrace| & |if (x) {|\cr
159\+& |if_clause| |stmt| |else_like| |if_like| & |if_like| \hfill
160 $|force|\,I\,\\{in}\,\\{bsp}\,S\,\\{out}\,|force|\,E\,\.\ I$ &
161 |if (x) y; else if|\cr
162\+& |if_clause| |stmt| |else_like| & |else_like| \hfill
163 $|force|\,I\,\\{in}\,\\{bsp}\,S\,\\{out}\,|force|\,E$ &
164 |if (x) y; else|\cr
165\+& |if_clause| |stmt| & |else_like| |stmt| & |if (x)|\cr
166\+& |if_head| \alt|stmt| |exp| |else_like| |if_like| & |if_like| \hfill
167 $|force|\,I\,\\{bsp}\,|noop|\,|cancel|\,S\,|force|\,E\,\.\ I$ &
168 |if (x){y;}else if|\cr
169\+& |if_head| \alt|stmt| |exp| |else_like| & |else_like| \hfill
170 $|force|\,I\,\\{bsp}\,|noop|\,|cancel|\,S\,|force|\,E$ &
171 |if (x){y;}else|\cr
172\+& |if_head| \alt|stmt| |exp| & |else_head| \alt|stmt| |exp| & |if (x){y;}|\cr
173\advance\midcol20pt
174\+& |do_like| |stmt| |else_like| |semi| & |stmt| \hfill
175 $D\,\\{bsp}\,|noop|\,|cancel|\,S\,|cancel|\,|noop|\,\\{bsp}\,ES$%
176 & |do f(x); while (g(x));|\cr
177\advance\midcol-20pt
178\+& |case_like| |semi| & |stmt| & |return;|\cr
179\+& |case_like| |colon| & |tag| & |default:|\cr
180\+& |case_like| |exp| |semi| & |stmt| \hfill $C\.\ ES$ & |return 0;|\cr
181\+& |case_like| |exp| |colon| & |tag| \hfill $C\.\ EC$ & |case 0:|\cr
182\+& |tag| |tag| & |tag| \hfill $T_1\,\\{bsp}\,T_2$ & |case 0: case 1:|\cr
183\+& |tag| \altt|stmt| |decl| |function| & \altt|stmt| |decl| |function|
184 \hfill $|force|\,\\{back}\,T\,\\{bsp}\,S$ & |case 0: z=0;|\cr
185\+\dag\theprodno& |stmt| \altt|stmt| |decl| |function| &
186 \altt|stmt| |decl| |function|
187 \hfill $S\,$\altt$|force|\,S$ $|big_force|\,D$ $|big_force|\,F$ &
188 |x=1;y=2;|\cr
189\+& |semi| & |stmt| \hfill \.\ $S$& empty statement\cr
190\+\dag\theprodno& |lproc| \altt |if_like| |else_like| |define_like| & |lproc| &
191 \maltt {{\bf \#include}} {\bf\#else} {\bf\#define} \cr
192\+& |lproc| |rproc| & |insert| & {\bf\#endif} \cr
193\+& |lproc| \alt {|exp| [|exp|]} |function| |rproc| & |insert| \hfill
194 $I$\.\ \alt {$E{[\.{\ \\5}E]}$} {$F$} &
195 \malt{{\bf\#define} $a$\enspace 1} {{\bf\#define} $a$\enspace$\{\,b;\,\}$} \cr
196\+& |section_scrap| |semi| & |stmt|\hfill $MS$ |force|
197 &$\langle\,$section name$\,\rangle$;\cr
198\+& |section_scrap| & |exp| &$\langle\,$section name$\,\rangle$\cr
199\+& |insert| |any| & |any| & \.{\v\#include\v}\cr
200\+& |prelangle| & |binop| \hfill $<$ & $<$ not in template\cr
201\+& |prerangle| & |binop| \hfill $>$ & $>$ not in template\cr
202\+& |langle| |exp| |prerangle| & |cast| & $\langle\,0\,\rangle$\cr
203\+& |langle| |prerangle| & |cast| \hfill $L\.{\\,}P$ & $\langle\,\rangle$\cr
204\+& |langle| \alt|decl_head| |int_like| |prerangle| & |cast| &
205 $\langle\&{class}\,\&C\rangle$\cr
206\+& |langle| \alt|decl_head| |int_like| |comma| & |langle| \hfill
207 L\,\alt $D$ $I$ C\,|opt|9 & $\langle\&{class}\,\&C,$\cr
208\+& |public_like| |colon| & |tag| & \&{private}:\cr
209\+& |public_like| & |int_like| & \&{private}\cr
210\+& |colcol| \alt|exp| |int_like| & \alt|exp| |int_like| & |::x|\cr
211\+\dag\theprodno&
212 |new_like| \alt|exp| |raw_int| & |new_like| \hfill $N\.\ E$ & |new(1)|\cr
213\+& |new_like| \alt|raw_unorbin| |colcol| & |new_like| & |new ::*|\cr
214\+& |new_like| |cast| & |exp| & |new(*)|\cr
215\+\dag\theprodno& |new_like| & |exp| & |new|\cr
216\+\dag\theprodno& |operator_like| \altt|binop| |unop| |unorbinop| & |exp|
217 \hfill $O$\.\{\altt $B$ $U$ $U$\unskip \.\} & |operator+|\cr
218\+& |operator_like| \alt|new_like| |sizeof_like| & |exp| \hfill $O\.\ N$
219 & |operator delete|\cr
220\+& |operator_like| & |new_like| & conversion operator\cr
221\+& |catch_like| \alt|cast| |exp| & |fn_decl| \hfill $CE\,\\{in}\,\\{in}$ &
222 |catch (...)|\cr
223\+& |base| |public_like| |exp| |comma| & |base| \hfill $BP\.\ EC$ &
224 : \&{public} $a$,\cr
225\+& |base| |public_like| |exp| & |base| |int_like| \hfill $I=P\.\ E$ &
226 : \&{public} $a$\cr
227\+& |raw_rpar| |const_like| & |raw_rpar| \hfill $R\.\ C$ & ) \&{const};\cr
228\+& |raw_rpar| & |rpar| & );\cr
229\+& |raw_unorbin| |const_like| & |raw_unorbin| \hfill $RC$\.{\\\ }
230 & $*$\&{const} |x|\cr
231\+& |raw_unorbin| & |unorbinop| & $*$ |x|\cr
232\+& |const_like| & |int_like| & \&{const} |x|\cr
233\+& |raw_int| |lpar| & |exp| & \&{complex}$(x,y)$\cr
234\+& |raw_int| & |int_like| & \&{complex} |z|\cr
235\+& |begin_arg| |end_arg| & |exp| & \.{@@[}\&{char}$*$\.{@@]}\cr
236\+& |any_other| |end_arg| & |end_arg| & \&{char}$*$\.{@@]}\cr
237\yskip
238\yskip
239\yskip
240\parindent=0pt
241\dag{\bf Notes}
242\yskip
243Rule 35: The |exp| must not be immediately followed by |lpar| or~|exp|.
244
245Rule 38: The |int_like| must not be immediately followed by |colcol|.
246
247Rule 42: The |exp| must not be immediately followed by |lpar| or~|exp|.
248
249Rule 48: The |exp| or |int_like| must not be immediately followed by |base|.
250
251Rule 76: The |force| in the |stmt| line becomes \\{bsp} if \.{CWEAVE} has
252been invoked with the \.{-f} option.
253
254Rule 78: The |define_like| case calls |make_underlined| on the following scrap.
255
256Rule 93: The |raw_int| must not be immediately followed by
257|prelangle| or |langle|.
258
259Rule 96: The |new_like| must not be immediately followed by |lpar|,
260|raw_int|, or |struct_like|.
261
262Rule 97: The operator after |operator_like|
263must not be immediately followed by a |binop|.
264
265\endgroup

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t