Home | History | Annotate | Download | only in gendict
      1 /*
      2 **********************************************************************
      3 *   Copyright (C) 2002-2014, International Business Machines
      4 *   Corporation and others.  All Rights Reserved.
      5 **********************************************************************
      6 *
      7 * File gendict.cpp
      8 */
      9 
     10 #include "unicode/utypes.h"
     11 #include "unicode/uchar.h"
     12 #include "unicode/ucnv.h"
     13 #include "unicode/uniset.h"
     14 #include "unicode/unistr.h"
     15 #include "unicode/uclean.h"
     16 #include "unicode/udata.h"
     17 #include "unicode/putil.h"
     18 #include "unicode/ucharstriebuilder.h"
     19 #include "unicode/bytestriebuilder.h"
     20 #include "unicode/ucharstrie.h"
     21 #include "unicode/bytestrie.h"
     22 #include "unicode/ucnv.h"
     23 #include "unicode/utf16.h"
     24 
     25 #include "charstr.h"
     26 #include "dictionarydata.h"
     27 #include "uoptions.h"
     28 #include "unewdata.h"
     29 #include "cmemory.h"
     30 #include "uassert.h"
     31 #include "ucbuf.h"
     32 #include "toolutil.h"
     33 #include "cstring.h"
     34 
     35 #include <stdio.h>
     36 #include <stdlib.h>
     37 #include <string.h>
     38 
     39 #include "putilimp.h"
     40 UDate startTime;
     41 
     42 static int elapsedTime() {
     43   return (int)uprv_floor((uprv_getRawUTCtime()-startTime)/1000.0);
     44 }
     45 
     46 U_NAMESPACE_USE
     47 
     48 static char *progName;
     49 static UOption options[]={
     50     UOPTION_HELP_H,             /* 0 */
     51     UOPTION_HELP_QUESTION_MARK, /* 1 */
     52     UOPTION_VERBOSE,            /* 2 */
     53     UOPTION_ICUDATADIR,         /* 4 */
     54     UOPTION_COPYRIGHT,          /* 5 */
     55     { "uchars", NULL, NULL, NULL, '\1', UOPT_NO_ARG, 0}, /* 6 */
     56     { "bytes", NULL, NULL, NULL, '\1', UOPT_NO_ARG, 0}, /* 7 */
     57     { "transform", NULL, NULL, NULL, '\1', UOPT_REQUIRES_ARG, 0}, /* 8 */
     58 };
     59 
     60 enum arguments {
     61     ARG_HELP = 0,
     62     ARG_QMARK,
     63     ARG_VERBOSE,
     64     ARG_ICUDATADIR,
     65     ARG_COPYRIGHT,
     66     ARG_UCHARS,
     67     ARG_BYTES,
     68     ARG_TRANSFORM
     69 };
     70 
     71 // prints out the standard usage method describing command line arguments,
     72 // then bails out with the desired exit code
     73 static void usageAndDie(UErrorCode retCode) {
     74     fprintf((U_SUCCESS(retCode) ? stdout : stderr), "Usage: %s -trietype [-options] input-dictionary-file output-file\n", progName);
     75     fprintf((U_SUCCESS(retCode) ? stdout : stderr),
     76            "\tRead in a word list and write out a string trie dictionary\n"
     77            "options:\n"
     78            "\t-h or -? or --help  this usage text\n"
     79            "\t-V or --version     show a version message\n"
     80            "\t-c or --copyright   include a copyright notice\n"
     81            "\t-v or --verbose     turn on verbose output\n"
     82            "\t-i or --icudatadir  directory for locating any needed intermediate data files,\n" // TODO: figure out if we need this option
     83            "\t                    followed by path, defaults to %s\n"
     84            "\t--uchars            output a UCharsTrie (mutually exclusive with -b!)\n"
     85            "\t--bytes             output a BytesTrie (mutually exclusive with -u!)\n"
     86            "\t--transform         the kind of transform to use (eg --transform offset-40A3,\n"
     87            "\t                    which specifies an offset transform with constant 0x40A3)\n",
     88             u_getDataDirectory());
     89     exit(retCode);
     90 }
     91 
     92 
     93 /* UDataInfo cf. udata.h */
     94 static UDataInfo dataInfo = {
     95     sizeof(UDataInfo),
     96     0,
     97 
     98     U_IS_BIG_ENDIAN,
     99     U_CHARSET_FAMILY,
    100     U_SIZEOF_UCHAR,
    101     0,
    102 
    103     { 0x44, 0x69, 0x63, 0x74 },     /* "Dict" */
    104     { 1, 0, 0, 0 },                 /* format version */
    105     { 0, 0, 0, 0 }                  /* data version */
    106 };
    107 
    108 #if !UCONFIG_NO_BREAK_ITERATION
    109 
    110 // A wrapper for both BytesTrieBuilder and UCharsTrieBuilder.
    111 // may want to put this somewhere in ICU, as it could be useful outside
    112 // of this tool?
    113 class DataDict {
    114 private:
    115     BytesTrieBuilder *bt;
    116     UCharsTrieBuilder *ut;
    117     UChar32 transformConstant;
    118     int32_t transformType;
    119 public:
    120     // constructs a new data dictionary. if there is an error,
    121     // it will be returned in status
    122     // isBytesTrie != 0 will produce a BytesTrieBuilder,
    123     // isBytesTrie == 0 will produce a UCharsTrieBuilder
    124     DataDict(UBool isBytesTrie, UErrorCode &status) : bt(NULL), ut(NULL),
    125         transformConstant(0), transformType(DictionaryData::TRANSFORM_NONE) {
    126         if (isBytesTrie) {
    127             bt = new BytesTrieBuilder(status);
    128         } else {
    129             ut = new UCharsTrieBuilder(status);
    130         }
    131     }
    132 
    133     ~DataDict() {
    134         delete bt;
    135         delete ut;
    136     }
    137 
    138 private:
    139     char transform(UChar32 c, UErrorCode &status) {
    140         if (transformType == DictionaryData::TRANSFORM_TYPE_OFFSET) {
    141             if (c == 0x200D) { return (char)0xFF; }
    142             else if (c == 0x200C) { return (char)0xFE; }
    143             int32_t delta = c - transformConstant;
    144             if (delta < 0 || 0xFD < delta) {
    145                 fprintf(stderr, "Codepoint U+%04lx out of range for --transform offset-%04lx!\n",
    146                         (long)c, (long)transformConstant);
    147                 exit(U_ILLEGAL_ARGUMENT_ERROR); // TODO: should return and print the line number
    148             }
    149             return (char)delta;
    150         } else { // no such transform type
    151             status = U_INTERNAL_PROGRAM_ERROR;
    152             return (char)c; // it should be noted this transform type will not generally work
    153         }
    154     }
    155 
    156     void transform(const UnicodeString &word, CharString &buf, UErrorCode &errorCode) {
    157         UChar32 c = 0;
    158         int32_t len = word.length();
    159         for (int32_t i = 0; i < len; i += U16_LENGTH(c)) {
    160             c = word.char32At(i);
    161             buf.append(transform(c, errorCode), errorCode);
    162         }
    163     }
    164 
    165 public:
    166     // sets the desired transformation data.
    167     // should be populated from a command line argument
    168     // so far the only acceptable format is offset-<hex constant>
    169     // eventually others (mask-<hex constant>?) may be enabled
    170     // more complex functions may be more difficult
    171     void setTransform(const char *t) {
    172         if (strncmp(t, "offset-", 7) == 0) {
    173             char *end;
    174             unsigned long base = uprv_strtoul(t + 7, &end, 16);
    175             if (end == (t + 7) || *end != 0 || base > 0x10FF80) {
    176                 fprintf(stderr, "Syntax for offset value in --transform offset-%s invalid!\n", t + 7);
    177                 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    178             }
    179             transformType = DictionaryData::TRANSFORM_TYPE_OFFSET;
    180             transformConstant = (UChar32)base;
    181         }
    182         else {
    183             fprintf(stderr, "Invalid transform specified: %s\n", t);
    184             usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    185         }
    186     }
    187 
    188     // add a word to the trie
    189     void addWord(const UnicodeString &word, int32_t value, UErrorCode &status) {
    190         if (bt) {
    191             CharString buf;
    192             transform(word, buf, status);
    193             bt->add(buf.toStringPiece(), value, status);
    194         }
    195         if (ut) { ut->add(word, value, status); }
    196     }
    197 
    198     // if we are a bytestrie, give back the StringPiece representing the serialized version of us
    199     StringPiece serializeBytes(UErrorCode &status) {
    200         return bt->buildStringPiece(USTRINGTRIE_BUILD_SMALL, status);
    201     }
    202 
    203     // if we are a ucharstrie, produce the UnicodeString representing the serialized version of us
    204     void serializeUChars(UnicodeString &s, UErrorCode &status) {
    205         ut->buildUnicodeString(USTRINGTRIE_BUILD_SMALL, s, status);
    206     }
    207 
    208     int32_t getTransform() {
    209         return (int32_t)(transformType | transformConstant);
    210     }
    211 };
    212 #endif
    213 
    214 static const UChar LINEFEED_CHARACTER = 0x000A;
    215 static const UChar CARRIAGE_RETURN_CHARACTER = 0x000D;
    216 
    217 static UBool readLine(UCHARBUF *f, UnicodeString &fileLine, IcuToolErrorCode &errorCode) {
    218     int32_t lineLength;
    219     const UChar *line = ucbuf_readline(f, &lineLength, errorCode);
    220     if(line == NULL || errorCode.isFailure()) { return FALSE; }
    221     // Strip trailing CR/LF, comments, and spaces.
    222     const UChar *comment = u_memchr(line, 0x23, lineLength);  // '#'
    223     if(comment != NULL) {
    224         lineLength = (int32_t)(comment - line);
    225     } else {
    226         while(lineLength > 0 && (line[lineLength - 1] == CARRIAGE_RETURN_CHARACTER || line[lineLength - 1] == LINEFEED_CHARACTER)) { --lineLength; }
    227     }
    228     while(lineLength > 0 && u_isspace(line[lineLength - 1])) { --lineLength; }
    229     fileLine.setTo(FALSE, line, lineLength);
    230     return TRUE;
    231 }
    232 
    233 //----------------------------------------------------------------------------
    234 //
    235 //  main      for gendict
    236 //
    237 //----------------------------------------------------------------------------
    238 int  main(int argc, char **argv) {
    239     //
    240     // Pick up and check the command line arguments,
    241     //    using the standard ICU tool utils option handling.
    242     //
    243     U_MAIN_INIT_ARGS(argc, argv);
    244     progName = argv[0];
    245     argc=u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options);
    246     if(argc<0) {
    247         // Unrecognized option
    248         fprintf(stderr, "error in command line argument \"%s\"\n", argv[-argc]);
    249         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    250     }
    251 
    252     if(options[ARG_HELP].doesOccur || options[ARG_QMARK].doesOccur) {
    253         //  -? or -h for help.
    254         usageAndDie(U_ZERO_ERROR);
    255     }
    256 
    257     UBool verbose = options[ARG_VERBOSE].doesOccur;
    258 
    259     if (argc < 3) {
    260         fprintf(stderr, "input and output file must both be specified.\n");
    261         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    262     }
    263     const char *outFileName  = argv[2];
    264     const char *wordFileName = argv[1];
    265 
    266     startTime = uprv_getRawUTCtime(); // initialize start timer
    267 
    268 	if (options[ARG_ICUDATADIR].doesOccur) {
    269         u_setDataDirectory(options[ARG_ICUDATADIR].value);
    270     }
    271 
    272     const char *copyright = NULL;
    273     if (options[ARG_COPYRIGHT].doesOccur) {
    274         copyright = U_COPYRIGHT_STRING;
    275     }
    276 
    277     if (options[ARG_UCHARS].doesOccur == options[ARG_BYTES].doesOccur) {
    278         fprintf(stderr, "you must specify exactly one type of trie to output!\n");
    279         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    280     }
    281     UBool isBytesTrie = options[ARG_BYTES].doesOccur;
    282     if (isBytesTrie != options[ARG_TRANSFORM].doesOccur) {
    283         fprintf(stderr, "you must provide a transformation for a bytes trie, and must not provide one for a uchars trie!\n");
    284         usageAndDie(U_ILLEGAL_ARGUMENT_ERROR);
    285     }
    286 
    287     IcuToolErrorCode status("gendict/main()");
    288 
    289 #if UCONFIG_NO_BREAK_ITERATION || UCONFIG_NO_FILE_IO
    290     const char* outDir=NULL;
    291 
    292     UNewDataMemory *pData;
    293     char msg[1024];
    294     UErrorCode tempstatus = U_ZERO_ERROR;
    295 
    296     /* write message with just the name */ // potential for a buffer overflow here...
    297     sprintf(msg, "gendict writes dummy %s because of UCONFIG_NO_BREAK_ITERATION and/or UCONFIG_NO_FILE_IO, see uconfig.h", outFileName);
    298     fprintf(stderr, "%s\n", msg);
    299 
    300     /* write the dummy data file */
    301     pData = udata_create(outDir, NULL, outFileName, &dataInfo, NULL, &tempstatus);
    302     udata_writeBlock(pData, msg, strlen(msg));
    303     udata_finish(pData, &tempstatus);
    304     return (int)tempstatus;
    305 
    306 #else
    307     //  Read in the dictionary source file
    308     if (verbose) { printf("Opening file %s...\n", wordFileName); }
    309     const char *codepage = "UTF-8";
    310     UCHARBUF *f = ucbuf_open(wordFileName, &codepage, TRUE, FALSE, status);
    311     if (status.isFailure()) {
    312         fprintf(stderr, "error opening input file: ICU Error \"%s\"\n", status.errorName());
    313         exit(status.reset());
    314     }
    315     if (verbose) { printf("Initializing dictionary builder of type %s...\n", (isBytesTrie ? "BytesTrie" : "UCharsTrie")); }
    316     DataDict dict(isBytesTrie, status);
    317     if (status.isFailure()) {
    318         fprintf(stderr, "new DataDict: ICU Error \"%s\"\n", status.errorName());
    319         exit(status.reset());
    320     }
    321     if (options[ARG_TRANSFORM].doesOccur) {
    322         dict.setTransform(options[ARG_TRANSFORM].value);
    323     }
    324 
    325     UnicodeString fileLine;
    326     if (verbose) { puts("Adding words to dictionary..."); }
    327     UBool hasValues = FALSE;
    328     UBool hasValuelessContents = FALSE;
    329     int lineCount = 0;
    330     int wordCount = 0;
    331     int minlen = 255;
    332     int maxlen = 0;
    333     UBool isOk = TRUE;
    334     while (readLine(f, fileLine, status)) {
    335         lineCount++;
    336         if (fileLine.isEmpty()) continue;
    337 
    338         // Parse word [spaces value].
    339         int32_t keyLen;
    340         for (keyLen = 0; keyLen < fileLine.length() && !u_isspace(fileLine[keyLen]); ++keyLen) {}
    341         if (keyLen == 0) {
    342             fprintf(stderr, "Error: no word on line %i!\n", lineCount);
    343             isOk = FALSE;
    344             continue;
    345         }
    346         int32_t valueStart;
    347         for (valueStart = keyLen;
    348             valueStart < fileLine.length() && u_isspace(fileLine[valueStart]);
    349             ++valueStart) {}
    350 
    351         if (keyLen < valueStart) {
    352             int32_t valueLength = fileLine.length() - valueStart;
    353             if (valueLength > 15) {
    354                 fprintf(stderr, "Error: value too long on line %i!\n", lineCount);
    355                 isOk = FALSE;
    356                 continue;
    357             }
    358             char s[16];
    359             fileLine.extract(valueStart, valueLength, s, 16, US_INV);
    360             char *end;
    361             unsigned long value = uprv_strtoul(s, &end, 0);
    362             if (end == s || *end != 0 || (int32_t)uprv_strlen(s) != valueLength || value > 0xffffffff) {
    363                 fprintf(stderr, "Error: value syntax error or value too large on line %i!\n", lineCount);
    364                 isOk = FALSE;
    365                 continue;
    366             }
    367             dict.addWord(fileLine.tempSubString(0, keyLen), (int32_t)value, status);
    368             hasValues = TRUE;
    369             wordCount++;
    370             if (keyLen < minlen) minlen = keyLen;
    371             if (keyLen > maxlen) maxlen = keyLen;
    372         } else {
    373             dict.addWord(fileLine.tempSubString(0, keyLen), 0, status);
    374             hasValuelessContents = TRUE;
    375             wordCount++;
    376             if (keyLen < minlen) minlen = keyLen;
    377             if (keyLen > maxlen) maxlen = keyLen;
    378         }
    379 
    380         if (status.isFailure()) {
    381             fprintf(stderr, "ICU Error \"%s\": Failed to add word to trie at input line %d in input file\n",
    382                 status.errorName(), lineCount);
    383             exit(status.reset());
    384         }
    385     }
    386     if (verbose) { printf("Processed %d lines, added %d words, minlen %d, maxlen %d\n", lineCount, wordCount, minlen, maxlen); }
    387 
    388     if (!isOk && status.isSuccess()) {
    389         status.set(U_ILLEGAL_ARGUMENT_ERROR);
    390     }
    391     if (hasValues && hasValuelessContents) {
    392         fprintf(stderr, "warning: file contained both valued and unvalued strings!\n");
    393     }
    394 
    395     if (verbose) { printf("Serializing data...isBytesTrie? %d\n", isBytesTrie); }
    396     int32_t outDataSize;
    397     const void *outData;
    398     UnicodeString usp;
    399     if (isBytesTrie) {
    400         StringPiece sp = dict.serializeBytes(status);
    401         outDataSize = sp.size();
    402         outData = sp.data();
    403     } else {
    404         dict.serializeUChars(usp, status);
    405         outDataSize = usp.length() * U_SIZEOF_UCHAR;
    406         outData = usp.getBuffer();
    407     }
    408     if (status.isFailure()) {
    409         fprintf(stderr, "gendict: got failure of type %s while serializing, if U_ILLEGAL_ARGUMENT_ERROR possibly due to duplicate dictionary entries\n", status.errorName());
    410         exit(status.reset());
    411     }
    412     if (verbose) { puts("Opening output file..."); }
    413     UNewDataMemory *pData = udata_create(NULL, NULL, outFileName, &dataInfo, copyright, status);
    414     if (status.isFailure()) {
    415         fprintf(stderr, "gendict: could not open output file \"%s\", \"%s\"\n", outFileName, status.errorName());
    416         exit(status.reset());
    417     }
    418 
    419     if (verbose) { puts("Writing to output file..."); }
    420     int32_t indexes[DictionaryData::IX_COUNT] = {
    421         DictionaryData::IX_COUNT * sizeof(int32_t), 0, 0, 0, 0, 0, 0, 0
    422     };
    423     int32_t size = outDataSize + indexes[DictionaryData::IX_STRING_TRIE_OFFSET];
    424     indexes[DictionaryData::IX_RESERVED1_OFFSET] = size;
    425     indexes[DictionaryData::IX_RESERVED2_OFFSET] = size;
    426     indexes[DictionaryData::IX_TOTAL_SIZE] = size;
    427 
    428     indexes[DictionaryData::IX_TRIE_TYPE] = isBytesTrie ? DictionaryData::TRIE_TYPE_BYTES : DictionaryData::TRIE_TYPE_UCHARS;
    429     if (hasValues) {
    430         indexes[DictionaryData::IX_TRIE_TYPE] |= DictionaryData::TRIE_HAS_VALUES;
    431     }
    432 
    433     indexes[DictionaryData::IX_TRANSFORM] = dict.getTransform();
    434     udata_writeBlock(pData, indexes, sizeof(indexes));
    435     udata_writeBlock(pData, outData, outDataSize);
    436     size_t bytesWritten = udata_finish(pData, status);
    437     if (status.isFailure()) {
    438         fprintf(stderr, "gendict: error \"%s\" writing the output file\n", status.errorName());
    439         exit(status.reset());
    440     }
    441 
    442     if (bytesWritten != (size_t)size) {
    443         fprintf(stderr, "Error writing to output file \"%s\"\n", outFileName);
    444         exit(U_INTERNAL_PROGRAM_ERROR);
    445     }
    446 
    447     printf("%s: done writing\t%s (%ds).\n", progName, outFileName, elapsedTime());
    448 
    449 #ifdef TEST_GENDICT
    450     if (isBytesTrie) {
    451         BytesTrie::Iterator it(outData, outDataSize, status);
    452         while (it.hasNext()) {
    453             it.next(status);
    454             const StringPiece s = it.getString();
    455             int32_t val = it.getValue();
    456             printf("%s -> %i\n", s.data(), val);
    457         }
    458     } else {
    459         UCharsTrie::Iterator it((const UChar *)outData, outDataSize, status);
    460         while (it.hasNext()) {
    461             it.next(status);
    462             const UnicodeString s = it.getString();
    463             int32_t val = it.getValue();
    464             char tmp[1024];
    465             s.extract(0, s.length(), tmp, 1024);
    466             printf("%s -> %i\n", tmp, val);
    467         }
    468     }
    469 #endif
    470 
    471     return 0;
    472 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */
    473 }
    474