2 **********************************************************************
3 * Copyright (C) 2002-2014, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
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"
26 #include "dictionarydata.h"
42 static int elapsedTime() {
43 return (int)uprv_floor((uprv_getRawUTCtime()-startTime
)/1000.0);
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 */
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"
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());
93 /* UDataInfo cf. udata.h */
94 static UDataInfo dataInfo
= {
103 { 0x44, 0x69, 0x63, 0x74 }, /* "Dict" */
104 { 1, 0, 0, 0 }, /* format version */
105 { 0, 0, 0, 0 } /* data version */
108 #if !UCONFIG_NO_BREAK_ITERATION
110 // A wrapper for both BytesTrieBuilder and UCharsTrieBuilder.
111 // may want to put this somewhere in ICU, as it could be useful outside
115 BytesTrieBuilder
*bt
;
116 UCharsTrieBuilder
*ut
;
117 UChar32 transformConstant
;
118 int32_t transformType
;
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
) {
127 bt
= new BytesTrieBuilder(status
);
129 ut
= new UCharsTrieBuilder(status
);
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
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
156 void transform(const UnicodeString
&word
, CharString
&buf
, UErrorCode
&errorCode
) {
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
);
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) {
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
);
179 transformType
= DictionaryData::TRANSFORM_TYPE_OFFSET
;
180 transformConstant
= (UChar32
)base
;
183 fprintf(stderr
, "Invalid transform specified: %s\n", t
);
184 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
188 // add a word to the trie
189 void addWord(const UnicodeString
&word
, int32_t value
, UErrorCode
&status
) {
192 transform(word
, buf
, status
);
193 bt
->add(buf
.toStringPiece(), value
, status
);
195 if (ut
) { ut
->add(word
, value
, status
); }
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
);
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
);
208 int32_t getTransform() {
209 return (int32_t)(transformType
| transformConstant
);
214 static const UChar LINEFEED_CHARACTER
= 0x000A;
215 static const UChar CARRIAGE_RETURN_CHARACTER
= 0x000D;
217 static UBool
readLine(UCHARBUF
*f
, UnicodeString
&fileLine
, IcuToolErrorCode
&errorCode
) {
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
);
226 while(lineLength
> 0 && (line
[lineLength
- 1] == CARRIAGE_RETURN_CHARACTER
|| line
[lineLength
- 1] == LINEFEED_CHARACTER
)) { --lineLength
; }
228 while(lineLength
> 0 && u_isspace(line
[lineLength
- 1])) { --lineLength
; }
229 fileLine
.setTo(FALSE
, line
, lineLength
);
233 //----------------------------------------------------------------------------
237 //----------------------------------------------------------------------------
238 int main(int argc
, char **argv
) {
240 // Pick up and check the command line arguments,
241 // using the standard ICU tool utils option handling.
243 U_MAIN_INIT_ARGS(argc
, argv
);
245 argc
=u_parseArgs(argc
, argv
, sizeof(options
)/sizeof(options
[0]), options
);
247 // Unrecognized option
248 fprintf(stderr
, "error in command line argument \"%s\"\n", argv
[-argc
]);
249 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
252 if(options
[ARG_HELP
].doesOccur
|| options
[ARG_QMARK
].doesOccur
) {
253 // -? or -h for help.
254 usageAndDie(U_ZERO_ERROR
);
257 UBool verbose
= options
[ARG_VERBOSE
].doesOccur
;
260 fprintf(stderr
, "input and output file must both be specified.\n");
261 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
263 const char *outFileName
= argv
[2];
264 const char *wordFileName
= argv
[1];
266 startTime
= uprv_getRawUTCtime(); // initialize start timer
268 if (options
[ARG_ICUDATADIR
].doesOccur
) {
269 u_setDataDirectory(options
[ARG_ICUDATADIR
].value
);
272 const char *copyright
= NULL
;
273 if (options
[ARG_COPYRIGHT
].doesOccur
) {
274 copyright
= U_COPYRIGHT_STRING
;
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
);
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
);
287 IcuToolErrorCode
status("gendict/main()");
289 #if UCONFIG_NO_BREAK_ITERATION || UCONFIG_NO_FILE_IO
290 const char* outDir
=NULL
;
292 UNewDataMemory
*pData
;
294 UErrorCode tempstatus
= U_ZERO_ERROR
;
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
);
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
;
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());
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());
321 if (options
[ARG_TRANSFORM
].doesOccur
) {
322 dict
.setTransform(options
[ARG_TRANSFORM
].value
);
325 UnicodeString fileLine
;
326 if (verbose
) { puts("Adding words to dictionary..."); }
327 UBool hasValues
= FALSE
;
328 UBool hasValuelessContents
= FALSE
;
334 while (readLine(f
, fileLine
, status
)) {
336 if (fileLine
.isEmpty()) continue;
338 // Parse word [spaces value].
340 for (keyLen
= 0; keyLen
< fileLine
.length() && !u_isspace(fileLine
[keyLen
]); ++keyLen
) {}
342 fprintf(stderr
, "Error: no word on line %i!\n", lineCount
);
347 for (valueStart
= keyLen
;
348 valueStart
< fileLine
.length() && u_isspace(fileLine
[valueStart
]);
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
);
359 fileLine
.extract(valueStart
, valueLength
, s
, 16, US_INV
);
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
);
367 dict
.addWord(fileLine
.tempSubString(0, keyLen
), (int32_t)value
, status
);
370 if (keyLen
< minlen
) minlen
= keyLen
;
371 if (keyLen
> maxlen
) maxlen
= keyLen
;
373 dict
.addWord(fileLine
.tempSubString(0, keyLen
), 0, status
);
374 hasValuelessContents
= TRUE
;
376 if (keyLen
< minlen
) minlen
= keyLen
;
377 if (keyLen
> maxlen
) maxlen
= keyLen
;
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());
386 if (verbose
) { printf("Processed %d lines, added %d words, minlen %d, maxlen %d\n", lineCount
, wordCount
, minlen
, maxlen
); }
388 if (!isOk
&& status
.isSuccess()) {
389 status
.set(U_ILLEGAL_ARGUMENT_ERROR
);
391 if (hasValues
&& hasValuelessContents
) {
392 fprintf(stderr
, "warning: file contained both valued and unvalued strings!\n");
395 if (verbose
) { printf("Serializing data...isBytesTrie? %d\n", isBytesTrie
); }
400 StringPiece sp
= dict
.serializeBytes(status
);
401 outDataSize
= sp
.size();
404 dict
.serializeUChars(usp
, status
);
405 outDataSize
= usp
.length() * U_SIZEOF_UCHAR
;
406 outData
= usp
.getBuffer();
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());
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());
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
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
;
428 indexes
[DictionaryData::IX_TRIE_TYPE
] = isBytesTrie
? DictionaryData::TRIE_TYPE_BYTES
: DictionaryData::TRIE_TYPE_UCHARS
;
430 indexes
[DictionaryData::IX_TRIE_TYPE
] |= DictionaryData::TRIE_HAS_VALUES
;
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());
442 if (bytesWritten
!= (size_t)size
) {
443 fprintf(stderr
, "Error writing to output file \"%s\"\n", outFileName
);
444 exit(U_INTERNAL_PROGRAM_ERROR
);
447 printf("%s: done writing\t%s (%ds).\n", progName
, outFileName
, elapsedTime());
451 BytesTrie::Iterator
it(outData
, outDataSize
, status
);
452 while (it
.hasNext()) {
454 const StringPiece s
= it
.getString();
455 int32_t val
= it
.getValue();
456 printf("%s -> %i\n", s
.data(), val
);
459 UCharsTrie::Iterator
it((const UChar
*)outData
, outDataSize
, status
);
460 while (it
.hasNext()) {
462 const UnicodeString s
= it
.getString();
463 int32_t val
= it
.getValue();
465 s
.extract(0, s
.length(), tmp
, 1024);
466 printf("%s -> %i\n", tmp
, val
);
472 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */