1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 **********************************************************************
5 * Copyright (C) 2002-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
12 #include "unicode/utypes.h"
13 #include "unicode/uchar.h"
14 #include "unicode/ucnv.h"
15 #include "unicode/uniset.h"
16 #include "unicode/unistr.h"
17 #include "unicode/uclean.h"
18 #include "unicode/udata.h"
19 #include "unicode/putil.h"
20 #include "unicode/ucharstriebuilder.h"
21 #include "unicode/bytestriebuilder.h"
22 #include "unicode/ucharstrie.h"
23 #include "unicode/bytestrie.h"
24 #include "unicode/ucnv.h"
25 #include "unicode/ustring.h"
26 #include "unicode/utf16.h"
29 #include "dictionarydata.h"
45 static int elapsedTime() {
46 return (int)uprv_floor((uprv_getRawUTCtime()-startTime
)/1000.0);
51 static char *progName
;
52 static UOption options
[]={
53 UOPTION_HELP_H
, /* 0 */
54 UOPTION_HELP_QUESTION_MARK
, /* 1 */
55 UOPTION_VERBOSE
, /* 2 */
56 UOPTION_ICUDATADIR
, /* 4 */
57 UOPTION_COPYRIGHT
, /* 5 */
58 { "uchars", NULL
, NULL
, NULL
, '\1', UOPT_NO_ARG
, 0}, /* 6 */
59 { "bytes", NULL
, NULL
, NULL
, '\1', UOPT_NO_ARG
, 0}, /* 7 */
60 { "transform", NULL
, NULL
, NULL
, '\1', UOPT_REQUIRES_ARG
, 0}, /* 8 */
61 UOPTION_QUIET
, /* 9 */
76 // prints out the standard usage method describing command line arguments,
77 // then bails out with the desired exit code
78 static void usageAndDie(UErrorCode retCode
) {
79 fprintf((U_SUCCESS(retCode
) ? stdout
: stderr
), "Usage: %s -trietype [-options] input-dictionary-file output-file\n", progName
);
80 fprintf((U_SUCCESS(retCode
) ? stdout
: stderr
),
81 "\tRead in a word list and write out a string trie dictionary\n"
83 "\t-h or -? or --help this usage text\n"
84 "\t-V or --version show a version message\n"
85 "\t-c or --copyright include a copyright notice\n"
86 "\t-v or --verbose turn on verbose output\n"
87 "\t-q or --quiet do not display warnings and progress\n"
88 "\t-i or --icudatadir directory for locating any needed intermediate data files,\n" // TODO: figure out if we need this option
89 "\t followed by path, defaults to %s\n"
90 "\t--uchars output a UCharsTrie (mutually exclusive with -b!)\n"
91 "\t--bytes output a BytesTrie (mutually exclusive with -u!)\n"
92 "\t--transform the kind of transform to use (eg --transform offset-40A3,\n"
93 "\t which specifies an offset transform with constant 0x40A3)\n",
94 u_getDataDirectory());
99 /* UDataInfo cf. udata.h */
100 static UDataInfo dataInfo
= {
109 { 0x44, 0x69, 0x63, 0x74 }, /* "Dict" */
110 { 1, 0, 0, 0 }, /* format version */
111 { 0, 0, 0, 0 } /* data version */
114 #if !UCONFIG_NO_BREAK_ITERATION
116 // A wrapper for both BytesTrieBuilder and UCharsTrieBuilder.
117 // may want to put this somewhere in ICU, as it could be useful outside
121 BytesTrieBuilder
*bt
;
122 UCharsTrieBuilder
*ut
;
123 UChar32 transformConstant
;
124 int32_t transformType
;
126 // constructs a new data dictionary. if there is an error,
127 // it will be returned in status
128 // isBytesTrie != 0 will produce a BytesTrieBuilder,
129 // isBytesTrie == 0 will produce a UCharsTrieBuilder
130 DataDict(UBool isBytesTrie
, UErrorCode
&status
) : bt(NULL
), ut(NULL
),
131 transformConstant(0), transformType(DictionaryData::TRANSFORM_NONE
) {
133 bt
= new BytesTrieBuilder(status
);
135 ut
= new UCharsTrieBuilder(status
);
145 char transform(UChar32 c
, UErrorCode
&status
) {
146 if (transformType
== DictionaryData::TRANSFORM_TYPE_OFFSET
) {
147 if (c
== 0x200D) { return (char)0xFF; }
148 else if (c
== 0x200C) { return (char)0xFE; }
149 int32_t delta
= c
- transformConstant
;
150 if (delta
< 0 || 0xFD < delta
) {
151 fprintf(stderr
, "Codepoint U+%04lx out of range for --transform offset-%04lx!\n",
152 (long)c
, (long)transformConstant
);
153 exit(U_ILLEGAL_ARGUMENT_ERROR
); // TODO: should return and print the line number
156 } else { // no such transform type
157 status
= U_INTERNAL_PROGRAM_ERROR
;
158 return (char)c
; // it should be noted this transform type will not generally work
162 void transform(const UnicodeString
&word
, CharString
&buf
, UErrorCode
&errorCode
) {
164 int32_t len
= word
.length();
165 for (int32_t i
= 0; i
< len
; i
+= U16_LENGTH(c
)) {
166 c
= word
.char32At(i
);
167 buf
.append(transform(c
, errorCode
), errorCode
);
172 // sets the desired transformation data.
173 // should be populated from a command line argument
174 // so far the only acceptable format is offset-<hex constant>
175 // eventually others (mask-<hex constant>?) may be enabled
176 // more complex functions may be more difficult
177 void setTransform(const char *t
) {
178 if (strncmp(t
, "offset-", 7) == 0) {
180 unsigned long base
= uprv_strtoul(t
+ 7, &end
, 16);
181 if (end
== (t
+ 7) || *end
!= 0 || base
> 0x10FF80) {
182 fprintf(stderr
, "Syntax for offset value in --transform offset-%s invalid!\n", t
+ 7);
183 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
185 transformType
= DictionaryData::TRANSFORM_TYPE_OFFSET
;
186 transformConstant
= (UChar32
)base
;
189 fprintf(stderr
, "Invalid transform specified: %s\n", t
);
190 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
194 // add a word to the trie
195 void addWord(const UnicodeString
&word
, int32_t value
, UErrorCode
&status
) {
198 transform(word
, buf
, status
);
199 bt
->add(buf
.toStringPiece(), value
, status
);
201 if (ut
) { ut
->add(word
, value
, status
); }
204 // if we are a bytestrie, give back the StringPiece representing the serialized version of us
205 StringPiece
serializeBytes(UErrorCode
&status
) {
206 return bt
->buildStringPiece(USTRINGTRIE_BUILD_SMALL
, status
);
209 // if we are a ucharstrie, produce the UnicodeString representing the serialized version of us
210 void serializeUChars(UnicodeString
&s
, UErrorCode
&status
) {
211 ut
->buildUnicodeString(USTRINGTRIE_BUILD_SMALL
, s
, status
);
214 int32_t getTransform() {
215 return (int32_t)(transformType
| transformConstant
);
220 static const UChar LINEFEED_CHARACTER
= 0x000A;
221 static const UChar CARRIAGE_RETURN_CHARACTER
= 0x000D;
223 static UBool
readLine(UCHARBUF
*f
, UnicodeString
&fileLine
, IcuToolErrorCode
&errorCode
) {
225 const UChar
*line
= ucbuf_readline(f
, &lineLength
, errorCode
);
226 if(line
== NULL
|| errorCode
.isFailure()) { return FALSE
; }
227 // Strip trailing CR/LF, comments, and spaces.
228 const UChar
*comment
= u_memchr(line
, 0x23, lineLength
); // '#'
229 if(comment
!= NULL
) {
230 lineLength
= (int32_t)(comment
- line
);
232 while(lineLength
> 0 && (line
[lineLength
- 1] == CARRIAGE_RETURN_CHARACTER
|| line
[lineLength
- 1] == LINEFEED_CHARACTER
)) { --lineLength
; }
234 while(lineLength
> 0 && u_isspace(line
[lineLength
- 1])) { --lineLength
; }
235 fileLine
.setTo(FALSE
, line
, lineLength
);
239 //----------------------------------------------------------------------------
243 //----------------------------------------------------------------------------
244 int main(int argc
, char **argv
) {
246 // Pick up and check the command line arguments,
247 // using the standard ICU tool utils option handling.
249 U_MAIN_INIT_ARGS(argc
, argv
);
251 argc
=u_parseArgs(argc
, argv
, UPRV_LENGTHOF(options
), options
);
253 // Unrecognized option
254 fprintf(stderr
, "error in command line argument \"%s\"\n", argv
[-argc
]);
255 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
258 if(options
[ARG_HELP
].doesOccur
|| options
[ARG_QMARK
].doesOccur
) {
259 // -? or -h for help.
260 usageAndDie(U_ZERO_ERROR
);
263 UBool verbose
= options
[ARG_VERBOSE
].doesOccur
;
264 UBool quiet
= options
[ARG_QUIET
].doesOccur
;
267 fprintf(stderr
, "input and output file must both be specified.\n");
268 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
270 const char *outFileName
= argv
[2];
271 const char *wordFileName
= argv
[1];
273 startTime
= uprv_getRawUTCtime(); // initialize start timer
275 if (options
[ARG_ICUDATADIR
].doesOccur
) {
276 u_setDataDirectory(options
[ARG_ICUDATADIR
].value
);
279 const char *copyright
= NULL
;
280 if (options
[ARG_COPYRIGHT
].doesOccur
) {
281 copyright
= U_COPYRIGHT_STRING
;
284 if (options
[ARG_UCHARS
].doesOccur
== options
[ARG_BYTES
].doesOccur
) {
285 fprintf(stderr
, "you must specify exactly one type of trie to output!\n");
286 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
288 UBool isBytesTrie
= options
[ARG_BYTES
].doesOccur
;
289 if (isBytesTrie
!= options
[ARG_TRANSFORM
].doesOccur
) {
290 fprintf(stderr
, "you must provide a transformation for a bytes trie, and must not provide one for a uchars trie!\n");
291 usageAndDie(U_ILLEGAL_ARGUMENT_ERROR
);
294 IcuToolErrorCode
status("gendict/main()");
296 #if UCONFIG_NO_BREAK_ITERATION || UCONFIG_NO_FILE_IO
297 const char* outDir
=NULL
;
299 UNewDataMemory
*pData
;
301 UErrorCode tempstatus
= U_ZERO_ERROR
;
303 /* write message with just the name */ // potential for a buffer overflow here...
304 sprintf(msg
, "gendict writes dummy %s because of UCONFIG_NO_BREAK_ITERATION and/or UCONFIG_NO_FILE_IO, see uconfig.h", outFileName
);
305 fprintf(stderr
, "%s\n", msg
);
307 /* write the dummy data file */
308 pData
= udata_create(outDir
, NULL
, outFileName
, &dataInfo
, NULL
, &tempstatus
);
309 udata_writeBlock(pData
, msg
, strlen(msg
));
310 udata_finish(pData
, &tempstatus
);
311 return (int)tempstatus
;
314 // Read in the dictionary source file
315 if (verbose
) { printf("Opening file %s...\n", wordFileName
); }
316 const char *codepage
= "UTF-8";
317 UCHARBUF
*f
= ucbuf_open(wordFileName
, &codepage
, TRUE
, FALSE
, status
);
318 if (status
.isFailure()) {
319 fprintf(stderr
, "error opening input file: ICU Error \"%s\"\n", status
.errorName());
320 exit(status
.reset());
322 if (verbose
) { printf("Initializing dictionary builder of type %s...\n", (isBytesTrie
? "BytesTrie" : "UCharsTrie")); }
323 DataDict
dict(isBytesTrie
, status
);
324 if (status
.isFailure()) {
325 fprintf(stderr
, "new DataDict: ICU Error \"%s\"\n", status
.errorName());
326 exit(status
.reset());
328 if (options
[ARG_TRANSFORM
].doesOccur
) {
329 dict
.setTransform(options
[ARG_TRANSFORM
].value
);
332 UnicodeString fileLine
;
333 if (verbose
) { puts("Adding words to dictionary..."); }
334 UBool hasValues
= FALSE
;
335 UBool hasValuelessContents
= FALSE
;
341 while (readLine(f
, fileLine
, status
)) {
343 if (fileLine
.isEmpty()) continue;
345 // Parse word [spaces value].
347 for (keyLen
= 0; keyLen
< fileLine
.length() && !u_isspace(fileLine
[keyLen
]); ++keyLen
) {}
349 fprintf(stderr
, "Error: no word on line %i!\n", lineCount
);
354 for (valueStart
= keyLen
;
355 valueStart
< fileLine
.length() && u_isspace(fileLine
[valueStart
]);
358 if (keyLen
< valueStart
) {
359 int32_t valueLength
= fileLine
.length() - valueStart
;
360 if (valueLength
> 15) {
361 fprintf(stderr
, "Error: value too long on line %i!\n", lineCount
);
366 fileLine
.extract(valueStart
, valueLength
, s
, 16, US_INV
);
368 unsigned long value
= uprv_strtoul(s
, &end
, 0);
369 if (end
== s
|| *end
!= 0 || (int32_t)uprv_strlen(s
) != valueLength
|| value
> 0xffffffff) {
370 fprintf(stderr
, "Error: value syntax error or value too large on line %i!\n", lineCount
);
374 dict
.addWord(fileLine
.tempSubString(0, keyLen
), (int32_t)value
, status
);
377 if (keyLen
< minlen
) minlen
= keyLen
;
378 if (keyLen
> maxlen
) maxlen
= keyLen
;
380 dict
.addWord(fileLine
.tempSubString(0, keyLen
), 0, status
);
381 hasValuelessContents
= TRUE
;
383 if (keyLen
< minlen
) minlen
= keyLen
;
384 if (keyLen
> maxlen
) maxlen
= keyLen
;
387 if (status
.isFailure()) {
388 fprintf(stderr
, "ICU Error \"%s\": Failed to add word to trie at input line %d in input file\n",
389 status
.errorName(), lineCount
);
390 exit(status
.reset());
393 if (verbose
) { printf("Processed %d lines, added %d words, minlen %d, maxlen %d\n", lineCount
, wordCount
, minlen
, maxlen
); }
395 if (!isOk
&& status
.isSuccess()) {
396 status
.set(U_ILLEGAL_ARGUMENT_ERROR
);
398 if (hasValues
&& hasValuelessContents
) {
399 fprintf(stderr
, "warning: file contained both valued and unvalued strings!\n");
402 if (verbose
) { printf("Serializing data...isBytesTrie? %d\n", isBytesTrie
); }
407 StringPiece sp
= dict
.serializeBytes(status
);
408 outDataSize
= sp
.size();
411 dict
.serializeUChars(usp
, status
);
412 outDataSize
= usp
.length() * U_SIZEOF_UCHAR
;
413 outData
= usp
.getBuffer();
415 if (status
.isFailure()) {
416 fprintf(stderr
, "gendict: got failure of type %s while serializing, if U_ILLEGAL_ARGUMENT_ERROR possibly due to duplicate dictionary entries\n", status
.errorName());
417 exit(status
.reset());
419 if (verbose
) { puts("Opening output file..."); }
420 UNewDataMemory
*pData
= udata_create(NULL
, NULL
, outFileName
, &dataInfo
, copyright
, status
);
421 if (status
.isFailure()) {
422 fprintf(stderr
, "gendict: could not open output file \"%s\", \"%s\"\n", outFileName
, status
.errorName());
423 exit(status
.reset());
426 if (verbose
) { puts("Writing to output file..."); }
427 int32_t indexes
[DictionaryData::IX_COUNT
] = {
428 DictionaryData::IX_COUNT
* sizeof(int32_t), 0, 0, 0, 0, 0, 0, 0
430 int32_t size
= outDataSize
+ indexes
[DictionaryData::IX_STRING_TRIE_OFFSET
];
431 indexes
[DictionaryData::IX_RESERVED1_OFFSET
] = size
;
432 indexes
[DictionaryData::IX_RESERVED2_OFFSET
] = size
;
433 indexes
[DictionaryData::IX_TOTAL_SIZE
] = size
;
435 indexes
[DictionaryData::IX_TRIE_TYPE
] = isBytesTrie
? DictionaryData::TRIE_TYPE_BYTES
: DictionaryData::TRIE_TYPE_UCHARS
;
437 indexes
[DictionaryData::IX_TRIE_TYPE
] |= DictionaryData::TRIE_HAS_VALUES
;
440 indexes
[DictionaryData::IX_TRANSFORM
] = dict
.getTransform();
441 udata_writeBlock(pData
, indexes
, sizeof(indexes
));
442 udata_writeBlock(pData
, outData
, outDataSize
);
443 size_t bytesWritten
= udata_finish(pData
, status
);
444 if (status
.isFailure()) {
445 fprintf(stderr
, "gendict: error \"%s\" writing the output file\n", status
.errorName());
446 exit(status
.reset());
449 if (bytesWritten
!= (size_t)size
) {
450 fprintf(stderr
, "Error writing to output file \"%s\"\n", outFileName
);
451 exit(U_INTERNAL_PROGRAM_ERROR
);
454 if (!quiet
) { printf("%s: done writing\t%s (%ds).\n", progName
, outFileName
, elapsedTime()); }
458 BytesTrie::Iterator
it(outData
, outDataSize
, status
);
459 while (it
.hasNext()) {
461 const StringPiece s
= it
.getString();
462 int32_t val
= it
.getValue();
463 printf("%s -> %i\n", s
.data(), val
);
466 UCharsTrie::Iterator
it((const UChar
*)outData
, outDataSize
, status
);
467 while (it
.hasNext()) {
469 const UnicodeString s
= it
.getString();
470 int32_t val
= it
.getValue();
472 s
.extract(0, s
.length(), tmp
, 1024);
473 printf("%s -> %i\n", tmp
, val
);
479 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */