[project @ 2004-09-16 22:41:33 by sof]
[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 <stdlib.h>
45 #include <ctype.h>
46
47 #define NULLSTR        ((char *)0)
48 #define DEFNCHAR       '>'
49 #define MISSINGBLANK   "unlit: Program line next to comment"
50 #define EMPTYSCRIPT    "unlit: No definitions in file (perhaps you forgot the '>'s?)"
51 #define USAGE          "usage: unlit [-q] [-n] [-c] [-#] [-P] [-h label] file1 file2\n"
52 #define CANNOTOPEN     "unlit: cannot open \"%s\"\n"
53 #define CANNOTWRITE    "unlit: error writing \"%s\"\n"
54 #define CANNOTWRITESTDOUT "unlit: error writing standard output\n"
55 #define DISTINCTNAMES  "unlit: input and output filenames must differ\n"
56 #define MISSINGENDCODE "unlit: missing \\end{code}\n"
57
58 #define BEGINCODE "\\begin{code}"
59 #define LENBEGINCODE 12
60 #define ENDCODE "\\end{code}"
61 #define LENENDCODE 10
62 #ifdef PSEUDOCODE
63 /* According to Will Partain, the inventor of pseudocode, this gone now. */
64 #define MISSINGENDPSEUDOCODE "unlit: missing \\end{pseudocode}\n"
65 #define BEGINPSEUDOCODE "\\begin{pseudocode}"
66 #define LENBEGINPSEUDOCODE 18
67 #define ENDPSEUDOCODE "\\end{pseudocode}"
68 #define LENENDPSEUDOCODE 16
69 #endif
70
71 typedef enum { START, BLANK, TEXT, DEFN, BEGIN, /*PSEUDO,*/ END, HASH, SHEBANG } line;
72 #define isWhitespace(c)  (c==' '  || c=='\t')
73 #define isLineTerm(c)    (c=='\n' || c==EOF)
74
75 static int noisy  = 1;   /* 0 => keep quiet about errors, 1 => report errors */
76 static int errors = 0;   /* count the number of errors reported              */
77 static int crunchnl = 0; /* don't print \n for removed lines                 */
78 static int leavecpp = 1; /* leave preprocessor lines */
79 static int ignore_shebang = 1; /* Leave out shebang (#!) lines */
80 static int no_line_pragma = 0; /* Leave out initial line pragma */
81
82 static char* prefix_str = NULL; /* Prefix output with a string */
83
84 static char *ofilename = NULL;
85
86 /* complain(file,line,what)
87  *
88  * print error message `what' for `file' at `line'.  The error is suppressed
89  * if noisy is not set.
90  */
91
92 complain(file, lin, what)
93 char *file;
94 char *what;
95 int lin; {
96     if (noisy) {
97         if (file)
98             fprintf(stderr, "%s ", file);
99         fprintf(stderr,"line %d: %s\n",lin,what);
100         errors++;
101     }
102 }
103
104 writeerror()
105 {
106     if (!strcmp(ofilename,"-")) {
107         fprintf(stderr, CANNOTWRITESTDOUT);
108     } else {
109         fprintf(stderr, CANNOTWRITE, ofilename);
110     }
111     exit(1);
112 }
113
114 myputc(c, ostream)
115 char c;
116 FILE *ostream; {
117     if (putc(c,ostream) == EOF) {
118         writeerror();
119     }   
120 }
121
122 #define TABPOS 8
123
124 /* As getc, but does TAB expansion */
125 int
126 egetc(istream)
127 FILE *istream;
128 {
129     static int spleft = 0;
130     static int linepos = 0;
131     int c;
132
133     if (spleft > 0) {
134         spleft--;
135         linepos++;
136         return ' ';
137     }
138     c = getc(istream);
139     if (c == EOF)
140         return c;
141     else if (c == '\n' || c == '\f') {
142         linepos = 0;
143         return c;
144     } else if (c == '\t') {
145         spleft = TABPOS - linepos % TABPOS;
146         spleft--;
147         linepos++;
148         return ' ';
149     } else {
150         linepos++;
151         return c;
152     }
153
154 }
155
156 /* readline(istream, ostream)
157  *
158  * Read a line from the input stream `istream', and return a value
159  * indicating whether that line was:
160  *     BLANK (whitespace only),
161  *     DEFN  (first character is DEFNCHAR),
162  *     TEXT  (a line of text)
163  *     BEGIN (a \begin{code} line)
164  *     PSEUDO (a \begin{pseodocode} line)
165  *     HASH  (a preprocessor line)
166  * or  END   (indicating an EOF).
167  * Lines of type DEFN are copied to the output stream `ostream'
168  * (without the leading DEFNCHAR).  BLANK and TEXT lines are
169  * replaced by empty (i.e. blank lines) in the output stream, so
170  * that error messages refering to line numbers in the output file
171  * can also be used to locate the corresponding line in the input
172  * stream.
173  */
174
175 line readline(istream,ostream)
176 FILE *istream, *ostream; {
177     int c, c1;
178     char buf[100];
179     int i;
180
181     c = egetc(istream);
182
183     if (c==EOF)
184         return END;
185   
186     if ( c == '#' ) {
187       if ( ignore_shebang ) {
188          c1 = egetc(istream);
189          if ( c1 == '!' ) {
190            while (c=egetc(istream), !isLineTerm(c)) ;
191            return SHEBANG;
192          }
193          myputc(c, ostream);
194          c=c1;
195       }
196       if ( leavecpp ) {
197         myputc(c, ostream);
198         while (c=egetc(istream), !isLineTerm(c))
199             myputc(c,ostream);
200         myputc('\n',ostream);
201         return HASH;
202       }
203     }
204
205     if (c==DEFNCHAR) {
206 /*      myputc(' ',ostream);*/
207         while (c=egetc(istream), !isLineTerm(c))
208             myputc(c,ostream);
209         myputc('\n',ostream);
210         return DEFN;
211     }
212
213     if (!crunchnl)
214         myputc('\n',ostream);
215
216     while (isWhitespace(c))
217         c=egetc(istream);
218     if (isLineTerm(c))
219         return BLANK;
220
221     i = 0;
222     buf[i++] = c;
223     while (c=egetc(istream), !isLineTerm(c))
224         if (i < sizeof buf - 1)
225             buf[i++] = c;
226     while(i > 0 && isspace(buf[i-1]))
227         i--;
228     buf[i] = 0;
229     if (strcmp(buf, BEGINCODE) == 0)
230         return BEGIN;
231 #ifdef PSEUDOCODE
232     else if (strcmp(buf, BEGINPSEUDOCODE) == 0)
233         return PSEUDO;
234 #endif
235     else
236         return TEXT;
237 }
238
239
240 /* unlit(file,istream,ostream)
241  *
242  * Copy the file named `file', accessed using the input stream `istream'
243  * to the output stream `ostream', removing any comments and checking
244  * for bad use of literate script features:
245  *  - there should be at least one BLANK line between a DEFN and TEXT
246  *  - there should be at least one DEFN line in a script.
247  */
248
249 unlit(file, istream, ostream)
250 char *file;
251 FILE *istream;
252 FILE *ostream; {
253     line last, this=START;
254     int  linesread=0;
255     int  defnsread=0;
256
257     do {
258         last = this;
259         this = readline(istream, ostream);
260         linesread++;
261         if (this==DEFN)
262             defnsread++;
263         if (last==DEFN && this==TEXT)
264             complain(file, linesread-1, MISSINGBLANK);
265         if (last==TEXT && this==DEFN)
266             complain(file, linesread, MISSINGBLANK);
267         if (this == BEGIN) {
268             /* start of code, copy to end */
269             char lineb[1000];
270             for(;;) {
271                 if (fgets(lineb, sizeof lineb, istream) == NULL) {
272                     complain(file, linesread, MISSINGENDCODE);
273                     exit(1);
274                 }
275                 linesread++;
276                 if (strncmp(lineb,ENDCODE,LENENDCODE) == 0) {
277                     myputc('\n', ostream);
278                     break;
279                 }
280                 fputs(lineb, ostream);
281             }
282             defnsread++;
283         }
284 #ifdef PSEUDOCODE
285         if (this == PSEUDO) {
286             char lineb[1000];
287             for(;;) {
288                 if (fgets(lineb, sizeof lineb, istream) == NULL) {
289                     complain(file, linesread, MISSINGENDPSEUDOCODE);
290                     exit(1);
291                 }
292                 linesread++;
293                 myputc('\n', ostream);
294                 if (strncmp(lineb,ENDPSEUDOCODE,LENENDPSEUDOCODE) == 0) {
295                     break;
296                 }
297             }
298         }
299 #endif
300     } while(this!=END);
301
302     if (defnsread==0)
303         complain(file,linesread,EMPTYSCRIPT);
304 }
305
306 /* main(argc, argv)
307  *
308  * Main program.  Processes command line arguments, looking for leading:
309  *  -q  quiet mode - do not complain about bad literate script files
310  *  -n  noisy mode - complain about bad literate script files.
311  *  -r  remove cpp droppings in output.
312  *  -P  don't output any CPP line pragmas.
313  * Expects two additional arguments, a file name for the input and a file
314  * name for the output file.  These two names must normally be distinct.
315  * An exception is made for the special name "-" which can be used in either
316  * position to specify the standard input or the standard output respectively.
317  */
318
319 main(argc,argv)
320 int argc;
321 char **argv; {
322     FILE *istream, *ostream;
323     char *file;
324
325     for (argc--, argv++; argc > 0; argc--, argv++)
326         if (strcmp(*argv,"-n")==0)
327             noisy = 1;
328         else if (strcmp(*argv,"-q")==0)
329             noisy = 0;
330         else if (strcmp(*argv,"-c")==0)
331             crunchnl = 1;
332         else if (strcmp(*argv,"-P")==0)
333             no_line_pragma = 1;
334         else if (strcmp(*argv,"-h")==0) {
335           if (argc > 1) {
336             argc--; argv++;
337             if (prefix_str) 
338               free(prefix_str);
339             prefix_str = (char*)malloc(sizeof(char)*(1+strlen(*argv)));
340             if (prefix_str) 
341               strcpy(prefix_str, *argv);
342           }
343         } else if (strcmp(*argv,"-#")==0)
344             ignore_shebang = 0;
345         else
346             break;
347
348     if (argc!=2) {
349         fprintf(stderr, USAGE);
350         exit(1);
351     }
352
353     if (strcmp(argv[0],argv[1])==0 && strcmp(argv[0],"-")!=0) {
354         fprintf(stderr, DISTINCTNAMES);
355         exit(1);
356     }
357
358     file = argv[0];
359     if (strcmp(argv[0], "-")==0) {
360         istream = stdin;
361         file    = "stdin";
362     }
363     else
364         if ((istream=fopen(argv[0], "r")) == NULL) {
365             fprintf(stderr, CANNOTOPEN, argv[0]);
366             exit(1);
367         }
368
369     ofilename=argv[1];
370     if (strcmp(argv[1], "-")==0) 
371         ostream = stdout; 
372     else
373         if ((ostream=fopen(argv[1], "w")) == NULL)  {
374             fprintf(stderr, CANNOTOPEN, argv[1]);
375             exit(1);
376         }
377
378     /* Prefix the output with line pragmas */
379     if (!no_line_pragma && prefix_str) {
380       /* Both GHC and CPP understand the #line pragma.
381        * We used to throw in both a #line and a {-# LINE #-} pragma
382        * here, but CPP doesn't understand {-# LINE #-} so it thought
383        * the line numbers were off by one.  We could put the {-# LINE
384        * #-} before the #line, but there's no point since GHC
385        * understands #line anyhow.  --SDM 8/2003
386        */
387       fprintf(ostream, "#line 1 \"%s\"\n", prefix_str);
388     }
389
390     unlit(file, istream, ostream);
391
392     if (istream != stdin) fclose(istream);
393     if (ostream != stdout) {
394         if (fclose(ostream) == EOF) {
395             writeerror();
396         }
397     }
398
399     exit(errors==0 ? 0 : 1);
400 }