summaryrefslogtreecommitdiffstats
path: root/gettext-tools/src/cldr-plurals.c
blob: ee3b3c6b1862ed82f73ff9c4a32374b0276516b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/* Unicode CLDR plural rule parser and converter
   Copyright (C) 2015 Free Software Foundation, Inc.

   This file was written by Daiki Ueno <ueno@gnu.org>, 2015.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "basename.h"
#include "cldr-plural-exp.h"
#include "c-ctype.h"
#include <errno.h>
#include <error.h>
#include <getopt.h>
#include "gettext.h"
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <locale.h>
#include "progname.h"
#include "propername.h"
#include "relocatable.h"
#include <stdlib.h>
#include <string.h>
#include "xalloc.h"

#define _(s) gettext(s)


static char *
extract_rules (FILE *fp,
               const char *real_filename, const char *logical_filename,
               const char *locale)
{
  xmlDocPtr doc;
  xmlNodePtr node, n;
  size_t locale_length;
  char *buffer = NULL, *p;
  size_t bufmax = 0;
  size_t buflen = 0;

  doc = xmlReadFd (fileno (fp), logical_filename, NULL,
                   XML_PARSE_NONET
                   | XML_PARSE_NOWARNING
                   | XML_PARSE_NOERROR
                   | XML_PARSE_NOBLANKS);
  if (doc == NULL)
    error (EXIT_FAILURE, 0, _("memory exhausted"));

  node = xmlDocGetRootElement (doc);
  if (node && !xmlStrEqual (node->name, BAD_CAST "supplementalData"))
    {
      error_at_line (0, 0,
                     logical_filename,
                     xmlGetLineNo (node),
                     _("\
The root element <%s> is not allowed in a valid CLDR file"),
                     node->name);
      goto out;
    }

  for (n = node->children; n; n = n->next)
    {
      if (n->type == XML_ELEMENT_NODE
          && xmlStrEqual (n->name, BAD_CAST "plurals"))
        break;
    }
  if (!n)
    {
      error (0, 0, _("The element <%s> does not contain a <%s> element"),
             "supplementalData", "plurals");
      goto out;
    }

  locale_length = strlen (locale);
  for (n = n->children; n; n = n->next)
    {
      xmlChar *locales;
      xmlChar *cp;
      xmlNodePtr n2;
      bool found = false;

      if (n->type != XML_ELEMENT_NODE
          || !xmlStrEqual (n->name, BAD_CAST "pluralRules"))
        continue;

      if (!xmlHasProp (n, BAD_CAST "locales"))
        {
          error_at_line (0, 0,
                         logical_filename,
                         xmlGetLineNo (n),
                         _("\
The element <%s> does not have attribute <%s>"),
                         "pluralRules", "locales");
          continue;
        }

      cp = locales = xmlGetProp (n, BAD_CAST "locales");
      while (*cp != '\0')
        {
          while (c_isspace (*cp))
            cp++;
          if (xmlStrncmp (cp, BAD_CAST locale, locale_length) == 0
              && (*(cp + locale_length) == '\0'
                  || c_isspace (*(cp + locale_length))))
            {
              found = true;
              break;
            }
          while (*cp && !c_isspace (*cp))
            cp++;
        }
      xmlFree (locales);

      if (!found)
        continue;

      for (n2 = n->children; n2; n2 = n2->next)
        {
          xmlChar *count;
          xmlChar *content;
          size_t length;

          if (n2->type != XML_ELEMENT_NODE
              || !xmlStrEqual (n2->name, BAD_CAST "pluralRule"))
            continue;

          if (!xmlHasProp (n2, BAD_CAST "count"))
            {
              error_at_line (0, 0,
                             logical_filename,
                             xmlGetLineNo (n2),
                             _("\
The element <%s> does not have attribute <%s>"),
                             "pluralRule", "count");
              break;
            }

          count = xmlGetProp (n2, BAD_CAST "count");
          content = xmlNodeGetContent (n2);
          length = xmlStrlen (count) + strlen (": ")
            + xmlStrlen (content) + strlen ("; ");

          if (buflen + length + 1 > bufmax)
            {
              bufmax *= 2;
              if (bufmax < buflen + length + 1)
                bufmax = buflen + length + 1;
              buffer = (char *) xrealloc (buffer, bufmax);
            }

          sprintf (buffer + buflen, "%s: %s; ", count, content);
          xmlFree (count);
          xmlFree (content);

          buflen += length;
          buffer[buflen] = '\0';
        }
    }

  /* Scrub the last semicolon, if any.  */
  p = strrchr (buffer, ';');
  if (p)
    *p = '\0';

 out:
  xmlFreeDoc (doc);
  return buffer;
}

/* Display usage information and exit.  */
static void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    fprintf (stderr, _("Try '%s --help' for more information.\n"),
             program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION...] [LOCALE RULES]...\n\
"), program_name);
      printf ("\n");
      /* xgettext: no-wrap */
      printf (_("\
Extract or convert Unicode CLDR plural rules.\n\
\n\
If both LOCALE and RULES are specified, it reads CLDR plural rules for\n\
LOCALE from RULES and print them in a form suitable for gettext use.\n\
If no argument is given, it reads CLDR plural rules from the standard input.\n\
"));
      printf ("\n");
      /* xgettext: no-wrap */
      printf (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
Similarly for optional arguments.\n\
"));
      printf ("\n");
      printf (_("\
  -c, --cldr                  print plural rules in the CLDR format\n"));
      printf (_("\
  -h, --help                  display this help and exit\n"));
      printf (_("\
  -V, --version               output version information and exit\n"));
      printf ("\n");
      /* TRANSLATORS: The placeholder indicates the bug-reporting address
         for this package.  Please add _another line_ saying
         "Report translation bugs to <...>\n" with the address for translation
         bugs (typically your translation team's web or email address).  */
      fputs (_("Report bugs to <bug-gnu-gettext@gnu.org>.\n"),
             stdout);
    }
  exit (status);
}

/* Long options.  */
static const struct option long_options[] =
{
  { "cldr", no_argument, NULL, 'c' },
  { "help", no_argument, NULL, 'h' },
  { "version", no_argument, NULL, 'V' },
  { NULL, 0, NULL, 0 }
};

int
main (int argc, char **argv)
{
  bool opt_cldr_format = false;
  bool do_help = false;
  bool do_version = false;
  int optchar;

  /* Set program name for messages.  */
  set_program_name (argv[0]);

#ifdef HAVE_SETLOCALE
  /* Set locale via LC_ALL.  */
  setlocale (LC_ALL, "");
#endif

  /* Set the text message domain.  */
  bindtextdomain (PACKAGE, relocate (LOCALEDIR));
  bindtextdomain ("bison-runtime", relocate (BISON_LOCALEDIR));
  textdomain (PACKAGE);

  while ((optchar = getopt_long (argc, argv, "chV", long_options, NULL)) != EOF)
    switch (optchar)
      {
      case '\0':                /* Long option.  */
        break;

      case 'c':
        opt_cldr_format = true;
        break;

      case 'h':
        do_help = true;
        break;

      case 'V':
        do_version = true;
        break;

      default:
        usage (EXIT_FAILURE);
        /* NOTREACHED */
      }

  /* Version information requested.  */
  if (do_version)
    {
      printf ("%s (GNU %s) %s\n", basename (program_name), PACKAGE, VERSION);
      /* xgettext: no-wrap */
      printf (_("Copyright (C) %s Free Software Foundation, Inc.\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\
"),
              "2015");
      printf (_("Written by %s.\n"), proper_name ("Daiki Ueno"));
      exit (EXIT_SUCCESS);
    }

  /* Help is requested.  */
  if (do_help)
    usage (EXIT_SUCCESS);

  if (argc == optind + 2)
    {
      /* Two arguments: Read CLDR rules from a file.  */
      const char *locale = argv[optind];
      const char *logical_filename = argv[optind + 1];
      char *extracted_rules;
      FILE *fp;

      LIBXML_TEST_VERSION

      fp = fopen (logical_filename, "r");
      if (fp == NULL)
        error (1, 0, _("%s cannot be read"), logical_filename);

      extracted_rules = extract_rules (fp, logical_filename, logical_filename,
                                       locale);
      fclose (fp);
      if (extracted_rules == NULL)
        error (1, 0, _("cannot extract rules for %s"), locale);

      if (opt_cldr_format)
        printf ("%s\n", extracted_rules);
      else
        {
          struct cldr_plural_rule_list_ty *result;

          result = cldr_plural_parse (extracted_rules);
          if (result == NULL)
            error (1, 0, _("cannot parse CLDR rule"));

          cldr_plural_rule_list_print (result, stdout);
          cldr_plural_rule_list_free (result);
        }
      free (extracted_rules);
    }
  else if (argc == optind)
    {
      /* No argument: Read CLDR rules from standard input.  */
      char *line = NULL;
      size_t line_size = 0;
      for (;;)
        {
          int line_len;
          struct cldr_plural_rule_list_ty *result;

          line_len = getline (&line, &line_size, stdin);
          if (line_len < 0)
            break;
          if (line_len > 0 && line[line_len - 1] == '\n')
            line[--line_len] = '\0';

          result = cldr_plural_parse (line);
          if (result)
            {
              cldr_plural_rule_list_print (result, stdout);
              cldr_plural_rule_list_free (result);
            }
        }

      free (line);
    }
  else
    {
      error (1, 0, _("extra operand %s"), argv[optind]);
    }

  return 0;
}