Home | History | Annotate | Download | only in gencnval
      1 /*
      2 *******************************************************************************
      3 *
      4 *   Copyright (C) 1999-2009, International Business Machines
      5 *   Corporation and others.  All Rights Reserved.
      6 *
      7 *******************************************************************************
      8 *   file name:  gencnval.c
      9 *   encoding:   US-ASCII
     10 *   tab size:   8 (not used)
     11 *   indentation:4
     12 *
     13 *   created on: 1999nov05
     14 *   created by: Markus W. Scherer
     15 *
     16 *   This program reads convrtrs.txt and writes a memory-mappable
     17 *   converter name alias table to cnvalias.dat .
     18 *
     19 *   This program currently writes version 2.1 of the data format. See
     20 *   ucnv_io.c for more details on the format. Note that version 2.1
     21 *   is written in such a way that a 2.0 reader will be able to use it,
     22 *   and a 2.1 reader will be able to read 2.0.
     23 */
     24 
     25 #include "unicode/utypes.h"
     26 #include "unicode/putil.h"
     27 #include "unicode/ucnv.h" /* ucnv_compareNames() */
     28 #include "ucnv_io.h"
     29 #include "cmemory.h"
     30 #include "cstring.h"
     31 #include "uinvchar.h"
     32 #include "filestrm.h"
     33 #include "unicode/uclean.h"
     34 #include "unewdata.h"
     35 #include "uoptions.h"
     36 
     37 #include <stdio.h>
     38 #include <stdlib.h>
     39 #include <ctype.h>
     40 
     41 /* TODO: Need to check alias name length is less than UCNV_MAX_CONVERTER_NAME_LENGTH */
     42 
     43 /* STRING_STORE_SIZE + TAG_STORE_SIZE <= ((2^16 - 1) * 2)
     44  That is the maximum size for the string stores combined
     45  because the strings are index at 16-bit boundries by a
     46  16-bit index, and there is only one section for the
     47  strings.
     48  */
     49 #define STRING_STORE_SIZE 0x1FBFE   /* 130046 */
     50 #define TAG_STORE_SIZE      0x400   /* 1024 */
     51 
     52 /* The combined tag and converter count can affect the number of lists
     53  created.  The size of all lists must be less than (2^17 - 1)
     54  because the lists are indexed as a 16-bit array with a 16-bit index.
     55  */
     56 #define MAX_TAG_COUNT 0x3F      /* 63 */
     57 #define MAX_CONV_COUNT UCNV_CONVERTER_INDEX_MASK
     58 #define MAX_ALIAS_COUNT 0xFFFF  /* 65535 */
     59 
     60 /* The maximum number of aliases that a standard tag/converter combination can have.
     61  At this moment 6/18/2002, IANA has 12 names for ASCII. Don't go below 15 for
     62  this value. I don't recommend more than 31 for this value.
     63  */
     64 #define MAX_TC_ALIAS_COUNT 0x1F    /* 31 */
     65 
     66 #define MAX_LINE_SIZE 0x7FFF    /* 32767 */
     67 #define MAX_LIST_SIZE 0xFFFF    /* 65535 */
     68 
     69 #define DATA_NAME "cnvalias"
     70 #define DATA_TYPE "icu" /* ICU alias table */
     71 
     72 #define ALL_TAG_STR "ALL"
     73 #define ALL_TAG_NUM 1
     74 #define EMPTY_TAG_NUM 0
     75 
     76 /* UDataInfo cf. udata.h */
     77 static const UDataInfo dataInfo={
     78     sizeof(UDataInfo),
     79     0,
     80 
     81     U_IS_BIG_ENDIAN,
     82     U_CHARSET_FAMILY,
     83     sizeof(UChar),
     84     0,
     85 
     86     {0x43, 0x76, 0x41, 0x6c},     /* dataFormat="CvAl" */
     87     {3, 0, 1, 0},                 /* formatVersion */
     88     {1, 4, 2, 0}                  /* dataVersion */
     89 };
     90 
     91 typedef struct {
     92     char *store;
     93     uint32_t top;
     94     uint32_t max;
     95 } StringBlock;
     96 
     97 static char stringStore[STRING_STORE_SIZE];
     98 static StringBlock stringBlock = { stringStore, 0, STRING_STORE_SIZE };
     99 
    100 typedef struct {
    101     uint16_t    aliasCount;
    102     uint16_t    *aliases;     /* Index into stringStore */
    103 } AliasList;
    104 
    105 typedef struct {
    106     uint16_t converter;     /* Index into stringStore */
    107     uint16_t totalAliasCount;    /* Total aliases in this column */
    108 } Converter;
    109 
    110 static Converter converters[MAX_CONV_COUNT];
    111 static uint16_t converterCount=0;
    112 
    113 static char tagStore[TAG_STORE_SIZE];
    114 static StringBlock tagBlock = { tagStore, 0, TAG_STORE_SIZE };
    115 
    116 typedef struct {
    117     uint16_t    tag;        /* Index into tagStore */
    118     uint16_t    totalAliasCount; /* Total aliases in this row */
    119     AliasList   aliasList[MAX_CONV_COUNT];
    120 } Tag;
    121 
    122 /* Think of this as a 3D array. It's tagCount by converterCount by aliasCount */
    123 static Tag tags[MAX_TAG_COUNT];
    124 static uint16_t tagCount = 0;
    125 
    126 /* Used for storing all aliases  */
    127 static uint16_t knownAliases[MAX_ALIAS_COUNT];
    128 static uint16_t knownAliasesCount = 0;
    129 /*static uint16_t duplicateKnownAliasesCount = 0;*/
    130 
    131 /* Used for storing the lists section that point to aliases */
    132 static uint16_t aliasLists[MAX_LIST_SIZE];
    133 static uint16_t aliasListsSize = 0;
    134 
    135 /* Were the standard tags declared before the aliases. */
    136 static UBool standardTagsUsed = FALSE;
    137 static UBool verbose = FALSE;
    138 static int lineNum = 1;
    139 
    140 static UConverterAliasOptions tableOptions = {
    141     UCNV_IO_STD_NORMALIZED,
    142     1 /* containsCnvOptionInfo */
    143 };
    144 
    145 
    146 /**
    147  * path to convrtrs.txt
    148  */
    149 const char *path;
    150 
    151 /* prototypes --------------------------------------------------------------- */
    152 
    153 static void
    154 parseLine(const char *line);
    155 
    156 static void
    157 parseFile(FileStream *in);
    158 
    159 static int32_t
    160 chomp(char *line);
    161 
    162 static void
    163 addOfficialTaggedStandards(char *line, int32_t lineLen);
    164 
    165 static uint16_t
    166 addAlias(const char *alias, uint16_t standard, uint16_t converter, UBool defaultName);
    167 
    168 static uint16_t
    169 addConverter(const char *converter);
    170 
    171 static char *
    172 allocString(StringBlock *block, const char *s, int32_t length);
    173 
    174 static uint16_t
    175 addToKnownAliases(const char *alias);
    176 
    177 static int
    178 compareAliases(const void *alias1, const void *alias2);
    179 
    180 static uint16_t
    181 getTagNumber(const char *tag, uint16_t tagLen);
    182 
    183 /*static void
    184 addTaggedAlias(uint16_t tag, const char *alias, uint16_t converter);*/
    185 
    186 static void
    187 writeAliasTable(UNewDataMemory *out);
    188 
    189 /* -------------------------------------------------------------------------- */
    190 
    191 /* Presumes that you used allocString() */
    192 #define GET_ALIAS_STR(index) (stringStore + ((size_t)(index) << 1))
    193 #define GET_TAG_STR(index) (tagStore + ((size_t)(index) << 1))
    194 
    195 /* Presumes that you used allocString() */
    196 #define GET_ALIAS_NUM(str) ((uint16_t)((str - stringStore) >> 1))
    197 #define GET_TAG_NUM(str) ((uint16_t)((str - tagStore) >> 1))
    198 
    199 enum
    200 {
    201     HELP1,
    202     HELP2,
    203     VERBOSE,
    204     COPYRIGHT,
    205     DESTDIR,
    206     SOURCEDIR
    207 };
    208 
    209 static UOption options[]={
    210     UOPTION_HELP_H,
    211     UOPTION_HELP_QUESTION_MARK,
    212     UOPTION_VERBOSE,
    213     UOPTION_COPYRIGHT,
    214     UOPTION_DESTDIR,
    215     UOPTION_SOURCEDIR
    216 };
    217 
    218 extern int
    219 main(int argc, char* argv[]) {
    220     char pathBuf[512];
    221     FileStream *in;
    222     UNewDataMemory *out;
    223     UErrorCode errorCode=U_ZERO_ERROR;
    224 
    225     U_MAIN_INIT_ARGS(argc, argv);
    226 
    227     /* preset then read command line options */
    228     options[DESTDIR].value=options[SOURCEDIR].value=u_getDataDirectory();
    229     argc=u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options);
    230 
    231     /* error handling, printing usage message */
    232     if(argc<0) {
    233         fprintf(stderr,
    234             "error in command line argument \"%s\"\n",
    235             argv[-argc]);
    236     }
    237     if(argc<0 || options[HELP1].doesOccur || options[HELP2].doesOccur) {
    238         fprintf(stderr,
    239             "usage: %s [-options] [convrtrs.txt]\n"
    240             "\tread convrtrs.txt and create " U_ICUDATA_NAME "_" DATA_NAME "." DATA_TYPE "\n"
    241             "options:\n"
    242             "\t-h or -? or --help  this usage text\n"
    243             "\t-v or --verbose     prints out extra information about the alias table\n"
    244             "\t-c or --copyright   include a copyright notice\n"
    245             "\t-d or --destdir     destination directory, followed by the path\n"
    246             "\t-s or --sourcedir   source directory, followed by the path\n",
    247             argv[0]);
    248         return argc<0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR;
    249     }
    250 
    251     if(options[VERBOSE].doesOccur) {
    252         verbose = TRUE;
    253     }
    254 
    255     if(argc>=2) {
    256         path=argv[1];
    257     } else {
    258         path=options[SOURCEDIR].value;
    259         if(path!=NULL && *path!=0) {
    260             char *end;
    261 
    262             uprv_strcpy(pathBuf, path);
    263             end = uprv_strchr(pathBuf, 0);
    264             if(*(end-1)!=U_FILE_SEP_CHAR) {
    265                 *(end++)=U_FILE_SEP_CHAR;
    266             }
    267             uprv_strcpy(end, "convrtrs.txt");
    268             path=pathBuf;
    269         } else {
    270             path = "convrtrs.txt";
    271         }
    272     }
    273 
    274     uprv_memset(stringStore, 0, sizeof(stringStore));
    275     uprv_memset(tagStore, 0, sizeof(tagStore));
    276     uprv_memset(converters, 0, sizeof(converters));
    277     uprv_memset(tags, 0, sizeof(tags));
    278     uprv_memset(aliasLists, 0, sizeof(aliasLists));
    279     uprv_memset(knownAliases, 0, sizeof(aliasLists));
    280 
    281 
    282     in=T_FileStream_open(path, "r");
    283     if(in==NULL) {
    284         fprintf(stderr, "gencnval: unable to open input file %s\n", path);
    285         exit(U_FILE_ACCESS_ERROR);
    286     }
    287     parseFile(in);
    288     T_FileStream_close(in);
    289 
    290     /* create the output file */
    291     out=udata_create(options[DESTDIR].value, DATA_TYPE, DATA_NAME, &dataInfo,
    292                      options[COPYRIGHT].doesOccur ? U_COPYRIGHT_STRING : NULL, &errorCode);
    293     if(U_FAILURE(errorCode)) {
    294         fprintf(stderr, "gencnval: unable to open output file - error %s\n", u_errorName(errorCode));
    295         exit(errorCode);
    296     }
    297 
    298     /* write the table of aliases based on a tag/converter name combination */
    299     writeAliasTable(out);
    300 
    301     /* finish */
    302     udata_finish(out, &errorCode);
    303     if(U_FAILURE(errorCode)) {
    304         fprintf(stderr, "gencnval: error finishing output file - %s\n", u_errorName(errorCode));
    305         exit(errorCode);
    306     }
    307 
    308     return 0;
    309 }
    310 
    311 static void
    312 parseFile(FileStream *in) {
    313     char line[MAX_LINE_SIZE];
    314     char lastLine[MAX_LINE_SIZE];
    315     int32_t lineSize = 0;
    316     int32_t lastLineSize = 0;
    317     UBool validParse = TRUE;
    318 
    319     lineNum = 0;
    320 
    321     /* Add the empty tag, which is for untagged aliases */
    322     getTagNumber("", 0);
    323     getTagNumber(ALL_TAG_STR, 3);
    324     allocString(&stringBlock, "", 0);
    325 
    326     /* read the list of aliases */
    327     while (validParse) {
    328         validParse = FALSE;
    329 
    330         /* Read non-empty lines that don't start with a space character. */
    331         while (T_FileStream_readLine(in, lastLine, MAX_LINE_SIZE) != NULL) {
    332             lastLineSize = chomp(lastLine);
    333             if (lineSize == 0 || (lastLineSize > 0 && isspace(*lastLine))) {
    334                 uprv_strcpy(line + lineSize, lastLine);
    335                 lineSize += lastLineSize;
    336             } else if (lineSize > 0) {
    337                 validParse = TRUE;
    338                 break;
    339             }
    340             lineNum++;
    341         }
    342 
    343         if (validParse || lineSize > 0) {
    344             if (isspace(*line)) {
    345                 fprintf(stderr, "%s:%d: error: cannot start an alias with a space\n", path, lineNum-1);
    346                 exit(U_PARSE_ERROR);
    347             } else if (line[0] == '{') {
    348                 if (!standardTagsUsed && line[lineSize - 1] != '}') {
    349                     fprintf(stderr, "%s:%d: error: alias needs to start with a converter name\n", path, lineNum);
    350                     exit(U_PARSE_ERROR);
    351                 }
    352                 addOfficialTaggedStandards(line, lineSize);
    353                 standardTagsUsed = TRUE;
    354             } else {
    355                 if (standardTagsUsed) {
    356                     parseLine(line);
    357                 }
    358                 else {
    359                     fprintf(stderr, "%s:%d: error: alias table needs to start a list of standard tags\n", path, lineNum);
    360                     exit(U_PARSE_ERROR);
    361                 }
    362             }
    363             /* Was the last line consumed */
    364             if (lastLineSize > 0) {
    365                 uprv_strcpy(line, lastLine);
    366                 lineSize = lastLineSize;
    367             }
    368             else {
    369                 lineSize = 0;
    370             }
    371         }
    372         lineNum++;
    373     }
    374 }
    375 
    376 /* This works almost like the Perl chomp.
    377  It removes the newlines, comments and trailing whitespace (not preceding whitespace).
    378 */
    379 static int32_t
    380 chomp(char *line) {
    381     char *s = line;
    382     char *lastNonSpace = line;
    383     while(*s!=0) {
    384         /* truncate at a newline or a comment */
    385         if(*s == '\r' || *s == '\n' || *s == '#') {
    386             *s = 0;
    387             break;
    388         }
    389         if (!isspace(*s)) {
    390             lastNonSpace = s;
    391         }
    392         ++s;
    393     }
    394     if (lastNonSpace++ > line) {
    395         *lastNonSpace = 0;
    396         s = lastNonSpace;
    397     }
    398     return (int32_t)(s - line);
    399 }
    400 
    401 static void
    402 parseLine(const char *line) {
    403     uint16_t pos=0, start, limit, length, cnv;
    404     char *converter, *alias;
    405 
    406     /* skip leading white space */
    407     /* There is no whitespace at the beginning anymore */
    408 /*    while(line[pos]!=0 && isspace(line[pos])) {
    409         ++pos;
    410     }
    411 */
    412 
    413     /* is there nothing on this line? */
    414     if(line[pos]==0) {
    415         return;
    416     }
    417 
    418     /* get the converter name */
    419     start=pos;
    420     while(line[pos]!=0 && !isspace(line[pos])) {
    421         ++pos;
    422     }
    423     limit=pos;
    424 
    425     /* store the converter name */
    426     length=(uint16_t)(limit-start);
    427     converter=allocString(&stringBlock, line+start, length);
    428 
    429     /* add the converter to the converter table */
    430     cnv=addConverter(converter);
    431 
    432     /* The name itself may be tagged, so let's added it to the aliases list properly */
    433     pos = start;
    434 
    435     /* get all the real aliases */
    436     for(;;) {
    437 
    438         /* skip white space */
    439         while(line[pos]!=0 && isspace(line[pos])) {
    440             ++pos;
    441         }
    442 
    443         /* is there no more alias name on this line? */
    444         if(line[pos]==0) {
    445             break;
    446         }
    447 
    448         /* get an alias name */
    449         start=pos;
    450         while(line[pos]!=0 && line[pos]!='{' && !isspace(line[pos])) {
    451             ++pos;
    452         }
    453         limit=pos;
    454 
    455         /* store the alias name */
    456         length=(uint16_t)(limit-start);
    457         if (start == 0) {
    458             /* add the converter as its own alias to the alias table */
    459             alias = converter;
    460             addAlias(alias, ALL_TAG_NUM, cnv, TRUE);
    461         }
    462         else {
    463             alias=allocString(&stringBlock, line+start, length);
    464             addAlias(alias, ALL_TAG_NUM, cnv, FALSE);
    465         }
    466         addToKnownAliases(alias);
    467 
    468         /* add the alias/converter pair to the alias table */
    469         /* addAlias(alias, 0, cnv, FALSE);*/
    470 
    471         /* skip whitespace */
    472         while (line[pos] && isspace(line[pos])) {
    473             ++pos;
    474         }
    475 
    476         /* handle tags if they are present */
    477         if (line[pos] == '{') {
    478             ++pos;
    479             do {
    480                 start = pos;
    481                 while (line[pos] && line[pos] != '}' && !isspace( line[pos])) {
    482                     ++pos;
    483                 }
    484                 limit = pos;
    485 
    486                 if (start != limit) {
    487                     /* add the tag to the tag table */
    488                     uint16_t tag = getTagNumber(line + start, (uint16_t)(limit - start));
    489                     addAlias(alias, tag, cnv, (UBool)(line[limit-1] == '*'));
    490                 }
    491 
    492                 while (line[pos] && isspace(line[pos])) {
    493                     ++pos;
    494                 }
    495             } while (line[pos] && line[pos] != '}');
    496 
    497             if (line[pos] == '}') {
    498                 ++pos;
    499             } else {
    500                 fprintf(stderr, "%s:%d: Unterminated tag list\n", path, lineNum);
    501                 exit(U_UNMATCHED_BRACES);
    502             }
    503         } else {
    504             addAlias(alias, EMPTY_TAG_NUM, cnv, (UBool)(tags[0].aliasList[cnv].aliasCount == 0));
    505         }
    506     }
    507 }
    508 
    509 static uint16_t
    510 getTagNumber(const char *tag, uint16_t tagLen) {
    511     char *atag;
    512     uint16_t t;
    513     UBool preferredName = ((tagLen > 0) ? (tag[tagLen - 1] == '*') : (FALSE));
    514 
    515     if (tagCount >= MAX_TAG_COUNT) {
    516         fprintf(stderr, "%s:%d: too many tags\n", path, lineNum);
    517         exit(U_BUFFER_OVERFLOW_ERROR);
    518     }
    519 
    520     if (preferredName) {
    521 /*        puts(tag);*/
    522         tagLen--;
    523     }
    524 
    525     for (t = 0; t < tagCount; ++t) {
    526         const char *currTag = GET_TAG_STR(tags[t].tag);
    527         if (uprv_strlen(currTag) == tagLen && !uprv_strnicmp(currTag, tag, tagLen)) {
    528             return t;
    529         }
    530     }
    531 
    532     /* we need to add this tag */
    533     if (tagCount >= MAX_TAG_COUNT) {
    534         fprintf(stderr, "%s:%d: error: too many tags\n", path, lineNum);
    535         exit(U_BUFFER_OVERFLOW_ERROR);
    536     }
    537 
    538     /* allocate a new entry in the tag table */
    539     atag = allocString(&tagBlock, tag, tagLen);
    540 
    541     if (standardTagsUsed) {
    542         fprintf(stderr, "%s:%d: error: Tag \"%s\" is not declared at the beginning of the alias table.\n",
    543             path, lineNum, atag);
    544         exit(1);
    545     }
    546     else if (tagLen > 0 && strcmp(tag, ALL_TAG_STR) != 0) {
    547         fprintf(stderr, "%s:%d: warning: Tag \"%s\" was added to the list of standards because it was not declared at beginning of the alias table.\n",
    548             path, lineNum, atag);
    549     }
    550 
    551     /* add the tag to the tag table */
    552     tags[tagCount].tag = GET_TAG_NUM(atag);
    553     /* The aliasList should be set to 0's already */
    554 
    555     return tagCount++;
    556 }
    557 
    558 /*static void
    559 addTaggedAlias(uint16_t tag, const char *alias, uint16_t converter) {
    560     tags[tag].aliases[converter] = alias;
    561 }
    562 */
    563 
    564 static void
    565 addOfficialTaggedStandards(char *line, int32_t lineLen) {
    566     char *atag;
    567     char *endTagExp;
    568     char *tag;
    569     static const char WHITESPACE[] = " \t";
    570 
    571     if (tagCount > UCNV_NUM_RESERVED_TAGS) {
    572         fprintf(stderr, "%s:%d: error: official tags already added\n", path, lineNum);
    573         exit(U_BUFFER_OVERFLOW_ERROR);
    574     }
    575     tag = strchr(line, '{');
    576     if (tag == NULL) {
    577         /* Why were we called? */
    578         fprintf(stderr, "%s:%d: error: Missing start of tag group\n", path, lineNum);
    579         exit(U_PARSE_ERROR);
    580     }
    581     tag++;
    582     endTagExp = strchr(tag, '}');
    583     if (endTagExp == NULL) {
    584         fprintf(stderr, "%s:%d: error: Missing end of tag group\n", path, lineNum);
    585         exit(U_PARSE_ERROR);
    586     }
    587     endTagExp[0] = 0;
    588 
    589     tag = strtok(tag, WHITESPACE);
    590     while (tag != NULL) {
    591 /*        printf("Adding original tag \"%s\"\n", tag);*/
    592 
    593         /* allocate a new entry in the tag table */
    594         atag = allocString(&tagBlock, tag, -1);
    595 
    596         /* add the tag to the tag table */
    597         tags[tagCount++].tag = (uint16_t)((atag - tagStore) >> 1);
    598 
    599         /* The aliasList should already be set to 0's */
    600 
    601         /* Get next tag */
    602         tag = strtok(NULL, WHITESPACE);
    603     }
    604 }
    605 
    606 static uint16_t
    607 addToKnownAliases(const char *alias) {
    608 /*    uint32_t idx; */
    609     /* strict matching */
    610 /*    for (idx = 0; idx < knownAliasesCount; idx++) {
    611         uint16_t num = GET_ALIAS_NUM(alias);
    612         if (knownAliases[idx] != num
    613             && uprv_strcmp(alias, GET_ALIAS_STR(knownAliases[idx])) == 0)
    614         {
    615             fprintf(stderr, "%s:%d: warning: duplicate alias %s and %s found\n", path,
    616                 lineNum, alias, GET_ALIAS_STR(knownAliases[idx]));
    617             duplicateKnownAliasesCount++;
    618             break;
    619         }
    620         else if (knownAliases[idx] != num
    621             && ucnv_compareNames(alias, GET_ALIAS_STR(knownAliases[idx])) == 0)
    622         {
    623             if (verbose) {
    624                 fprintf(stderr, "%s:%d: information: duplicate alias %s and %s found\n", path,
    625                     lineNum, alias, GET_ALIAS_STR(knownAliases[idx]));
    626             }
    627             duplicateKnownAliasesCount++;
    628             break;
    629         }
    630     }
    631 */
    632     if (knownAliasesCount >= MAX_ALIAS_COUNT) {
    633         fprintf(stderr, "%s:%d: warning: Too many aliases defined for all converters\n",
    634             path, lineNum);
    635         exit(U_BUFFER_OVERFLOW_ERROR);
    636     }
    637     /* TODO: We could try to unlist exact duplicates. */
    638     return knownAliases[knownAliasesCount++] = GET_ALIAS_NUM(alias);
    639 }
    640 
    641 /*
    642 @param standard When standard is 0, then it's the "empty" tag.
    643 */
    644 static uint16_t
    645 addAlias(const char *alias, uint16_t standard, uint16_t converter, UBool defaultName) {
    646     uint32_t idx, idx2;
    647     UBool dupFound = FALSE;
    648     UBool startEmptyWithoutDefault = FALSE;
    649     AliasList *aliasList;
    650 
    651     if(standard>=MAX_TAG_COUNT) {
    652         fprintf(stderr, "%s:%d: error: too many standard tags\n", path, lineNum);
    653         exit(U_BUFFER_OVERFLOW_ERROR);
    654     }
    655     if(converter>=MAX_CONV_COUNT) {
    656         fprintf(stderr, "%s:%d: error: too many converter names\n", path, lineNum);
    657         exit(U_BUFFER_OVERFLOW_ERROR);
    658     }
    659     aliasList = &tags[standard].aliasList[converter];
    660 
    661     if (strchr(alias, '}')) {
    662         fprintf(stderr, "%s:%d: error: unmatched } found\n", path,
    663             lineNum);
    664     }
    665 
    666     if(aliasList->aliasCount + 1 >= MAX_TC_ALIAS_COUNT) {
    667         fprintf(stderr, "%s:%d: error: too many aliases for alias %s and converter %s\n", path,
    668             lineNum, alias, GET_ALIAS_STR(converters[converter].converter));
    669         exit(U_BUFFER_OVERFLOW_ERROR);
    670     }
    671 
    672     /* Show this warning only once. All aliases are added to the "ALL" tag. */
    673     if (standard == ALL_TAG_NUM && GET_ALIAS_STR(converters[converter].converter) != alias) {
    674         /* Normally these option values are parsed at runtime, and they can
    675            be discarded when the alias is a default converter. Options should
    676            only be on a converter and not an alias. */
    677         if (uprv_strchr(alias, UCNV_OPTION_SEP_CHAR) != 0)
    678         {
    679             fprintf(stderr, "warning(line %d): alias %s contains a \""UCNV_OPTION_SEP_STRING"\". Options are parsed at run-time and do not need to be in the alias table.\n",
    680                 lineNum, alias);
    681         }
    682         if (uprv_strchr(alias, UCNV_VALUE_SEP_CHAR) != 0)
    683         {
    684             fprintf(stderr, "warning(line %d): alias %s contains an \""UCNV_VALUE_SEP_STRING"\". Options are parsed at run-time and do not need to be in the alias table.\n",
    685                 lineNum, alias);
    686         }
    687     }
    688 
    689     if (standard != ALL_TAG_NUM) {
    690         /* Check for duplicate aliases for this tag on all converters */
    691         for (idx = 0; idx < converterCount; idx++) {
    692             for (idx2 = 0; idx2 < tags[standard].aliasList[idx].aliasCount; idx2++) {
    693                 uint16_t aliasNum = tags[standard].aliasList[idx].aliases[idx2];
    694                 if (aliasNum
    695                     && ucnv_compareNames(alias, GET_ALIAS_STR(aliasNum)) == 0)
    696                 {
    697                     if (idx == converter) {
    698                         /*
    699                          * (alias, standard) duplicates are harmless if they map to the same converter.
    700                          * Only print a warning in verbose mode, or if the alias is a precise duplicate,
    701                          * not just a lenient-match duplicate.
    702                          */
    703                         if (verbose || 0 == uprv_strcmp(alias, GET_ALIAS_STR(aliasNum))) {
    704                             fprintf(stderr, "%s:%d: warning: duplicate aliases %s and %s found for standard %s and converter %s\n", path,
    705                                 lineNum, alias, GET_ALIAS_STR(aliasNum),
    706                                 GET_TAG_STR(tags[standard].tag),
    707                                 GET_ALIAS_STR(converters[converter].converter));
    708                         }
    709                     } else {
    710                         fprintf(stderr, "%s:%d: warning: duplicate aliases %s and %s found for standard tag %s between converter %s and converter %s\n", path,
    711                             lineNum, alias, GET_ALIAS_STR(aliasNum),
    712                             GET_TAG_STR(tags[standard].tag),
    713                             GET_ALIAS_STR(converters[converter].converter),
    714                             GET_ALIAS_STR(converters[idx].converter));
    715                     }
    716                     dupFound = TRUE;
    717                     break;
    718                 }
    719             }
    720         }
    721 
    722         /* Check for duplicate default aliases for this converter on all tags */
    723         /* It's okay to have multiple standards prefer the same name */
    724 /*        if (verbose && !dupFound) {
    725             for (idx = 0; idx < tagCount; idx++) {
    726                 if (tags[idx].aliasList[converter].aliases) {
    727                     uint16_t aliasNum = tags[idx].aliasList[converter].aliases[0];
    728                     if (aliasNum
    729                         && ucnv_compareNames(alias, GET_ALIAS_STR(aliasNum)) == 0)
    730                     {
    731                         fprintf(stderr, "%s:%d: warning: duplicate alias %s found for converter %s and standard tag %s\n", path,
    732                             lineNum, alias, GET_ALIAS_STR(converters[converter].converter), GET_TAG_STR(tags[standard].tag));
    733                         break;
    734                     }
    735                 }
    736             }
    737         }*/
    738     }
    739 
    740     if (aliasList->aliasCount <= 0) {
    741         aliasList->aliasCount++;
    742         startEmptyWithoutDefault = TRUE;
    743     }
    744     aliasList->aliases = (uint16_t *)uprv_realloc(aliasList->aliases, (aliasList->aliasCount + 1) * sizeof(aliasList->aliases[0]));
    745     if (startEmptyWithoutDefault) {
    746         aliasList->aliases[0] = 0;
    747     }
    748     if (defaultName) {
    749         if (aliasList->aliases[0] != 0) {
    750             fprintf(stderr, "%s:%d: error: Alias %s and %s cannot both be the default alias for standard tag %s and converter %s\n", path,
    751                 lineNum,
    752                 alias,
    753                 GET_ALIAS_STR(aliasList->aliases[0]),
    754                 GET_TAG_STR(tags[standard].tag),
    755                 GET_ALIAS_STR(converters[converter].converter));
    756             exit(U_PARSE_ERROR);
    757         }
    758         aliasList->aliases[0] = GET_ALIAS_NUM(alias);
    759     } else {
    760         aliasList->aliases[aliasList->aliasCount++] = GET_ALIAS_NUM(alias);
    761     }
    762 /*    aliasList->converter = converter;*/
    763 
    764     converters[converter].totalAliasCount++; /* One more to the column */
    765     tags[standard].totalAliasCount++; /* One more to the row */
    766 
    767     return aliasList->aliasCount;
    768 }
    769 
    770 static uint16_t
    771 addConverter(const char *converter) {
    772     uint32_t idx;
    773     if(converterCount>=MAX_CONV_COUNT) {
    774         fprintf(stderr, "%s:%d: error: too many converters\n", path, lineNum);
    775         exit(U_BUFFER_OVERFLOW_ERROR);
    776     }
    777 
    778     for (idx = 0; idx < converterCount; idx++) {
    779         if (ucnv_compareNames(converter, GET_ALIAS_STR(converters[idx].converter)) == 0) {
    780             fprintf(stderr, "%s:%d: error: duplicate converter %s found!\n", path, lineNum, converter);
    781             exit(U_PARSE_ERROR);
    782             break;
    783         }
    784     }
    785 
    786     converters[converterCount].converter = GET_ALIAS_NUM(converter);
    787     converters[converterCount].totalAliasCount = 0;
    788 
    789     return converterCount++;
    790 }
    791 
    792 /* resolve this alias based on the prioritization of the standard tags. */
    793 static void
    794 resolveAliasToConverter(uint16_t alias, uint16_t *tagNum, uint16_t *converterNum) {
    795     uint16_t idx, idx2, idx3;
    796 
    797     for (idx = UCNV_NUM_RESERVED_TAGS; idx < tagCount; idx++) {
    798         for (idx2 = 0; idx2 < converterCount; idx2++) {
    799             for (idx3 = 0; idx3 < tags[idx].aliasList[idx2].aliasCount; idx3++) {
    800                 uint16_t aliasNum = tags[idx].aliasList[idx2].aliases[idx3];
    801                 if (aliasNum == alias) {
    802                     *tagNum = idx;
    803                     *converterNum = idx2;
    804                     return;
    805                 }
    806             }
    807         }
    808     }
    809     /* Do the leftovers last, just in case */
    810     /* There is no need to do the ALL tag */
    811     idx = 0;
    812     for (idx2 = 0; idx2 < converterCount; idx2++) {
    813         for (idx3 = 0; idx3 < tags[idx].aliasList[idx2].aliasCount; idx3++) {
    814             uint16_t aliasNum = tags[idx].aliasList[idx2].aliases[idx3];
    815             if (aliasNum == alias) {
    816                 *tagNum = idx;
    817                 *converterNum = idx2;
    818                 return;
    819             }
    820         }
    821     }
    822     *tagNum = UINT16_MAX;
    823     *converterNum = UINT16_MAX;
    824     fprintf(stderr, "%s: warning: alias %s not found\n",
    825         path,
    826         GET_ALIAS_STR(alias));
    827     return;
    828 }
    829 
    830 /* The knownAliases should be sorted before calling this function */
    831 static uint32_t
    832 resolveAliases(uint16_t *uniqueAliasArr, uint16_t *uniqueAliasToConverterArr, uint16_t aliasOffset) {
    833     uint32_t uniqueAliasIdx = 0;
    834     uint32_t idx;
    835     uint16_t currTagNum, oldTagNum;
    836     uint16_t currConvNum, oldConvNum;
    837     const char *lastName;
    838 
    839     resolveAliasToConverter(knownAliases[0], &oldTagNum, &currConvNum);
    840     uniqueAliasToConverterArr[uniqueAliasIdx] = currConvNum;
    841     oldConvNum = currConvNum;
    842     uniqueAliasArr[uniqueAliasIdx] = knownAliases[0] + aliasOffset;
    843     uniqueAliasIdx++;
    844     lastName = GET_ALIAS_STR(knownAliases[0]);
    845 
    846     for (idx = 1; idx < knownAliasesCount; idx++) {
    847         resolveAliasToConverter(knownAliases[idx], &currTagNum, &currConvNum);
    848         if (ucnv_compareNames(lastName, GET_ALIAS_STR(knownAliases[idx])) == 0) {
    849             /* duplicate found */
    850             if ((currTagNum < oldTagNum && currTagNum >= UCNV_NUM_RESERVED_TAGS)
    851                 || oldTagNum == 0) {
    852                 oldTagNum = currTagNum;
    853                 uniqueAliasToConverterArr[uniqueAliasIdx - 1] = currConvNum;
    854                 uniqueAliasArr[uniqueAliasIdx - 1] = knownAliases[idx] + aliasOffset;
    855                 if (verbose) {
    856                     printf("using %s instead of %s -> %s",
    857                         GET_ALIAS_STR(knownAliases[idx]),
    858                         lastName,
    859                         GET_ALIAS_STR(converters[currConvNum].converter));
    860                     if (oldConvNum != currConvNum) {
    861                         printf(" (alias conflict)");
    862                     }
    863                     puts("");
    864                 }
    865             }
    866             else {
    867                 /* else ignore it */
    868                 if (verbose) {
    869                     printf("folding %s into %s -> %s",
    870                         GET_ALIAS_STR(knownAliases[idx]),
    871                         lastName,
    872                         GET_ALIAS_STR(converters[oldConvNum].converter));
    873                     if (oldConvNum != currConvNum) {
    874                         printf(" (alias conflict)");
    875                     }
    876                     puts("");
    877                 }
    878             }
    879             if (oldConvNum != currConvNum) {
    880                 uniqueAliasToConverterArr[uniqueAliasIdx - 1] |= UCNV_AMBIGUOUS_ALIAS_MAP_BIT;
    881             }
    882         }
    883         else {
    884             uniqueAliasToConverterArr[uniqueAliasIdx] = currConvNum;
    885             oldConvNum = currConvNum;
    886             uniqueAliasArr[uniqueAliasIdx] = knownAliases[idx] + aliasOffset;
    887             uniqueAliasIdx++;
    888             lastName = GET_ALIAS_STR(knownAliases[idx]);
    889             oldTagNum = currTagNum;
    890             /*printf("%s -> %s\n", GET_ALIAS_STR(knownAliases[idx]), GET_ALIAS_STR(converters[currConvNum].converter));*/
    891         }
    892         if (uprv_strchr(GET_ALIAS_STR(converters[currConvNum].converter), UCNV_OPTION_SEP_CHAR) != NULL) {
    893             uniqueAliasToConverterArr[uniqueAliasIdx-1] |= UCNV_CONTAINS_OPTION_BIT;
    894         }
    895     }
    896     return uniqueAliasIdx;
    897 }
    898 
    899 static void
    900 createOneAliasList(uint16_t *aliasArrLists, uint32_t tag, uint32_t converter, uint16_t offset) {
    901     uint32_t aliasNum;
    902     AliasList *aliasList = &tags[tag].aliasList[converter];
    903 
    904     if (aliasList->aliasCount == 0) {
    905         aliasArrLists[tag*converterCount + converter] = 0;
    906     }
    907     else {
    908         aliasLists[aliasListsSize++] = aliasList->aliasCount;
    909 
    910         /* write into the array area a 1's based index. */
    911         aliasArrLists[tag*converterCount + converter] = aliasListsSize;
    912 
    913 /*        printf("tag %s converter %s\n",
    914             GET_TAG_STR(tags[tag].tag),
    915             GET_ALIAS_STR(converters[converter].converter));*/
    916         for (aliasNum = 0; aliasNum < aliasList->aliasCount; aliasNum++) {
    917             uint16_t value;
    918 /*            printf("   %s\n",
    919                 GET_ALIAS_STR(aliasList->aliases[aliasNum]));*/
    920             if (aliasList->aliases[aliasNum]) {
    921                 value = aliasList->aliases[aliasNum] + offset;
    922             } else {
    923                 value = 0;
    924                 if (tag != 0) { /* Only show the warning when it's not the leftover tag. */
    925                     fprintf(stderr, "%s: warning: tag %s does not have a default alias for %s\n",
    926                             path,
    927                             GET_TAG_STR(tags[tag].tag),
    928                             GET_ALIAS_STR(converters[converter].converter));
    929                 }
    930             }
    931             aliasLists[aliasListsSize++] = value;
    932             if (aliasListsSize >= MAX_LIST_SIZE) {
    933                 fprintf(stderr, "%s: error: Too many alias lists\n", path);
    934                 exit(U_BUFFER_OVERFLOW_ERROR);
    935             }
    936 
    937         }
    938     }
    939 }
    940 
    941 static void
    942 createNormalizedAliasStrings(char *normalizedStrings, const char *origStringBlock, int32_t stringBlockLength) {
    943     int32_t currStrLen;
    944     uprv_memcpy(normalizedStrings, origStringBlock, stringBlockLength);
    945     while ((currStrLen = (int32_t)uprv_strlen(origStringBlock)) < stringBlockLength) {
    946         int32_t currStrSize = currStrLen + 1;
    947         if (currStrLen > 0) {
    948             int32_t normStrLen;
    949             ucnv_io_stripForCompare(normalizedStrings, origStringBlock);
    950             normStrLen = uprv_strlen(normalizedStrings);
    951             if (normStrLen > 0) {
    952                 uprv_memset(normalizedStrings + normStrLen, 0, currStrSize - normStrLen);
    953             }
    954         }
    955         stringBlockLength -= currStrSize;
    956         normalizedStrings += currStrSize;
    957         origStringBlock += currStrSize;
    958     }
    959 }
    960 
    961 static void
    962 writeAliasTable(UNewDataMemory *out) {
    963     uint32_t i, j;
    964     uint32_t uniqueAliasesSize;
    965     uint16_t aliasOffset = (uint16_t)(tagBlock.top/sizeof(uint16_t));
    966     uint16_t *aliasArrLists = (uint16_t *)uprv_malloc(tagCount * converterCount * sizeof(uint16_t));
    967     uint16_t *uniqueAliases = (uint16_t *)uprv_malloc(knownAliasesCount * sizeof(uint16_t));
    968     uint16_t *uniqueAliasesToConverter = (uint16_t *)uprv_malloc(knownAliasesCount * sizeof(uint16_t));
    969 
    970     qsort(knownAliases, knownAliasesCount, sizeof(knownAliases[0]), compareAliases);
    971     uniqueAliasesSize = resolveAliases(uniqueAliases, uniqueAliasesToConverter, aliasOffset);
    972 
    973     /* Array index starts at 1. aliasLists[0] is the size of the lists section. */
    974     aliasListsSize = 0;
    975 
    976     /* write the offsets of all the aliases lists in a 2D array, and create the lists. */
    977     for (i = 0; i < tagCount; ++i) {
    978         for (j = 0; j < converterCount; ++j) {
    979             createOneAliasList(aliasArrLists, i, j, aliasOffset);
    980         }
    981     }
    982 
    983     /* Write the size of the TOC */
    984     if (tableOptions.stringNormalizationType == UCNV_IO_UNNORMALIZED) {
    985         udata_write32(out, 8);
    986     }
    987     else {
    988         udata_write32(out, 9);
    989     }
    990 
    991     /* Write the sizes of each section */
    992     /* All sizes are the number of uint16_t units, not bytes */
    993     udata_write32(out, converterCount);
    994     udata_write32(out, tagCount);
    995     udata_write32(out, uniqueAliasesSize);  /* list of aliases */
    996     udata_write32(out, uniqueAliasesSize);  /* The preresolved form of mapping an untagged the alias to a converter */
    997     udata_write32(out, tagCount * converterCount);
    998     udata_write32(out, aliasListsSize + 1);
    999     udata_write32(out, sizeof(tableOptions) / sizeof(uint16_t));
   1000     udata_write32(out, (tagBlock.top + stringBlock.top) / sizeof(uint16_t));
   1001     if (tableOptions.stringNormalizationType != UCNV_IO_UNNORMALIZED) {
   1002         udata_write32(out, (tagBlock.top + stringBlock.top) / sizeof(uint16_t));
   1003     }
   1004 
   1005     /* write the table of converters */
   1006     /* Think of this as the column headers */
   1007     for(i=0; i<converterCount; ++i) {
   1008         udata_write16(out, (uint16_t)(converters[i].converter + aliasOffset));
   1009     }
   1010 
   1011     /* write the table of tags */
   1012     /* Think of this as the row headers */
   1013     for(i=UCNV_NUM_RESERVED_TAGS; i<tagCount; ++i) {
   1014         udata_write16(out, tags[i].tag);
   1015     }
   1016     /* The empty tag is considered the leftover list, and put that at the end of the priority list. */
   1017     udata_write16(out, tags[EMPTY_TAG_NUM].tag);
   1018     udata_write16(out, tags[ALL_TAG_NUM].tag);
   1019 
   1020     /* Write the unique list of aliases */
   1021     udata_writeBlock(out, uniqueAliases, uniqueAliasesSize * sizeof(uint16_t));
   1022 
   1023     /* Write the unique list of aliases */
   1024     udata_writeBlock(out, uniqueAliasesToConverter, uniqueAliasesSize * sizeof(uint16_t));
   1025 
   1026     /* Write the array to the lists */
   1027     udata_writeBlock(out, (const void *)(aliasArrLists + (2*converterCount)), (((tagCount - 2) * converterCount) * sizeof(uint16_t)));
   1028     /* Now write the leftover part of the array for the EMPTY and ALL lists */
   1029     udata_writeBlock(out, (const void *)aliasArrLists, (2 * converterCount * sizeof(uint16_t)));
   1030 
   1031     /* Offset the next array to make the index start at 1. */
   1032     udata_write16(out, 0xDEAD);
   1033 
   1034     /* Write the lists */
   1035     udata_writeBlock(out, (const void *)aliasLists, aliasListsSize * sizeof(uint16_t));
   1036 
   1037     /* Write any options for the alias table. */
   1038     udata_writeBlock(out, (const void *)&tableOptions, sizeof(tableOptions));
   1039 
   1040     /* write the tags strings */
   1041     udata_writeString(out, tagBlock.store, tagBlock.top);
   1042 
   1043     /* write the aliases strings */
   1044     udata_writeString(out, stringBlock.store, stringBlock.top);
   1045 
   1046     /* write the normalized aliases strings */
   1047     if (tableOptions.stringNormalizationType != UCNV_IO_UNNORMALIZED) {
   1048         char *normalizedStrings = (char *)uprv_malloc(tagBlock.top + stringBlock.top);
   1049         createNormalizedAliasStrings(normalizedStrings, tagBlock.store, tagBlock.top);
   1050         createNormalizedAliasStrings(normalizedStrings + tagBlock.top, stringBlock.store, stringBlock.top);
   1051 
   1052         /* Write out the complete normalized array. */
   1053         udata_writeString(out, normalizedStrings, tagBlock.top + stringBlock.top);
   1054         uprv_free(normalizedStrings);
   1055     }
   1056 
   1057     uprv_free(aliasArrLists);
   1058     uprv_free(uniqueAliases);
   1059 }
   1060 
   1061 static char *
   1062 allocString(StringBlock *block, const char *s, int32_t length) {
   1063     uint32_t top;
   1064     char *p;
   1065 
   1066     if(length<0) {
   1067         length=(int32_t)uprv_strlen(s);
   1068     }
   1069 
   1070     /*
   1071      * add 1 for the terminating NUL
   1072      * and round up (+1 &~1)
   1073      * to keep the addresses on a 16-bit boundary
   1074      */
   1075     top=block->top + (uint32_t)((length + 1 + 1) & ~1);
   1076 
   1077     if(top >= block->max) {
   1078         fprintf(stderr, "%s:%d: error: out of memory\n", path, lineNum);
   1079         exit(U_MEMORY_ALLOCATION_ERROR);
   1080     }
   1081 
   1082     /* get the pointer and copy the string */
   1083     p = block->store + block->top;
   1084     uprv_memcpy(p, s, length);
   1085     p[length] = 0; /* NUL-terminate it */
   1086     if((length & 1) == 0) {
   1087         p[length + 1] = 0; /* set the padding byte */
   1088     }
   1089 
   1090     /* check for invariant characters now that we have a NUL-terminated string for easy output */
   1091     if(!uprv_isInvariantString(p, length)) {
   1092         fprintf(stderr, "%s:%d: error: the name %s contains not just invariant characters\n", path, lineNum, p);
   1093         exit(U_INVALID_TABLE_FORMAT);
   1094     }
   1095 
   1096     block->top = top;
   1097     return p;
   1098 }
   1099 
   1100 static int
   1101 compareAliases(const void *alias1, const void *alias2) {
   1102     /* Names like IBM850 and ibm-850 need to be sorted together */
   1103     int result = ucnv_compareNames(GET_ALIAS_STR(*(uint16_t*)alias1), GET_ALIAS_STR(*(uint16_t*)alias2));
   1104     if (!result) {
   1105         /* Sort the shortest first */
   1106         return (int)uprv_strlen(GET_ALIAS_STR(*(uint16_t*)alias1)) - (int)uprv_strlen(GET_ALIAS_STR(*(uint16_t*)alias2));
   1107     }
   1108     return result;
   1109 }
   1110 
   1111 /*
   1112  * Hey, Emacs, please set the following:
   1113  *
   1114  * Local Variables:
   1115  * indent-tabs-mode: nil
   1116  * End:
   1117  *
   1118  */
   1119 
   1120