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