1 /*
2 *******************************************************************************
3 * Copyright (C) 2007-2015, International Business Machines Corporation and
4 * others. All Rights Reserved.
5 *******************************************************************************
6 *
7 * File plurrule.cpp
8 */
9 
10 #include <math.h>
11 #include <stdio.h>
12 
13 #include "unicode/utypes.h"
14 #include "unicode/localpointer.h"
15 #include "unicode/plurrule.h"
16 #include "unicode/upluralrules.h"
17 #include "unicode/ures.h"
18 #include "charstr.h"
19 #include "cmemory.h"
20 #include "cstring.h"
21 #include "digitlst.h"
22 #include "hash.h"
23 #include "locutil.h"
24 #include "mutex.h"
25 #include "patternprops.h"
26 #include "plurrule_impl.h"
27 #include "putilimp.h"
28 #include "ucln_in.h"
29 #include "ustrfmt.h"
30 #include "uassert.h"
31 #include "uvectr32.h"
32 #include "sharedpluralrules.h"
33 #include "unifiedcache.h"
34 #include "digitinterval.h"
35 #include "visibledigits.h"
36 
37 
38 #if !UCONFIG_NO_FORMATTING
39 
40 U_NAMESPACE_BEGIN
41 
42 #define ARRAY_SIZE(array) (int32_t)(sizeof array  / sizeof array[0])
43 
44 static const UChar PLURAL_KEYWORD_OTHER[]={LOW_O,LOW_T,LOW_H,LOW_E,LOW_R,0};
45 static const UChar PLURAL_DEFAULT_RULE[]={LOW_O,LOW_T,LOW_H,LOW_E,LOW_R,COLON,SPACE,LOW_N,0};
46 static const UChar PK_IN[]={LOW_I,LOW_N,0};
47 static const UChar PK_NOT[]={LOW_N,LOW_O,LOW_T,0};
48 static const UChar PK_IS[]={LOW_I,LOW_S,0};
49 static const UChar PK_MOD[]={LOW_M,LOW_O,LOW_D,0};
50 static const UChar PK_AND[]={LOW_A,LOW_N,LOW_D,0};
51 static const UChar PK_OR[]={LOW_O,LOW_R,0};
52 static const UChar PK_VAR_N[]={LOW_N,0};
53 static const UChar PK_VAR_I[]={LOW_I,0};
54 static const UChar PK_VAR_F[]={LOW_F,0};
55 static const UChar PK_VAR_T[]={LOW_T,0};
56 static const UChar PK_VAR_V[]={LOW_V,0};
57 static const UChar PK_WITHIN[]={LOW_W,LOW_I,LOW_T,LOW_H,LOW_I,LOW_N,0};
58 static const UChar PK_DECIMAL[]={LOW_D,LOW_E,LOW_C,LOW_I,LOW_M,LOW_A,LOW_L,0};
59 static const UChar PK_INTEGER[]={LOW_I,LOW_N,LOW_T,LOW_E,LOW_G,LOW_E,LOW_R,0};
60 
61 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(PluralRules)
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(PluralKeywordEnumeration)62 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(PluralKeywordEnumeration)
63 
64 PluralRules::PluralRules(UErrorCode& /*status*/)
65 :   UObject(),
66     mRules(NULL)
67 {
68 }
69 
PluralRules(const PluralRules & other)70 PluralRules::PluralRules(const PluralRules& other)
71 : UObject(other),
72     mRules(NULL)
73 {
74     *this=other;
75 }
76 
~PluralRules()77 PluralRules::~PluralRules() {
78     delete mRules;
79 }
80 
~SharedPluralRules()81 SharedPluralRules::~SharedPluralRules() {
82     delete ptr;
83 }
84 
85 PluralRules*
clone() const86 PluralRules::clone() const {
87     return new PluralRules(*this);
88 }
89 
90 PluralRules&
operator =(const PluralRules & other)91 PluralRules::operator=(const PluralRules& other) {
92     if (this != &other) {
93         delete mRules;
94         if (other.mRules==NULL) {
95             mRules = NULL;
96         }
97         else {
98             mRules = new RuleChain(*other.mRules);
99         }
100     }
101 
102     return *this;
103 }
104 
getAvailableLocales(UErrorCode & status)105 StringEnumeration* PluralRules::getAvailableLocales(UErrorCode &status) {
106     StringEnumeration *result = new PluralAvailableLocalesEnumeration(status);
107     if (result == NULL && U_SUCCESS(status)) {
108         status = U_MEMORY_ALLOCATION_ERROR;
109     }
110     if (U_FAILURE(status)) {
111         delete result;
112         result = NULL;
113     }
114     return result;
115 }
116 
117 
118 PluralRules* U_EXPORT2
createRules(const UnicodeString & description,UErrorCode & status)119 PluralRules::createRules(const UnicodeString& description, UErrorCode& status) {
120     if (U_FAILURE(status)) {
121         return NULL;
122     }
123 
124     PluralRuleParser parser;
125     PluralRules *newRules = new PluralRules(status);
126     if (U_SUCCESS(status) && newRules == NULL) {
127         status = U_MEMORY_ALLOCATION_ERROR;
128     }
129     parser.parse(description, newRules, status);
130     if (U_FAILURE(status)) {
131         delete newRules;
132         newRules = NULL;
133     }
134     return newRules;
135 }
136 
137 
138 PluralRules* U_EXPORT2
createDefaultRules(UErrorCode & status)139 PluralRules::createDefaultRules(UErrorCode& status) {
140     return createRules(UnicodeString(TRUE, PLURAL_DEFAULT_RULE, -1), status);
141 }
142 
143 /******************************************************************************/
144 /* Create PluralRules cache */
145 
146 template<> U_I18N_API
createObject(const void *,UErrorCode & status) const147 const SharedPluralRules *LocaleCacheKey<SharedPluralRules>::createObject(
148         const void * /*unused*/, UErrorCode &status) const {
149     const char *localeId = fLoc.getName();
150     PluralRules *pr = PluralRules::internalForLocale(
151             localeId, UPLURAL_TYPE_CARDINAL, status);
152     if (U_FAILURE(status)) {
153         return NULL;
154     }
155     SharedPluralRules *result = new SharedPluralRules(pr);
156     if (result == NULL) {
157         status = U_MEMORY_ALLOCATION_ERROR;
158         delete pr;
159         return NULL;
160     }
161     result->addRef();
162     return result;
163 }
164 
165 /* end plural rules cache */
166 /******************************************************************************/
167 
168 const SharedPluralRules* U_EXPORT2
createSharedInstance(const Locale & locale,UPluralType type,UErrorCode & status)169 PluralRules::createSharedInstance(
170         const Locale& locale, UPluralType type, UErrorCode& status) {
171     if (U_FAILURE(status)) {
172         return NULL;
173     }
174     if (type != UPLURAL_TYPE_CARDINAL) {
175         status = U_UNSUPPORTED_ERROR;
176         return NULL;
177     }
178     const SharedPluralRules *result = NULL;
179     UnifiedCache::getByLocale(locale, result, status);
180     return result;
181 }
182 
183 PluralRules* U_EXPORT2
forLocale(const Locale & locale,UErrorCode & status)184 PluralRules::forLocale(const Locale& locale, UErrorCode& status) {
185     return forLocale(locale, UPLURAL_TYPE_CARDINAL, status);
186 }
187 
188 PluralRules* U_EXPORT2
forLocale(const Locale & locale,UPluralType type,UErrorCode & status)189 PluralRules::forLocale(const Locale& locale, UPluralType type, UErrorCode& status) {
190     if (type != UPLURAL_TYPE_CARDINAL) {
191         return internalForLocale(locale, type, status);
192     }
193     const SharedPluralRules *shared = createSharedInstance(
194             locale, type, status);
195     if (U_FAILURE(status)) {
196         return NULL;
197     }
198     PluralRules *result = (*shared)->clone();
199     shared->removeRef();
200     if (result == NULL) {
201         status = U_MEMORY_ALLOCATION_ERROR;
202     }
203     return result;
204 }
205 
206 PluralRules* U_EXPORT2
internalForLocale(const Locale & locale,UPluralType type,UErrorCode & status)207 PluralRules::internalForLocale(const Locale& locale, UPluralType type, UErrorCode& status) {
208     if (U_FAILURE(status)) {
209         return NULL;
210     }
211     if (type >= UPLURAL_TYPE_COUNT) {
212         status = U_ILLEGAL_ARGUMENT_ERROR;
213         return NULL;
214     }
215     PluralRules *newObj = new PluralRules(status);
216     if (newObj==NULL || U_FAILURE(status)) {
217         delete newObj;
218         return NULL;
219     }
220     UnicodeString locRule = newObj->getRuleFromResource(locale, type, status);
221     // TODO: which errors, if any, should be returned?
222     if (locRule.length() == 0) {
223         // Locales with no specific rules (all numbers have the "other" category
224         //   will return a U_MISSING_RESOURCE_ERROR at this point. This is not
225         //   an error.
226         locRule =  UnicodeString(PLURAL_DEFAULT_RULE);
227         status = U_ZERO_ERROR;
228     }
229     PluralRuleParser parser;
230     parser.parse(locRule, newObj, status);
231         //  TODO: should rule parse errors be returned, or
232         //        should we silently use default rules?
233         //        Original impl used default rules.
234         //        Ask the question to ICU Core.
235 
236     return newObj;
237 }
238 
239 UnicodeString
select(int32_t number) const240 PluralRules::select(int32_t number) const {
241     return select(FixedDecimal(number));
242 }
243 
244 UnicodeString
select(double number) const245 PluralRules::select(double number) const {
246     return select(FixedDecimal(number));
247 }
248 
249 UnicodeString
select(const FixedDecimal & number) const250 PluralRules::select(const FixedDecimal &number) const {
251     if (mRules == NULL) {
252         return UnicodeString(TRUE, PLURAL_DEFAULT_RULE, -1);
253     }
254     else {
255         return mRules->select(number);
256     }
257 }
258 
259 UnicodeString
select(const VisibleDigitsWithExponent & number) const260 PluralRules::select(const VisibleDigitsWithExponent &number) const {
261     if (number.getExponent() != NULL) {
262         return UnicodeString(TRUE, PLURAL_DEFAULT_RULE, -1);
263     }
264     return select(FixedDecimal(number.getMantissa()));
265 }
266 
267 
268 
269 StringEnumeration*
getKeywords(UErrorCode & status) const270 PluralRules::getKeywords(UErrorCode& status) const {
271     if (U_FAILURE(status))  return NULL;
272     StringEnumeration* nameEnumerator = new PluralKeywordEnumeration(mRules, status);
273     if (U_FAILURE(status)) {
274       delete nameEnumerator;
275       return NULL;
276     }
277 
278     return nameEnumerator;
279 }
280 
281 double
getUniqueKeywordValue(const UnicodeString &)282 PluralRules::getUniqueKeywordValue(const UnicodeString& /* keyword */) {
283   // Not Implemented.
284   return UPLRULES_NO_UNIQUE_VALUE;
285 }
286 
287 int32_t
getAllKeywordValues(const UnicodeString &,double *,int32_t,UErrorCode & error)288 PluralRules::getAllKeywordValues(const UnicodeString & /* keyword */, double * /* dest */,
289                                  int32_t /* destCapacity */, UErrorCode& error) {
290     error = U_UNSUPPORTED_ERROR;
291     return 0;
292 }
293 
294 
scaleForInt(double d)295 static double scaleForInt(double d) {
296     double scale = 1.0;
297     while (d != floor(d)) {
298         d = d * 10.0;
299         scale = scale * 10.0;
300     }
301     return scale;
302 }
303 
304 static int32_t
getSamplesFromString(const UnicodeString & samples,double * dest,int32_t destCapacity,UErrorCode & status)305 getSamplesFromString(const UnicodeString &samples, double *dest,
306                         int32_t destCapacity, UErrorCode& status) {
307     int32_t sampleCount = 0;
308     int32_t sampleStartIdx = 0;
309     int32_t sampleEndIdx = 0;
310 
311     //std::string ss;  // TODO: debugging.
312     // std::cout << "PluralRules::getSamples(), samples = \"" << samples.toUTF8String(ss) << "\"\n";
313     for (sampleCount = 0; sampleCount < destCapacity && sampleStartIdx < samples.length(); ) {
314         sampleEndIdx = samples.indexOf(COMMA, sampleStartIdx);
315         if (sampleEndIdx == -1) {
316             sampleEndIdx = samples.length();
317         }
318         const UnicodeString &sampleRange = samples.tempSubStringBetween(sampleStartIdx, sampleEndIdx);
319         // ss.erase();
320         // std::cout << "PluralRules::getSamples(), samplesRange = \"" << sampleRange.toUTF8String(ss) << "\"\n";
321         int32_t tildeIndex = sampleRange.indexOf(TILDE);
322         if (tildeIndex < 0) {
323             FixedDecimal fixed(sampleRange, status);
324             double sampleValue = fixed.source;
325             if (fixed.visibleDecimalDigitCount == 0 || sampleValue != floor(sampleValue)) {
326                 dest[sampleCount++] = sampleValue;
327             }
328         } else {
329 
330             FixedDecimal fixedLo(sampleRange.tempSubStringBetween(0, tildeIndex), status);
331             FixedDecimal fixedHi(sampleRange.tempSubStringBetween(tildeIndex+1), status);
332             double rangeLo = fixedLo.source;
333             double rangeHi = fixedHi.source;
334             if (U_FAILURE(status)) {
335                 break;
336             }
337             if (rangeHi < rangeLo) {
338                 status = U_INVALID_FORMAT_ERROR;
339                 break;
340             }
341 
342             // For ranges of samples with fraction decimal digits, scale the number up so that we
343             //   are adding one in the units place. Avoids roundoffs from repetitive adds of tenths.
344 
345             double scale = scaleForInt(rangeLo);
346             double t = scaleForInt(rangeHi);
347             if (t > scale) {
348                 scale = t;
349             }
350             rangeLo *= scale;
351             rangeHi *= scale;
352             for (double n=rangeLo; n<=rangeHi; n+=1) {
353                 // Hack Alert: don't return any decimal samples with integer values that
354                 //    originated from a format with trailing decimals.
355                 //    This API is returning doubles, which can't distinguish having displayed
356                 //    zeros to the right of the decimal.
357                 //    This results in test failures with values mapping back to a different keyword.
358                 double sampleValue = n/scale;
359                 if (!(sampleValue == floor(sampleValue) && fixedLo.visibleDecimalDigitCount > 0)) {
360                     dest[sampleCount++] = sampleValue;
361                 }
362                 if (sampleCount >= destCapacity) {
363                     break;
364                 }
365             }
366         }
367         sampleStartIdx = sampleEndIdx + 1;
368     }
369     return sampleCount;
370 }
371 
372 
373 int32_t
getSamples(const UnicodeString & keyword,double * dest,int32_t destCapacity,UErrorCode & status)374 PluralRules::getSamples(const UnicodeString &keyword, double *dest,
375                         int32_t destCapacity, UErrorCode& status) {
376     RuleChain *rc = rulesForKeyword(keyword);
377     if (rc == NULL || destCapacity == 0 || U_FAILURE(status)) {
378         return 0;
379     }
380     int32_t numSamples = getSamplesFromString(rc->fIntegerSamples, dest, destCapacity, status);
381     if (numSamples == 0) {
382         numSamples = getSamplesFromString(rc->fDecimalSamples, dest, destCapacity, status);
383     }
384     return numSamples;
385 }
386 
387 
rulesForKeyword(const UnicodeString & keyword) const388 RuleChain *PluralRules::rulesForKeyword(const UnicodeString &keyword) const {
389     RuleChain *rc;
390     for (rc = mRules; rc != NULL; rc = rc->fNext) {
391         if (rc->fKeyword == keyword) {
392             break;
393         }
394     }
395     return rc;
396 }
397 
398 
399 UBool
isKeyword(const UnicodeString & keyword) const400 PluralRules::isKeyword(const UnicodeString& keyword) const {
401     if (0 == keyword.compare(PLURAL_KEYWORD_OTHER, 5)) {
402         return true;
403     }
404     return rulesForKeyword(keyword) != NULL;
405 }
406 
407 UnicodeString
getKeywordOther() const408 PluralRules::getKeywordOther() const {
409     return UnicodeString(TRUE, PLURAL_KEYWORD_OTHER, 5);
410 }
411 
412 UBool
operator ==(const PluralRules & other) const413 PluralRules::operator==(const PluralRules& other) const  {
414     const UnicodeString *ptrKeyword;
415     UErrorCode status= U_ZERO_ERROR;
416 
417     if ( this == &other ) {
418         return TRUE;
419     }
420     LocalPointer<StringEnumeration> myKeywordList(getKeywords(status));
421     LocalPointer<StringEnumeration> otherKeywordList(other.getKeywords(status));
422     if (U_FAILURE(status)) {
423         return FALSE;
424     }
425 
426     if (myKeywordList->count(status)!=otherKeywordList->count(status)) {
427         return FALSE;
428     }
429     myKeywordList->reset(status);
430     while ((ptrKeyword=myKeywordList->snext(status))!=NULL) {
431         if (!other.isKeyword(*ptrKeyword)) {
432             return FALSE;
433         }
434     }
435     otherKeywordList->reset(status);
436     while ((ptrKeyword=otherKeywordList->snext(status))!=NULL) {
437         if (!this->isKeyword(*ptrKeyword)) {
438             return FALSE;
439         }
440     }
441     if (U_FAILURE(status)) {
442         return FALSE;
443     }
444 
445     return TRUE;
446 }
447 
448 
449 void
parse(const UnicodeString & ruleData,PluralRules * prules,UErrorCode & status)450 PluralRuleParser::parse(const UnicodeString& ruleData, PluralRules *prules, UErrorCode &status)
451 {
452     if (U_FAILURE(status)) {
453         return;
454     }
455     U_ASSERT(ruleIndex == 0);    // Parsers are good for a single use only!
456     ruleSrc = &ruleData;
457 
458     while (ruleIndex< ruleSrc->length()) {
459         getNextToken(status);
460         if (U_FAILURE(status)) {
461             return;
462         }
463         checkSyntax(status);
464         if (U_FAILURE(status)) {
465             return;
466         }
467         switch (type) {
468         case tAnd:
469             U_ASSERT(curAndConstraint != NULL);
470             curAndConstraint = curAndConstraint->add();
471             break;
472         case tOr:
473             {
474                 U_ASSERT(currentChain != NULL);
475                 OrConstraint *orNode=currentChain->ruleHeader;
476                 while (orNode->next != NULL) {
477                     orNode = orNode->next;
478                 }
479                 orNode->next= new OrConstraint();
480                 orNode=orNode->next;
481                 orNode->next=NULL;
482                 curAndConstraint = orNode->add();
483             }
484             break;
485         case tIs:
486             U_ASSERT(curAndConstraint != NULL);
487             U_ASSERT(curAndConstraint->value == -1);
488             U_ASSERT(curAndConstraint->rangeList == NULL);
489             break;
490         case tNot:
491             U_ASSERT(curAndConstraint != NULL);
492             curAndConstraint->negated=TRUE;
493             break;
494 
495         case tNotEqual:
496             curAndConstraint->negated=TRUE;
497         case tIn:
498         case tWithin:
499         case tEqual:
500             U_ASSERT(curAndConstraint != NULL);
501             curAndConstraint->rangeList = new UVector32(status);
502             curAndConstraint->rangeList->addElement(-1, status);  // range Low
503             curAndConstraint->rangeList->addElement(-1, status);  // range Hi
504             rangeLowIdx = 0;
505             rangeHiIdx  = 1;
506             curAndConstraint->value=PLURAL_RANGE_HIGH;
507             curAndConstraint->integerOnly = (type != tWithin);
508             break;
509         case tNumber:
510             U_ASSERT(curAndConstraint != NULL);
511             if ( (curAndConstraint->op==AndConstraint::MOD)&&
512                  (curAndConstraint->opNum == -1 ) ) {
513                 curAndConstraint->opNum=getNumberValue(token);
514             }
515             else {
516                 if (curAndConstraint->rangeList == NULL) {
517                     // this is for an 'is' rule
518                     curAndConstraint->value = getNumberValue(token);
519                 } else {
520                     // this is for an 'in' or 'within' rule
521                     if (curAndConstraint->rangeList->elementAti(rangeLowIdx) == -1) {
522                         curAndConstraint->rangeList->setElementAt(getNumberValue(token), rangeLowIdx);
523                         curAndConstraint->rangeList->setElementAt(getNumberValue(token), rangeHiIdx);
524                     }
525                     else {
526                         curAndConstraint->rangeList->setElementAt(getNumberValue(token), rangeHiIdx);
527                         if (curAndConstraint->rangeList->elementAti(rangeLowIdx) >
528                                 curAndConstraint->rangeList->elementAti(rangeHiIdx)) {
529                             // Range Lower bound > Range Upper bound.
530                             // U_UNEXPECTED_TOKEN seems a little funny, but it is consistently
531                             // used for all plural rule parse errors.
532                             status = U_UNEXPECTED_TOKEN;
533                             break;
534                         }
535                     }
536                 }
537             }
538             break;
539         case tComma:
540             // TODO: rule syntax checking is inadequate, can happen with badly formed rules.
541             //       Catch cases like "n mod 10, is 1" here instead.
542             if (curAndConstraint == NULL || curAndConstraint->rangeList == NULL) {
543                 status = U_UNEXPECTED_TOKEN;
544                 break;
545             }
546             U_ASSERT(curAndConstraint->rangeList->size() >= 2);
547             rangeLowIdx = curAndConstraint->rangeList->size();
548             curAndConstraint->rangeList->addElement(-1, status);  // range Low
549             rangeHiIdx = curAndConstraint->rangeList->size();
550             curAndConstraint->rangeList->addElement(-1, status);  // range Hi
551             break;
552         case tMod:
553             U_ASSERT(curAndConstraint != NULL);
554             curAndConstraint->op=AndConstraint::MOD;
555             break;
556         case tVariableN:
557         case tVariableI:
558         case tVariableF:
559         case tVariableT:
560         case tVariableV:
561             U_ASSERT(curAndConstraint != NULL);
562             curAndConstraint->digitsType = type;
563             break;
564         case tKeyword:
565             {
566             RuleChain *newChain = new RuleChain;
567             if (newChain == NULL) {
568                 status = U_MEMORY_ALLOCATION_ERROR;
569                 break;
570             }
571             newChain->fKeyword = token;
572             if (prules->mRules == NULL) {
573                 prules->mRules = newChain;
574             } else {
575                 // The new rule chain goes at the end of the linked list of rule chains,
576                 //   unless there is an "other" keyword & chain. "other" must remain last.
577                 RuleChain *insertAfter = prules->mRules;
578                 while (insertAfter->fNext!=NULL &&
579                        insertAfter->fNext->fKeyword.compare(PLURAL_KEYWORD_OTHER, 5) != 0 ){
580                     insertAfter=insertAfter->fNext;
581                 }
582                 newChain->fNext = insertAfter->fNext;
583                 insertAfter->fNext = newChain;
584             }
585             OrConstraint *orNode = new OrConstraint();
586             newChain->ruleHeader = orNode;
587             curAndConstraint = orNode->add();
588             currentChain = newChain;
589             }
590             break;
591 
592         case tInteger:
593             for (;;) {
594                 getNextToken(status);
595                 if (U_FAILURE(status) || type == tSemiColon || type == tEOF || type == tAt) {
596                     break;
597                 }
598                 if (type == tEllipsis) {
599                     currentChain->fIntegerSamplesUnbounded = TRUE;
600                     continue;
601                 }
602                 currentChain->fIntegerSamples.append(token);
603             }
604             break;
605 
606         case tDecimal:
607             for (;;) {
608                 getNextToken(status);
609                 if (U_FAILURE(status) || type == tSemiColon || type == tEOF || type == tAt) {
610                     break;
611                 }
612                 if (type == tEllipsis) {
613                     currentChain->fDecimalSamplesUnbounded = TRUE;
614                     continue;
615                 }
616                 currentChain->fDecimalSamples.append(token);
617             }
618             break;
619 
620         default:
621             break;
622         }
623         prevType=type;
624         if (U_FAILURE(status)) {
625             break;
626         }
627     }
628 }
629 
630 UnicodeString
getRuleFromResource(const Locale & locale,UPluralType type,UErrorCode & errCode)631 PluralRules::getRuleFromResource(const Locale& locale, UPluralType type, UErrorCode& errCode) {
632     UnicodeString emptyStr;
633 
634     if (U_FAILURE(errCode)) {
635         return emptyStr;
636     }
637     LocalUResourceBundlePointer rb(ures_openDirect(NULL, "plurals", &errCode));
638     if(U_FAILURE(errCode)) {
639         return emptyStr;
640     }
641     const char *typeKey;
642     switch (type) {
643     case UPLURAL_TYPE_CARDINAL:
644         typeKey = "locales";
645         break;
646     case UPLURAL_TYPE_ORDINAL:
647         typeKey = "locales_ordinals";
648         break;
649     default:
650         // Must not occur: The caller should have checked for valid types.
651         errCode = U_ILLEGAL_ARGUMENT_ERROR;
652         return emptyStr;
653     }
654     LocalUResourceBundlePointer locRes(ures_getByKey(rb.getAlias(), typeKey, NULL, &errCode));
655     if(U_FAILURE(errCode)) {
656         return emptyStr;
657     }
658     int32_t resLen=0;
659     const char *curLocaleName=locale.getName();
660     const UChar* s = ures_getStringByKey(locRes.getAlias(), curLocaleName, &resLen, &errCode);
661 
662     if (s == NULL) {
663         // Check parent locales.
664         UErrorCode status = U_ZERO_ERROR;
665         char parentLocaleName[ULOC_FULLNAME_CAPACITY];
666         const char *curLocaleName=locale.getName();
667         uprv_strcpy(parentLocaleName, curLocaleName);
668 
669         while (uloc_getParent(parentLocaleName, parentLocaleName,
670                                        ULOC_FULLNAME_CAPACITY, &status) > 0) {
671             resLen=0;
672             s = ures_getStringByKey(locRes.getAlias(), parentLocaleName, &resLen, &status);
673             if (s != NULL) {
674                 errCode = U_ZERO_ERROR;
675                 break;
676             }
677             status = U_ZERO_ERROR;
678         }
679     }
680     if (s==NULL) {
681         return emptyStr;
682     }
683 
684     char setKey[256];
685     u_UCharsToChars(s, setKey, resLen + 1);
686     // printf("\n PluralRule: %s\n", setKey);
687 
688     LocalUResourceBundlePointer ruleRes(ures_getByKey(rb.getAlias(), "rules", NULL, &errCode));
689     if(U_FAILURE(errCode)) {
690         return emptyStr;
691     }
692     LocalUResourceBundlePointer setRes(ures_getByKey(ruleRes.getAlias(), setKey, NULL, &errCode));
693     if (U_FAILURE(errCode)) {
694         return emptyStr;
695     }
696 
697     int32_t numberKeys = ures_getSize(setRes.getAlias());
698     UnicodeString result;
699     const char *key=NULL;
700     for(int32_t i=0; i<numberKeys; ++i) {   // Keys are zero, one, few, ...
701         UnicodeString rules = ures_getNextUnicodeString(setRes.getAlias(), &key, &errCode);
702         UnicodeString uKey(key, -1, US_INV);
703         result.append(uKey);
704         result.append(COLON);
705         result.append(rules);
706         result.append(SEMI_COLON);
707     }
708     return result;
709 }
710 
711 
712 UnicodeString
getRules() const713 PluralRules::getRules() const {
714     UnicodeString rules;
715     if (mRules != NULL) {
716         mRules->dumpRules(rules);
717     }
718     return rules;
719 }
720 
721 
AndConstraint()722 AndConstraint::AndConstraint() {
723     op = AndConstraint::NONE;
724     opNum=-1;
725     value = -1;
726     rangeList = NULL;
727     negated = FALSE;
728     integerOnly = FALSE;
729     digitsType = none;
730     next=NULL;
731 }
732 
733 
AndConstraint(const AndConstraint & other)734 AndConstraint::AndConstraint(const AndConstraint& other) {
735     this->op = other.op;
736     this->opNum=other.opNum;
737     this->value=other.value;
738     this->rangeList=NULL;
739     if (other.rangeList != NULL) {
740         UErrorCode status = U_ZERO_ERROR;
741         this->rangeList = new UVector32(status);
742         this->rangeList->assign(*other.rangeList, status);
743     }
744     this->integerOnly=other.integerOnly;
745     this->negated=other.negated;
746     this->digitsType = other.digitsType;
747     if (other.next==NULL) {
748         this->next=NULL;
749     }
750     else {
751         this->next = new AndConstraint(*other.next);
752     }
753 }
754 
~AndConstraint()755 AndConstraint::~AndConstraint() {
756     delete rangeList;
757     if (next!=NULL) {
758         delete next;
759     }
760 }
761 
762 
763 UBool
isFulfilled(const FixedDecimal & number)764 AndConstraint::isFulfilled(const FixedDecimal &number) {
765     UBool result = TRUE;
766     if (digitsType == none) {
767         // An empty AndConstraint, created by a rule with a keyword but no following expression.
768         return TRUE;
769     }
770     double n = number.get(digitsType);  // pulls n | i | v | f value for the number.
771                                         // Will always be positive.
772                                         // May be non-integer (n option only)
773     do {
774         if (integerOnly && n != uprv_floor(n)) {
775             result = FALSE;
776             break;
777         }
778 
779         if (op == MOD) {
780             n = fmod(n, opNum);
781         }
782         if (rangeList == NULL) {
783             result = value == -1 ||    // empty rule
784                      n == value;       //  'is' rule
785             break;
786         }
787         result = FALSE;                // 'in' or 'within' rule
788         for (int32_t r=0; r<rangeList->size(); r+=2) {
789             if (rangeList->elementAti(r) <= n && n <= rangeList->elementAti(r+1)) {
790                 result = TRUE;
791                 break;
792             }
793         }
794     } while (FALSE);
795 
796     if (negated) {
797         result = !result;
798     }
799     return result;
800 }
801 
802 
803 AndConstraint*
add()804 AndConstraint::add()
805 {
806     this->next = new AndConstraint();
807     return this->next;
808 }
809 
OrConstraint()810 OrConstraint::OrConstraint() {
811     childNode=NULL;
812     next=NULL;
813 }
814 
OrConstraint(const OrConstraint & other)815 OrConstraint::OrConstraint(const OrConstraint& other) {
816     if ( other.childNode == NULL ) {
817         this->childNode = NULL;
818     }
819     else {
820         this->childNode = new AndConstraint(*(other.childNode));
821     }
822     if (other.next == NULL ) {
823         this->next = NULL;
824     }
825     else {
826         this->next = new OrConstraint(*(other.next));
827     }
828 }
829 
~OrConstraint()830 OrConstraint::~OrConstraint() {
831     if (childNode!=NULL) {
832         delete childNode;
833     }
834     if (next!=NULL) {
835         delete next;
836     }
837 }
838 
839 AndConstraint*
add()840 OrConstraint::add()
841 {
842     OrConstraint *curOrConstraint=this;
843     {
844         while (curOrConstraint->next!=NULL) {
845             curOrConstraint = curOrConstraint->next;
846         }
847         U_ASSERT(curOrConstraint->childNode == NULL);
848         curOrConstraint->childNode = new AndConstraint();
849     }
850     return curOrConstraint->childNode;
851 }
852 
853 UBool
isFulfilled(const FixedDecimal & number)854 OrConstraint::isFulfilled(const FixedDecimal &number) {
855     OrConstraint* orRule=this;
856     UBool result=FALSE;
857 
858     while (orRule!=NULL && !result) {
859         result=TRUE;
860         AndConstraint* andRule = orRule->childNode;
861         while (andRule!=NULL && result) {
862             result = andRule->isFulfilled(number);
863             andRule=andRule->next;
864         }
865         orRule = orRule->next;
866     }
867 
868     return result;
869 }
870 
871 
RuleChain()872 RuleChain::RuleChain(): fKeyword(), fNext(NULL), ruleHeader(NULL), fDecimalSamples(), fIntegerSamples(),
873                         fDecimalSamplesUnbounded(FALSE), fIntegerSamplesUnbounded(FALSE) {
874 }
875 
RuleChain(const RuleChain & other)876 RuleChain::RuleChain(const RuleChain& other) :
877         fKeyword(other.fKeyword), fNext(NULL), ruleHeader(NULL), fDecimalSamples(other.fDecimalSamples),
878         fIntegerSamples(other.fIntegerSamples), fDecimalSamplesUnbounded(other.fDecimalSamplesUnbounded),
879         fIntegerSamplesUnbounded(other.fIntegerSamplesUnbounded) {
880     if (other.ruleHeader != NULL) {
881         this->ruleHeader = new OrConstraint(*(other.ruleHeader));
882     }
883     if (other.fNext != NULL ) {
884         this->fNext = new RuleChain(*other.fNext);
885     }
886 }
887 
~RuleChain()888 RuleChain::~RuleChain() {
889     delete fNext;
890     delete ruleHeader;
891 }
892 
893 
894 UnicodeString
select(const FixedDecimal & number) const895 RuleChain::select(const FixedDecimal &number) const {
896     if (!number.isNanOrInfinity) {
897         for (const RuleChain *rules = this; rules != NULL; rules = rules->fNext) {
898              if (rules->ruleHeader->isFulfilled(number)) {
899                  return rules->fKeyword;
900              }
901         }
902     }
903     return UnicodeString(TRUE, PLURAL_KEYWORD_OTHER, 5);
904 }
905 
tokenString(tokenType tok)906 static UnicodeString tokenString(tokenType tok) {
907     UnicodeString s;
908     switch (tok) {
909       case tVariableN:
910         s.append(LOW_N); break;
911       case tVariableI:
912         s.append(LOW_I); break;
913       case tVariableF:
914         s.append(LOW_F); break;
915       case tVariableV:
916         s.append(LOW_V); break;
917       case tVariableT:
918         s.append(LOW_T); break;
919       default:
920         s.append(TILDE);
921     }
922     return s;
923 }
924 
925 void
dumpRules(UnicodeString & result)926 RuleChain::dumpRules(UnicodeString& result) {
927     UChar digitString[16];
928 
929     if ( ruleHeader != NULL ) {
930         result +=  fKeyword;
931         result += COLON;
932         result += SPACE;
933         OrConstraint* orRule=ruleHeader;
934         while ( orRule != NULL ) {
935             AndConstraint* andRule=orRule->childNode;
936             while ( andRule != NULL ) {
937                 if ((andRule->op==AndConstraint::NONE) &&  (andRule->rangeList==NULL) && (andRule->value == -1)) {
938                     // Empty Rules.
939                 } else if ( (andRule->op==AndConstraint::NONE) && (andRule->rangeList==NULL) ) {
940                     result += tokenString(andRule->digitsType);
941                     result += UNICODE_STRING_SIMPLE(" is ");
942                     if (andRule->negated) {
943                         result += UNICODE_STRING_SIMPLE("not ");
944                     }
945                     uprv_itou(digitString,16, andRule->value,10,0);
946                     result += UnicodeString(digitString);
947                 }
948                 else {
949                     result += tokenString(andRule->digitsType);
950                     result += SPACE;
951                     if (andRule->op==AndConstraint::MOD) {
952                         result += UNICODE_STRING_SIMPLE("mod ");
953                         uprv_itou(digitString,16, andRule->opNum,10,0);
954                         result += UnicodeString(digitString);
955                     }
956                     if (andRule->rangeList==NULL) {
957                         if (andRule->negated) {
958                             result += UNICODE_STRING_SIMPLE(" is not ");
959                             uprv_itou(digitString,16, andRule->value,10,0);
960                             result += UnicodeString(digitString);
961                         }
962                         else {
963                             result += UNICODE_STRING_SIMPLE(" is ");
964                             uprv_itou(digitString,16, andRule->value,10,0);
965                             result += UnicodeString(digitString);
966                         }
967                     }
968                     else {
969                         if (andRule->negated) {
970                             if ( andRule->integerOnly ) {
971                                 result += UNICODE_STRING_SIMPLE(" not in ");
972                             }
973                             else {
974                                 result += UNICODE_STRING_SIMPLE(" not within ");
975                             }
976                         }
977                         else {
978                             if ( andRule->integerOnly ) {
979                                 result += UNICODE_STRING_SIMPLE(" in ");
980                             }
981                             else {
982                                 result += UNICODE_STRING_SIMPLE(" within ");
983                             }
984                         }
985                         for (int32_t r=0; r<andRule->rangeList->size(); r+=2) {
986                             int32_t rangeLo = andRule->rangeList->elementAti(r);
987                             int32_t rangeHi = andRule->rangeList->elementAti(r+1);
988                             uprv_itou(digitString,16, rangeLo, 10, 0);
989                             result += UnicodeString(digitString);
990                             result += UNICODE_STRING_SIMPLE("..");
991                             uprv_itou(digitString,16, rangeHi, 10,0);
992                             result += UnicodeString(digitString);
993                             if (r+2 < andRule->rangeList->size()) {
994                                 result += UNICODE_STRING_SIMPLE(", ");
995                             }
996                         }
997                     }
998                 }
999                 if ( (andRule=andRule->next) != NULL) {
1000                     result += UNICODE_STRING_SIMPLE(" and ");
1001                 }
1002             }
1003             if ( (orRule = orRule->next) != NULL ) {
1004                 result += UNICODE_STRING_SIMPLE(" or ");
1005             }
1006         }
1007     }
1008     if ( fNext != NULL ) {
1009         result += UNICODE_STRING_SIMPLE("; ");
1010         fNext->dumpRules(result);
1011     }
1012 }
1013 
1014 
1015 UErrorCode
getKeywords(int32_t capacityOfKeywords,UnicodeString * keywords,int32_t & arraySize) const1016 RuleChain::getKeywords(int32_t capacityOfKeywords, UnicodeString* keywords, int32_t& arraySize) const {
1017     if ( arraySize < capacityOfKeywords-1 ) {
1018         keywords[arraySize++]=fKeyword;
1019     }
1020     else {
1021         return U_BUFFER_OVERFLOW_ERROR;
1022     }
1023 
1024     if ( fNext != NULL ) {
1025         return fNext->getKeywords(capacityOfKeywords, keywords, arraySize);
1026     }
1027     else {
1028         return U_ZERO_ERROR;
1029     }
1030 }
1031 
1032 UBool
isKeyword(const UnicodeString & keywordParam) const1033 RuleChain::isKeyword(const UnicodeString& keywordParam) const {
1034     if ( fKeyword == keywordParam ) {
1035         return TRUE;
1036     }
1037 
1038     if ( fNext != NULL ) {
1039         return fNext->isKeyword(keywordParam);
1040     }
1041     else {
1042         return FALSE;
1043     }
1044 }
1045 
1046 
PluralRuleParser()1047 PluralRuleParser::PluralRuleParser() :
1048         ruleIndex(0), token(), type(none), prevType(none),
1049         curAndConstraint(NULL), currentChain(NULL), rangeLowIdx(-1), rangeHiIdx(-1)
1050 {
1051 }
1052 
~PluralRuleParser()1053 PluralRuleParser::~PluralRuleParser() {
1054 }
1055 
1056 
1057 int32_t
getNumberValue(const UnicodeString & token)1058 PluralRuleParser::getNumberValue(const UnicodeString& token) {
1059     int32_t i;
1060     char digits[128];
1061 
1062     i = token.extract(0, token.length(), digits, ARRAY_SIZE(digits), US_INV);
1063     digits[i]='\0';
1064 
1065     return((int32_t)atoi(digits));
1066 }
1067 
1068 
1069 void
checkSyntax(UErrorCode & status)1070 PluralRuleParser::checkSyntax(UErrorCode &status)
1071 {
1072     if (U_FAILURE(status)) {
1073         return;
1074     }
1075     if (!(prevType==none || prevType==tSemiColon)) {
1076         type = getKeyType(token, type);  // Switch token type from tKeyword if we scanned a reserved word,
1077                                                //   and we are not at the start of a rule, where a
1078                                                //   keyword is expected.
1079     }
1080 
1081     switch(prevType) {
1082     case none:
1083     case tSemiColon:
1084         if (type!=tKeyword && type != tEOF) {
1085             status = U_UNEXPECTED_TOKEN;
1086         }
1087         break;
1088     case tVariableN:
1089     case tVariableI:
1090     case tVariableF:
1091     case tVariableT:
1092     case tVariableV:
1093         if (type != tIs && type != tMod && type != tIn &&
1094             type != tNot && type != tWithin && type != tEqual && type != tNotEqual) {
1095             status = U_UNEXPECTED_TOKEN;
1096         }
1097         break;
1098     case tKeyword:
1099         if (type != tColon) {
1100             status = U_UNEXPECTED_TOKEN;
1101         }
1102         break;
1103     case tColon:
1104         if (!(type == tVariableN ||
1105               type == tVariableI ||
1106               type == tVariableF ||
1107               type == tVariableT ||
1108               type == tVariableV ||
1109               type == tAt)) {
1110             status = U_UNEXPECTED_TOKEN;
1111         }
1112         break;
1113     case tIs:
1114         if ( type != tNumber && type != tNot) {
1115             status = U_UNEXPECTED_TOKEN;
1116         }
1117         break;
1118     case tNot:
1119         if (type != tNumber && type != tIn && type != tWithin) {
1120             status = U_UNEXPECTED_TOKEN;
1121         }
1122         break;
1123     case tMod:
1124     case tDot2:
1125     case tIn:
1126     case tWithin:
1127     case tEqual:
1128     case tNotEqual:
1129         if (type != tNumber) {
1130             status = U_UNEXPECTED_TOKEN;
1131         }
1132         break;
1133     case tAnd:
1134     case tOr:
1135         if ( type != tVariableN &&
1136              type != tVariableI &&
1137              type != tVariableF &&
1138              type != tVariableT &&
1139              type != tVariableV) {
1140             status = U_UNEXPECTED_TOKEN;
1141         }
1142         break;
1143     case tComma:
1144         if (type != tNumber) {
1145             status = U_UNEXPECTED_TOKEN;
1146         }
1147         break;
1148     case tNumber:
1149         if (type != tDot2  && type != tSemiColon && type != tIs       && type != tNot    &&
1150             type != tIn    && type != tEqual     && type != tNotEqual && type != tWithin &&
1151             type != tAnd   && type != tOr        && type != tComma    && type != tAt     &&
1152             type != tEOF)
1153         {
1154             status = U_UNEXPECTED_TOKEN;
1155         }
1156         // TODO: a comma following a number that is not part of a range will be allowed.
1157         //       It's not the only case of this sort of thing. Parser needs a re-write.
1158         break;
1159     case tAt:
1160         if (type != tDecimal && type != tInteger) {
1161             status = U_UNEXPECTED_TOKEN;
1162         }
1163         break;
1164     default:
1165         status = U_UNEXPECTED_TOKEN;
1166         break;
1167     }
1168 }
1169 
1170 
1171 /*
1172  *  Scan the next token from the input rules.
1173  *     rules and returned token type are in the parser state variables.
1174  */
1175 void
getNextToken(UErrorCode & status)1176 PluralRuleParser::getNextToken(UErrorCode &status)
1177 {
1178     if (U_FAILURE(status)) {
1179         return;
1180     }
1181 
1182     UChar ch;
1183     while (ruleIndex < ruleSrc->length()) {
1184         ch = ruleSrc->charAt(ruleIndex);
1185         type = charType(ch);
1186         if (type != tSpace) {
1187             break;
1188         }
1189         ++(ruleIndex);
1190     }
1191     if (ruleIndex >= ruleSrc->length()) {
1192         type = tEOF;
1193         return;
1194     }
1195     int32_t curIndex= ruleIndex;
1196 
1197     switch (type) {
1198       case tColon:
1199       case tSemiColon:
1200       case tComma:
1201       case tEllipsis:
1202       case tTilde:   // scanned '~'
1203       case tAt:      // scanned '@'
1204       case tEqual:   // scanned '='
1205       case tMod:     // scanned '%'
1206         // Single character tokens.
1207         ++curIndex;
1208         break;
1209 
1210       case tNotEqual:  // scanned '!'
1211         if (ruleSrc->charAt(curIndex+1) == EQUALS) {
1212             curIndex += 2;
1213         } else {
1214             type = none;
1215             curIndex += 1;
1216         }
1217         break;
1218 
1219       case tKeyword:
1220          while (type == tKeyword && ++curIndex < ruleSrc->length()) {
1221              ch = ruleSrc->charAt(curIndex);
1222              type = charType(ch);
1223          }
1224          type = tKeyword;
1225          break;
1226 
1227       case tNumber:
1228          while (type == tNumber && ++curIndex < ruleSrc->length()) {
1229              ch = ruleSrc->charAt(curIndex);
1230              type = charType(ch);
1231          }
1232          type = tNumber;
1233          break;
1234 
1235        case tDot:
1236          // We could be looking at either ".." in a range, or "..." at the end of a sample.
1237          if (curIndex+1 >= ruleSrc->length() || ruleSrc->charAt(curIndex+1) != DOT) {
1238              ++curIndex;
1239              break; // Single dot
1240          }
1241          if (curIndex+2 >= ruleSrc->length() || ruleSrc->charAt(curIndex+2) != DOT) {
1242              curIndex += 2;
1243              type = tDot2;
1244              break; // double dot
1245          }
1246          type = tEllipsis;
1247          curIndex += 3;
1248          break;     // triple dot
1249 
1250        default:
1251          status = U_UNEXPECTED_TOKEN;
1252          ++curIndex;
1253          break;
1254     }
1255 
1256     U_ASSERT(ruleIndex <= ruleSrc->length());
1257     U_ASSERT(curIndex <= ruleSrc->length());
1258     token=UnicodeString(*ruleSrc, ruleIndex, curIndex-ruleIndex);
1259     ruleIndex = curIndex;
1260 }
1261 
1262 tokenType
charType(UChar ch)1263 PluralRuleParser::charType(UChar ch) {
1264     if ((ch>=U_ZERO) && (ch<=U_NINE)) {
1265         return tNumber;
1266     }
1267     if (ch>=LOW_A && ch<=LOW_Z) {
1268         return tKeyword;
1269     }
1270     switch (ch) {
1271     case COLON:
1272         return tColon;
1273     case SPACE:
1274         return tSpace;
1275     case SEMI_COLON:
1276         return tSemiColon;
1277     case DOT:
1278         return tDot;
1279     case COMMA:
1280         return tComma;
1281     case EXCLAMATION:
1282         return tNotEqual;
1283     case EQUALS:
1284         return tEqual;
1285     case PERCENT_SIGN:
1286         return tMod;
1287     case AT:
1288         return tAt;
1289     case ELLIPSIS:
1290         return tEllipsis;
1291     case TILDE:
1292         return tTilde;
1293     default :
1294         return none;
1295     }
1296 }
1297 
1298 
1299 //  Set token type for reserved words in the Plural Rule syntax.
1300 
1301 tokenType
getKeyType(const UnicodeString & token,tokenType keyType)1302 PluralRuleParser::getKeyType(const UnicodeString &token, tokenType keyType)
1303 {
1304     if (keyType != tKeyword) {
1305         return keyType;
1306     }
1307 
1308     if (0 == token.compare(PK_VAR_N, 1)) {
1309         keyType = tVariableN;
1310     } else if (0 == token.compare(PK_VAR_I, 1)) {
1311         keyType = tVariableI;
1312     } else if (0 == token.compare(PK_VAR_F, 1)) {
1313         keyType = tVariableF;
1314     } else if (0 == token.compare(PK_VAR_T, 1)) {
1315         keyType = tVariableT;
1316     } else if (0 == token.compare(PK_VAR_V, 1)) {
1317         keyType = tVariableV;
1318     } else if (0 == token.compare(PK_IS, 2)) {
1319         keyType = tIs;
1320     } else if (0 == token.compare(PK_AND, 3)) {
1321         keyType = tAnd;
1322     } else if (0 == token.compare(PK_IN, 2)) {
1323         keyType = tIn;
1324     } else if (0 == token.compare(PK_WITHIN, 6)) {
1325         keyType = tWithin;
1326     } else if (0 == token.compare(PK_NOT, 3)) {
1327         keyType = tNot;
1328     } else if (0 == token.compare(PK_MOD, 3)) {
1329         keyType = tMod;
1330     } else if (0 == token.compare(PK_OR, 2)) {
1331         keyType = tOr;
1332     } else if (0 == token.compare(PK_DECIMAL, 7)) {
1333         keyType = tDecimal;
1334     } else if (0 == token.compare(PK_INTEGER, 7)) {
1335         keyType = tInteger;
1336     }
1337     return keyType;
1338 }
1339 
1340 
PluralKeywordEnumeration(RuleChain * header,UErrorCode & status)1341 PluralKeywordEnumeration::PluralKeywordEnumeration(RuleChain *header, UErrorCode& status)
1342         : pos(0), fKeywordNames(status) {
1343     if (U_FAILURE(status)) {
1344         return;
1345     }
1346     fKeywordNames.setDeleter(uprv_deleteUObject);
1347     UBool  addKeywordOther=TRUE;
1348     RuleChain *node=header;
1349     while(node!=NULL) {
1350         fKeywordNames.addElement(new UnicodeString(node->fKeyword), status);
1351         if (U_FAILURE(status)) {
1352             return;
1353         }
1354         if (0 == node->fKeyword.compare(PLURAL_KEYWORD_OTHER, 5)) {
1355             addKeywordOther= FALSE;
1356         }
1357         node=node->fNext;
1358     }
1359 
1360     if (addKeywordOther) {
1361         fKeywordNames.addElement(new UnicodeString(PLURAL_KEYWORD_OTHER), status);
1362     }
1363 }
1364 
1365 const UnicodeString*
snext(UErrorCode & status)1366 PluralKeywordEnumeration::snext(UErrorCode& status) {
1367     if (U_SUCCESS(status) && pos < fKeywordNames.size()) {
1368         return (const UnicodeString*)fKeywordNames.elementAt(pos++);
1369     }
1370     return NULL;
1371 }
1372 
1373 void
reset(UErrorCode &)1374 PluralKeywordEnumeration::reset(UErrorCode& /*status*/) {
1375     pos=0;
1376 }
1377 
1378 int32_t
count(UErrorCode &) const1379 PluralKeywordEnumeration::count(UErrorCode& /*status*/) const {
1380        return fKeywordNames.size();
1381 }
1382 
~PluralKeywordEnumeration()1383 PluralKeywordEnumeration::~PluralKeywordEnumeration() {
1384 }
1385 
FixedDecimal(const VisibleDigits & digits)1386 FixedDecimal::FixedDecimal(const VisibleDigits &digits) {
1387     digits.getFixedDecimal(
1388             source, intValue, decimalDigits,
1389             decimalDigitsWithoutTrailingZeros,
1390             visibleDecimalDigitCount, hasIntegerValue);
1391     isNegative = digits.isNegative();
1392     isNanOrInfinity = digits.isNaNOrInfinity();
1393 }
1394 
FixedDecimal(double n,int32_t v,int64_t f)1395 FixedDecimal::FixedDecimal(double n, int32_t v, int64_t f) {
1396     init(n, v, f);
1397     // check values. TODO make into unit test.
1398     //
1399     //            long visiblePower = (int) Math.pow(10, v);
1400     //            if (decimalDigits > visiblePower) {
1401     //                throw new IllegalArgumentException();
1402     //            }
1403     //            double fraction = intValue + (decimalDigits / (double) visiblePower);
1404     //            if (fraction != source) {
1405     //                double diff = Math.abs(fraction - source)/(Math.abs(fraction) + Math.abs(source));
1406     //                if (diff > 0.00000001d) {
1407     //                    throw new IllegalArgumentException();
1408     //                }
1409     //            }
1410 }
1411 
FixedDecimal(double n,int32_t v)1412 FixedDecimal::FixedDecimal(double n, int32_t v) {
1413     // Ugly, but for samples we don't care.
1414     init(n, v, getFractionalDigits(n, v));
1415 }
1416 
FixedDecimal(double n)1417 FixedDecimal::FixedDecimal(double n) {
1418     init(n);
1419 }
1420 
FixedDecimal()1421 FixedDecimal::FixedDecimal() {
1422     init(0, 0, 0);
1423 }
1424 
1425 
1426 // Create a FixedDecimal from a UnicodeString containing a number.
1427 //    Inefficient, but only used for samples, so simplicity trumps efficiency.
1428 
FixedDecimal(const UnicodeString & num,UErrorCode & status)1429 FixedDecimal::FixedDecimal(const UnicodeString &num, UErrorCode &status) {
1430     CharString cs;
1431     cs.appendInvariantChars(num, status);
1432     DigitList dl;
1433     dl.set(cs.toStringPiece(), status);
1434     if (U_FAILURE(status)) {
1435         init(0, 0, 0);
1436         return;
1437     }
1438     int32_t decimalPoint = num.indexOf(DOT);
1439     double n = dl.getDouble();
1440     if (decimalPoint == -1) {
1441         init(n, 0, 0);
1442     } else {
1443         int32_t v = num.length() - decimalPoint - 1;
1444         init(n, v, getFractionalDigits(n, v));
1445     }
1446 }
1447 
1448 
FixedDecimal(const FixedDecimal & other)1449 FixedDecimal::FixedDecimal(const FixedDecimal &other) {
1450     source = other.source;
1451     visibleDecimalDigitCount = other.visibleDecimalDigitCount;
1452     decimalDigits = other.decimalDigits;
1453     decimalDigitsWithoutTrailingZeros = other.decimalDigitsWithoutTrailingZeros;
1454     intValue = other.intValue;
1455     hasIntegerValue = other.hasIntegerValue;
1456     isNegative = other.isNegative;
1457     isNanOrInfinity = other.isNanOrInfinity;
1458 }
1459 
1460 
init(double n)1461 void FixedDecimal::init(double n) {
1462     int32_t numFractionDigits = decimals(n);
1463     init(n, numFractionDigits, getFractionalDigits(n, numFractionDigits));
1464 }
1465 
1466 
init(double n,int32_t v,int64_t f)1467 void FixedDecimal::init(double n, int32_t v, int64_t f) {
1468     isNegative = n < 0.0;
1469     source = fabs(n);
1470     isNanOrInfinity = uprv_isNaN(source) || uprv_isPositiveInfinity(source);
1471     if (isNanOrInfinity) {
1472         v = 0;
1473         f = 0;
1474         intValue = 0;
1475         hasIntegerValue = FALSE;
1476     } else {
1477         intValue = (int64_t)source;
1478         hasIntegerValue = (source == intValue);
1479     }
1480 
1481     visibleDecimalDigitCount = v;
1482     decimalDigits = f;
1483     if (f == 0) {
1484          decimalDigitsWithoutTrailingZeros = 0;
1485     } else {
1486         int64_t fdwtz = f;
1487         while ((fdwtz%10) == 0) {
1488             fdwtz /= 10;
1489         }
1490         decimalDigitsWithoutTrailingZeros = fdwtz;
1491     }
1492 }
1493 
1494 
1495 //  Fast path only exact initialization. Return true if successful.
1496 //     Note: Do not multiply by 10 each time through loop, rounding cruft can build
1497 //           up that makes the check for an integer result fail.
1498 //           A single multiply of the original number works more reliably.
1499 static int32_t p10[] = {1, 10, 100, 1000, 10000};
quickInit(double n)1500 UBool FixedDecimal::quickInit(double n) {
1501     UBool success = FALSE;
1502     n = fabs(n);
1503     int32_t numFractionDigits;
1504     for (numFractionDigits = 0; numFractionDigits <= 3; numFractionDigits++) {
1505         double scaledN = n * p10[numFractionDigits];
1506         if (scaledN == floor(scaledN)) {
1507             success = TRUE;
1508             break;
1509         }
1510     }
1511     if (success) {
1512         init(n, numFractionDigits, getFractionalDigits(n, numFractionDigits));
1513     }
1514     return success;
1515 }
1516 
1517 
1518 
decimals(double n)1519 int32_t FixedDecimal::decimals(double n) {
1520     // Count the number of decimal digits in the fraction part of the number, excluding trailing zeros.
1521     // fastpath the common cases, integers or fractions with 3 or fewer digits
1522     n = fabs(n);
1523     for (int ndigits=0; ndigits<=3; ndigits++) {
1524         double scaledN = n * p10[ndigits];
1525         if (scaledN == floor(scaledN)) {
1526             return ndigits;
1527         }
1528     }
1529 
1530     // Slow path, convert with sprintf, parse converted output.
1531     char  buf[30] = {0};
1532     sprintf(buf, "%1.15e", n);
1533     // formatted number looks like this: 1.234567890123457e-01
1534     int exponent = atoi(buf+18);
1535     int numFractionDigits = 15;
1536     for (int i=16; ; --i) {
1537         if (buf[i] != '0') {
1538             break;
1539         }
1540         --numFractionDigits;
1541     }
1542     numFractionDigits -= exponent;   // Fraction part of fixed point representation.
1543     return numFractionDigits;
1544 }
1545 
1546 
1547 // Get the fraction digits of a double, represented as an integer.
1548 //    v is the number of visible fraction digits in the displayed form of the number.
1549 //       Example: n = 1001.234, v = 6, result = 234000
1550 //    TODO: need to think through how this is used in the plural rule context.
1551 //          This function can easily encounter integer overflow,
1552 //          and can easily return noise digits when the precision of a double is exceeded.
1553 
getFractionalDigits(double n,int32_t v)1554 int64_t FixedDecimal::getFractionalDigits(double n, int32_t v) {
1555     if (v == 0 || n == floor(n) || uprv_isNaN(n) || uprv_isPositiveInfinity(n)) {
1556         return 0;
1557     }
1558     n = fabs(n);
1559     double fract = n - floor(n);
1560     switch (v) {
1561       case 1: return (int64_t)(fract*10.0 + 0.5);
1562       case 2: return (int64_t)(fract*100.0 + 0.5);
1563       case 3: return (int64_t)(fract*1000.0 + 0.5);
1564       default:
1565           double scaled = floor(fract * pow(10.0, (double)v) + 0.5);
1566           if (scaled > U_INT64_MAX) {
1567               return U_INT64_MAX;
1568           } else {
1569               return (int64_t)scaled;
1570           }
1571       }
1572 }
1573 
1574 
adjustForMinFractionDigits(int32_t minFractionDigits)1575 void FixedDecimal::adjustForMinFractionDigits(int32_t minFractionDigits) {
1576     int32_t numTrailingFractionZeros = minFractionDigits - visibleDecimalDigitCount;
1577     if (numTrailingFractionZeros > 0) {
1578         for (int32_t i=0; i<numTrailingFractionZeros; i++) {
1579             // Do not let the decimalDigits value overflow if there are many trailing zeros.
1580             // Limit the value to 18 digits, the most that a 64 bit int can fully represent.
1581             if (decimalDigits >= 100000000000000000LL) {
1582                 break;
1583             }
1584             decimalDigits *= 10;
1585         }
1586         visibleDecimalDigitCount += numTrailingFractionZeros;
1587     }
1588 }
1589 
1590 
get(tokenType operand) const1591 double FixedDecimal::get(tokenType operand) const {
1592     switch(operand) {
1593         case tVariableN: return source;
1594         case tVariableI: return (double)intValue;
1595         case tVariableF: return (double)decimalDigits;
1596         case tVariableT: return (double)decimalDigitsWithoutTrailingZeros;
1597         case tVariableV: return visibleDecimalDigitCount;
1598         default:
1599              U_ASSERT(FALSE);  // unexpected.
1600              return source;
1601     }
1602 }
1603 
getVisibleFractionDigitCount() const1604 int32_t FixedDecimal::getVisibleFractionDigitCount() const {
1605     return visibleDecimalDigitCount;
1606 }
1607 
1608 
1609 
PluralAvailableLocalesEnumeration(UErrorCode & status)1610 PluralAvailableLocalesEnumeration::PluralAvailableLocalesEnumeration(UErrorCode &status) {
1611     fLocales = NULL;
1612     fRes = NULL;
1613     fOpenStatus = status;
1614     if (U_FAILURE(status)) {
1615         return;
1616     }
1617     fOpenStatus = U_ZERO_ERROR;
1618     LocalUResourceBundlePointer rb(ures_openDirect(NULL, "plurals", &fOpenStatus));
1619     fLocales = ures_getByKey(rb.getAlias(), "locales", NULL, &fOpenStatus);
1620 }
1621 
~PluralAvailableLocalesEnumeration()1622 PluralAvailableLocalesEnumeration::~PluralAvailableLocalesEnumeration() {
1623     ures_close(fLocales);
1624     ures_close(fRes);
1625     fLocales = NULL;
1626     fRes = NULL;
1627 }
1628 
next(int32_t * resultLength,UErrorCode & status)1629 const char *PluralAvailableLocalesEnumeration::next(int32_t *resultLength, UErrorCode &status) {
1630     if (U_FAILURE(status)) {
1631         return NULL;
1632     }
1633     if (U_FAILURE(fOpenStatus)) {
1634         status = fOpenStatus;
1635         return NULL;
1636     }
1637     fRes = ures_getNextResource(fLocales, fRes, &status);
1638     if (fRes == NULL || U_FAILURE(status)) {
1639         if (status == U_INDEX_OUTOFBOUNDS_ERROR) {
1640             status = U_ZERO_ERROR;
1641         }
1642         return NULL;
1643     }
1644     const char *result = ures_getKey(fRes);
1645     if (resultLength != NULL) {
1646         *resultLength = uprv_strlen(result);
1647     }
1648     return result;
1649 }
1650 
1651 
reset(UErrorCode & status)1652 void PluralAvailableLocalesEnumeration::reset(UErrorCode &status) {
1653     if (U_FAILURE(status)) {
1654        return;
1655     }
1656     if (U_FAILURE(fOpenStatus)) {
1657         status = fOpenStatus;
1658         return;
1659     }
1660     ures_resetIterator(fLocales);
1661 }
1662 
count(UErrorCode & status) const1663 int32_t PluralAvailableLocalesEnumeration::count(UErrorCode &status) const {
1664     if (U_FAILURE(status)) {
1665         return 0;
1666     }
1667     if (U_FAILURE(fOpenStatus)) {
1668         status = fOpenStatus;
1669         return 0;
1670     }
1671     return ures_getSize(fLocales);
1672 }
1673 
1674 U_NAMESPACE_END
1675 
1676 
1677 #endif /* #if !UCONFIG_NO_FORMATTING */
1678 
1679 //eof
1680