acb444f20018c3dceb87da7a106592be21acaed9
[pspp] / tests / language / lexer / segment-test.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <limits.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistr.h>
27
28 #include "libpspp/assertion.h"
29 #include "libpspp/cast.h"
30 #include "libpspp/compiler.h"
31 #include "libpspp/misc.h"
32 #include "language/lexer/segment.h"
33
34 #include "gl/error.h"
35 #include "gl/minmax.h"
36 #include "gl/progname.h"
37 #include "gl/read-file.h"
38 #include "gl/xalloc.h"
39 #include "gl/xmemdup0.h"
40
41 /* -a/--auto, -b/--batch, -i/--interactive: syntax mode. */
42 static enum segmenter_mode mode = SEG_MODE_AUTO;
43
44 /* -v, --verbose: Print row and column information. */
45 static bool verbose;
46
47 /* -1, --one-byte: Feed in one byte at a time? */
48 static bool one_byte;
49
50 /* -0, --truncations: Check that every truncation of input yields a result. */
51 static bool check_truncations;
52
53 /* -s, --strip-trailing-newline: Strip trailing newline from last line of
54     input. */
55 static bool strip_trailing_newline;
56
57 static const char *parse_options (int argc, char **argv);
58 static void usage (void) NO_RETURN;
59
60 static void check_segmentation (const char *input, size_t length,
61                                 bool print_segments);
62
63 int
64 main (int argc, char *argv[])
65 {
66   const char *file_name;
67   size_t length;
68   char *input;
69
70   set_program_name (argv[0]);
71   file_name = parse_options (argc, argv);
72
73   setvbuf (stdout, NULL, _IONBF, 0);
74
75   /* Read from stdin into 'input'.  Ensure that 'input' ends in a new-line
76      followed by a null byte. */
77   input = (!strcmp (file_name, "-")
78            ? fread_file (stdin, 0, &length)
79            : read_file (file_name, 0, &length));
80   if (input == NULL)
81     error (EXIT_FAILURE, errno, "reading %s failed", file_name);
82
83   if (strip_trailing_newline && length && input[length - 1] == '\n')
84     {
85       length--;
86       if (length && input[length - 1] == '\r')
87         length--;
88     }
89
90   if (!check_truncations)
91     check_segmentation (input, length, true);
92   else
93     {
94       size_t test_len;
95
96       for (test_len = 0; test_len <= length; test_len++)
97         {
98           char *copy = xmemdup (input, test_len);
99           check_segmentation (copy, test_len, false);
100           free (copy);
101         }
102     }
103   free (input);
104
105   return 0;
106 }
107
108 static void
109 check_segmentation (const char *input, size_t length, bool print_segments)
110 {
111   struct segmenter s = segmenter_init (mode, false);
112
113   size_t line_number = 1;
114   size_t line_offset = 0;
115   int prev_type = -1;
116   size_t offset = 0;
117   enum segment_type type;
118   do
119     {
120       const char *type_name, *p;
121       int n;
122
123       if (one_byte)
124         {
125           int n_newlines = 0;
126           int i;
127
128           for (i = 0; i <= length - offset; i++)
129             {
130               /* Make a copy to ensure that segmenter_push() isn't actually
131                  looking ahead. */
132               char *copy;
133
134               if (i > 0 && input[offset + i - 1] == '\n')
135                 n_newlines++;
136
137               copy = xmemdup (input + offset, i);
138               n = segmenter_push (&s, copy, i, i + offset >= length, &type);
139               free (copy);
140
141               if (n >= 0)
142                 break;
143             }
144           assert (n_newlines <= 2);
145         }
146       else
147         n = segmenter_push (&s, input + offset, length - offset, true, &type);
148
149       if (n < 0)
150         {
151           if (!print_segments)
152             check_segmentation (input, length, true);
153           else
154             error (EXIT_FAILURE, 0, "segmenter_push returned -1 at offset %zu",
155                    offset);
156         }
157       assert (offset + n <= length);
158
159       if (type == SEG_NEWLINE)
160         {
161           if (n == 1 ? input[offset] != '\n'
162               : n == 2 ? input[offset] != '\r' || input[offset + 1] != '\n'
163               : false)
164             error (EXIT_FAILURE, 0, "NEWLINE segment at offset %zu contains "
165                    "non-newline content \"%.*s\"", offset, n, &input[offset]);
166         }
167       else if (memchr (&input[offset], '\n', n))
168         error (EXIT_FAILURE, 0, "%s segment \"%.*s\" contains new-line",
169                segment_type_to_string (type), n, &input[offset]);
170
171       if (!print_segments)
172         {
173           offset += n;
174           continue;
175         }
176
177       if (!verbose)
178         {
179           if (prev_type != SEG_SPACES && prev_type != -1
180               && type == SEG_SPACES && n == 1 && input[offset] == ' ')
181             {
182               printf ("    space\n");
183               offset++;
184               prev_type = -1;
185               continue;
186             }
187         }
188       if (prev_type != -1)
189         putchar ('\n');
190       prev_type = type;
191
192       if (verbose)
193         printf ("%2zu:%2zu: ", line_number, offset - line_offset);
194
195       type_name = segment_type_to_string (type);
196       for (p = type_name; *p != '\0'; p++)
197         putchar (tolower ((unsigned char) *p));
198       if (n > 0)
199         {
200           int i;
201
202           for (i = MIN (15, strlen (type_name)); i < 16; i++)
203             putchar (' ');
204           for (i = 0; i < n;)
205             {
206               const uint8_t *u_input = CHAR_CAST (const uint8_t *, input);
207               ucs4_t uc;
208               int mblen;
209
210               mblen = u8_mbtoucr (&uc, u_input + (offset + i), n - i);
211               if (mblen < 0)
212                 {
213                   int j;
214
215                   mblen = u8_mbtouc (&uc, u_input + (offset + i), n - i);
216                   putchar ('<');
217                   for (j = 0; j < mblen; j++)
218                     {
219                       if (j > 0)
220                         putchar (' ');
221                       printf ("%02x", input[offset + i + j]);
222                     }
223                   putchar ('>');
224                 }
225               else
226                 {
227                   switch (uc)
228                     {
229                     case ' ':
230                       printf ("_");
231                       break;
232
233                     case '_':
234                       printf ("\\_");
235                       break;
236
237                     case '\\':
238                       printf ("\\\\");
239                       break;
240
241                     case '\t':
242                       printf ("\\t");
243                       break;
244
245                     case '\r':
246                       printf ("\\r");
247                       break;
248
249                     case '\n':
250                       printf ("\\n");
251                       break;
252
253                     case '\v':
254                       printf ("\\v");
255                       break;
256
257                     default:
258                       if (uc < 0x20 || uc == 0x00a0)
259                         printf ("<U+%04X>", uc);
260                       else
261                         fwrite (input + offset + i, 1, mblen, stdout);
262                       break;
263                     }
264                 }
265
266               i += mblen;
267             }
268         }
269
270       offset += n;
271       if (type == SEG_NEWLINE)
272         {
273           enum prompt_style prompt;
274
275           line_number++;
276           line_offset = offset;
277
278           prompt = segmenter_get_prompt (&s);
279           printf (" (%s)\n", prompt_style_to_string (prompt));
280         }
281       fflush (stdout);
282     }
283   while (type != SEG_END);
284
285   if (print_segments)
286     putchar ('\n');
287 }
288
289 static const char *
290 parse_options (int argc, char **argv)
291 {
292   for (;;)
293     {
294       static const struct option options[] =
295         {
296           {"one-byte", no_argument, NULL, '1'},
297           {"truncations", no_argument, NULL, '0'},
298           {"strip-trailing-newline", no_argument, NULL, 's'},
299           {"auto", no_argument, NULL, 'a'},
300           {"batch", no_argument, NULL, 'b'},
301           {"interactive", no_argument, NULL, 'i'},
302           {"verbose", no_argument, NULL, 'v'},
303           {"help", no_argument, NULL, 'h'},
304           {NULL, 0, NULL, 0},
305         };
306
307       int c = getopt_long (argc, argv, "01abivhs", options, NULL);
308       if (c == -1)
309         break;
310
311       switch (c)
312         {
313         case '1':
314           one_byte = true;
315           break;
316
317         case '0':
318           check_truncations = true;
319           break;
320
321         case 's':
322           strip_trailing_newline = true;
323           break;
324
325         case 'a':
326           mode = SEG_MODE_AUTO;
327           break;
328
329         case 'b':
330           mode = SEG_MODE_BATCH;
331           break;
332
333         case 'i':
334           mode = SEG_MODE_INTERACTIVE;
335           break;
336
337         case 'v':
338           verbose = true;
339           break;
340
341         case 'h':
342           usage ();
343
344         case 0:
345           break;
346
347         case '?':
348           exit (EXIT_FAILURE);
349           break;
350
351         default:
352           NOT_REACHED ();
353         }
354
355     }
356
357   if (optind + 1 != argc)
358     error (1, 0, "exactly one non-option argument required; "
359            "use --help for help");
360   return argv[optind];
361 }
362
363 static void
364 usage (void)
365 {
366   printf ("\
367 %s, to test breaking PSPP syntax into lexical segments\n\
368 usage: %s [OPTIONS] INPUT\n\
369 \n\
370 Options:\n\
371   -1, --one-byte      feed one byte at a time\n\
372   -0, --truncations   check null truncation of each prefix of input\n\
373   -s, --strip-trailing-newline  remove newline from end of input\n\
374   -a, --auto          use \"auto\" syntax mode\n\
375   -b, --batch         use \"batch\" syntax mode\n\
376   -i, --interactive   use \"interactive\" syntax mode (default)\n\
377   -v, --verbose       include rows and column numbers in output\n\
378   -h, --help          print this help message\n",
379           program_name, program_name);
380   exit (EXIT_SUCCESS);
381 }