a9645fba1e9b58c3e85465e2998a291bf0cba536
[ghc-hetmet.git] / ghc / utils / unlit / unlit.c
1 /* unlit.c                                   Wed Dec  5 17:16:24 GMT 1990
2  *
3  * Literate script filter.  In contrast with the format used by most
4  * programming languages, a literate script is a program in which
5  * comments are given the leading role, whilst program text must be
6  * explicitly flagged as such by placing a `>' character in the first
7  * column on each line.  It is hoped that this style of programming will
8  * encourage the writing of accurate and clearly documented programs
9  * in which the writer may include motivating arguments, examples
10  * and explanations.  
11  *
12  * Unlit is a filter that can be used to strip all of the comment lines
13  * out of a literate script file.  The command format for unlit is:
14  *              unlit [-n] [-q] ifile ofile
15  * where ifile and ofile are the names of the input (literate script) and
16  * output (raw program) files respectively.  Either of these names may
17  * be `-' representing the standard input or the standard output resp.
18  * A number of rules are used in an attempt to guard against the most
19  * common errors that are made when writing literate scripts:
20  * 1) Empty script files are not permitted.  A file in which no lines
21  *    begin with `>' usually indicates a file in which the programmer
22  *    has forgotten about the literate script convention.
23  * 2) A line containing part of program definition (i.e. preceeded by `>')
24  *    cannot be used immediately before or after a comment line unless
25  *    the comment line is blank.  This error usually indicates that
26  *    the `>' character has been omitted from a line in a section of
27  *    program spread over a number of lines.
28  * Using the -q (quiet) flag suppresses the signalling of these error
29  * conditions.  The default behaviour can be selected explicitly using
30  * the -n (noisy) option so that any potential errors in the script file
31  * are reported.
32  *
33  * The original idea for the use of literate scripts is due to Richard
34  * Bird of the programming Research Group, Oxford and was initially
35  * adopted for use in the implementation of the functional programming
36  * language Orwell used for teaching in Oxford.  This idea has subsequently
37  * been borrowed in a number of other language implementations.
38  *
39  * Modified to understand \begin{code} ... \end{code} used in Glasgow.  -- LA
40  * And \begin{pseudocode} ... \end{pseudocode}.  -- LA
41  */
42
43 #include <stdio.h>
44 #include <ctype.h>
45
46 #define NULLSTR        ((char *)0)
47 #define DEFNCHAR       '>'
48 #define MISSINGBLANK   "unlit: Program line next to comment"
49 #define EMPTYSCRIPT    "unlit: No definitions in file (perhaps you forgot the '>'s?)"
50 #define USAGE          "usage: unlit [-q] [-n] [-c] file1 file2\n"
51 #define CANNOTOPEN     "unlit: cannot open \"%s\"\n"
52 #define DISTINCTNAMES  "unlit: input and output filenames must differ\n"
53 #define MISSINGENDCODE "unlit: missing \\end{code}\n"
54
55 #define BEGINCODE "\\begin{code}"
56 #define LENBEGINCODE 12
57 #define ENDCODE "\\end{code}"
58 #define LENENDCODE 10
59 #ifdef PSEUDOCODE
60 /* According to Will Partain, the inventor of pseudocode, this gone now. */
61 #define MISSINGENDPSEUDOCODE "unlit: missing \\end{pseudocode}\n"
62 #define BEGINPSEUDOCODE "\\begin{pseudocode}"
63 #define LENBEGINPSEUDOCODE 18
64 #define ENDPSEUDOCODE "\\end{pseudocode}"
65 #define LENENDPSEUDOCODE 16
66 #endif
67
68 typedef enum { START, BLANK, TEXT, DEFN, BEGIN, /*PSEUDO,*/ END, HASH, SHEBANG } line;
69 #define isWhitespace(c)  (c==' '  || c=='\t')
70 #define isLineTerm(c)    (c=='\n' || c==EOF)
71
72 static int noisy  = 1;   /* 0 => keep quiet about errors, 1 => report errors */
73 static int errors = 0;   /* count the number of errors reported              */
74 static int crunchnl = 0; /* don't print \n for removed lines                 */
75 static int leavecpp = 1; /* leave preprocessor lines */
76 static int ignore_shebang = 1; /* Leave out shebang (#!) lines */
77
78 static char* prefix_str = NULL; /* Prefix output with a string */
79
80 /* complain(file,line,what)
81  *
82  * print error message `what' for `file' at `line'.  The error is suppressed
83  * if noisy is not set.
84  */
85
86 complain(file, lin, what)
87 char *file;
88 char *what;
89 int lin; {
90     if (noisy) {
91         if (file)
92             fprintf(stderr, "%s ", file);
93         fprintf(stderr,"line %d: %s\n",lin,what);
94         errors++;
95     }
96 }
97
98 #define TABPOS 8
99
100 /* As getc, but does TAB expansion */
101 int
102 egetc(istream)
103 FILE *istream;
104 {
105     static int spleft = 0;
106     static int linepos = 0;
107     int c;
108
109     if (spleft > 0) {
110         spleft--;
111         linepos++;
112         return ' ';
113     }
114     c = getc(istream);
115     if (c == EOF)
116         return c;
117     else if (c == '\n' || c == '\f') {
118         linepos = 0;
119         return c;
120     } else if (c == '\t') {
121         spleft = TABPOS - linepos % TABPOS;
122         spleft--;
123         linepos++;
124         return ' ';
125     } else {
126         linepos++;
127         return c;
128     }
129
130 }
131
132 /* readline(istream, ostream)
133  *
134  * Read a line from the input stream `istream', and return a value
135  * indicating whether that line was:
136  *     BLANK (whitespace only),
137  *     DEFN  (first character is DEFNCHAR),
138  *     TEXT  (a line of text)
139  *     BEGIN (a \begin{code} line)
140  *     PSEUDO (a \begin{pseodocode} line)
141  *     HASH  (a preprocessor line)
142  * or  END   (indicating an EOF).
143  * Lines of type DEFN are copied to the output stream `ostream'
144  * (without the leading DEFNCHAR).  BLANK and TEXT lines are
145  * replaced by empty (i.e. blank lines) in the output stream, so
146  * that error messages refering to line numbers in the output file
147  * can also be used to locate the corresponding line in the input
148  * stream.
149  */
150
151 line readline(istream,ostream)
152 FILE *istream, *ostream; {
153     int c, c1;
154     char buf[100];
155     int i;
156
157     c = egetc(istream);
158
159     if (c==EOF)
160         return END;
161   
162     if ( c == '#' ) {
163       if ( ignore_shebang ) {
164          c1 = egetc(istream);
165          if ( c1 == '!' ) {
166            while (c=egetc(istream), !isLineTerm(c)) ;
167            return SHEBANG;
168          }
169          putc(c, ostream);
170          c=c1;
171       }
172       if ( leavecpp ) {
173         putc(c, ostream);
174         while (c=egetc(istream), !isLineTerm(c))
175             putc(c,ostream);
176         putc('\n',ostream);
177         return HASH;
178       }
179     }
180
181     if (c==DEFNCHAR) {
182 /*      putc(' ',ostream);*/
183         while (c=egetc(istream), !isLineTerm(c))
184             putc(c,ostream);
185         putc('\n',ostream);
186         return DEFN;
187     }
188
189     if (!crunchnl)
190         putc('\n',ostream);
191
192     while (isWhitespace(c))
193         c=egetc(istream);
194     if (isLineTerm(c))
195         return BLANK;
196
197     i = 0;
198     buf[i++] = c;
199     while (c=egetc(istream), !isLineTerm(c))
200         if (i < sizeof buf - 1)
201             buf[i++] = c;
202     while(i > 0 && isspace(buf[i-1]))
203         i--;
204     buf[i] = 0;
205     if (strcmp(buf, BEGINCODE) == 0)
206         return BEGIN;
207 #ifdef PSEUDOCODE
208     else if (strcmp(buf, BEGINPSEUDOCODE) == 0)
209         return PSEUDO;
210 #endif
211     else
212         return TEXT;
213 }
214
215
216 /* unlit(file,istream,ostream)
217  *
218  * Copy the file named `file', accessed using the input stream `istream'
219  * to the output stream `ostream', removing any comments and checking
220  * for bad use of literate script features:
221  *  - there should be at least one BLANK line between a DEFN and TEXT
222  *  - there should be at least one DEFN line in a script.
223  */
224
225 unlit(file, istream, ostream)
226 char *file;
227 FILE *istream;
228 FILE *ostream; {
229     line last, this=START;
230     int  linesread=0;
231     int  defnsread=0;
232
233     do {
234         last = this;
235         this = readline(istream, ostream);
236         linesread++;
237         if (this==DEFN)
238             defnsread++;
239         if (last==DEFN && this==TEXT)
240             complain(file, linesread-1, MISSINGBLANK);
241         if (last==TEXT && this==DEFN)
242             complain(file, linesread, MISSINGBLANK);
243         if (this == BEGIN) {
244             /* start of code, copy to end */
245             char lineb[1000];
246             for(;;) {
247                 if (fgets(lineb, sizeof lineb, istream) == NULL) {
248                     complain(file, linesread, MISSINGENDCODE);
249                     exit(1);
250                 }
251                 linesread++;
252                 if (strncmp(lineb,ENDCODE,LENENDCODE) == 0) {
253                     putc('\n', ostream);
254                     break;
255                 }
256                 fputs(lineb, ostream);
257             }
258             defnsread++;
259         }
260 #ifdef PSEUDOCODE
261         if (this == PSEUDO) {
262             char lineb[1000];
263             for(;;) {
264                 if (fgets(lineb, sizeof lineb, istream) == NULL) {
265                     complain(file, linesread, MISSINGENDPSEUDOCODE);
266                     exit(1);
267                 }
268                 linesread++;
269                 putc('\n', ostream);
270                 if (strncmp(lineb,ENDPSEUDOCODE,LENENDPSEUDOCODE) == 0) {
271                     break;
272                 }
273             }
274         }
275 #endif
276     } while(this!=END);
277
278     if (defnsread==0)
279         complain(file,linesread,EMPTYSCRIPT);
280 }
281
282 /* main(argc, argv)
283  *
284  * Main program.  Processes command line arguments, looking for leading:
285  *  -q  quiet mode - do not complain about bad literate script files
286  *  -n  noisy mode - complain about bad literate script files.
287  *  -r  remove cpp droppings in output.
288  * Expects two additional arguments, a file name for the input and a file
289  * name for the output file.  These two names must normally be distinct.
290  * An exception is made for the special name "-" which can be used in either
291  * position to specify the standard input or the standard output respectively.
292  */
293
294 main(argc,argv)
295 int argc;
296 char **argv; {
297     FILE *istream, *ostream;
298     char *file;
299
300     for (argc--, argv++; argc > 0; argc--, argv++)
301         if (strcmp(*argv,"-n")==0)
302             noisy = 1;
303         else if (strcmp(*argv,"-q")==0)
304             noisy = 0;
305         else if (strcmp(*argv,"-c")==0)
306             crunchnl = 1;
307         else if (strcmp(*argv,"-h")==0) {
308           if (argc > 1) {
309             argc--; argv++;
310             if (prefix_str) 
311               free(prefix_str);
312             prefix_str = (char*)malloc(sizeof(char)*(1+strlen(*argv)));
313             if (prefix_str) 
314               strcpy(prefix_str, *argv);
315           }
316         } else if (strcmp(*argv,"-#")==0)
317             ignore_shebang = 0;
318         else
319             break;
320
321     if (argc!=2) {
322         fprintf(stderr, USAGE);
323         exit(1);
324     }
325
326     if (strcmp(argv[0],argv[1])==0 && strcmp(argv[0],"-")!=0) {
327         fprintf(stderr, DISTINCTNAMES);
328         exit(1);
329     }
330
331     file = argv[0];
332     if (strcmp(argv[0], "-")==0) {
333         istream = stdin;
334         file    = "stdin";
335     }
336     else
337         if ((istream=fopen(argv[0], "r")) == NULL) {
338             fprintf(stderr, CANNOTOPEN, argv[0]);
339             exit(1);
340         }
341
342     if (strcmp(argv[1], "-")==0) 
343         ostream = stdout; 
344     else
345         if ((ostream=fopen(argv[1], "w")) == NULL)  {
346             fprintf(stderr, CANNOTOPEN, argv[1]);
347             exit(1);
348         }
349
350     /* Prefix the output with line pragmas */
351     if (prefix_str) {
352       fprintf(ostream, "#line 1 \"%s\"\n{-# LINE 1 \"%s\" #-}\n", prefix_str, prefix_str);
353     }
354
355     unlit(file, istream, ostream);
356
357     if (istream != stdin)  fclose(istream);
358     if (ostream != stdout) fclose(ostream);
359
360     exit(errors==0 ? 0 : 1);
361 }