summaryrefslogtreecommitdiff
path: root/web/funnelAC/fwACsrc/tangle.c
blob: 121995f2c0f73f6b74df5e8b70ecd237a5c348b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*##############################################################################

FUNNNELWEB COPYRIGHT
====================
FunnelWeb is a literate-programming macro preprocessor.

Copyright (C) 1992 Ross N. Williams.

   Ross N. Williams
   ross@spam.adelaide.edu.au
   16 Lerwick Avenue, Hazelwood Park 5066, Australia.

This program is free software; you can redistribute it and/or modify
it under the terms of Version 2 of the GNU General Public License as
published by the Free Software Foundation.

This program is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See Version 2 of the GNU General Public License for more details.

You should have received a copy of Version 2 of the GNU General Public
License along with this program. If not, you can FTP the license from
prep.ai.mit.edu/pub/gnu/COPYING-2 or write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Section 2a of the license requires that all changes to this file be
recorded prominently in this file. Please record all changes here.

Programmers:
   RNW  Ross N. Williams  ross@spam.adelaide.edu.au
   ABC  Anthony B. Coates coates@physics.uq.edu.au

Changes:
   07-May-1992  RNW  Program prepared for release under GNU GPL V2.
   31-Aug-1993  ABC  Added support for EL_SPEC.
                     Added an extra parameter, for the position of the
                     parent macro call, to many of the functions
                     ex_ex...
   10-May-1994  ABC  Added DYN_NAMES option to allow macro and
                     section names to be allocated dynamically
                     instead of statically.
   18-Sep-1994  ABC  Added support for the automatic insertion of
                     line directives when `aldmname' is a non-null
                     string referring to a macro without parameters.
   25-Jul-1995  ABC  Replaced `aldmname' with a list of structures
                     containing a source code type name (or NULL)
                     and a corresponding automatic line directive
                     insertion macro name.
   08-Aug-1995  ABC  Changed include file name from "memory.h"
                     to "fwmem.h" to avoid a clash with the C++
                     standard header file "memory.h".
   10-Aug-1995  ABC  Added support for SF_TMS (#timestamp) internal
                     macro.

##############################################################################*/


/******************************************************************************/
/*                                   TANGLE.C                                 */
/******************************************************************************/

/* Note: In this module, "ex_" at the start of a function name means "expand" */
/*       rather than the standard meaning of "ex" of "expression.             */

/******************************************************************************/

#include "style.h"
/* ABC { */
/* The ANSI time functions are required for the #timestamp macro */
#include <time.h>
/* } ABC */

#include "as.h"
#include "data.h"
#include "lister.h"
#include "fwmem.h"
#include "misc.h"
#include "table.h"
#include "tangle.h"
#include "writfile.h"

/******************************************************************************/

/* The following variable keeps track of the output line number. This is      */
/* needed to report lines that are too long.                                  */
LOCVAR ulong lineno;

/* Last line for which error message was generated.    */
LOCVAR ulong errlin;

/* Number of too-long lines seen so far in this file. */
LOCVAR ulong numlong;
/* Number of long line error messages we can tolerate per product file. */
#define LONGMESS 5

/* Note: An indentation of n means n blanks before current material.          */
/* tgindent is a global variable set by the scanner. It is TRUE if blank      */
/* indenting is required and FALSE if no indenting is required.               */
LOCVAR ulong ind_base;  /* Base indenting level of macro being expanded.      */
LOCVAR ulong ind_curr;  /* Current indenting position.                        */

LOCVAR char  *fn_targ;  /* Name of current (target) product file.             */
LOCVAR wf_t  f_o;       /* Current product file.                              */
/* ABC { */
LOCVAR bool  inaldmQ;   /* Whether inside the automatic line directive        */
                        /* insertion macro or not.                            */
LOCVAR bool  Need_aldmQ; /* Whether to insert a line directive before the     */
                         /* next scrap.                                       */
LOCVAR bool  no_next_aldmQ; /* Whether to suppress the next line directive    */
                         /* before a scrap.                                   */
/* } ABC */

/******************************************************************************/

/* The expression expansion function has to have a forward declaration. */
/* ABC { The second parameter points to the parent invocation. } */
LOCAL void ex_ex P_((p_ells_t,p_el_t,p_srcnmac_t));

/******************************************************************************/

LOCAL void eolblank P_((ulong));
LOCAL void eolblank(n)
/* Writes an EOL followed by n blanks to the product file. Efficiently!       */
ulong n;
{
 /* The whole aim of this routine is to write blanks EFFICIENTLY. In          */
 /* particular avoiding any per-char procedure call overhead (e.g. calls to   */
 /* wf_chr). The best way to avoid this is to create a static array of blanks */
 /* and write out large blocks of blanks all at once.                         */
#define BLANKLEN 100             /* Number of BLANKS in blank array.          */
 STAVAR bool notinit=TRUE;       /* Has blank array been initialized?         */
 STAVAR char blanks[1+BLANKLEN]; /* EOL followed by BLANKLEN blanks.          */

 /* Set up the blank array. This only ever done once because of the static    */
 /* boolean. Note that use of an initialized static here does not make the    */
 /* code non-reentrant, as the state does not change after initialization.    */
 if (notinit)
    {blanks[0]=EOL; memset(blanks+1,' ',(size_t) BLANKLEN); notinit=FALSE;}

 /* The most common case will be a small indentation. Do this case fast. */
 if (n<=BLANKLEN)
    wf_blk(&f_o,&blanks[0],(size_t) n+1);
 else
   {
    /* We now know that n>=BLANKLEN. Write out a long line with \n at front. */
    wf_blk(&f_o,&blanks[0],BLANKLEN+1); n-=BLANKLEN;

    /* Now get into large scale blank production! */
    while (n>0)
      {
       ulong len=MIN(n,BLANKLEN);
       wf_blk(&f_o,&blanks[1],(size_t) len); n-=len;
      }
   }
}

/******************************************************************************/

/* ABC { */
LOCAL void blank P_((ulong));
LOCAL void blank(n)
/* Writes an EOL followed by n blanks to the product file. Efficiently!       */
/* This is like `eolblank', but without the `eol' first.                      */
ulong n;
{
 /* The whole aim of this routine is to write blanks EFFICIENTLY. In          */
 /* particular avoiding any per-char procedure call overhead (e.g. calls to   */
 /* wf_chr). The best way to avoid this is to create a static array of blanks */
 /* and write out large blocks of blanks all at once.                         */
#define BLANKLEN 100             /* Number of BLANKS in blank array.          */
 STAVAR bool notinit=TRUE;       /* Has blank array been initialized?         */
 STAVAR char blanks[BLANKLEN]; /* EOL followed by BLANKLEN blanks.            */

 /* Set up the blank array. This only ever done once because of the static    */
 /* boolean. Note that use of an initialized static here does not make the    */
 /* code non-reentrant, as the state does not change after initialization.    */
 if (notinit)
    {memset(blanks,' ',(size_t) BLANKLEN); notinit=FALSE;}

 /* The most common case will be a small indentation. Do this case fast. */
 if (n<=BLANKLEN)
    wf_blk(&f_o,&blanks[0],(size_t) n);
 else
   {
    /* We now know that n>=BLANKLEN. Write out a long line with \n at front. */
    wf_blk(&f_o,&blanks[0],BLANKLEN); n-=BLANKLEN;

    /* Now get into large scale blank production! */
    while (n>0)
      {
       ulong len=MIN(n,BLANKLEN);
       wf_blk(&f_o,&blanks[0],(size_t) len); n-=len;
      }
   }
}
/* } ABC */

/******************************************************************************/

/* ABC { */
LOCAL void ex_call P_((char*,p_ps_t,p_srcnmac_t));
LOCAL void ex_call(mcname,p_ps,p_srctype)
/* This function calls the named FunnelWeb macro without parameters.
 */
char *mcname;
p_ps_t p_ps;
p_srcnmac_t p_srctype;
{
 STAVAR el_t el = {
   EL_INVC,                 /* el_kind  */
   NULL,                    /* el_text  */
   NULL,                    /* el_p_mac */
   NULL,                    /* el_parls */
   NULL,                    /* el_pretx */
   NULL,                    /* el_postx */
   NULL,                    /* el_p_par */
   NULL,                    /* el_which */
   0,                       /* el_parno */
   SF_ERR,                  /* el_selec */
   { 0, 0, 0, NULL, FALSE } /* el_ps    */
 };
 p_ma_t p_ma;
 p_bp_t p_bp;
 ulong  ind_save;
 p_void p_mark;
 bool oldaldmQ = inaldmQ;

 /* Save the current indentation base and set it to the current level. */
 ind_save=ind_base;
 ind_base=ind_curr;

 /* Get up the macro parameters */
 tb_loo(macro_table, PV mcname, PV &p_ma);

 /* Note if macro is that used for automatic line directives */
 if ((p_srctype != NULL) && (p_srctype->lnmac != NULL))
   inaldmQ |= !strcmp(mcname, p_srctype->lnmac);

 /* Set up an empty actual parameter list */
 el.el_p_mac = p_ma;
 if (el.el_parls == NULL) el.el_parls = ls_cre(sizeof(p_ells_t));
 if (el.el_pretx == NULL) el.el_pretx = ls_cre(sizeof(p_scls_t));
 if (el.el_postx == NULL) el.el_postx = ls_cre(sizeof(p_scls_t));
 el.el_ps = *p_ps;

 /* Push the actual parameter list onto the invoked macro's activation list. */
 ls_add(p_ma->ma_actn,PV &el.el_parls);

 /* Expand each body part expression. */
 ls_fir(p_ma->ma_defn.md_body);
 while (TRUE)
   {
    ls_nxt(p_ma->ma_defn.md_body,PPV &p_bp);
    if (p_bp==NULL) break;
    p_mark=ls_mar(p_ma->ma_defn.md_body); /* Protect againt recursion. */
    ex_ex(p_bp->bp_ex, &el, p_srctype);
    ls_set(p_ma->ma_defn.md_body,p_mark);
   }

 /* Pop the activated macro's parameter list. */
 ls_lop(p_ma->ma_actn);

 /* Restore the indentation base. */
 ind_base=ind_save;

 /* ABC { */
 /* Restore the initial state of `inaldmQ' */
 inaldmQ = oldaldmQ;
 /* } ABC */
}
/* } ABC */

/******************************************************************************/

#define SENDLINE {wl_l(linet1); if (option.op_s_b) wl_sj(linet1);}

/* ABC { */
LOCAL void ex_sc P_((p_sc_t,p_ps_t,p_srcnmac_t));
LOCAL void ex_sc(p_sc,p_ps,p_srctype)
/* } ABC */
/* This function writes the specified scrap to the product file. It also      */
/* performs two other tasks:                                                  */
/*    If tgindent==TRUE, inserts indentation at the start of each line.       */
/*    If tglinmax>0, checks for product file lines longer than tglinmax.      */
/* Note: The speed of this routine is fairly critical.                        */
p_sc_t p_sc;
p_ps_t p_ps;
p_srcnmac_t p_srctype;
{
 /* Add an automatic line insertion macro if necessary, *
  * taking care of preserving the indenting             */
 if (
      (p_srctype != NULL)
      && (p_srctype->lnmac != NULL)
      && !(inaldmQ) && Need_aldmQ && !no_next_aldmQ
      && (p_ps != NULL)
    ) {
   int ind_save = ind_curr;
   if (ind_curr > 0) wf_chr(&f_o, '\n');
   ind_curr = 0; /* directive starts at beginning of line */
   ex_call(p_srctype->lnmac,p_ps,p_srctype);
   if (ind_curr > 0) wf_chr(&f_o, '\n');
   if (ind_save > 0) blank(ind_save);
   ind_curr = ind_save;
 } /* end if */
 Need_aldmQ = FALSE;
 /* } ABC */

 /* Output of a scrap is straightforward if we are not inserting indentation  */
 /* or watching for lines that are too long. If neither of these tasks have   */
 /* to be performed, we can bang the scrap out directly with a wf_blk.        */
 if (!tgindent && tglinmax==TGMAXINF)
   {
    wf_blk(&f_o, p_sc->sc_first, (size_t) (p_sc->sc_last-p_sc->sc_first+1));
    return;
   }

 /* Otherwise it gets rather messy. Basically, we have to watch for end of    */
 /* lines and perform special actions there.                                  */
 /* ind_curr is the number of characters already written to the current line. */
 {
  char *p      = p_sc->sc_first;
  char *p_post = p_sc->sc_last+1;
  while (TRUE)
    {
     char *p_sot = p;  /* SOT=Start of Text. */

     /* Scan scrap until we hit either its end or an EOL. */
     while (p!=p_post && *p!=EOL) p++;

     /* Assert: p==p_post || (p_sot<=p<p_post && *p==EOL). */

     /* If we scanned any non-EOL text, write out what we scanned. */
     if (p>p_sot) {wf_blk(&f_o,p_sot,(size_t) (p-p_sot));ind_curr+=p-p_sot;}

     /* Check that what we have written so far is not too long.            */
     /* Performing this check here rather than with the EOL processing     */
     /* means that we will detect overlong final non-EOL terminated lines. */
     /* Use of errlin suppresses multiple errors on the same line.         */
     /* Note: We assume that TGMAXINF is very large.                       */
     if (ind_curr>tglinmax && lineno!=errlin)
       {
        numlong++;
        if (numlong <= LONGMESS)
          {
           if (option.op_b7_b)
              sprintf(linet1,
                      "E: Product file line is too long (line %lu of \"%s\").",
                             (ulong) lineno,SUPPNAME);
           else
              sprintf(linet1,
                      "E: Product file line is too long (line %lu of \"%s\").",
                             (ulong) lineno,fn_targ);
           SENDLINE;
           if (numlong==1)
             {
              sprintf(linet1,"   Product file line length limit is %lu characters.",
                             (ulong) tglinmax);
              SENDLINE;
              sprintf(linet1,"   Note: You can change the limit by specifying.");
              SENDLINE;
              sprintf(linet1,"      @p maximum_output_line_length = <desired length>");
              SENDLINE;
              sprintf(linet1,"   somewhere in the input file.");
              SENDLINE;
             }
           errlin=lineno;
           num_err++;
          }
        if (numlong == LONGMESS+1)
          {
           sprintf(linet1,
           "Further line-too-long warnings for file \"%s\" have been suppressed.",
              fn_targ);
           SENDLINE;
          }
       }

     /* Exit if we hit the end of the scrap. */
     if (p==p_post) break;

     /* Move past the EOL and bump up the line counter. */
     p++; lineno++;

     /* Output an EOL with indentation if desired. */
     if (tgindent)
        eolblank(ind_base);
     else
        wf_chr(&f_o,EOL);
     ind_curr=ind_base;
    }
 }
}

/******************************************************************************/

LOCAL void ex_eltx P_((p_el_t,p_el_t,p_srcnmac_t));
LOCAL void ex_eltx(p_el,p_par,p_srctype)
/* Writes the given text element to the product file. */
p_el_t p_el;
p_el_t p_par;
p_srcnmac_t p_srctype;
{
 p_sc_t p_sc;

 /* Make sure that we have actually been handed a text element. */
 as_cold(p_el->el_kind==EL_TEXT,"ex_eltx: Not a text element!");

 /* Write all the scraps in the text list to the product file. */
 ls_fir(p_el->el_text);
 while (TRUE)
   {
    ls_nxt(p_el->el_text,PPV &p_sc);
    if (p_sc==NULL) break;
    /* ABC { */
    ex_sc(p_sc,&(p_el->el_ps),p_srctype);
    /* } ABC */
   }
}

/******************************************************************************/

LOCAL void ex_elpr P_((p_el_t,p_el_t,p_srcnmac_t));
LOCAL void ex_elpr(p_el,p_par,p_srctype)
/* Write the expansion of the given parameter element to the product file. */
p_el_t p_el;
p_el_t p_par;
p_srcnmac_t p_srctype;
{
 p_ell3_t  actn = p_el->el_which->ma_actn;
 p_elll_t *pp_parls;
 p_ells_t *pp_exp;
 ulong    ind_save;

 /* Make sure that we have been handed a parameter element. */
 as_cold(p_el->el_kind==EL_PARM,"ex_elpr: Not a parameter element!");

 /* Save the current indentation base and set it to the current level. */
 ind_save=ind_base;
 ind_base=ind_curr;

 /* Get a pointer to the most recent parameter list of the target macro. */
 ls_loo(actn,ls_len(actn),PPV &pp_parls);

 /* Get the expression corresponding to the el_parno'th parameter. */
 ls_loo(*pp_parls,p_el->el_parno,PPV &pp_exp);

 /* Expand that expression. */
 ex_ex(*pp_exp,p_el,p_srctype);

 /* Restore the indentation base. */
 ind_base=ind_save;
}

/******************************************************************************/

LOCAL void ex_elin P_((p_el_t,p_el_t,p_srcnmac_t));
LOCAL void ex_elin(p_el,p_par,p_srctype)
/* Expand invocation element. */
p_el_t p_el;
p_el_t p_par;
p_srcnmac_t p_srctype;
{
 p_ma_t p_ma;
 p_bp_t p_bp;
 ulong  ind_save;
 p_void p_mark;
 /* ABC { */
 bool oldaldmQ = inaldmQ;
 /* } ABC */

 /* Make sure that we have been handed an invocation element. */
 as_cold(p_el->el_kind==EL_INVC,"ex_elin: Not an invocation element!");

 /* Save the current indentation base and set it to the current level. */
 ind_save=ind_base;
 ind_base=ind_curr;

 /* ABC { */
 /* Mark parent */
 p_el->el_p_par = p_par;
 /* } ABC */

 /* Grab a pointer to the macro being invoked. */
 p_ma=p_el->el_p_mac;

 /* ABC { */
 /* Note if macro is that used for automatic line directives */
 if ((p_srctype != NULL) && (p_srctype->lnmac != NULL))
   inaldmQ |= !strcmp(p_ma->ma_name, p_srctype->lnmac);
 /* } ABC */

 /* Push the actual parameter list onto the invoked macro's activation list. */
 ls_add(p_ma->ma_actn,PV &p_el->el_parls);

 /* Expand each body part expression. */
 ls_fir(p_ma->ma_defn.md_body);
 while (TRUE)
   {
    ls_nxt(p_ma->ma_defn.md_body,PPV &p_bp);
    if (p_bp==NULL) break;
    p_mark=ls_mar(p_ma->ma_defn.md_body); /* Protect againt recursion. */
    /* ABC { */
    /* May need a line directive for each part of the macro */
    if (!inaldmQ) Need_aldmQ = TRUE;
    /* } ABC */
    ex_ex(p_bp->bp_ex, p_el, p_srctype);
    ls_set(p_ma->ma_defn.md_body,p_mark);
   }

 /* Pop the activated macro's parameter list. */
 ls_lop(p_ma->ma_actn);

 /* Restore the indentation base. */
 ind_base=ind_save;

 /* ABC { */
 /* May need a line directive for the end of the macro */
 if (!inaldmQ) Need_aldmQ = TRUE;
 /* Restore the initial state of `inaldmQ' */
 inaldmQ = oldaldmQ;
 /* } ABC */
}

/* ABC { */
/******************************************************************************/

#define ELSP_NUMSZ (32)

LOCAL void ex_tstamp P_((char*));
LOCAL void ex_tstamp(strptr)
/* Copies the FunnelWeb timestamp into the argument string. */
char *strptr;
{
  static bool unfixedQ = TRUE;
  static char timestamp[ELSP_NUMSZ];
  time_t current = -1; /* time_t is defined in `time.h' */

  if (unfixedQ) {
    /* Initialise on the first call. */
    current = time(NULL);
    if (current == -1) {
      /* `time' failed */
      strcpy(timestamp, "????/??/??/??/??/??");
    } else {
      /* `time' was successful */
      strftime(
        timestamp, ELSP_NUMSZ,
        "%Y/%m/%d/%H/%M/%S",
        localtime(&current)
      );
    } /* end if */
    unfixedQ = FALSE;
  } /* end if */

  strcpy(strptr, timestamp);
}

/******************************************************************************/

LOCAL void ex_elsp P_((p_el_t,p_el_t,p_srcnmac_t));
LOCAL void ex_elsp(p_el,p_par,p_srctype)
/* Writes the given internal function result to the product file. */
p_el_t p_el;
p_el_t p_par;
p_srcnmac_t p_srctype;
{
 p_sc_t p_sc;
 char *p_res = NULL;
 char errmss[32];
 p_el_t punwnd;
 uword i;

 /* Make sure that we have actually been handed a text element. */
 as_cold(p_el->el_kind==EL_SPEC,"ex_elsp: Not a special function!");

 /* Check special function and write result string. */
 p_sc = (p_sc_t)mm_temp(sizeof(sc_t));
 switch (p_el->el_selec) {
   case SF_LIN  :
     if (p_par) {
       punwnd = p_par;
       for (i=0; (i<lin_dep)&&punwnd; i++) punwnd = punwnd->el_p_par;
       if (punwnd) {
         p_res = (char *)mm_temp(ELSP_NUMSZ*sizeof(char));
         sprintf(p_res, "%lu", punwnd->el_ps.ps_localno+lin_off);
         p_sc->sc_white = FALSE;
       } /* end if */
     } /* end if */
     break;
   case SF_FIL  :
     if (p_par) {
       punwnd = p_par;
       for (i=0; (i<lin_dep)&&punwnd; i++) punwnd = punwnd->el_p_par;
       if (punwnd) {
         p_res = (char *)mm_temp(
           (strlen(punwnd->el_ps.ps_fnam->fnam_name)+1) * sizeof(char)
         );
         strcpy(p_res, punwnd->el_ps.ps_fnam->fnam_name);
         p_sc->sc_white = FALSE;
       } /* end if */
     } /* end if */
     break;
   case SF_TMS  :
     p_res = (char *)mm_temp(ELSP_NUMSZ*sizeof(char));
     ex_tstamp(p_res);
     p_sc->sc_white = FALSE;
     break;
   case SF_ERR  :
   default      :
     wl_sjl("An erroneous internal function designator was seen.");
     if (p_el->el_selec == SF_ERR) {
       wl_sjl("Type: SF_ERR");
     } else {
       sprintf(errmss, "Type: SF_??? = %lu", (ulong)p_el->el_selec);
       wl_sjl(errmss);
     } /* end if */
     wl_sjl("Aborted internal function.");
     return;
 } /* end switch */

 /* Write internal result to the product file. */
 p_sc->sc_first = p_res;
 p_sc->sc_last = p_res + strlen(p_res) - 1;
 ex_sc(p_sc, NULL, NULL);
}

/* } ABC */

/******************************************************************************/

LOCAL void ex_ex(p_exp,p_par,p_srctype)
/* Expand the specified expression. */
p_ells_t p_exp;
p_el_t p_par;
p_srcnmac_t p_srctype;
{
 p_void p_mark;

 /* We need to save the current position in the expression list in case we    */
 /* are being recursively invoked (e.g. in @<X@>@(@"@<X@>@(@"sloth@"@)@"@).   */
 ls_fir(p_exp);
 while (TRUE)
   {
    p_el_t p_el;
    ls_nxt(p_exp,PPV &p_el);
    if (p_el==NULL) break;
    p_mark=ls_mar(p_exp);
    switch (p_el->el_kind)
      {
       /* ABC { */
       case EL_TEXT: ex_eltx(p_el,p_par,p_srctype);
                     no_next_aldmQ = FALSE;  break;
       case EL_INVC: ex_elin(p_el,p_par,p_srctype); break;
       case EL_PARM: ex_elpr(p_el,p_par,p_srctype); break;
       case EL_SPEC: ex_elsp(p_el,p_par,p_srctype);
                     no_next_aldmQ = TRUE;  break;
       /* } ABC */
       default     : as_bomb("ex_ex: Case defaulted.");
      }
    ls_set(p_exp,p_mark);
   }
}

/******************************************************************************/

LOCAL void ex_file P_((p_ma_t));
LOCAL void ex_file(p_ma)
/* This function accepts a pointer to a macro. It creates a product file      */
/* with the same name as the macro (inheriting any filename parts given in    */
/* the command line) and expands the macro, writing the expansion to the      */
/* product file.                                                              */
p_ma_t  p_ma;
{
 fn_t  fn_tmp;  /* Name of temporary file.                                    */
 bool  renfil;   /* Do we wish to rename product file?                        */
 bool  istarg;   /* Does a target file already exist?                         */
/* ABC { */
 p_srcnmac_t p_srctype; /* Source code type                                     */
/* } ABC */

 /* Writing product files differs to the other output files. With non         */
 /* critical files such as the listing file that are really just logs,        */
 /* generation of half a listing file is acceptable if not desirable. However */
 /* in the case of product files, it is very bad to generate half a product   */
 /* file; far better to generate none at all. For this reason, and also       */
 /* because of the presence of the D option (which prohibits the writing      */
 /* of product files identical to existing files (to prevent MAKE             */
 /* propagations)) it is best to write a temporary file and then rename it.   */

 /* Construct the target file name.                                           */
 strcpy(fn_targ,"");                /* Start with an empty name.              */
 fn_ins(fn_targ,&option.op_o_s[0]);
 /* ABC { */
#if DYN_NAMES
 fn_ins(fn_targ,p_ma->ma_name);
#else /* !DYN_NAMES */
 fn_ins(fn_targ,&p_ma->ma_name[0]);
#endif /* DYN_NAMES */
 /* } ABC */

 /* The temporary file has to inherit too, because the output directory may   */
 /* not be the default directory and some computers can't rename across       */
 /* directories (and we have to rename it later).                             */
 strcpy(fn_tmp,fn_targ);
 fn_ins(fn_tmp,fn_temp());

/* ABC { */
 /* Set the source code type */
 p_srctype = p_ma->ma_defn.md_aldm;
/* } ABC */

 /* Expand the macro to the temporary file. */
 wf_ini(&f_o,TRUE);
 wf_ope(&f_o,fn_tmp);
 if (wf_err(&f_o))
   {
    sprintf(linet1,"Error creating temporary product file \"%s\".",&fn_tmp[0]);
    wl_sjl(linet1);
    (void) remove(fn_tmp);
    goto severe;
   }

 /* Now expand the target macro into the file. */
 /* ABC { */
 /* An automatic line directive may be needed at the start */
 Need_aldmQ = TRUE;
 no_next_aldmQ = FALSE;
 /* } ABC */
 {
  el_t el;
  el.el_kind  = EL_INVC;
  el.el_p_mac = p_ma;
  el.el_parls = ls_cre(sizeof(p_ells_t));
  /* Note: We don't set el_pretx and el_postx as they are not used here. */
  ind_base = 0;
  ind_curr = 0;
  lineno   = 1;
  errlin   = 0;
  numlong  = 0;
  ex_elin(&el, (p_el_t)0, p_srctype);
 }

 /* Make sure that there weren't any errors writing to the product file. */
 if (wf_err(&f_o))
   {
    sprintf(linet1,"S: Error writing to temporary product file \"%s\".",&fn_tmp[0]);
    wl_sjl(linet1);
    (void) remove(fn_tmp);
    goto severe;
   }

 /* Close the product file. */
 wf_clo(&f_o);
 if (wf_err(&f_o))
   {
    sprintf(linet1,"S: Error closing temporary product file \"%s\".",&fn_tmp[0]);
    wl_sjl(linet1);
    (void) remove(fn_tmp);
    goto severe;
   }

 /* The rest of the code in this function copes with the renaming. */

 /* By default, we wish to rename the temporary file. */
 renfil=TRUE;

 /* Deal with any existing file of the target name. */
 istarg=fexists(fn_targ);
 if (istarg && option.op_d_b)
   {
    /* A target already exists, and the D option is on. If the target is      */
    /* identical to the temporary, we can simply delete the temporary!        */
    char *errstr;
    bool  same;
    errstr=eq_files(fn_tmp,fn_targ,&same);
    if (errstr != NULL)
      {
       wl_sjl("S: Error comparing temporary file with previous product file.");
       wl_sjl("(A comparison was attempted because the D option was turned on.)");
       wl_sjl("Error from comparison routine was as follows (first=temp):");
       wr_sjl("   ");wl_sjl(errstr);
       sprintf(linet1,"Temporary file name was \"%s\".",&fn_tmp[0]);
       wl_sjl(linet1);
       sprintf(linet1,"Product   file name was \"%s\".",fn_targ);
       wl_sjl(linet1);
       wl_sjl("FunnelWeb will leave both files intact so you can look at them.");
       goto severe;
      }
    /* If the two files are the same, we can simply delete the temporary. */
    if (same)
      {
       int status;
       status=remove(fn_tmp);
       if (status != REMOVE_S)
 {
  sprintf(linet1,"S: Error deleting (under +D option) temporary file \"%s\".",&fn_tmp[0]);
  wl_sjl(linet1);
  goto severe;
 }
       sprintf(linet1,"Deleted identical product file \"%s\".",fn_targ);
       wl_sjl(linet1);
       renfil=FALSE;
      }
   }

 if (renfil)
   {
    int status;
    /* We need to delete any existing file of the target name. */
    if (istarg)
      {
       status=remove(fn_targ);
       if (status != REMOVE_S)
 {
  sprintf(linet1,"S: Error deleting existing product file \"%s\".",fn_targ);
  wl_sjl(linet1);
  goto severe;
 }
      }
    /* Rename the temporary file to the product file. */
    status=rename(fn_tmp,fn_targ);
    if (status != RENAME_S)
      {
       wl_sjl("S: Error renaming temporary product file to product file.");
       sprintf(linet1,"Temporary file name was \"%s\".",&fn_tmp[0]);
       wl_sjl(linet1);
       sprintf(linet1,"Product   file name was \"%s\".",fn_targ);
       wl_sjl(linet1);
       wl_sjl("FunnelWeb will leave both files intact so you can look at them.");
       goto severe;
      }
   }

 /* Tell everyone that we have written a product file. */
 /* Note that we use the macro name. The full name is usually too messy. */
 /* ABC { */
#if DYN_NAMES
 sprintf(linet1,"Tangle: Completed %s.",p_ma->ma_name);
#else /* !DYN_NAMES */
 sprintf(linet1,"Tangle: Completed %s.",&p_ma->ma_name[0]);
#endif /* DYN_NAMES */
 /* } ABC */
 wl_sjl(linet1);
 return;

 /* Jump here is a nasty file error occurs. */
 severe:
 sprintf(linet1,"A problem occurred during the generation of product file \"%s\".",&fn_targ[0]);
 wl_sjl(linet1);
 wl_sjl("S: Aborting...");
 num_sev++;
 return;

}

/******************************************************************************/

EXPORT void tangle()
{
 name_t dummyname;
 p_ma_t p_ma;

 /* ABC { */
 /* Initialise inaldmQ: not in auto line directive macro */
 inaldmQ = FALSE;
 /* Initialise Need_aldmQ: no directive needed before next scrap */
 Need_aldmQ = FALSE;
 /* } ABC */

 /* Possibly decrease tglinmax if W option is turned on. */
 if (option.op_w_b)
    tglinmax=MIN(tglinmax,option.op_w_i);

 /* Some compilers do not allow much space for statics so we allocate fn_targ */
 /* dynamically to save static space.                                         */
 fn_targ=(char *) mm_temp(sizeof(fn_t));

 /* Generate each file contained in the file table. */
 tb_fir(file_table);
 while (num_sev==0 && tb_rea(file_table,PV dummyname,PV &p_ma))
    ex_file(p_ma);
}

/******************************************************************************/
/*                               End of TANGLE.C                              */
/******************************************************************************/