Imported Upstream version 0.19.7
[platform/upstream/gettext.git] / gettext-tools / src / format-sh.c
1 /* Shell format strings.
2    Copyright (C) 2003-2004, 2006-2007, 2009, 2015 Free Software
3    Foundation, Inc.
4    Written by Bruno Haible <bruno@clisp.org>, 2003.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "format.h"
28 #include "c-ctype.h"
29 #include "xalloc.h"
30 #include "format-invalid.h"
31 #include "gettext.h"
32
33 #define _(str) gettext (str)
34
35 /* Shell format strings are simply strings subjects to variable substitution.
36    A variable substitution starts with '$' and is finished by either
37    - a nonempty sequence of alphanumeric ASCII characters, the first being
38      not a digit, or
39    - an opening brace '{', a nonempty sequence of alphanumeric ASCII
40      characters, the first being not a digit, and a closing brace '}'.
41    We don't support variable references like $1, $$ or $? since they make
42    no sense when 'envsubst' is invoked.
43    We don't support non-ASCII variable names, to avoid dependencies w.r.t. the
44    current encoding: While "${\xe0}" looks like a variable access in ISO-8859-1
45    encoding, it doesn't look like one in the BIG5, BIG5-HKSCS, GBK, GB18030,
46    SHIFT_JIS, JOHAB encodings, because \xe0\x7d is a single character in these
47    encodings.
48    We don't support the POSIX syntax for default or alternate values:
49      ${variable-default}        ${variable:-default}
50      ${variable=default}        ${variable:=default}
51      ${variable+replacement}    ${variable:+replacement}
52      ${variable?ignored}        ${variable:?ignored}
53    because the translator might be tempted to change the default value; if
54    we allow it we have a security problem; if we don't allow it the translator
55    will be surprised.
56  */
57
58 struct named_arg
59 {
60   char *name;
61 };
62
63 struct spec
64 {
65   unsigned int directives;
66   unsigned int named_arg_count;
67   unsigned int allocated;
68   struct named_arg *named;
69 };
70
71
72 static int
73 named_arg_compare (const void *p1, const void *p2)
74 {
75   return strcmp (((const struct named_arg *) p1)->name,
76                  ((const struct named_arg *) p2)->name);
77 }
78
79 #define INVALID_NON_ASCII_VARIABLE() \
80   xstrdup (_("The string refers to a shell variable with a non-ASCII name."))
81 #define INVALID_SHELL_SYNTAX() \
82   xstrdup (_("The string refers to a shell variable with complex shell brace syntax. This syntax is unsupported here due to security reasons."))
83 #define INVALID_CONTEXT_DEPENDENT_VARIABLE() \
84   xstrdup (_("The string refers to a shell variable whose value may be different inside shell functions."))
85 #define INVALID_EMPTY_VARIABLE() \
86   xstrdup (_("The string refers to a shell variable with an empty name."))
87
88 static void *
89 format_parse (const char *format, bool translated, char *fdi,
90               char **invalid_reason)
91 {
92   const char *const format_start = format;
93   struct spec spec;
94   struct spec *result;
95
96   spec.directives = 0;
97   spec.named_arg_count = 0;
98   spec.allocated = 0;
99   spec.named = NULL;
100
101   for (; *format != '\0';)
102     if (*format++ == '$')
103       {
104         /* A variable substitution.  */
105         char *name;
106
107         FDI_SET (format - 1, FMTDIR_START);
108         spec.directives++;
109
110         if (*format == '{')
111           {
112             const char *name_start;
113             const char *name_end;
114             size_t n;
115
116             name_start = ++format;
117             for (; *format != '\0'; format++)
118               {
119                 if (*format == '}')
120                   break;
121                 if (!c_isascii (*format))
122                   {
123                     *invalid_reason = INVALID_NON_ASCII_VARIABLE ();
124                     FDI_SET (format, FMTDIR_ERROR);
125                     goto bad_format;
126                   }
127                 if (format > name_start
128                     && (*format == '-' || *format == '=' || *format == '+'
129                         || *format == '?' || *format == ':'))
130                   {
131                     *invalid_reason = INVALID_SHELL_SYNTAX ();
132                     FDI_SET (format, FMTDIR_ERROR);
133                     goto bad_format;
134                   }
135                 if (!(c_isalnum (*format) || *format == '_')
136                     || (format == name_start && c_isdigit (*format)))
137                   {
138                     *invalid_reason = INVALID_CONTEXT_DEPENDENT_VARIABLE ();
139                     FDI_SET (format, FMTDIR_ERROR);
140                     goto bad_format;
141                   }
142               }
143             if (*format == '\0')
144               {
145                 *invalid_reason = INVALID_UNTERMINATED_DIRECTIVE ();
146                 FDI_SET (format - 1, FMTDIR_ERROR);
147                 goto bad_format;
148               }
149             name_end = format++;
150
151             n = name_end - name_start;
152             if (n == 0)
153               {
154                 *invalid_reason = INVALID_EMPTY_VARIABLE ();
155                 FDI_SET (format - 1, FMTDIR_ERROR);
156                 goto bad_format;
157               }
158             name = XNMALLOC (n + 1, char);
159             memcpy (name, name_start, n);
160             name[n] = '\0';
161           }
162         else if (c_isalpha (*format) || *format == '_')
163           {
164             const char *name_start;
165             const char *name_end;
166             size_t n;
167
168             name_start = format;
169             do
170               format++;
171             while (*format != '\0' && (c_isalnum (*format) || *format == '_'));
172             name_end = format;
173
174             n = name_end - name_start;
175             name = XNMALLOC (n + 1, char);
176             memcpy (name, name_start, n);
177             name[n] = '\0';
178           }
179         else if (*format != '\0')
180           {
181             if (!c_isascii (*format))
182               {
183                 *invalid_reason = INVALID_NON_ASCII_VARIABLE ();
184                 FDI_SET (format, FMTDIR_ERROR);
185                 goto bad_format;
186               }
187             else
188               {
189                 *invalid_reason = INVALID_CONTEXT_DEPENDENT_VARIABLE ();
190                 FDI_SET (format, FMTDIR_ERROR);
191                 goto bad_format;
192               }
193           }
194         else
195           {
196             *invalid_reason = INVALID_UNTERMINATED_DIRECTIVE ();
197             FDI_SET (format - 1, FMTDIR_ERROR);
198             goto bad_format;
199           }
200
201         /* Named argument.  */
202         if (spec.allocated == spec.named_arg_count)
203           {
204             spec.allocated = 2 * spec.allocated + 1;
205             spec.named = (struct named_arg *) xrealloc (spec.named, spec.allocated * sizeof (struct named_arg));
206           }
207         spec.named[spec.named_arg_count].name = name;
208         spec.named_arg_count++;
209
210         FDI_SET (format - 1, FMTDIR_END);
211       }
212
213   /* Sort the named argument array, and eliminate duplicates.  */
214   if (spec.named_arg_count > 1)
215     {
216       unsigned int i, j;
217
218       qsort (spec.named, spec.named_arg_count, sizeof (struct named_arg),
219              named_arg_compare);
220
221       /* Remove duplicates: Copy from i to j, keeping 0 <= j <= i.  */
222       for (i = j = 0; i < spec.named_arg_count; i++)
223         if (j > 0 && strcmp (spec.named[i].name, spec.named[j-1].name) == 0)
224           free (spec.named[i].name);
225         else
226           {
227             if (j < i)
228               spec.named[j].name = spec.named[i].name;
229             j++;
230           }
231       spec.named_arg_count = j;
232     }
233
234   result = XMALLOC (struct spec);
235   *result = spec;
236   return result;
237
238  bad_format:
239   if (spec.named != NULL)
240     {
241       unsigned int i;
242       for (i = 0; i < spec.named_arg_count; i++)
243         free (spec.named[i].name);
244       free (spec.named);
245     }
246   return NULL;
247 }
248
249 static void
250 format_free (void *descr)
251 {
252   struct spec *spec = (struct spec *) descr;
253
254   if (spec->named != NULL)
255     {
256       unsigned int i;
257       for (i = 0; i < spec->named_arg_count; i++)
258         free (spec->named[i].name);
259       free (spec->named);
260     }
261   free (spec);
262 }
263
264 static int
265 format_get_number_of_directives (void *descr)
266 {
267   struct spec *spec = (struct spec *) descr;
268
269   return spec->directives;
270 }
271
272 static bool
273 format_check (void *msgid_descr, void *msgstr_descr, bool equality,
274               formatstring_error_logger_t error_logger,
275               const char *pretty_msgid, const char *pretty_msgstr)
276 {
277   struct spec *spec1 = (struct spec *) msgid_descr;
278   struct spec *spec2 = (struct spec *) msgstr_descr;
279   bool err = false;
280
281   if (spec1->named_arg_count + spec2->named_arg_count > 0)
282     {
283       unsigned int i, j;
284       unsigned int n1 = spec1->named_arg_count;
285       unsigned int n2 = spec2->named_arg_count;
286
287       /* Check the argument names are the same.
288          Both arrays are sorted.  We search for the first difference.  */
289       for (i = 0, j = 0; i < n1 || j < n2; )
290         {
291           int cmp = (i >= n1 ? 1 :
292                      j >= n2 ? -1 :
293                      strcmp (spec1->named[i].name, spec2->named[j].name));
294
295           if (cmp > 0)
296             {
297               if (error_logger)
298                 error_logger (_("a format specification for argument '%s', as in '%s', doesn't exist in '%s'"),
299                               spec2->named[j].name, pretty_msgstr,
300                               pretty_msgid);
301               err = true;
302               break;
303             }
304           else if (cmp < 0)
305             {
306               if (equality)
307                 {
308                   if (error_logger)
309                     error_logger (_("a format specification for argument '%s' doesn't exist in '%s'"),
310                                   spec1->named[i].name, pretty_msgstr);
311                   err = true;
312                   break;
313                 }
314               else
315                 i++;
316             }
317           else
318             j++, i++;
319         }
320     }
321
322   return err;
323 }
324
325
326 struct formatstring_parser formatstring_sh =
327 {
328   format_parse,
329   format_free,
330   format_get_number_of_directives,
331   NULL,
332   format_check
333 };
334
335
336 #ifdef TEST
337
338 /* Test program: Print the argument list specification returned by
339    format_parse for strings read from standard input.  */
340
341 #include <stdio.h>
342
343 static void
344 format_print (void *descr)
345 {
346   struct spec *spec = (struct spec *) descr;
347   unsigned int i;
348
349   if (spec == NULL)
350     {
351       printf ("INVALID");
352       return;
353     }
354
355   printf ("{");
356   for (i = 0; i < spec->named_arg_count; i++)
357     {
358       if (i > 0)
359         printf (", ");
360       printf ("'%s'", spec->named[i].name);
361     }
362   printf ("}");
363 }
364
365 int
366 main ()
367 {
368   for (;;)
369     {
370       char *line = NULL;
371       size_t line_size = 0;
372       int line_len;
373       char *invalid_reason;
374       void *descr;
375
376       line_len = getline (&line, &line_size, stdin);
377       if (line_len < 0)
378         break;
379       if (line_len > 0 && line[line_len - 1] == '\n')
380         line[--line_len] = '\0';
381
382       invalid_reason = NULL;
383       descr = format_parse (line, false, NULL, &invalid_reason);
384
385       format_print (descr);
386       printf ("\n");
387       if (descr == NULL)
388         printf ("%s\n", invalid_reason);
389
390       free (invalid_reason);
391       free (line);
392     }
393
394   return 0;
395 }
396
397 /*
398  * For Emacs M-x compile
399  * Local Variables:
400  * compile-command: "/bin/sh ../libtool --tag=CC --mode=link gcc -o a.out -static -O -g -Wall -I.. -I../gnulib-lib -I../intl -DHAVE_CONFIG_H -DTEST format-sh.c ../gnulib-lib/libgettextlib.la"
401  * End:
402  */
403
404 #endif /* TEST */