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