Debian Codegraph @

texk/web2c/cwebdir/ctangle.w

raw
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 4.12.2 --- July 2025
6
7 % Copyright (C) 1987,1990,1993,2000 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 % Amendments to 'ctangle.w' resulting in this updated version were created
19 % by numerous collaborators over the course of many years.
20
21 % Please send comments, suggestions, etc. to tex-k@@tug.org.
22
23 % Here is TeX material that gets inserted after \input cwebmac
24 \def\hang{\hangindent 3em\indent\ignorespaces}
25 \def\pb{$\.|\ldots\.|$} % C brackets (|...|)
26 \def\v{\char'174} % vertical (|) in typewriter font
27 \mathchardef\RA="3221 % right arrow
28 \mathchardef\BA="3224 % double arrow
29
30 \def\title{CTANGLE (Version 4.12.2)}
31 \def\topofcontents{\null\vfill
32 \centerline{\titlefont The {\ttitlefont CTANGLE} processor}
33 \vskip 15pt
34 \centerline{(Version 4.12.2)}
35 \vfill}
36 \def\botofcontents{\vfill
37 \noindent
38 Copyright \copyright\ 1987, 1990, 1993, 2000 Silvio Levy and Donald E. Knuth
39 \bigskip\noindent
40 Permission is granted to make and distribute verbatim copies of this
41 document provided that the copyright notice and this permission notice
42 are preserved on all copies.
43
44 \smallskip\noindent
45 Permission is granted to copy and distribute modified versions of this
46 document under the conditions for verbatim copying, provided that the
47 entire resulting derived work is given a different name and distributed
48 under 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.
54 This is the \.{CTANGLE} program by Silvio Levy and Donald E. Knuth,
55 based on \.{TANGLE} by Knuth.
56 We are thankful to
57 Nelson Beebe, Hans-Hermann Bode (to whom the \CPLUSPLUS/ adaptation is due),
58 Klaus Guntermann, Norman Ramsey, Tomas Rokicki, Joachim Schnitter,
59 Joachim Schrod, Lee Wittenberg, and others who have contributed improvements.
60
61 The ``banner line'' defined here should be changed whenever \.{CTANGLE}
62 is modified.
63
64 @d banner "This is CTANGLE (Version 4.12.2)"
65
66 @c
67 @<Include files@>@/
68 @h
69 @<Common code for \.{CWEAVE} and \.{CTANGLE}@>@/
70 @<Typedef declarations@>@/
71 @<Private variables@>@/
72 @<Predeclaration of procedures@>
73
74 @ \.{CTANGLE} has a fairly straightforward outline. It operates in
75 two phases: First it reads the source file, saving the \CEE/ code in
76 compressed form; then it shuffles and outputs the code.
77
78 Please read the documentation for \.{COMMON}, the set of routines common
79 to \.{CTANGLE} and \.{CWEAVE}, before proceeding further.
80
81 @c
82 int main (
83 int ac,
84 char **av)
85 {
86 argc=ac; argv=av;
87 program=ctangle;
88 @<Set initial values@>@;
89 common_init();
90 if (show_banner) puts(banner); /* print a ``banner line'' */
91 phase_one(); /* read all the user's text and compress it into |tok_mem| */
92 phase_two(); /* output the contents of the compressed tables */
93 return wrap_up(); /* and exit gracefully */
94 }
95
96 @ The next few sections contain stuff from the file |"common.w"| that must
97 be included in both |"ctangle.w"| and |"cweave.w"|. It appears in
98 file |"common.h"|, which is also included in |"common.w"| to propagate
99 possible changes from this \.{COMMON} interface consistently.
100
101 @i common.h
102
103 @* Data structures exclusive to {\tt CTANGLE}.
104 We've already seen that the |byte_mem| array holds the names of identifiers,
105 strings, and sections;
106 the |tok_mem| array holds the replacement texts
107 for sections. Allocation is sequential, since things are deleted only
108 during Phase II, and only in a last-in-first-out manner.
109
110 A \&{text} variable is a structure containing a pointer into
111 |tok_mem|, which tells where the corresponding text starts, and an
112 integer |text_link|, which, as we shall see later, is used to connect
113 pieces of text that have the same name. All the \&{text}s are stored in
114 the array |text_info|, and we use a \&{text\_pointer} variable to refer
115 to them.
116
117 The first position of |tok_mem| that is unoccupied by
118 replacement text is called |tok_ptr|, and the first unused location of
119 |text_info| is called |text_ptr|. Thus we usually have the identity
120 |text_ptr->tok_start==tok_ptr|.
121
122 @<Typed...@>=
123 typedef struct {
124 eight_bits *tok_start; /* pointer into |tok_mem| */
125 sixteen_bits text_link; /* relates replacement texts */
126 } text;
127 typedef text *text_pointer;
128
129 @ @d max_texts 4000 /* number of replacement texts, must be less than 10240 */
130 @d max_toks 270000 /* number of bytes in compressed \CEE/ code */
131 @<Private...@>=
132 static text text_info[max_texts];
133 static text_pointer text_info_end=text_info+max_texts-1;
134 static text_pointer text_ptr; /* first unused position in |text_info| */
135 static eight_bits tok_mem[max_toks];
136 static eight_bits *tok_mem_end=tok_mem+max_toks-1;
137 static eight_bits *tok_ptr; /* first unused position in |tok_mem| */
138
139 @ @<Set init...@>=
140 text_info->tok_start=tok_ptr=tok_mem;
141 text_ptr=text_info+1; text_ptr->tok_start=tok_mem;
142 /* this makes replacement text 0 of length zero */
143
144 @ If |p| is a pointer to a section name, |p->equiv| is a pointer to its
145 replacement text, an element of the array |text_info|.
146
147 @d equiv equiv_or_xref /* info corresponding to names */
148
149 @ @<Set init...@>=
150 init_node(name_dir); /* the undefined section has no replacement text */
151
152 @ Here's the procedure that decides whether a name of length |l|
153 starting at position |first| equals the identifier pointed to by |p|:
154
155 @c
156 bool names_match(
157 name_pointer p, /* points to the proposed match */
158 const char *first, /* position of first character of string */
159 size_t l, /* length of identifier */
160 eight_bits t) /* not used by \.{CTANGLE} */
161 {@+(void)t;@/
162 return length(p)==l && strncmp(first,p->byte_start,l)==0;
163 }
164
165 @ The common lookup routine |id_lookup| refers to a separate routine
166 |init_node| when the data structure grows.
167
168 @c
169 void
170 init_node(
171 name_pointer node)
172 {
173 node->equiv=(void *)text_info;
174 }
175
176 @* Tokens.
177 Replacement texts, which represent \CEE/ code in a compressed format,
178 appear in |tok_mem| as mentioned above. The codes in
179 these texts are called `tokens'; some tokens occupy two consecutive
180 eight-bit byte positions, and the others take just one byte.
181
182 If $p$ points to a replacement text, |p->tok_start| is the |tok_mem| position
183 of the first eight-bit code of that text. If |p->text_link==0|,
184 this is the replacement text for a macro, otherwise it is the replacement
185 text for a section. In the latter case |p->text_link| is either equal to
186 |section_flag|, which means that there is no further text for this section, or
187 |p->text_link| points to a continuation of this replacement text; such
188 links are created when several sections have \CEE/ texts with the same
189 name, and they also tie together all the \CEE/ texts of unnamed sections.
190 The replacement text pointer for the first unnamed section appears in
191 |text_info->text_link|, and the most recent such pointer is |last_unnamed|.
192
193 @d macro 0
194 @d section_flag max_texts /* final |text_link| in section replacement texts */
195
196 @<Private...@>=
197 static text_pointer last_unnamed; /* most recent replacement text of unnamed section */
198
199 @ @<Set init...@>= last_unnamed=text_info; text_info->text_link=macro;
200
201 @ If the first byte of a token is less than |0200|, the token occupies a
202 single byte. Otherwise we make a sixteen-bit token by combining two consecutive
203 bytes |a| and |b|. If |0200<=a<0250|, then |(a-0200)@t${}\times2^8$@>+b|
204 points to an identifier; if |0250<=a<0320|, then
205 |(a-0250)@t${}\times2^8$@>+b| points to a section name
206 (or, if it has the special value |output_defs_flag|,
207 to the area where the preprocessor definitions are stored); and if
208 |0320<=a<0400|, then |(a-0320)@t${}\times2^8$@>+b| is the number of the section
209 in which the current replacement text appears.
210
211 Codes less than |0200| are 7-bit |char| codes that represent themselves.
212 Some of the 7-bit codes will not be present, however, so we can
213 use them for special purposes. The following symbolic names are used:
214
215 \yskip \hang |string| denotes the beginning or end of a string
216 or a verbatim construction.
217
218 \hang |constant| denotes a numerical constant.
219
220 \hang |join| denotes the concatenation of adjacent items with no space
221 or line breaks allowed between them (the \.{@@\&} operation of \.{CWEB}).
222 @^ASCII code dependencies@>
223
224 @d string 02 /* takes the place of ASCII \.{STX} */
225 @d constant 03 /* takes the place of ASCII \.{ETX} */
226 @d join 0177 /* takes the place of ASCII \.{DEL} */
227 @d output_defs_flag (2*024000-1) /* |024000==(0250-0200)*0400| */
228
229 @ The following procedure is used to enter a two-byte value into
230 |tok_mem| when a replacement text is being generated.
231
232 @c
233 static void
234 store_two_bytes(
235 sixteen_bits x)
236 {
237 if (tok_ptr+2>tok_mem_end) overflow("token");
238 *tok_ptr++=x>>8; /* store high byte */
239 *tok_ptr++=x&0377; /* store low byte */
240 }
241
242 @ @<Predecl...@>=@+static void store_two_bytes(sixteen_bits);
243
244 @** Stacks for output. The output process uses a stack to keep track
245 of what is going on at different ``levels'' as the sections are being
246 written out. Entries on this stack have four parts:
247
248 \yskip\hang |byte_field| is the |tok_mem| location from which the next
249 token on a particular level will be read;
250
251 \hang |name_field| points to the name corresponding to a particular level;
252
253 \hang |repl_field| points to the replacement text currently being read
254 at a particular level;
255
256 \hang |section_field| is the section number, or zero if this is a macro.
257
258 \yskip\noindent The current values of these four quantities are referred to
259 quite frequently, so they are stored in an extra slot at the very end of the
260 |stack| array. We call the current values |cur_byte|, |cur_name|, |cur_repl|,
261 and |cur_section|.
262
263 The global variable |stack_ptr| tells how many levels of output are
264 currently in progress. The end of all output occurs when the stack is
265 empty, i.e., when |stack_ptr==stack|.
266
267 @<Typed...@>=
268 typedef struct {
269 eight_bits *byte_field; /* present location within replacement text */
270 name_pointer name_field; /* |byte_start| index for text being output */
271 text_pointer repl_field; /* |tok_start| index for text being output */
272 sixteen_bits section_field; /* section number or zero if not a section */
273 } output_state;
274 typedef output_state *stack_pointer;
275
276 @ @d stack_size 50 /* number of simultaneous levels of macro expansion */
277 @d cur_state stack[stack_size+1] /* |cur_byte|, |cur_name|, |cur_repl|,
278 and |cur_section| */
279 @d cur_byte cur_state.byte_field /* location of next output byte in |tok_mem|*/
280 @d cur_name cur_state.name_field /* pointer to current name being expanded */
281 @d cur_repl cur_state.repl_field /* pointer to current replacement text */
282 @d cur_section cur_state.section_field /* current section number being expanded */
283 @d cur_end (cur_repl+1)->tok_start /* current ending location in |tok_mem| */
284
285 @<Private...@>=
286 static output_state stack[stack_size+2]; /* info for non-current levels */
287 static stack_pointer stack_end=stack+stack_size; /* end of |stack| */
288 static stack_pointer stack_ptr; /* first unused location in the output state stack */
289
290 @ To get the output process started, we will perform the following
291 initialization steps. We may assume that |text_info->text_link| is nonzero,
292 since it points to the \CEE/ text in the first unnamed section that generates
293 code; if there are no such sections, there is nothing to output, and an
294 error message will have been generated before we do any of the initialization.
295
296 @<Initialize the output stacks@>=
297 stack_ptr=stack+1; cur_name=name_dir;
298 cur_repl=text_info->text_link+text_info;
299 cur_byte=cur_repl->tok_start; cur_section=0;
300
301 @ Similar settings are used for secondary output files.
302
303 @<Initialize the secondary output@>=
304 stack_ptr=stack+1; cur_name=*an_output_file;
305 cur_repl=(text_pointer)cur_name->equiv;
306 cur_byte=cur_repl->tok_start;
307
308 @ When the replacement text for name |p| is to be inserted into the output,
309 the following subroutine is called to save the old level of output and get
310 the new one going.
311
312 We assume that the \CEE/ compiler can copy structures.
313 @^system dependencies@>
314
315 @c
316 static void
317 push_level( /* suspends the current level */
318 name_pointer p)
319 {
320 if (stack_ptr==stack_end) overflow("stack");
321 *stack_ptr=cur_state;
322 stack_ptr++;
323 if (p!=NULL) { /* |p==NULL| means we are in |output_defs| */
324 cur_name=p; cur_repl=(text_pointer)p->equiv;
325 cur_byte=cur_repl->tok_start; cur_section=0;
326 }
327 }
328
329
330 @ When we come to the end of a replacement text, the |pop_level| subroutine
331 does the right thing: It either moves to the continuation of this replacement
332 text or returns the state to the most recently stacked level.
333
334 @c
335 static void
336 pop_level( /* do this when |cur_byte| reaches |cur_end| */
337 bool flag) /* |flag==false| means we are in |output_defs| */
338 {
339 if (flag && cur_repl->text_link<section_flag) { /* link to a continuation */
340 cur_repl=cur_repl->text_link+text_info; /* stay on the same level */
341 cur_byte=cur_repl->tok_start; return;
342 }
343 stack_ptr--; /* go down to the previous level */
344 if (stack_ptr>stack) cur_state=*stack_ptr;@^system dependencies@>
345 }
346
347 @ @<Predecl...@>=
348 static void push_level(name_pointer);@/
349 static void pop_level(bool);@/
350 static void get_output(void);
351
352 @ The heart of the output procedure is the function |get_output|,
353 which produces the next token of output and sends it on to the lower-level
354 function |out_char|. The main purpose of |get_output| is to handle the
355 necessary stacking and unstacking. It sends the value |section_number|
356 if the next output begins or ends the replacement text of some section,
357 in which case |cur_val| is that section's number (if beginning) or the
358 negative of that value (if ending). (A section number of 0 indicates
359 not the beginning or ending of a section, but a \#\&{line} command.)
360 And it sends the value |identifier|
361 if the next output is an identifier, in which case
362 |cur_val| points to that identifier name.
363
364 @d section_number 0201 /* code returned by |get_output| for section numbers */
365 @d identifier 0202 /* code returned by |get_output| for identifiers */
366
367 @<Private...@>=
368 static int cur_val; /* additional information corresponding to output token */
369
370 @ If |get_output| finds that no more output remains, it returns with
371 |stack_ptr==stack|.
372 @^high-bit character handling@>
373
374 @c
375 static void
376 get_output(void) /* sends next token to |out_char| */
377 {
378 sixteen_bits a; /* value of current byte */
379 restart: if (stack_ptr==stack) return;
380 if (cur_byte==cur_end) {
381 cur_val=-((int)cur_section); /* cast needed because of sign extension */
382 pop_level(true);
383 if (cur_val==0) goto restart;
384 out_char(section_number); return;
385 }
386 a=*cur_byte++;
387 if (out_state==verbatim && a!=string && a!=constant && a!='\n')
388 C_putc(a); /* a high-bit character can occur in a string */
389 else if (a<0200) out_char(a); /* one-byte token */
390 else {
391 a=(a-0200)*0400+*cur_byte++;
392 switch (a/024000) { /* |024000==(0250-0200)*0400| */
393 case 0: cur_val=(int)a; out_char(identifier); break;
394 case 1: if (a==output_defs_flag) output_defs();
395 else @<Expand section |a-024000|, |goto restart|@>@;
396 break;
397 default: cur_val=(int)a-050000;
398 if (cur_val>0) cur_section=(sixteen_bits)cur_val;
399 out_char(section_number);
400 }
401 }
402 }
403
404 @ The user may have forgotten to give any \CEE/ text for a section name,
405 or the \CEE/ text may have been associated with a different name by mistake.
406
407 @<Expand section |a-...@>=
408 {
409 a-=024000;
410 if ((a+name_dir)->equiv!=(void *)text_info) push_level(a+name_dir);
411 else if (a!=0) {
412 printf("%s","\n! Not present: <");
413 print_section_name(a+name_dir); err_print(">");
414 @.Not present: <section name>@>
415 }
416 goto restart;
417 }
418
419 @* Producing the output.
420 The |get_output| routine above handles most of the complexity of output
421 generation, but there are two further considerations that have a nontrivial
422 effect on \.{CTANGLE}'s algorithms.
423
424 @ First,
425 we want to make sure that the output has spaces and line breaks in
426 the right places (e.g., not in the middle of a string or a constant or an
427 identifier, not at a `\.{@@\&}' position
428 where quantities are being joined together, and certainly after an \.=
429 because the \CEE/ compiler thinks \.{=-} is ambiguous).
430
431 The output process can be in one of following states:
432
433 \yskip\hang |num_or_id| means that the last item in the buffer is a number or
434 identifier, hence a blank space or line break must be inserted if the next
435 item is also a number or identifier.
436
437 \yskip\hang |unbreakable| means that the last item in the buffer was followed
438 by the \.{@@\&} operation that inhibits spaces between it and the next item.
439
440 \yskip\hang |verbatim| means we're copying only character tokens, and
441 that they are to be output exactly as stored. This is the case during
442 strings, verbatim constructions and numerical constants.
443
444 \yskip\hang |post_slash| means we've just output a slash.
445
446 \yskip\hang |normal| means none of the above.
447
448 \yskip\noindent Furthermore, if the variable |protect| is |true|, newlines
449 are preceded by a `\.\\'.
450
451 @d normal 0 /* non-unusual state */
452 @d num_or_id 1 /* state associated with numbers and identifiers */
453 @d post_slash 2 /* state following a \./ */
454 @d unbreakable 3 /* state associated with \.{@@\&} */
455 @d verbatim 4 /* state in the middle of a string */
456
457 @<Private...@>=
458 static eight_bits out_state; /* current status of partial output */
459 static bool protect; /* should newline characters be quoted? */
460
461 @ Here is a routine that is invoked when we want to output the current line.
462 During the output process, |cur_line| equals the number of the next line
463 to be output.
464
465 @c
466 static void
467 flush_buffer(void) /* writes one line to output file */
468 {
469 C_putc('\n');
470 if (cur_line % 100 == 0 && show_progress) {
471 putchar('.');
472 if (cur_line % 500 == 0) printf("%d",cur_line);
473 update_terminal(); /* progress report */
474 }
475 cur_line++;
476 }
477
478 @ @<Predecl...@>=@+static void flush_buffer(void);
479
480 @ Second, we have modified the original \.{TANGLE} so that it will write output
481 on multiple files.
482 If a section name is introduced in at least one place by \.{@@(}
483 instead of \.{@@<}, we treat it as the name of a file.
484 All these special sections are saved on a stack, |output_files|.
485 We write them out after we've done the unnamed section.
486
487 @d max_files 256
488 @<Private...@>=
489 static name_pointer output_files[max_files];
490 static name_pointer *cur_out_file, *end_output_files, *an_output_file;
491 static char cur_section_name_char; /* is it |'<'| or |'('| */
492 static char output_file_name[longest_name+1]; /* name of the file */
493
494 @ We make |end_output_files| point just beyond the end of
495 |output_files|. The stack pointer
496 |cur_out_file| starts out there. Every time we see a new file, we
497 decrement |cur_out_file| and then write it in.
498 @<Set initial...@>=
499 cur_out_file=end_output_files=output_files+max_files;
500
501 @ @<If it's not there, add |cur_section_name| to the output file stack, or
502 complain we're out of room@>=
503 {
504 for (an_output_file=cur_out_file;
505 an_output_file<end_output_files; an_output_file++)
506 if (*an_output_file==cur_section_name) break;
507 if (an_output_file==end_output_files) {
508 if (cur_out_file>output_files)
509 *--cur_out_file=cur_section_name;
510 else overflow("output files");
511 }
512 }
513
514 @* The big output switch. Here then is the routine that does the
515 output.
516
517 @c
518 static void
519 phase_two (void) {
520 phase=2;
521 web_file_open=false;
522 cur_line=1;
523 @<Initialize the output stacks@>@;
524 @<Output macro definitions if appropriate@>@;
525 if (text_info->text_link==macro && cur_out_file==end_output_files) {
526 printf("%s","\n! No program text was specified."); mark_harmless();
527 @.No program text...@>
528 }
529 else {
530 if (show_progress) {
531 printf(cur_out_file==end_output_files ? @|
532 "\nWriting the output file (%s):" : @|
533 "\nWriting the output files: (%s)",C_file_name);
534 @.Writing the output...@>
535 update_terminal();
536 }
537 if (text_info->text_link!=macro)
538 @<Output material...@>@;
539 @<Write all the named output files@>@;
540 if (show_happiness) {
541 if (show_progress) new_line();
542 printf("%s","Done.");
543 }
544 }
545 }
546
547 @ @<Predecl...@>=
548 static void phase_two(void);@/
549 static void output_defs(void);@/
550 static void out_char(eight_bits);
551
552 @ To write the named output files, we proceed as for the unnamed
553 section.
554 The only subtlety is that we have to open each one.
555
556 @<Write all the named output files@>=
557 for (an_output_file=end_output_files; an_output_file>cur_out_file;) {
558 an_output_file--;
559 sprint_section_name(output_file_name,*an_output_file);
560 fclose(C_file);
561 if ((C_file=fopen(output_file_name,"wb"))==NULL)
562 fatal("! Cannot open output file ",output_file_name);
563 @.Cannot open output file@>
564 if (show_progress) { printf("\n(%s)",output_file_name); update_terminal(); }
565 cur_line=1;
566 @<Initialize the secondary output@>@;
567 @<Output material...@>@;
568 }
569
570 @ @<Output material from |stack|@>=
571 {
572 while (stack_ptr>stack) get_output();
573 flush_buffer();
574 }
575
576 @ If a \.{@@h} was not encountered in the input,
577 we go through the list of replacement texts and copy the ones
578 that refer to macros, preceded by the \.{\#define} preprocessor command.
579
580 @<Output macro definitions if appropriate@>=
581 if (!output_defs_seen)
582 output_defs();
583
584 @ @<Private...@>=
585 static bool output_defs_seen=false;
586
587 @ @d C_printf(c,a) fprintf(C_file,c,a)
588 @d C_putc(c) fputc((int)(c),C_file) /* isn't \CEE/ wonderfully consistent? */
589
590 @c
591 static void
592 output_defs(void)
593 {
594 sixteen_bits a; eight_bits *macro_end;
595 push_level(NULL);
596 for (cur_text=text_info+1; cur_text<text_ptr; cur_text++)
597 if (cur_text->text_link==macro) { /* |cur_text| is the text for a |macro| */
598 cur_byte=cur_text->tok_start;
599 macro_end=(cur_text+1)->tok_start; /* end of |macro| replacement text */
600 C_printf("%s","#define ");
601 out_state=normal;
602 protect=true; /* newlines should be preceded by |'\\'| */
603 do macro_end--; while (isspace(*macro_end)&&plus_plus!=*macro_end);
604 /* discard trailing whitespace; |plus_plus=='\v'| */
605 while (cur_byte<=macro_end) {
606 a=*cur_byte++;
607 if (out_state==verbatim && a!=string && a!=constant && a!='\n')
608 C_putc(a); /* a high-bit character can occur in a string */
609 @^high-bit character handling@>
610 else if (a<0200) out_char(a); /* one-byte token */
611 else {
612 a=(a-0200)*0400+*cur_byte++;
613 if (a<024000) { /* |024000==(0250-0200)*0400| */
614 cur_val=(int)a; out_char(identifier);
615 }
616 else if (a<050000) confusion("macro defs have strange char");
617 else {
618 cur_val=(int)a-050000; cur_section=(sixteen_bits)cur_val;
619 out_char(section_number);
620 }
621 /* no other cases */
622 }
623 }
624 protect=false;
625 flush_buffer();
626 }
627 pop_level(false);
628 }
629
630 @ A many-way switch is used to send the output. Note that this function
631 is not called if |out_state==verbatim|, except perhaps with arguments
632 |'\n'| (protect the newline), |string| (end the string), or |constant|
633 (end the constant).
634
635 @c
636 static void
637 out_char(
638 eight_bits cur_char)
639 {
640 char *j; /* pointer into |byte_mem| */
641 restart:
642 switch (cur_char) {
643 case '\n': if (protect && out_state!=verbatim) C_putc(' ');
644 if (protect || out_state==verbatim) C_putc('\\');
645 flush_buffer(); if (out_state!=verbatim) out_state=normal; break;
646 @/@t\4@>@<Case of an identifier@>@;
647 @/@t\4@>@<Case of a section number@>@;
648 @/@t\4@>@<Cases like \.{!=}@>@;
649 case '=': case '>': C_putc(cur_char);@+C_putc(' ');
650 out_state=normal; break;
651 case join: out_state=unbreakable; break;
652 case constant: if (out_state==verbatim) {
653 out_state=num_or_id; break;
654 }
655 if(out_state==num_or_id) C_putc(' '); out_state=verbatim; break;
656 case string: if (out_state==verbatim) out_state=normal;
657 else out_state=verbatim; break;
658 case '/': C_putc('/'); out_state=post_slash; break;
659 case '*': if (out_state==post_slash) C_putc(' ');
660 @=/* fall through */@>@;
661 default: C_putc(cur_char); out_state=normal; break;
662 }
663 }
664
665 @ @<Cases like \.{!=}@>=@t\1\quad@>
666 case plus_plus: C_putc('+');@+C_putc('+'); out_state=normal; break;
667 case minus_minus: C_putc('-');@+C_putc('-'); out_state=normal; break;
668 case minus_gt: C_putc('-');@+C_putc('>'); out_state=normal; break;
669 case gt_gt: C_putc('>');@+C_putc('>'); out_state=normal; break;
670 case eq_eq: C_putc('=');@+C_putc('='); out_state=normal; break;
671 case lt_lt: C_putc('<');@+C_putc('<'); out_state=normal; break;
672 case gt_eq: C_putc('>');@+C_putc('='); out_state=normal; break;
673 case lt_eq: C_putc('<');@+C_putc('='); out_state=normal; break;
674 case non_eq: C_putc('!');@+C_putc('='); out_state=normal; break;
675 case and_and: C_putc('&');@+C_putc('&'); out_state=normal; break;
676 case or_or: C_putc('|');@+C_putc('|'); out_state=normal; break;
677 case dot_dot_dot: C_putc('.');@+C_putc('.');@+C_putc('.'); out_state=normal;
678 break;
679 case colon_colon: C_putc(':');@+C_putc(':'); out_state=normal; break;
680 case period_ast: C_putc('.');@+C_putc('*'); out_state=normal; break;
681 case minus_gt_ast: C_putc('-');@+C_putc('>');@+C_putc('*'); out_state=normal;
682 break;
683
684 @ When an identifier is output to the \CEE/ file, characters in the range
685 128--255 (|0200|--|0377|) must be changed into something else, so the \CEE/
686 compiler won't complain. By default, \.{CTANGLE} converts the
687 character with code $16 x+y$ to the three characters `\.X$xy$', but
688 a different transliteration table can be specified. Thus a German
689 might want {\it gr\"un\/} to appear as a still readable \.{gruen}.
690 This makes debugging a lot less confusing.
691
692 @d translit_length 10
693
694 @<Private...@>=
695 static char translit[0200][translit_length];
696
697 @ @<Set init...@>=
698 { int i;
699 for (i=0;i<0200;i++)
700 snprintf(translit[i],translit_length,"X%02X",(unsigned int)(0200+i));
701 }
702
703 @ @<Case of an identifier@>=@t\1\quad@>
704 case identifier:
705 if (out_state==num_or_id) C_putc(' ');
706 for (j=(cur_val+name_dir)->byte_start;
707 j<(cur_val+name_dir+1)->byte_start; j++)
708 if (ishigh(*j)) C_printf("%s",translit[(eight_bits)(*j)-0200]);
709 @^high-bit character handling@>
710 else C_putc(*j);
711 out_state=num_or_id; break;
712
713 @ @<Case of a sec...@>=@t\1\quad@>
714 case section_number:
715 if (cur_val>0) C_printf("/*%d:*/",cur_val);
716 else if(cur_val<0) C_printf("/*:%d*/",-cur_val);
717 else if (protect) {
718 cur_byte +=4; /* skip line number and file name */
719 cur_char = (eight_bits)'\n';
720 goto restart;
721 } else {
722 sixteen_bits a;
723 a=*cur_byte++ *0400;
724 a+=*cur_byte++; /* gets the line number */
725 C_printf("\n#line %d \"",(int)a);
726 @:line}{\.{\#line}@>
727 cur_val=(int)(*cur_byte++-0200)*0400;
728 cur_val+=*cur_byte++; /* points to the file name */
729 for (j=(cur_val+name_dir)->byte_start;
730 j<(cur_val+name_dir+1)->byte_start; j++) {
731 if (*j=='\\' || *j=='"') C_putc('\\');
732 C_putc(*j);
733 }
734 C_putc('"');@+C_putc('\n');
735 }
736 break;
737
738 @** Introduction to the input phase.
739 We have now seen that \.{CTANGLE} will be able to output the full
740 \CEE/ program, if we can only get that program into the byte memory in
741 the proper format. The input process is something like the output process
742 in reverse, since we compress the text as we read it in and we expand it
743 as we write it out.
744
745 There are three main input routines. The most interesting is the one that gets
746 the next token of a \CEE/ text; the other two are used to scan rapidly past
747 \TEX/ text in the \.{CWEB} source code. One of the latter routines will jump to
748 the next token that starts with `\.{@@}', and the other skips to the end
749 of a \CEE/ comment.
750
751 @ Control codes in \.{CWEB} begin with `\.{@@}', and the next character
752 identifies the code. Some of these are of interest only to \.{CWEAVE},
753 so \.{CTANGLE} ignores them; the others are converted by \.{CTANGLE} into
754 internal code numbers by the |ccode| table below. The ordering
755 of these internal code numbers has been chosen to simplify the program logic;
756 larger numbers are given to the control codes that denote more significant
757 milestones.
758
759 @d ignore 00 /* control code of no interest to \.{CTANGLE} */
760 @d ord 0302 /* control code for `\.{@@'}' */
761 @d control_text 0303 /* control code for `\.{@@t}', `\.{@@\^}', etc. */
762 @d translit_code 0304 /* control code for `\.{@@l}' */
763 @d output_defs_code 0305 /* control code for `\.{@@h}' */
764 @d format_code 0306 /* control code for `\.{@@f}' */
765 @d definition 0307 /* control code for `\.{@@d}' */
766 @d begin_C 0310 /* control code for `\.{@@c}' */
767 @d section_name 0311 /* control code for `\.{@@<}' */
768 @d new_section 0312 /* control code for `\.{@@\ }' and `\.{@@*}' */
769
770 @<Private...@>=
771 static eight_bits ccode[256]={ignore}; /* meaning of a char following \.{@@} */
772
773 @ @<Set ini...@>=
774 ccode[' ']=ccode['\t']=ccode['\n']=ccode['\v']=ccode['\r']=ccode['\f']
775 =ccode['*']=new_section;
776 ccode['@@']=(eight_bits)'@@'; ccode['=']=string;
777 ccode['d']=ccode['D']=definition;
778 ccode['f']=ccode['F']=ccode['s']=ccode['S']=format_code;
779 ccode['c']=ccode['C']=ccode['p']=ccode['P']=begin_C;
780 ccode['^']=ccode[':']=ccode['.']=ccode['t']=ccode['T']=
781 ccode['q']=ccode['Q']=control_text;
782 ccode['h']=ccode['H']=output_defs_code;
783 ccode['l']=ccode['L']=translit_code;
784 ccode['&']=join;
785 ccode['<']=ccode['(']=section_name;
786 ccode['\'']=ord;
787
788 @ The |skip_ahead| procedure reads through the input at fairly high speed
789 until finding the next non-ignorable control code, which it returns.
790
791 @c
792 static eight_bits
793 skip_ahead(void) /* skip to next control code */
794 {
795 eight_bits c; /* control code found */
796 while (true) {
797 if (loc>limit && (get_line()==false)) return new_section;
798 *(limit+1)='@@';
799 while (*loc!='@@') loc++;
800 if (loc<=limit) {
801 loc++; c=ccode[(eight_bits)*loc]; loc++;
802 if (c!=ignore || *(loc-1)=='>') return c;
803 }
804 }
805 }
806
807 @ @<Predecl...@>=
808 static eight_bits skip_ahead(void);@/
809 static bool skip_comment(bool);
810
811 @ The |skip_comment| procedure reads through the input at somewhat high
812 speed in order to pass over comments, which \.{CTANGLE} does not transmit
813 to the output. If the comment is introduced by \.{/*}, |skip_comment|
814 proceeds until finding the end-comment token \.{*/} or a newline; in the
815 latter case |skip_comment| will be called again by |get_next|, since the
816 comment is not finished. This is done so that each newline in the
817 \CEE/ part of a section is copied to the output; otherwise the \#\&{line}
818 commands inserted into the \CEE/ file by the output routines become useless.
819 On the other hand, if the comment is introduced by \.{//} (i.e., if it
820 is a \CPLUSPLUS/ ``short comment''), it always is simply delimited by the next
821 newline. The boolean argument |is_long_comment| distinguishes between
822 the two types of comments.
823
824 If |skip_comment| comes to the end of the section, it prints an error message.
825 No comment, long or short, is allowed to contain `\.{@@\ }' or `\.{@@*}'.
826
827 @<Private...@>=
828 static bool comment_continues=false; /* are we scanning a comment? */
829
830 @ @c
831 static bool skip_comment( /* skips over comments */
832 bool is_long_comment)
833 {
834 char c; /* current character */
835 while (true) {
836 if (loc>limit) {
837 if (is_long_comment) {
838 if (get_line()) return comment_continues=true;
839 else {
840 err_print("! Input ended in mid-comment");
841 @.Input ended in mid-comment@>
842 return comment_continues=false;
843 }
844 }
845 else return comment_continues=false;
846 }
847 c=*(loc++);
848 if (is_long_comment && c=='*' && *loc=='/') {
849 loc++; return comment_continues=false;
850 }
851 if (c=='@@') {
852 if (ccode[(eight_bits)*loc]==new_section) {
853 err_print("! Section name ended in mid-comment"); loc--;
854 @.Section name ended in mid-comment@>
855 return comment_continues=false;
856 }
857 else loc++;
858 }
859 }
860 }
861
862 @* Inputting the next token.
863
864 @<Private...@>=
865 static name_pointer cur_section_name; /* name of section just scanned */
866 static bool no_where; /* suppress |print_where|? */
867
868 @ As one might expect, |get_next| consists mostly of a big switch
869 that branches to the various special cases that can arise.
870
871 @c
872 static eight_bits
873 get_next(void) /* produces the next input token */
874 {
875 static bool preprocessing=false;
876 eight_bits c; /* the current character */
877 while (true) {
878 if (loc>limit) {
879 if (preprocessing && *(limit-1)!='\\') preprocessing=false;
880 if (get_line()==false) return new_section;
881 else if (print_where && !no_where) {
882 sixteen_bits a;
883 print_where=false;
884 @<Insert the line number into |tok_mem|@>@;
885 }
886 else return (eight_bits)'\n';
887 }
888 c=(eight_bits)*loc;
889 if (comment_continues || (c=='/' && (*(loc+1)=='*' || *(loc+1)=='/'))) {
890 if (skip_comment(comment_continues||*(loc+1)=='*')) return '\n';
891 /* scan to end of comment or newline */
892 else continue;
893 }
894 loc++;
895 if (xisdigit(c) || c=='.') @<Get a constant@>@;
896 else if (c=='\'' || c=='"'@|
897 || ((c=='L' || c=='u' || c=='U')&&(*loc=='\'' || *loc=='"'))@|
898 || ((c=='u' && *loc=='8')&&(*(loc+1)=='\'' || *(loc+1)=='"')))
899 @<Get a string@>@;
900 else if (isalpha((int)c) || isxalpha(c) || ishigh(c))
901 @<Get an identifier@>@;
902 else if (c=='@@') @<Get control code and possible section name@>@;
903 else if (xisspace(c)) {
904 if (!preprocessing || loc>limit) continue;
905 /* we don't want a blank after a final backslash */
906 else return (eight_bits)' ';
907 /* ignore spaces and tabs, unless |preprocessing| */
908 }
909 else if (c=='#' && loc==buffer+1) preprocessing=true;
910 mistake: @<Compress two-symbol operator@>@;
911 return c;
912 }
913 }
914
915 @ @<Predecl...@>=@+static eight_bits get_next(void);
916
917 @ The following code assigns values to the combinations \.{++},
918 \.{--}, \.{->}, \.{>=}, \.{<=}, \.{==}, \.{<<}, \.{>>}, \.{!=}, %\.{||}
919 \.{\v\v} and~\.{\&\&}, and to the \CPLUSPLUS/
920 combinations \.{...}, \.{::}, \.{.*} and \.{->*}.
921 The compound assignment operators (e.g., \.{+=}) are
922 treated as separate tokens.
923
924 @<Compress tw...@>=
925 switch(c) {
926 case '+': if (*loc=='+') compress(plus_plus); break;
927 case '-': if (*loc=='-') {@+compress(minus_minus);@+}
928 else if (*loc=='>') {
929 if (*(loc+1)=='*') {loc++;@+compress(minus_gt_ast);}
930 else compress(minus_gt);
931 } break;
932 case '.': if (*loc=='*') {@+compress(period_ast);@+}
933 else if (*loc=='.' && *(loc+1)=='.') {
934 loc++;@+compress(dot_dot_dot);
935 } break;
936 case ':': if (*loc==':') compress(colon_colon); break;
937 case '=': if (*loc=='=') compress(eq_eq); break;
938 case '>': if (*loc=='=') {@+compress(gt_eq);@+}
939 else if (*loc=='>') compress(gt_gt); break;
940 case '<': if (*loc=='=') {@+compress(lt_eq);@+}
941 else if (*loc=='<') compress(lt_lt); break;
942 case '&': if (*loc=='&') compress(and_and); break;
943 case '|': if (*loc=='|') compress(or_or); break;
944 case '!': if (*loc=='=') compress(non_eq); break;
945 }
946
947 @ @<Get an identifier@>= {
948 id_first=--loc;
949 do
950 ++loc;
951 while (isalpha((int)*loc) || isdigit((int)*loc) @|
952 || isxalpha(*loc) || ishigh(*loc));
953 id_loc=loc; return identifier;
954 }
955
956 @ @<Get a constant@>= {
957 bool hex_flag = false; /* are we reading a hexadecimal literal? */
958 id_first=loc-1;
959 if (*id_first=='.' && !xisdigit(*loc)) goto mistake; /* not a constant */
960 if (*id_first=='0') {
961 if (*loc=='x' || *loc=='X') { /* hex constant */
962 hex_flag = true;
963 loc++; while (xisxdigit(*loc) || *loc=='\'') loc++;
964 }
965 else if (*loc=='b' || *loc=='B') { /* binary constant */
966 loc++; while (*loc=='0' || *loc=='1' || *loc=='\'') loc++; goto found;
967 }
968 }
969 while (xisdigit(*loc) || *loc=='\'') loc++;
970 if (*loc=='.') {
971 loc++;
972 while ((hex_flag && xisxdigit(*loc)) || xisdigit(*loc) || *loc=='\'') loc++;
973 }
974 if (*loc=='e' || *loc=='E') { /* float constant */
975 if (*++loc=='+' || *loc=='-') loc++;
976 while (xisdigit(*loc) || *loc=='\'') loc++;
977 }
978 else if (hex_flag && (*loc=='p' || *loc=='P')) { /* hex float constant */
979 if (*++loc=='+' || *loc=='-') loc++;
980 while (xisxdigit(*loc) || *loc=='\'') loc++;
981 }
982 found: while (*loc=='u' || *loc=='U' || *loc=='l' || *loc=='L'
983 || *loc=='f' || *loc=='F') loc++;
984 id_loc=loc;
985 return constant;
986 }
987
988 @ \CEE/ strings and character constants, delimited by double and single
989 quotes, respectively, can contain newlines or instances of their own
990 delimiters if they are protected by a backslash. We follow this
991 convention, but do not allow the string to be longer than |longest_name|.
992
993 @<Get a string@>= {
994 char delim = (char)c; /* what started the string */
995 id_first = section_text+1;
996 id_loc = section_text; *++id_loc=delim;
997 if (delim=='L' || delim=='u' || delim=='U') { /* wide character constant */
998 if (delim=='u' && *loc=='8') *++id_loc=*loc++;
999 delim=*loc++; *++id_loc=delim;
1000 }
1001 while (true) {
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()==false) {
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=(eight_bits)*loc++)==delim) {
1015 if (++id_loc<=section_text_end) *id_loc=(char)c;
1016 break;
1017 }
1018 if (c=='\\') {
1019 if (loc>=limit) continue;
1020 if (++id_loc<=section_text_end) *id_loc = '\\';
1021 c=(eight_bits)*loc++;
1022 }
1023 if (++id_loc<=section_text_end) *id_loc=(char)c;
1024 }
1025 if (id_loc>=section_text_end) {
1026 printf("%s","\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
1036 whether there is more work to do.
1037
1038 @<Get control code and possible section name@>=
1039 switch(c=ccode[(eight_bits)*loc++]) {
1040 case ignore: continue;
1041 case translit_code: err_print("! Use @@l in limbo only"); continue;
1042 @.Use @@l in limbo...@>
1043 case control_text: while ((c=skip_ahead())=='@@');
1044 /* only \.{@@@@} and \.{@@>} are expected */
1045 if (*(loc-1)!='>')
1046 err_print("! Double @@ should be used in control text");
1047 @.Double @@ should be used...@>
1048 continue;
1049 case section_name:
1050 cur_section_name_char=*(loc-1);
1051 @<Scan the section name and make |cur_section_name| point to it@>@;
1052 case string: @<Scan a verbatim string@>@;
1053 case ord: @<Scan an ASCII constant@>@;
1054 default: return c;
1055 }
1056
1057 @ After scanning a valid ASCII constant that follows
1058 \.{@@'}, this code plows ahead until it finds the next single quote.
1059 (Special care is taken if the quote is part of the constant.)
1060 Anything after a valid ASCII constant is ignored;
1061 thus, \.{@@'\\nopq'} gives the same result as \.{@@'\\n'}.
1062
1063 @<Scan an ASCII constant@>=
1064 id_first=loc;
1065 if (*loc=='\\')
1066 if (*++loc=='\'') loc++;
1067 while (*loc!='\'') {
1068 if (*loc=='@@') {
1069 if (*(loc+1)!='@@')
1070 err_print("! Double @@ should be used in ASCII constant");
1071 @.Double @@ should be used...@>
1072 else loc++;
1073 }
1074 loc++;
1075 if (loc>limit) {
1076 err_print("! String didn't end"); loc=limit-1; break;
1077 @.String didn't end@>
1078 }
1079 }
1080 loc++;
1081 return ord;
1082
1083 @ @<Scan the section name...@>= {
1084 char *k=section_text; /* pointer into |section_text| */
1085 @<Put section name into |section_text|@>@;
1086 if (k-section_text>3 && strncmp(k-2,"...",3)==0)
1087 cur_section_name=section_lookup(section_text+1,k-3,true);
1088 /* |true| means it's a prefix */
1089 else cur_section_name=section_lookup(section_text+1,k,false);
1090 /* |false| means it's not */
1091 if (cur_section_name_char=='(')
1092 @<If it's not there, add |cur_section_name| to the output file stack, or
1093 complain we're out of room@>@;
1094 return section_name;
1095 }
1096
1097 @ Section names are placed into the |section_text| array with consecutive spaces,
1098 tabs, and carriage-returns replaced by single spaces. There will be no
1099 spaces at the beginning or the end. (We set |section_text[0]=' '| to facilitate
1100 this, since the |section_lookup| routine uses |section_text[1]| as the first
1101 character of the name.)
1102
1103 @<Set init...@>=section_text[0]=' ';
1104
1105 @ @<Put section name...@>=
1106 while (true) {
1107 if (loc>limit && get_line()==false) {
1108 err_print("! Input ended in section name");
1109 @.Input ended in section name@>
1110 loc=buffer+1; break;
1111 }
1112 c=(eight_bits)*loc;
1113 @<If end of name or erroneous nesting, |break|@>@;
1114 loc++; if (k<section_text_end) k++;
1115 if (xisspace(c)) {
1116 c=(eight_bits)' '; if (*(k-1)==' ') k--;
1117 }
1118 *k=(char)c;
1119 }
1120 if (k>=section_text_end) {
1121 printf("%s","\n! Section name too long: ");
1122 @.Section name too long@>
1123 term_write(section_text+1,25);
1124 printf("..."); mark_harmless();
1125 }
1126 if (*k==' ' && k>section_text) k--;
1127
1128 @ @<If end of name or erroneous nesting,...@>=
1129 if (c=='@@') {
1130 c=(eight_bits)*(loc+1);
1131 if (c=='>') {
1132 loc+=2; break;
1133 }
1134 if (ccode[(eight_bits)c]==new_section) {
1135 err_print("! Section name didn't end"); break;
1136 @.Section name didn't end@>
1137 }
1138 if (ccode[(eight_bits)c]==section_name) {
1139 err_print("! Nesting of section names not allowed"); break;
1140 @.Nesting of section names...@>
1141 }
1142 *(++k)='@@'; loc++; /* now |c==*loc| again */
1143 }
1144
1145 @ At the present point in the program we
1146 have |*(loc-1)==string|; we set |id_first| to the beginning
1147 of the string itself, and |id_loc| to its ending-plus-one location in the
1148 buffer. We also set |loc| to the position just after the ending delimiter.
1149
1150 @<Scan a verbatim string@>=
1151 id_first=loc++; *(limit+1)='@@'; *(limit+2)='>';
1152 while (*loc!='@@' || *(loc+1)!='>') loc++;
1153 if (loc>=limit) err_print("! Verbatim string didn't end");
1154 @.Verbatim string didn't end@>
1155 id_loc=loc; loc+=2;
1156 return string;
1157
1158 @* Scanning a macro definition.
1159 The rules for generating the replacement texts corresponding to macros and
1160 \CEE/ texts of a section are almost identical; the only differences are that
1161
1162 \yskip \item{a)}Section names are not allowed in macros;
1163 in fact, the appearance of a section name terminates such macros and denotes
1164 the name of the current section.
1165
1166 \item{b)}The symbols \.{@@d} and \.{@@f} and \.{@@c} are not allowed after
1167 section names, while they terminate macro definitions.
1168
1169 \item{c)}Spaces are inserted after right parentheses in macros, because the
1170 ANSI \CEE/ preprocessor sometimes requires it.
1171
1172 \yskip Therefore there is a single procedure |scan_repl| whose parameter
1173 |t| specifies either |macro| or |section_name|. After |scan_repl| has
1174 acted, |cur_text| will point to the replacement text just generated, and
1175 |next_control| will contain the control code that terminated the activity.
1176
1177 @d app_repl(c) {
1178 if (tok_ptr==tok_mem_end) overflow("token");
1179 else *(tok_ptr++)=(eight_bits)c;
1180 }
1181
1182 @<Private...@>=
1183 static text_pointer cur_text; /* replacement text formed by |scan_repl| */
1184 static eight_bits next_control;
1185
1186 @ @c
1187 static void
1188 scan_repl( /* creates a replacement text */
1189 eight_bits t)
1190 { bool first_bracket=true; /* for cleaner output */
1191 sixteen_bits a; /* the current token */
1192 if (t==section_name) @<Insert the line number into |tok_mem|@>@;
1193 while (true) switch (a=get_next()) {
1194 @/@t\4@>@<In cases that |a| is a non-|char| token (|identifier|,
1195 |section_name|, etc.), either process it and change |a| to a byte
1196 that should be stored, or |continue| if |a| should be ignored,
1197 or |goto done| if |a| signals the end of this replacement text@>@;
1198 case ')': app_repl(a);
1199 if (t==macro&&first_bracket) {app_repl(' '); first_bracket=false;}
1200 break;
1201 default: app_repl(a); /* store |a| in |tok_mem| */
1202 }
1203 done: next_control=(eight_bits) a;
1204 if (text_ptr>text_info_end) overflow("text");
1205 cur_text=text_ptr; (++text_ptr)->tok_start=tok_ptr;
1206 }
1207
1208 @ @<Predecl...@>=@+static void scan_repl(eight_bits);
1209
1210 @ Here is the code for the line number: first a |sixteen_bits| equal
1211 to |0150000|; then the numeric line number; then a pointer to the
1212 file name.
1213
1214 @d store_id(a) a=id_lookup(id_first,id_loc,'\0')-name_dir;@/
1215 app_repl((a / 0400)+0200);
1216 app_repl(a % 0400)
1217
1218 @<Insert the line...@>=
1219 {
1220 store_two_bytes(0150000);
1221 if (changing && include_depth==change_depth) { /* correction made Feb 2017 */
1222 id_first=change_file_name;
1223 store_two_bytes((sixteen_bits)change_line);
1224 }@+else {
1225 id_first=cur_file_name;
1226 store_two_bytes((sixteen_bits)cur_line);
1227 }
1228 id_loc=id_first+strlen(id_first);
1229 store_id(a);
1230 }
1231
1232 @ @<In cases that |a| is...@>=@t\1\quad@>
1233 case identifier: store_id(a);
1234 if (*buffer=='#' && @| (
1235 ( id_loc-id_first==5 && strncmp("endif",id_first,5)==0 ) || @|
1236 ( id_loc-id_first==4 && strncmp("else",id_first,4)==0 ) || @|
1237 ( id_loc-id_first==4 && strncmp("elif",id_first,4)==0 ) ) )
1238 /* Avoid preprocessor calamities */
1239 print_where=true;
1240 break;
1241 case section_name: if (t!=section_name) goto done;
1242 else {
1243 @<Was an `\.{@@}' missed here?@>@;
1244 a=cur_section_name-name_dir;
1245 app_repl((a / 0400)+0250);
1246 app_repl(a % 0400);
1247 @<Insert the line number into |tok_mem|@>@;
1248 }
1249 break;
1250 case output_defs_code: if (t!=section_name) err_print("! Misplaced @@h");
1251 @.Misplaced @@h@>
1252 else {
1253 output_defs_seen=true;
1254 a=output_defs_flag;
1255 app_repl((a / 0400)+0200);
1256 app_repl(a % 0400);
1257 @<Insert the line number into |tok_mem|@>@;
1258 }
1259 break;
1260 case constant: case string:
1261 @<Copy a string or verbatim construction or numerical constant@>@;
1262 break;
1263 case ord:
1264 @<Copy an ASCII constant@>@;
1265 break;
1266 case definition: case format_code: case begin_C: if (t!=section_name) goto done;
1267 else {
1268 err_print("! @@d, @@f and @@c are ignored in C text"); continue;
1269 @.@@d, @@f and @@c are ignored in C text@>
1270 }
1271 case new_section: goto done;
1272
1273 @ @<Was an `\.{@@}'...@>= {
1274 char *try_loc=loc;
1275 while (*try_loc==' ' && try_loc<limit) try_loc++;
1276 if (*try_loc=='+' && try_loc<limit) try_loc++;
1277 while (*try_loc==' ' && try_loc<limit) try_loc++;
1278 if (*try_loc=='=') err_print ("! Missing `@@ ' before a named section");
1279 @.Missing `@@ '...@>
1280 /* user who isn't defining a section should put newline after the name,
1281 as explained in the manual */
1282 }
1283
1284 @ By default, \.{CTANGLE} purges single-quote characters from \CPLUSPLUS/-style
1285 literals, e.g., \.{1'000'000}, so that you can use this notation also in \CEE/
1286 code. The \.{+k} switch will `keep' the single quotes in the output.
1287
1288 @d keep_digit_separators flags['k']
1289
1290 @<Copy a string...@>=
1291 app_repl(a); /* |string| or |constant| */
1292 while (id_first < id_loc) { /* simplify \.{@@@@} pairs */
1293 if (*id_first=='@@') {
1294 if (*(id_first+1)=='@@') id_first++;
1295 else err_print("! Double @@ should be used in string");
1296 @.Double @@ should be used...@>
1297 }
1298 else if (a==constant && *id_first=='\'' && !keep_digit_separators)
1299 id_first++;
1300 app_repl(*id_first++);
1301 }
1302 app_repl(a);
1303
1304 @ This section should be rewritten on machines that don't use ASCII
1305 code internally.
1306 @^ASCII code dependencies@>
1307
1308 @<Copy an ASCII constant@>= {
1309 int c=(int)((eight_bits) *id_first);
1310 if (c=='\\') {
1311 c=(int)((eight_bits) *++id_first);
1312 if (c>='0' && c<='7') {
1313 c-='0';
1314 if (*(id_first+1)>='0' && *(id_first+1)<='7') {
1315 c=8*c+*(++id_first) - '0';
1316 if (*(id_first+1)>='0' && *(id_first+1)<='7' && c<32)
1317 c=8*c+*(++id_first)- '0';
1318 }
1319 }
1320 else switch (c) {
1321 case 't':c='\t';@+break;
1322 case 'n':c='\n';@+break;
1323 case 'b':c='\b';@+break;
1324 case 'f':c='\f';@+break;
1325 case 'v':c='\v';@+break;
1326 case 'r':c='\r';@+break;
1327 case 'a':c='\7';@+break;
1328 case '?':c='?';@+break;
1329 case 'x':
1330 if (xisdigit(*(id_first+1))) c=(int)(*(++id_first)-'0');
1331 else if (xisxdigit(*(id_first+1))) {
1332 ++id_first;
1333 c=toupper((int)*id_first)-'A'+10;
1334 }
1335 if (xisdigit(*(id_first+1))) c=16*c+(int)(*(++id_first)-'0');
1336 else if (xisxdigit(*(id_first+1))) {
1337 ++id_first;
1338 c=16*c+toupper((int)*id_first)-(int)'A'+10;
1339 }
1340 break;
1341 case '\\':c='\\';@+break;
1342 case '\'':c='\'';@+break;
1343 case '\"':c='\"';@+break;
1344 default: err_print("! Unrecognized escape sequence");
1345 @.Unrecognized escape sequence@>
1346 }
1347 }@/
1348 /* at this point |c| should have been converted to its ASCII code number */
1349 app_repl(constant);
1350 if (c>=100) app_repl((int)'0'+c/100);
1351 if (c>=10) app_repl((int)'0'+(c/10)%10);
1352 app_repl((int)'0'+c%10);
1353 app_repl(constant);
1354 }
1355
1356 @* Scanning a section.
1357 The |scan_section| procedure starts when `\.{@@\ }' or `\.{@@*}' has been
1358 sensed in the input, and it proceeds until the end of that section. It
1359 uses |section_count| to keep track of the current section number; with luck,
1360 \.{CWEAVE} and \.{CTANGLE} will both assign the same numbers to sections.
1361
1362 The body of |scan_section| is a loop where we look for control codes
1363 that are significant to \.{CTANGLE}: those
1364 that delimit a definition, the \CEE/ part of a module, or a new module.
1365
1366 @c
1367 static void
1368 scan_section(void)
1369 {
1370 name_pointer p; /* section name for the current section */
1371 text_pointer q; /* text for the current section */
1372 sixteen_bits a; /* token for left-hand side of definition */
1373 section_count++; @+ no_where=true;
1374 if (*(loc-1)=='*' && show_progress) { /* starred section */
1375 printf("*%d",(int)section_count); update_terminal();
1376 }
1377 next_control=ignore;
1378 while (true) {
1379 @<Skip ahead until |next_control| corresponds to \.{@@d}, \.{@@<},
1380 \.{@@\ } or the like@>@;
1381 if (next_control == definition) { /* \.{@@d} */
1382 @<Scan a definition@>@;
1383 continue;
1384 }
1385 if (next_control == begin_C) { /* \.{@@c} or \.{@@p} */
1386 p=name_dir; break;
1387 }
1388 if (next_control == section_name) { /* \.{@@<} or \.{@@(} */
1389 p=cur_section_name;
1390 @<If section is not being defined, |continue| @>@;
1391 break;
1392 }
1393 return; /* \.{@@\ } or \.{@@*} */
1394 }
1395 no_where=print_where=false;
1396 @<Scan the \CEE/ part of the current section@>@;
1397 }
1398
1399 @ @<Predecl...@>=@+static void scan_section(void);
1400
1401 @ At the top of this loop, if |next_control==section_name|, the
1402 section name has already been scanned (see |@<Get control code
1403 and...@>|). Thus, if we encounter |next_control==section_name| in the
1404 skip-ahead process, we should likewise scan the section name, so later
1405 processing will be the same in both cases.
1406
1407 @<Skip ahead until |next_control| ...@>=
1408 while (next_control<definition)
1409 /* |definition| is the lowest of the ``significant'' codes */
1410 if((next_control=skip_ahead())==section_name){
1411 loc-=2; next_control=get_next();
1412 }
1413
1414 @ @<Scan a definition@>=
1415 while ((next_control=get_next())=='\n'); /* allow newline before definition */
1416 if (next_control!=identifier) {
1417 err_print("! Definition flushed, must start with identifier");
1418 @.Definition flushed...@>
1419 continue;
1420 }
1421 store_id(a); /* append the lhs */
1422 if (*loc!='(') { /* identifier must be separated from replacement text */
1423 app_repl(string); app_repl(' '); app_repl(string);
1424 }
1425 scan_repl(macro);
1426 cur_text->text_link=macro;
1427
1428 @ If the section name is not followed by \.{=} or \.{+=}, no \CEE/
1429 code is forthcoming: the section is being cited, not being
1430 defined. This use is illegal after the definition part of the
1431 current section has started, except inside a comment, but
1432 \.{CTANGLE} does not enforce this rule; it simply ignores the offending
1433 section name and everything following it, up to the next significant
1434 control code.
1435
1436 @<If section is not being defined, |continue| @>=
1437 while ((next_control=get_next())=='+'); /* allow optional \.{+=} */
1438 if (next_control!='=' && next_control!=eq_eq)
1439 continue;
1440
1441 @ @<Scan the \CEE/...@>=
1442 @<Insert the section number into |tok_mem|@>@;
1443 scan_repl(section_name); /* now |cur_text| points to the replacement text */
1444 @<Update the data structure so that the replacement text is accessible@>@;
1445
1446 @ @<Insert the section number...@>=
1447 store_two_bytes((sixteen_bits)(0150000+section_count));
1448 /* |0150000==0320*0400| */
1449
1450 @ @<Update the data...@>=
1451 if (p==name_dir||p==NULL) { /* unnamed section, or bad section name */
1452 last_unnamed->text_link=cur_text-text_info; last_unnamed=cur_text;
1453 }
1454 else if (p->equiv==(void *)text_info) p->equiv=(void *)cur_text;
1455 /* first section of this name */
1456 else {
1457 q=(text_pointer)p->equiv;
1458 while (q->text_link<section_flag)
1459 q=q->text_link+text_info; /* find end of list */
1460 q->text_link=cur_text-text_info;
1461 }
1462 cur_text->text_link=section_flag;
1463 /* mark this replacement text as a nonmacro */
1464
1465 @ @c
1466 static void
1467 phase_one(void) {
1468 phase=1;
1469 section_count=0;
1470 reset_input();
1471 skip_limbo();
1472 while (!input_has_ended) scan_section();
1473 check_complete();
1474 }
1475
1476 @ @<Predec...@>=@+static void phase_one(void);
1477
1478 @ Only a small subset of the control codes is legal in limbo, so limbo
1479 processing is straightforward.
1480
1481 @c
1482 static void
1483 skip_limbo(void)
1484 {
1485 while (true) {
1486 if (loc>limit && get_line()==false) return;
1487 *(limit+1)='@@';
1488 while (*loc!='@@') loc++;
1489 if (loc++<=limit) {
1490 char c=*loc++;
1491 switch (ccode[(eight_bits)c]) {
1492 case new_section: return;
1493 case translit_code: @<Read in transliteration of a character@>@; break;
1494 case format_code: case '@@': break;
1495 case control_text: if (c=='q' || c=='Q') {
1496 while ((c=(char)skip_ahead())=='@@');
1497 if (*(loc-1)!='>')
1498 err_print("! Double @@ should be used in control text");
1499 @.Double @@ should be used...@>
1500 break;
1501 } @=/* otherwise fall through */@>@;
1502 default: err_print("! Double @@ should be used in limbo");
1503 @.Double @@ should be used...@>
1504 }
1505 }
1506 }
1507 }
1508
1509 @ @<Predecl...@>=@+static void skip_limbo(void);
1510
1511 @ @<Read in transliteration of a character@>=
1512 while(xisspace(*loc)&&loc<limit) loc++;
1513 loc+=3;
1514 if (loc>limit || !xisxdigit(*(loc-3)) || !xisxdigit(*(loc-2)) @|
1515 || (*(loc-3)>='0' && *(loc-3)<='7') || !xisspace(*(loc-1)))
1516 err_print("! Improper hex number following @@l");
1517 @.Improper hex number...@>
1518 else {
1519 unsigned int i;
1520 char *beg;
1521 sscanf(loc-3,"%x",&i);
1522 while(xisspace(*loc)&&loc<limit) loc++;
1523 beg=loc;
1524 while(loc<limit&&(xisalpha(*loc)||xisdigit(*loc)||isxalpha(*loc))) loc++;
1525 if (loc-beg>=translit_length)
1526 err_print("! Replacement string in @@l too long");
1527 @.Replacement string in @@l...@>
1528 else{
1529 strncpy(translit[i-0200],beg,(size_t)(loc-beg));
1530 translit[i-0200][loc-beg]='\0';
1531 }
1532 }
1533
1534 @ Because on some systems the difference between two pointers is a |ptrdiff_t|
1535 but not an |int|, we use \.{\%td} to print these quantities.
1536
1537 @c
1538 void
1539 print_stats(void) {
1540 puts("\nMemory usage statistics:");
1541 printf("%td names (out of %ld)\n",@^system dependencies@>
1542 (ptrdiff_t)(name_ptr-name_dir),(long)max_names);
1543 printf("%td replacement texts (out of %ld)\n",
1544 (ptrdiff_t)(text_ptr-text_info),(long)max_texts);
1545 printf("%td bytes (out of %ld)\n",
1546 (ptrdiff_t)(byte_ptr-byte_mem),(long)max_bytes);
1547 printf("%td tokens (out of %ld)\n",
1548 (ptrdiff_t)(tok_ptr-tok_mem),(long)max_toks);
1549 }
1550
1551 @** Index.
1552 Here is a cross-reference table for \.{CTANGLE}.
1553 All sections in which an identifier is
1554 used are listed with that identifier, except that reserved words are
1555 indexed only when they appear in format definitions, and the appearances
1556 of identifiers in section names are not indexed. Underlined entries
1557 correspond to where the identifier was declared. Error messages and
1558 a few other things like ``ASCII code dependencies'' are indexed here too.