Update recommended gnulib commit
[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   /* Read from stdin into 'input'.  Ensure that 'input' ends in a new-line
74      followed by a null byte. */
75   input = (!strcmp (file_name, "-")
76            ? fread_file (stdin, 0, &length)
77            : read_file (file_name, 0, &length));
78   if (input == NULL)
79     error (EXIT_FAILURE, errno, "reading %s failed", file_name);
80
81   if (strip_trailing_newline && length && input[length - 1] == '\n')
82     {
83       length--;
84       if (length && input[length - 1] == '\r')
85         length--;
86     }
87
88   if (!check_truncations)
89     check_segmentation (input, length, true);
90   else
91     {
92       size_t test_len;
93
94       for (test_len = 0; test_len <= length; test_len++)
95         {
96           char *copy = xmemdup (input, test_len);
97           check_segmentation (copy, test_len, false);
98           free (copy);
99         }
100     }
101   free (input);
102
103   return 0;
104 }
105
106 static void
107 check_segmentation (const char *input, size_t length, bool print_segments)
108 {
109   struct segmenter s;
110   segmenter_init (&s, mode);
111
112   size_t line_number = 1;
113   size_t line_offset = 0;
114   int prev_type = -1;
115   size_t offset = 0;
116   enum segment_type type;
117   do
118     {
119       const char *type_name, *p;
120       int n;
121
122       if (one_byte)
123         {
124           int n_newlines = 0;
125           int i;
126
127           for (i = 0; i <= length - offset; i++)
128             {
129               /* Make a copy to ensure that segmenter_push() isn't actually
130                  looking ahead. */
131               char *copy;
132
133               if (i > 0 && input[offset + i - 1] == '\n')
134                 n_newlines++;
135
136               copy = xmemdup (input + offset, i);
137               n = segmenter_push (&s, copy, i, i + offset >= length, &type);
138               free (copy);
139
140               if (n >= 0)
141                 break;
142             }
143           assert (n_newlines <= 2);
144         }
145       else
146         n = segmenter_push (&s, input + offset, length - offset, true, &type);
147
148       if (n < 0)
149         {
150           if (!print_segments)
151             check_segmentation (input, length, true);
152           else
153             error (EXIT_FAILURE, 0, "segmenter_push returned -1 at offset %zu",
154                    offset);
155         }
156       assert (offset + n <= length);
157
158       if (type == SEG_NEWLINE)
159         {
160           assert ((n == 1 && input[offset] == '\n')
161                   || (n == 2
162                       && input[offset] == '\r' && input[offset + 1] == '\n'));
163         }
164       else
165         assert (memchr (&input[offset], '\n', n) == NULL);
166
167       if (!print_segments)
168         {
169           offset += n;
170           continue;
171         }
172
173       if (!verbose)
174         {
175           if (prev_type != SEG_SPACES && prev_type != -1
176               && type == SEG_SPACES && n == 1 && input[offset] == ' ')
177             {
178               printf ("    space\n");
179               offset++;
180               prev_type = -1;
181               continue;
182             }
183         }
184       if (prev_type != -1)
185         putchar ('\n');
186       prev_type = type;
187
188       if (verbose)
189         printf ("%2zu:%2zu: ", line_number, offset - line_offset);
190
191       type_name = segment_type_to_string (type);
192       for (p = type_name; *p != '\0'; p++)
193         putchar (tolower ((unsigned char) *p));
194       if (n > 0)
195         {
196           int i;
197
198           for (i = MIN (15, strlen (type_name)); i < 16; i++)
199             putchar (' ');
200           for (i = 0; i < n; )
201             {
202               const uint8_t *u_input = CHAR_CAST (const uint8_t *, input);
203               ucs4_t uc;
204               int mblen;
205
206               mblen = u8_mbtoucr (&uc, u_input + (offset + i), n - i);
207               if (mblen < 0)
208                 {
209                   int j;
210
211                   mblen = u8_mbtouc (&uc, u_input + (offset + i), n - i);
212                   putchar ('<');
213                   for (j = 0; j < mblen; j++)
214                     {
215                       if (j > 0)
216                         putchar (' ');
217                       printf ("%02x", input[offset + i + j]);
218                     }
219                   putchar ('>');
220                 }
221               else
222                 {
223                   switch (uc)
224                     {
225                     case ' ':
226                       printf ("_");
227                       break;
228
229                     case '_':
230                       printf ("\\_");
231                       break;
232
233                     case '\\':
234                       printf ("\\\\");
235                       break;
236
237                     case '\t':
238                       printf ("\\t");
239                       break;
240
241                     case '\r':
242                       printf ("\\r");
243                       break;
244
245                     case '\n':
246                       printf ("\\n");
247                       break;
248
249                     case '\v':
250                       printf ("\\v");
251                       break;
252
253                     default:
254                       if (uc < 0x20 || uc == 0x00a0)
255                         printf ("<U+%04X>", uc);
256                       else
257                         fwrite (input + offset + i, 1, mblen, stdout);
258                       break;
259                     }
260                 }
261
262               i += mblen;
263             }
264         }
265
266       offset += n;
267       if (type == SEG_NEWLINE)
268         {
269           enum prompt_style prompt;
270
271           line_number++;
272           line_offset = offset;
273
274           prompt = segmenter_get_prompt (&s);
275           printf (" (%s)\n", prompt_style_to_string (prompt));
276         }
277     }
278   while (type != SEG_END);
279
280   if (print_segments)
281     putchar ('\n');
282 }
283
284 static const char *
285 parse_options (int argc, char **argv)
286 {
287   for (;;)
288     {
289       static const struct option options[] =
290         {
291           {"one-byte", no_argument, NULL, '1'},
292           {"truncations", no_argument, NULL, '0'},
293           {"strip-trailing-newline", no_argument, NULL, 's'},
294           {"auto", no_argument, NULL, 'a'},
295           {"batch", no_argument, NULL, 'b'},
296           {"interactive", no_argument, NULL, 'i'},
297           {"verbose", no_argument, NULL, 'v'},
298           {"help", no_argument, NULL, 'h'},
299           {NULL, 0, NULL, 0},
300         };
301
302       int c = getopt_long (argc, argv, "01abivhs", options, NULL);
303       if (c == -1)
304         break;
305
306       switch (c)
307         {
308         case '1':
309           one_byte = true;
310           break;
311
312         case '0':
313           check_truncations = true;
314           break;
315
316         case 's':
317           strip_trailing_newline = true;
318           break;
319
320         case 'a':
321           mode = SEG_MODE_AUTO;
322           break;
323
324         case 'b':
325           mode = SEG_MODE_BATCH;
326           break;
327
328         case 'i':
329           mode = SEG_MODE_INTERACTIVE;
330           break;
331
332         case 'v':
333           verbose = true;
334           break;
335
336         case 'h':
337           usage ();
338
339         case 0:
340           break;
341
342         case '?':
343           exit (EXIT_FAILURE);
344           break;
345
346         default:
347           NOT_REACHED ();
348         }
349
350     }
351
352   if (optind + 1 != argc)
353     error (1, 0, "exactly one non-option argument required; "
354            "use --help for help");
355   return argv[optind];
356 }
357
358 static void
359 usage (void)
360 {
361   printf ("\
362 %s, to test breaking PSPP syntax into lexical segments\n\
363 usage: %s [OPTIONS] INPUT\n\
364 \n\
365 Options:\n\
366   -1, --one-byte      feed one byte at a time\n\
367   -0, --truncations   check null truncation of each prefix of input\n\
368   -s, --strip-trailing-newline  remove newline from end of input\n\
369   -a, --auto          use \"auto\" syntax mode\n\
370   -b, --batch         use \"batch\" syntax mode\n\
371   -i, --interactive   use \"interactive\" syntax mode (default)\n\
372   -v, --verbose       include rows and column numbers in output\n\
373   -h, --help          print this help message\n",
374           program_name, program_name);
375   exit (EXIT_SUCCESS);
376 }