Home | History | Annotate | Download | only in common
      1 /*
      2 ******************************************************************************
      3 *
      4 *   Copyright (C) 1999-2012, International Business Machines
      5 *   Corporation and others.  All Rights Reserved.
      6 *
      7 ******************************************************************************
      8 *   file name:  ubidi.c
      9 *   encoding:   US-ASCII
     10 *   tab size:   8 (not used)
     11 *   indentation:4
     12 *
     13 *   created on: 1999jul27
     14 *   created by: Markus W. Scherer, updated by Matitiahu Allouche
     15 */
     16 
     17 #include "cmemory.h"
     18 #include "unicode/utypes.h"
     19 #include "unicode/ustring.h"
     20 #include "unicode/uchar.h"
     21 #include "unicode/ubidi.h"
     22 #include "unicode/utf16.h"
     23 #include "ubidi_props.h"
     24 #include "ubidiimp.h"
     25 #include "uassert.h"
     26 
     27 /*
     28  * General implementation notes:
     29  *
     30  * Throughout the implementation, there are comments like (W2) that refer to
     31  * rules of the BiDi algorithm in its version 5, in this example to the second
     32  * rule of the resolution of weak types.
     33  *
     34  * For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
     35  * character according to UTF-16, the second UChar gets the directional property of
     36  * the entire character assigned, while the first one gets a BN, a boundary
     37  * neutral, type, which is ignored by most of the algorithm according to
     38  * rule (X9) and the implementation suggestions of the BiDi algorithm.
     39  *
     40  * Later, adjustWSLevels() will set the level for each BN to that of the
     41  * following character (UChar), which results in surrogate pairs getting the
     42  * same level on each of their surrogates.
     43  *
     44  * In a UTF-8 implementation, the same thing could be done: the last byte of
     45  * a multi-byte sequence would get the "real" property, while all previous
     46  * bytes of that sequence would get BN.
     47  *
     48  * It is not possible to assign all those parts of a character the same real
     49  * property because this would fail in the resolution of weak types with rules
     50  * that look at immediately surrounding types.
     51  *
     52  * As a related topic, this implementation does not remove Boundary Neutral
     53  * types from the input, but ignores them wherever this is relevant.
     54  * For example, the loop for the resolution of the weak types reads
     55  * types until it finds a non-BN.
     56  * Also, explicit embedding codes are neither changed into BN nor removed.
     57  * They are only treated the same way real BNs are.
     58  * As stated before, adjustWSLevels() takes care of them at the end.
     59  * For the purpose of conformance, the levels of all these codes
     60  * do not matter.
     61  *
     62  * Note that this implementation never modifies the dirProps
     63  * after the initial setup.
     64  *
     65  *
     66  * In this implementation, the resolution of weak types (Wn),
     67  * neutrals (Nn), and the assignment of the resolved level (In)
     68  * are all done in one single loop, in resolveImplicitLevels().
     69  * Changes of dirProp values are done on the fly, without writing
     70  * them back to the dirProps array.
     71  *
     72  *
     73  * This implementation contains code that allows to bypass steps of the
     74  * algorithm that are not needed on the specific paragraph
     75  * in order to speed up the most common cases considerably,
     76  * like text that is entirely LTR, or RTL text without numbers.
     77  *
     78  * Most of this is done by setting a bit for each directional property
     79  * in a flags variable and later checking for whether there are
     80  * any LTR characters or any RTL characters, or both, whether
     81  * there are any explicit embedding codes, etc.
     82  *
     83  * If the (Xn) steps are performed, then the flags are re-evaluated,
     84  * because they will then not contain the embedding codes any more
     85  * and will be adjusted for override codes, so that subsequently
     86  * more bypassing may be possible than what the initial flags suggested.
     87  *
     88  * If the text is not mixed-directional, then the
     89  * algorithm steps for the weak type resolution are not performed,
     90  * and all levels are set to the paragraph level.
     91  *
     92  * If there are no explicit embedding codes, then the (Xn) steps
     93  * are not performed.
     94  *
     95  * If embedding levels are supplied as a parameter, then all
     96  * explicit embedding codes are ignored, and the (Xn) steps
     97  * are not performed.
     98  *
     99  * White Space types could get the level of the run they belong to,
    100  * and are checked with a test of (flags&MASK_EMBEDDING) to
    101  * consider if the paragraph direction should be considered in
    102  * the flags variable.
    103  *
    104  * If there are no White Space types in the paragraph, then
    105  * (L1) is not necessary in adjustWSLevels().
    106  */
    107 
    108 /* to avoid some conditional statements, use tiny constant arrays */
    109 static const Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
    110 static const Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
    111 static const Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
    112 
    113 #define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
    114 #define DIRPROP_FLAG_E(level) flagE[(level)&1]
    115 #define DIRPROP_FLAG_O(level) flagO[(level)&1]
    116 
    117 /* UBiDi object management -------------------------------------------------- */
    118 
    119 U_CAPI UBiDi * U_EXPORT2
    120 ubidi_open(void)
    121 {
    122     UErrorCode errorCode=U_ZERO_ERROR;
    123     return ubidi_openSized(0, 0, &errorCode);
    124 }
    125 
    126 U_CAPI UBiDi * U_EXPORT2
    127 ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode) {
    128     UBiDi *pBiDi;
    129 
    130     /* check the argument values */
    131     if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
    132         return NULL;
    133     } else if(maxLength<0 || maxRunCount<0) {
    134         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
    135         return NULL;    /* invalid arguments */
    136     }
    137 
    138     /* allocate memory for the object */
    139     pBiDi=(UBiDi *)uprv_malloc(sizeof(UBiDi));
    140     if(pBiDi==NULL) {
    141         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
    142         return NULL;
    143     }
    144 
    145     /* reset the object, all pointers NULL, all flags FALSE, all sizes 0 */
    146     uprv_memset(pBiDi, 0, sizeof(UBiDi));
    147 
    148     /* get BiDi properties */
    149     pBiDi->bdp=ubidi_getSingleton();
    150 
    151     /* allocate memory for arrays as requested */
    152     if(maxLength>0) {
    153         if( !getInitialDirPropsMemory(pBiDi, maxLength) ||
    154             !getInitialLevelsMemory(pBiDi, maxLength)
    155         ) {
    156             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
    157         }
    158     } else {
    159         pBiDi->mayAllocateText=TRUE;
    160     }
    161 
    162     if(maxRunCount>0) {
    163         if(maxRunCount==1) {
    164             /* use simpleRuns[] */
    165             pBiDi->runsSize=sizeof(Run);
    166         } else if(!getInitialRunsMemory(pBiDi, maxRunCount)) {
    167             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
    168         }
    169     } else {
    170         pBiDi->mayAllocateRuns=TRUE;
    171     }
    172 
    173     if(U_SUCCESS(*pErrorCode)) {
    174         return pBiDi;
    175     } else {
    176         ubidi_close(pBiDi);
    177         return NULL;
    178     }
    179 }
    180 
    181 /*
    182  * We are allowed to allocate memory if memory==NULL or
    183  * mayAllocate==TRUE for each array that we need.
    184  * We also try to grow memory as needed if we
    185  * allocate it.
    186  *
    187  * Assume sizeNeeded>0.
    188  * If *pMemory!=NULL, then assume *pSize>0.
    189  *
    190  * ### this realloc() may unnecessarily copy the old data,
    191  * which we know we don't need any more;
    192  * is this the best way to do this??
    193  */
    194 U_CFUNC UBool
    195 ubidi_getMemory(BidiMemoryForAllocation *bidiMem, int32_t *pSize, UBool mayAllocate, int32_t sizeNeeded) {
    196     void **pMemory = (void **)bidiMem;
    197     /* check for existing memory */
    198     if(*pMemory==NULL) {
    199         /* we need to allocate memory */
    200         if(mayAllocate && (*pMemory=uprv_malloc(sizeNeeded))!=NULL) {
    201             *pSize=sizeNeeded;
    202             return TRUE;
    203         } else {
    204             return FALSE;
    205         }
    206     } else {
    207         if(sizeNeeded<=*pSize) {
    208             /* there is already enough memory */
    209             return TRUE;
    210         }
    211         else if(!mayAllocate) {
    212             /* not enough memory, and we must not allocate */
    213             return FALSE;
    214         } else {
    215             /* we try to grow */
    216             void *memory;
    217             /* in most cases, we do not need the copy-old-data part of
    218              * realloc, but it is needed when adding runs using getRunsMemory()
    219              * in setParaRunsOnly()
    220              */
    221             if((memory=uprv_realloc(*pMemory, sizeNeeded))!=NULL) {
    222                 *pMemory=memory;
    223                 *pSize=sizeNeeded;
    224                 return TRUE;
    225             } else {
    226                 /* we failed to grow */
    227                 return FALSE;
    228             }
    229         }
    230     }
    231 }
    232 
    233 U_CAPI void U_EXPORT2
    234 ubidi_close(UBiDi *pBiDi) {
    235     if(pBiDi!=NULL) {
    236         pBiDi->pParaBiDi=NULL;          /* in case one tries to reuse this block */
    237         if(pBiDi->dirPropsMemory!=NULL) {
    238             uprv_free(pBiDi->dirPropsMemory);
    239         }
    240         if(pBiDi->levelsMemory!=NULL) {
    241             uprv_free(pBiDi->levelsMemory);
    242         }
    243         if(pBiDi->runsMemory!=NULL) {
    244             uprv_free(pBiDi->runsMemory);
    245         }
    246         if(pBiDi->parasMemory!=NULL) {
    247             uprv_free(pBiDi->parasMemory);
    248         }
    249         if(pBiDi->insertPoints.points!=NULL) {
    250             uprv_free(pBiDi->insertPoints.points);
    251         }
    252 
    253         uprv_free(pBiDi);
    254     }
    255 }
    256 
    257 /* set to approximate "inverse BiDi" ---------------------------------------- */
    258 
    259 U_CAPI void U_EXPORT2
    260 ubidi_setInverse(UBiDi *pBiDi, UBool isInverse) {
    261     if(pBiDi!=NULL) {
    262         pBiDi->isInverse=isInverse;
    263         pBiDi->reorderingMode = isInverse ? UBIDI_REORDER_INVERSE_NUMBERS_AS_L
    264                                           : UBIDI_REORDER_DEFAULT;
    265     }
    266 }
    267 
    268 U_CAPI UBool U_EXPORT2
    269 ubidi_isInverse(UBiDi *pBiDi) {
    270     if(pBiDi!=NULL) {
    271         return pBiDi->isInverse;
    272     } else {
    273         return FALSE;
    274     }
    275 }
    276 
    277 /* FOOD FOR THOUGHT: currently the reordering modes are a mixture of
    278  * algorithm for direct BiDi, algorithm for inverse BiDi and the bizarre
    279  * concept of RUNS_ONLY which is a double operation.
    280  * It could be advantageous to divide this into 3 concepts:
    281  * a) Operation: direct / inverse / RUNS_ONLY
    282  * b) Direct algorithm: default / NUMBERS_SPECIAL / GROUP_NUMBERS_WITH_R
    283  * c) Inverse algorithm: default / INVERSE_LIKE_DIRECT / NUMBERS_SPECIAL
    284  * This would allow combinations not possible today like RUNS_ONLY with
    285  * NUMBERS_SPECIAL.
    286  * Also allow to set INSERT_MARKS for the direct step of RUNS_ONLY and
    287  * REMOVE_CONTROLS for the inverse step.
    288  * Not all combinations would be supported, and probably not all do make sense.
    289  * This would need to document which ones are supported and what are the
    290  * fallbacks for unsupported combinations.
    291  */
    292 U_CAPI void U_EXPORT2
    293 ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode) {
    294     if ((pBiDi!=NULL) && (reorderingMode >= UBIDI_REORDER_DEFAULT)
    295                         && (reorderingMode < UBIDI_REORDER_COUNT)) {
    296         pBiDi->reorderingMode = reorderingMode;
    297         pBiDi->isInverse = (UBool)(reorderingMode == UBIDI_REORDER_INVERSE_NUMBERS_AS_L);
    298     }
    299 }
    300 
    301 U_CAPI UBiDiReorderingMode U_EXPORT2
    302 ubidi_getReorderingMode(UBiDi *pBiDi) {
    303     if (pBiDi!=NULL) {
    304         return pBiDi->reorderingMode;
    305     } else {
    306         return UBIDI_REORDER_DEFAULT;
    307     }
    308 }
    309 
    310 U_CAPI void U_EXPORT2
    311 ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions) {
    312     if (reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
    313         reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
    314     }
    315     if (pBiDi!=NULL) {
    316         pBiDi->reorderingOptions=reorderingOptions;
    317     }
    318 }
    319 
    320 U_CAPI uint32_t U_EXPORT2
    321 ubidi_getReorderingOptions(UBiDi *pBiDi) {
    322     if (pBiDi!=NULL) {
    323         return pBiDi->reorderingOptions;
    324     } else {
    325         return 0;
    326     }
    327 }
    328 
    329 U_CAPI UBiDiDirection U_EXPORT2
    330 ubidi_getBaseDirection(const UChar *text,
    331 int32_t length){
    332 
    333     int32_t i;
    334     UChar32 uchar;
    335     UCharDirection dir;
    336 
    337     if( text==NULL || length<-1 ){
    338         return UBIDI_NEUTRAL;
    339     }
    340 
    341     if(length==-1) {
    342         length=u_strlen(text);
    343     }
    344 
    345     for( i = 0 ; i < length; ) {
    346         /* i is incremented by U16_NEXT */
    347         U16_NEXT(text, i, length, uchar);
    348         dir = u_charDirection(uchar);
    349         if( dir == U_LEFT_TO_RIGHT )
    350                 return UBIDI_LTR;
    351         if( dir == U_RIGHT_TO_LEFT || dir ==U_RIGHT_TO_LEFT_ARABIC )
    352                 return UBIDI_RTL;
    353     }
    354     return UBIDI_NEUTRAL;
    355 }
    356 
    357 /* perform (P2)..(P3) ------------------------------------------------------- */
    358 
    359 static DirProp
    360 firstL_R_AL(UBiDi *pBiDi) {
    361     /* return first strong char after the last B in prologue if any */
    362     const UChar *text=pBiDi->prologue;
    363     int32_t length=pBiDi->proLength;
    364     int32_t i;
    365     UChar32 uchar;
    366     DirProp dirProp, result=ON;
    367     for(i=0; i<length; ) {
    368         /* i is incremented by U16_NEXT */
    369         U16_NEXT(text, i, length, uchar);
    370         dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
    371         if(result==ON) {
    372             if(dirProp==L || dirProp==R || dirProp==AL) {
    373                 result=dirProp;
    374             }
    375         } else {
    376             if(dirProp==B) {
    377                 result=ON;
    378             }
    379         }
    380     }
    381     return result;
    382 }
    383 
    384 /*
    385  * Get the directional properties for the text,
    386  * calculate the flags bit-set, and
    387  * determine the paragraph level if necessary.
    388  */
    389 static void
    390 getDirProps(UBiDi *pBiDi) {
    391     const UChar *text=pBiDi->text;
    392     DirProp *dirProps=pBiDi->dirPropsMemory;    /* pBiDi->dirProps is const */
    393 
    394     int32_t i=0, i1, length=pBiDi->originalLength;
    395     Flags flags=0;      /* collect all directionalities in the text */
    396     UChar32 uchar;
    397     DirProp dirProp=0, paraDirDefault=0;/* initialize to avoid compiler warnings */
    398     UBool isDefaultLevel=IS_DEFAULT_LEVEL(pBiDi->paraLevel);
    399     /* for inverse BiDi, the default para level is set to RTL if there is a
    400        strong R or AL character at either end of the text                           */
    401     UBool isDefaultLevelInverse=isDefaultLevel && (UBool)
    402             (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT ||
    403              pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL);
    404     int32_t lastArabicPos=-1;
    405     int32_t controlCount=0;
    406     UBool removeBiDiControls = (UBool)(pBiDi->reorderingOptions &
    407                                        UBIDI_OPTION_REMOVE_CONTROLS);
    408 
    409     typedef enum {
    410          NOT_CONTEXTUAL,                /* 0: not contextual paraLevel */
    411          LOOKING_FOR_STRONG,            /* 1: looking for first strong char */
    412          FOUND_STRONG_CHAR              /* 2: found first strong char       */
    413     } State;
    414     State state;
    415     int32_t paraStart=0;                /* index of first char in paragraph */
    416     DirProp paraDir;                    /* == CONTEXT_RTL within paragraphs
    417                                            starting with strong R char      */
    418     DirProp lastStrongDir=0;            /* for default level & inverse BiDi */
    419     int32_t lastStrongLTR=0;            /* for STREAMING option             */
    420 
    421     if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
    422         pBiDi->length=0;
    423         lastStrongLTR=0;
    424     }
    425     if(isDefaultLevel) {
    426         DirProp lastStrong;
    427         paraDirDefault=pBiDi->paraLevel&1 ? CONTEXT_RTL : 0;
    428         if(pBiDi->proLength>0 &&
    429            (lastStrong=firstL_R_AL(pBiDi))!=ON) {
    430             paraDir=(lastStrong==L) ? 0 : CONTEXT_RTL;
    431             state=FOUND_STRONG_CHAR;
    432         } else {
    433             paraDir=paraDirDefault;
    434             state=LOOKING_FOR_STRONG;
    435         }
    436         lastStrongDir=paraDir;
    437     } else {
    438         state=NOT_CONTEXTUAL;
    439         paraDir=0;
    440     }
    441     /* count paragraphs and determine the paragraph level (P2..P3) */
    442     /*
    443      * see comment in ubidi.h:
    444      * the DEFAULT_XXX values are designed so that
    445      * their bit 0 alone yields the intended default
    446      */
    447     for( /* i=0 above */ ; i<length; ) {
    448         /* i is incremented by U16_NEXT */
    449         U16_NEXT(text, i, length, uchar);
    450         flags|=DIRPROP_FLAG(dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar));
    451         dirProps[i-1]=dirProp|paraDir;
    452         if(uchar>0xffff) {  /* set the lead surrogate's property to BN */
    453             flags|=DIRPROP_FLAG(BN);
    454             dirProps[i-2]=(DirProp)(BN|paraDir);
    455         }
    456         if(state==LOOKING_FOR_STRONG) {
    457             if(dirProp==L) {
    458                 state=FOUND_STRONG_CHAR;
    459                 if(paraDir) {
    460                     paraDir=0;
    461                     for(i1=paraStart; i1<i; i1++) {
    462                         dirProps[i1]&=~CONTEXT_RTL;
    463                     }
    464                 }
    465                 continue;
    466             }
    467             if(dirProp==R || dirProp==AL) {
    468                 state=FOUND_STRONG_CHAR;
    469                 if(paraDir==0) {
    470                     paraDir=CONTEXT_RTL;
    471                     for(i1=paraStart; i1<i; i1++) {
    472                         dirProps[i1]|=CONTEXT_RTL;
    473                     }
    474                 }
    475                 continue;
    476             }
    477         }
    478         if(dirProp==L) {
    479             lastStrongDir=0;
    480             lastStrongLTR=i;            /* i is index to next character */
    481         }
    482         else if(dirProp==R) {
    483             lastStrongDir=CONTEXT_RTL;
    484         }
    485         else if(dirProp==AL) {
    486             lastStrongDir=CONTEXT_RTL;
    487             lastArabicPos=i-1;
    488         }
    489         else if(dirProp==B) {
    490             if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
    491                 pBiDi->length=i;        /* i is index to next character */
    492             }
    493             if(isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {
    494                 for( ; paraStart<i; paraStart++) {
    495                     dirProps[paraStart]|=CONTEXT_RTL;
    496                 }
    497             }
    498             if(i<length) {              /* B not last char in text */
    499                 if(!((uchar==CR) && (text[i]==LF))) {
    500                     pBiDi->paraCount++;
    501                 }
    502                 if(isDefaultLevel) {
    503                     state=LOOKING_FOR_STRONG;
    504                     paraStart=i;        /* i is index to next character */
    505                     paraDir=paraDirDefault;
    506                     lastStrongDir=paraDirDefault;
    507                 }
    508             }
    509         }
    510         if(removeBiDiControls && IS_BIDI_CONTROL_CHAR(uchar)) {
    511             controlCount++;
    512         }
    513     }
    514     if(isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {
    515         for(i1=paraStart; i1<length; i1++) {
    516             dirProps[i1]|=CONTEXT_RTL;
    517         }
    518     }
    519     if(isDefaultLevel) {
    520         pBiDi->paraLevel=GET_PARALEVEL(pBiDi, 0);
    521     }
    522     if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
    523         if((lastStrongLTR>pBiDi->length) &&
    524            (GET_PARALEVEL(pBiDi, lastStrongLTR)==0)) {
    525             pBiDi->length = lastStrongLTR;
    526         }
    527         if(pBiDi->length<pBiDi->originalLength) {
    528             pBiDi->paraCount--;
    529         }
    530     }
    531     /* The following line does nothing new for contextual paraLevel, but is
    532        needed for absolute paraLevel.                               */
    533     flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
    534 
    535     if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
    536         flags|=DIRPROP_FLAG(L);
    537     }
    538 
    539     pBiDi->controlCount = controlCount;
    540     pBiDi->flags=flags;
    541     pBiDi->lastArabicPos=lastArabicPos;
    542 }
    543 
    544 /* perform (X1)..(X9) ------------------------------------------------------- */
    545 
    546 /* determine if the text is mixed-directional or single-directional */
    547 static UBiDiDirection
    548 directionFromFlags(UBiDi *pBiDi) {
    549     Flags flags=pBiDi->flags;
    550     /* if the text contains AN and neutrals, then some neutrals may become RTL */
    551     if(!(flags&MASK_RTL || ((flags&DIRPROP_FLAG(AN)) && (flags&MASK_POSSIBLE_N)))) {
    552         return UBIDI_LTR;
    553     } else if(!(flags&MASK_LTR)) {
    554         return UBIDI_RTL;
    555     } else {
    556         return UBIDI_MIXED;
    557     }
    558 }
    559 
    560 /*
    561  * Resolve the explicit levels as specified by explicit embedding codes.
    562  * Recalculate the flags to have them reflect the real properties
    563  * after taking the explicit embeddings into account.
    564  *
    565  * The BiDi algorithm is designed to result in the same behavior whether embedding
    566  * levels are externally specified (from "styled text", supposedly the preferred
    567  * method) or set by explicit embedding codes (LRx, RLx, PDF) in the plain text.
    568  * That is why (X9) instructs to remove all explicit codes (and BN).
    569  * However, in a real implementation, this removal of these codes and their index
    570  * positions in the plain text is undesirable since it would result in
    571  * reallocated, reindexed text.
    572  * Instead, this implementation leaves the codes in there and just ignores them
    573  * in the subsequent processing.
    574  * In order to get the same reordering behavior, positions with a BN or an
    575  * explicit embedding code just get the same level assigned as the last "real"
    576  * character.
    577  *
    578  * Some implementations, not this one, then overwrite some of these
    579  * directionality properties at "real" same-level-run boundaries by
    580  * L or R codes so that the resolution of weak types can be performed on the
    581  * entire paragraph at once instead of having to parse it once more and
    582  * perform that resolution on same-level-runs.
    583  * This limits the scope of the implicit rules in effectively
    584  * the same way as the run limits.
    585  *
    586  * Instead, this implementation does not modify these codes.
    587  * On one hand, the paragraph has to be scanned for same-level-runs, but
    588  * on the other hand, this saves another loop to reset these codes,
    589  * or saves making and modifying a copy of dirProps[].
    590  *
    591  *
    592  * Note that (Pn) and (Xn) changed significantly from version 4 of the BiDi algorithm.
    593  *
    594  *
    595  * Handling the stack of explicit levels (Xn):
    596  *
    597  * With the BiDi stack of explicit levels,
    598  * as pushed with each LRE, RLE, LRO, and RLO and popped with each PDF,
    599  * the explicit level must never exceed UBIDI_MAX_EXPLICIT_LEVEL==61.
    600  *
    601  * In order to have a correct push-pop semantics even in the case of overflows,
    602  * there are two overflow counters:
    603  * - countOver60 is incremented with each LRx at level 60
    604  * - from level 60, one RLx increases the level to 61
    605  * - countOver61 is incremented with each LRx and RLx at level 61
    606  *
    607  * Popping levels with PDF must work in the opposite order so that level 61
    608  * is correct at the correct point. Underflows (too many PDFs) must be checked.
    609  *
    610  * This implementation assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd.
    611  */
    612 static UBiDiDirection
    613 resolveExplicitLevels(UBiDi *pBiDi) {
    614     const DirProp *dirProps=pBiDi->dirProps;
    615     UBiDiLevel *levels=pBiDi->levels;
    616     const UChar *text=pBiDi->text;
    617 
    618     int32_t i=0, length=pBiDi->length;
    619     Flags flags=pBiDi->flags;       /* collect all directionalities in the text */
    620     DirProp dirProp;
    621     UBiDiLevel level=GET_PARALEVEL(pBiDi, 0);
    622 
    623     UBiDiDirection direction;
    624     int32_t paraIndex=0;
    625 
    626     /* determine if the text is mixed-directional or single-directional */
    627     direction=directionFromFlags(pBiDi);
    628 
    629     /* we may not need to resolve any explicit levels, but for multiple
    630        paragraphs we want to loop on all chars to set the para boundaries */
    631     if((direction!=UBIDI_MIXED) && (pBiDi->paraCount==1)) {
    632         /* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
    633     } else if((pBiDi->paraCount==1) &&
    634               (!(flags&MASK_EXPLICIT) ||
    635                (pBiDi->reorderingMode > UBIDI_REORDER_LAST_LOGICAL_TO_VISUAL))) {
    636         /* mixed, but all characters are at the same embedding level */
    637         /* or we are in "inverse BiDi" */
    638         /* and we don't have contextual multiple paragraphs with some B char */
    639         /* set all levels to the paragraph level */
    640         for(i=0; i<length; ++i) {
    641             levels[i]=level;
    642         }
    643     } else {
    644         /* continue to perform (Xn) */
    645 
    646         /* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
    647         /* both variables may carry the UBIDI_LEVEL_OVERRIDE flag to indicate the override status */
    648         UBiDiLevel embeddingLevel=level, newLevel, stackTop=0;
    649 
    650         UBiDiLevel stack[UBIDI_MAX_EXPLICIT_LEVEL];        /* we never push anything >=UBIDI_MAX_EXPLICIT_LEVEL */
    651         uint32_t countOver60=0, countOver61=0;  /* count overflows of explicit levels */
    652 
    653         /* recalculate the flags */
    654         flags=0;
    655 
    656         for(i=0; i<length; ++i) {
    657             dirProp=NO_CONTEXT_RTL(dirProps[i]);
    658             switch(dirProp) {
    659             case LRE:
    660             case LRO:
    661                 /* (X3, X5) */
    662                 newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1)); /* least greater even level */
    663                 if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL) {
    664                     stack[stackTop]=embeddingLevel;
    665                     ++stackTop;
    666                     embeddingLevel=newLevel;
    667                     if(dirProp==LRO) {
    668                         embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
    669                     }
    670                     /* we don't need to set UBIDI_LEVEL_OVERRIDE off for LRE
    671                        since this has already been done for newLevel which is
    672                        the source for embeddingLevel.
    673                      */
    674                 } else if((embeddingLevel&~UBIDI_LEVEL_OVERRIDE)==UBIDI_MAX_EXPLICIT_LEVEL) {
    675                     ++countOver61;
    676                 } else /* (embeddingLevel&~UBIDI_LEVEL_OVERRIDE)==UBIDI_MAX_EXPLICIT_LEVEL-1 */ {
    677                     ++countOver60;
    678                 }
    679                 flags|=DIRPROP_FLAG(BN);
    680                 break;
    681             case RLE:
    682             case RLO:
    683                 /* (X2, X4) */
    684                 newLevel=(UBiDiLevel)(((embeddingLevel&~UBIDI_LEVEL_OVERRIDE)+1)|1); /* least greater odd level */
    685                 if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL) {
    686                     stack[stackTop]=embeddingLevel;
    687                     ++stackTop;
    688                     embeddingLevel=newLevel;
    689                     if(dirProp==RLO) {
    690                         embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
    691                     }
    692                     /* we don't need to set UBIDI_LEVEL_OVERRIDE off for RLE
    693                        since this has already been done for newLevel which is
    694                        the source for embeddingLevel.
    695                      */
    696                 } else {
    697                     ++countOver61;
    698                 }
    699                 flags|=DIRPROP_FLAG(BN);
    700                 break;
    701             case PDF:
    702                 /* (X7) */
    703                 /* handle all the overflow cases first */
    704                 if(countOver61>0) {
    705                     --countOver61;
    706                 } else if(countOver60>0 && (embeddingLevel&~UBIDI_LEVEL_OVERRIDE)!=UBIDI_MAX_EXPLICIT_LEVEL) {
    707                     /* handle LRx overflows from level 60 */
    708                     --countOver60;
    709                 } else if(stackTop>0) {
    710                     /* this is the pop operation; it also pops level 61 while countOver60>0 */
    711                     --stackTop;
    712                     embeddingLevel=stack[stackTop];
    713                 /* } else { (underflow) */
    714                 }
    715                 flags|=DIRPROP_FLAG(BN);
    716                 break;
    717             case B:
    718                 stackTop=0;
    719                 countOver60=countOver61=0;
    720                 level=GET_PARALEVEL(pBiDi, i);
    721                 if((i+1)<length) {
    722                     embeddingLevel=GET_PARALEVEL(pBiDi, i+1);
    723                     if(!((text[i]==CR) && (text[i+1]==LF))) {
    724                         pBiDi->paras[paraIndex++]=i+1;
    725                     }
    726                 }
    727                 flags|=DIRPROP_FLAG(B);
    728                 break;
    729             case BN:
    730                 /* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
    731                 /* they will get their levels set correctly in adjustWSLevels() */
    732                 flags|=DIRPROP_FLAG(BN);
    733                 break;
    734             default:
    735                 /* all other types get the "real" level */
    736                 if(level!=embeddingLevel) {
    737                     level=embeddingLevel;
    738                     if(level&UBIDI_LEVEL_OVERRIDE) {
    739                         flags|=DIRPROP_FLAG_O(level)|DIRPROP_FLAG_MULTI_RUNS;
    740                     } else {
    741                         flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG_MULTI_RUNS;
    742                     }
    743                 }
    744                 if(!(level&UBIDI_LEVEL_OVERRIDE)) {
    745                     flags|=DIRPROP_FLAG(dirProp);
    746                 }
    747                 break;
    748             }
    749 
    750             /*
    751              * We need to set reasonable levels even on BN codes and
    752              * explicit codes because we will later look at same-level runs (X10).
    753              */
    754             levels[i]=level;
    755         }
    756         if(flags&MASK_EMBEDDING) {
    757             flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
    758         }
    759         if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
    760             flags|=DIRPROP_FLAG(L);
    761         }
    762 
    763         /* subsequently, ignore the explicit codes and BN (X9) */
    764 
    765         /* again, determine if the text is mixed-directional or single-directional */
    766         pBiDi->flags=flags;
    767         direction=directionFromFlags(pBiDi);
    768     }
    769 
    770     return direction;
    771 }
    772 
    773 /*
    774  * Use a pre-specified embedding levels array:
    775  *
    776  * Adjust the directional properties for overrides (->LEVEL_OVERRIDE),
    777  * ignore all explicit codes (X9),
    778  * and check all the preset levels.
    779  *
    780  * Recalculate the flags to have them reflect the real properties
    781  * after taking the explicit embeddings into account.
    782  */
    783 static UBiDiDirection
    784 checkExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
    785     const DirProp *dirProps=pBiDi->dirProps;
    786     DirProp dirProp;
    787     UBiDiLevel *levels=pBiDi->levels;
    788     const UChar *text=pBiDi->text;
    789 
    790     int32_t i, length=pBiDi->length;
    791     Flags flags=0;  /* collect all directionalities in the text */
    792     UBiDiLevel level;
    793     uint32_t paraIndex=0;
    794 
    795     for(i=0; i<length; ++i) {
    796         level=levels[i];
    797         dirProp=NO_CONTEXT_RTL(dirProps[i]);
    798         if(level&UBIDI_LEVEL_OVERRIDE) {
    799             /* keep the override flag in levels[i] but adjust the flags */
    800             level&=~UBIDI_LEVEL_OVERRIDE;     /* make the range check below simpler */
    801             flags|=DIRPROP_FLAG_O(level);
    802         } else {
    803             /* set the flags */
    804             flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG(dirProp);
    805         }
    806         if((level<GET_PARALEVEL(pBiDi, i) &&
    807             !((0==level)&&(dirProp==B))) ||
    808            (UBIDI_MAX_EXPLICIT_LEVEL<level)) {
    809             /* level out of bounds */
    810             *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
    811             return UBIDI_LTR;
    812         }
    813         if((dirProp==B) && ((i+1)<length)) {
    814             if(!((text[i]==CR) && (text[i+1]==LF))) {
    815                 pBiDi->paras[paraIndex++]=i+1;
    816             }
    817         }
    818     }
    819     if(flags&MASK_EMBEDDING) {
    820         flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
    821     }
    822 
    823     /* determine if the text is mixed-directional or single-directional */
    824     pBiDi->flags=flags;
    825     return directionFromFlags(pBiDi);
    826 }
    827 
    828 /******************************************************************
    829  The Properties state machine table
    830 *******************************************************************
    831 
    832  All table cells are 8 bits:
    833       bits 0..4:  next state
    834       bits 5..7:  action to perform (if > 0)
    835 
    836  Cells may be of format "n" where n represents the next state
    837  (except for the rightmost column).
    838  Cells may also be of format "s(x,y)" where x represents an action
    839  to perform and y represents the next state.
    840 
    841 *******************************************************************
    842  Definitions and type for properties state table
    843 *******************************************************************
    844 */
    845 #define IMPTABPROPS_COLUMNS 14
    846 #define IMPTABPROPS_RES (IMPTABPROPS_COLUMNS - 1)
    847 #define GET_STATEPROPS(cell) ((cell)&0x1f)
    848 #define GET_ACTIONPROPS(cell) ((cell)>>5)
    849 #define s(action, newState) ((uint8_t)(newState+(action<<5)))
    850 
    851 static const uint8_t groupProp[] =          /* dirProp regrouped */
    852 {
    853 /*  L   R   EN  ES  ET  AN  CS  B   S   WS  ON  LRE LRO AL  RLE RLO PDF NSM BN  */
    854     0,  1,  2,  7,  8,  3,  9,  6,  5,  4,  4,  10, 10, 12, 10, 10, 10, 11, 10
    855 };
    856 enum { DirProp_L=0, DirProp_R=1, DirProp_EN=2, DirProp_AN=3, DirProp_ON=4, DirProp_S=5, DirProp_B=6 }; /* reduced dirProp */
    857 
    858 /******************************************************************
    859 
    860       PROPERTIES  STATE  TABLE
    861 
    862  In table impTabProps,
    863       - the ON column regroups ON and WS
    864       - the BN column regroups BN, LRE, RLE, LRO, RLO, PDF
    865       - the Res column is the reduced property assigned to a run
    866 
    867  Action 1: process current run1, init new run1
    868         2: init new run2
    869         3: process run1, process run2, init new run1
    870         4: process run1, set run1=run2, init new run2
    871 
    872  Notes:
    873   1) This table is used in resolveImplicitLevels().
    874   2) This table triggers actions when there is a change in the Bidi
    875      property of incoming characters (action 1).
    876   3) Most such property sequences are processed immediately (in
    877      fact, passed to processPropertySeq().
    878   4) However, numbers are assembled as one sequence. This means
    879      that undefined situations (like CS following digits, until
    880      it is known if the next char will be a digit) are held until
    881      following chars define them.
    882      Example: digits followed by CS, then comes another CS or ON;
    883               the digits will be processed, then the CS assigned
    884               as the start of an ON sequence (action 3).
    885   5) There are cases where more than one sequence must be
    886      processed, for instance digits followed by CS followed by L:
    887      the digits must be processed as one sequence, and the CS
    888      must be processed as an ON sequence, all this before starting
    889      assembling chars for the opening L sequence.
    890 
    891 
    892 */
    893 static const uint8_t impTabProps[][IMPTABPROPS_COLUMNS] =
    894 {
    895 /*                        L ,     R ,    EN ,    AN ,    ON ,     S ,     B ,    ES ,    ET ,    CS ,    BN ,   NSM ,    AL ,  Res */
    896 /* 0 Init        */ {     1 ,     2 ,     4 ,     5 ,     7 ,    15 ,    17 ,     7 ,     9 ,     7 ,     0 ,     7 ,     3 ,  DirProp_ON },
    897 /* 1 L           */ {     1 , s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7),     1 ,     1 , s(1,3),   DirProp_L },
    898 /* 2 R           */ { s(1,1),     2 , s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7),     2 ,     2 , s(1,3),   DirProp_R },
    899 /* 3 AL          */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),s(1,16),s(1,17), s(1,8), s(1,8), s(1,8),     3 ,     3 ,     3 ,   DirProp_R },
    900 /* 4 EN          */ { s(1,1), s(1,2),     4 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,10),    11 ,s(2,10),     4 ,     4 , s(1,3),  DirProp_EN },
    901 /* 5 AN          */ { s(1,1), s(1,2), s(1,4),     5 , s(1,7),s(1,15),s(1,17), s(1,7), s(1,9),s(2,12),     5 ,     5 , s(1,3),  DirProp_AN },
    902 /* 6 AL:EN/AN    */ { s(1,1), s(1,2),     6 ,     6 , s(1,8),s(1,16),s(1,17), s(1,8), s(1,8),s(2,13),     6 ,     6 , s(1,3),  DirProp_AN },
    903 /* 7 ON          */ { s(1,1), s(1,2), s(1,4), s(1,5),     7 ,s(1,15),s(1,17),     7 ,s(2,14),     7 ,     7 ,     7 , s(1,3),  DirProp_ON },
    904 /* 8 AL:ON       */ { s(1,1), s(1,2), s(1,6), s(1,6),     8 ,s(1,16),s(1,17),     8 ,     8 ,     8 ,     8 ,     8 , s(1,3),  DirProp_ON },
    905 /* 9 ET          */ { s(1,1), s(1,2),     4 , s(1,5),     7 ,s(1,15),s(1,17),     7 ,     9 ,     7 ,     9 ,     9 , s(1,3),  DirProp_ON },
    906 /*10 EN+ES/CS    */ { s(3,1), s(3,2),     4 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    10 , s(4,7), s(3,3),  DirProp_EN },
    907 /*11 EN+ET       */ { s(1,1), s(1,2),     4 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7),    11 , s(1,7),    11 ,    11 , s(1,3),  DirProp_EN },
    908 /*12 AN+CS       */ { s(3,1), s(3,2), s(3,4),     5 , s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    12 , s(4,7), s(3,3),  DirProp_AN },
    909 /*13 AL:EN/AN+CS */ { s(3,1), s(3,2),     6 ,     6 , s(4,8),s(3,16),s(3,17), s(4,8), s(4,8), s(4,8),    13 , s(4,8), s(3,3),  DirProp_AN },
    910 /*14 ON+ET       */ { s(1,1), s(1,2), s(4,4), s(1,5),     7 ,s(1,15),s(1,17),     7 ,    14 ,     7 ,    14 ,    14 , s(1,3),  DirProp_ON },
    911 /*15 S           */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),    15 ,s(1,17), s(1,7), s(1,9), s(1,7),    15 , s(1,7), s(1,3),   DirProp_S },
    912 /*16 AL:S        */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),    16 ,s(1,17), s(1,8), s(1,8), s(1,8),    16 , s(1,8), s(1,3),   DirProp_S },
    913 /*17 B           */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),    17 , s(1,7), s(1,9), s(1,7),    17 , s(1,7), s(1,3),   DirProp_B }
    914 };
    915 
    916 /*  we must undef macro s because the levels table have a different
    917  *  structure (4 bits for action and 4 bits for next state.
    918  */
    919 #undef s
    920 
    921 /******************************************************************
    922  The levels state machine tables
    923 *******************************************************************
    924 
    925  All table cells are 8 bits:
    926       bits 0..3:  next state
    927       bits 4..7:  action to perform (if > 0)
    928 
    929  Cells may be of format "n" where n represents the next state
    930  (except for the rightmost column).
    931  Cells may also be of format "s(x,y)" where x represents an action
    932  to perform and y represents the next state.
    933 
    934  This format limits each table to 16 states each and to 15 actions.
    935 
    936 *******************************************************************
    937  Definitions and type for levels state tables
    938 *******************************************************************
    939 */
    940 #define IMPTABLEVELS_COLUMNS (DirProp_B + 2)
    941 #define IMPTABLEVELS_RES (IMPTABLEVELS_COLUMNS - 1)
    942 #define GET_STATE(cell) ((cell)&0x0f)
    943 #define GET_ACTION(cell) ((cell)>>4)
    944 #define s(action, newState) ((uint8_t)(newState+(action<<4)))
    945 
    946 typedef uint8_t ImpTab[][IMPTABLEVELS_COLUMNS];
    947 typedef uint8_t ImpAct[];
    948 
    949 /* FOOD FOR THOUGHT: each ImpTab should have its associated ImpAct,
    950  * instead of having a pair of ImpTab and a pair of ImpAct.
    951  */
    952 typedef struct ImpTabPair {
    953     const void * pImpTab[2];
    954     const void * pImpAct[2];
    955 } ImpTabPair;
    956 
    957 /******************************************************************
    958 
    959       LEVELS  STATE  TABLES
    960 
    961  In all levels state tables,
    962       - state 0 is the initial state
    963       - the Res column is the increment to add to the text level
    964         for this property sequence.
    965 
    966  The impAct arrays for each table of a pair map the local action
    967  numbers of the table to the total list of actions. For instance,
    968  action 2 in a given table corresponds to the action number which
    969  appears in entry [2] of the impAct array for that table.
    970  The first entry of all impAct arrays must be 0.
    971 
    972  Action 1: init conditional sequence
    973         2: prepend conditional sequence to current sequence
    974         3: set ON sequence to new level - 1
    975         4: init EN/AN/ON sequence
    976         5: fix EN/AN/ON sequence followed by R
    977         6: set previous level sequence to level 2
    978 
    979  Notes:
    980   1) These tables are used in processPropertySeq(). The input
    981      is property sequences as determined by resolveImplicitLevels.
    982   2) Most such property sequences are processed immediately
    983      (levels are assigned).
    984   3) However, some sequences cannot be assigned a final level till
    985      one or more following sequences are received. For instance,
    986      ON following an R sequence within an even-level paragraph.
    987      If the following sequence is R, the ON sequence will be
    988      assigned basic run level+1, and so will the R sequence.
    989   4) S is generally handled like ON, since its level will be fixed
    990      to paragraph level in adjustWSLevels().
    991 
    992 */
    993 
    994 static const ImpTab impTabL_DEFAULT =   /* Even paragraph level */
    995 /*  In this table, conditional sequences receive the higher possible level
    996     until proven otherwise.
    997 */
    998 {
    999 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1000 /* 0 : init       */ {     0 ,     1 ,     0 ,     2 ,     0 ,     0 ,     0 ,  0 },
   1001 /* 1 : R          */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  1 },
   1002 /* 2 : AN         */ {     0 ,     1 ,     0 ,     2 , s(1,5), s(1,5),     0 ,  2 },
   1003 /* 3 : R+EN/AN    */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  2 },
   1004 /* 4 : R+ON       */ { s(2,0),     1 ,     3 ,     3 ,     4 ,     4 , s(2,0),  1 },
   1005 /* 5 : AN+ON      */ { s(2,0),     1 , s(2,0),     2 ,     5 ,     5 , s(2,0),  1 }
   1006 };
   1007 static const ImpTab impTabR_DEFAULT =   /* Odd  paragraph level */
   1008 /*  In this table, conditional sequences receive the lower possible level
   1009     until proven otherwise.
   1010 */
   1011 {
   1012 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1013 /* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
   1014 /* 1 : L          */ {     1 ,     0 ,     1 ,     3 , s(1,4), s(1,4),     0 ,  1 },
   1015 /* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
   1016 /* 3 : L+AN       */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  1 },
   1017 /* 4 : L+ON       */ { s(2,1),     0 , s(2,1),     3 ,     4 ,     4 ,     0 ,  0 },
   1018 /* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  0 }
   1019 };
   1020 static const ImpAct impAct0 = {0,1,2,3,4,5,6};
   1021 static const ImpTabPair impTab_DEFAULT = {{&impTabL_DEFAULT,
   1022                                            &impTabR_DEFAULT},
   1023                                           {&impAct0, &impAct0}};
   1024 
   1025 static const ImpTab impTabL_NUMBERS_SPECIAL =   /* Even paragraph level */
   1026 /*  In this table, conditional sequences receive the higher possible level
   1027     until proven otherwise.
   1028 */
   1029 {
   1030 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1031 /* 0 : init       */ {     0 ,     2 ,    1 ,      1 ,     0 ,     0 ,     0 ,  0 },
   1032 /* 1 : L+EN/AN    */ {     0 ,     2 ,    1 ,      1 ,     0 ,     0 ,     0 ,  2 },
   1033 /* 2 : R          */ {     0 ,     2 ,    4 ,      4 , s(1,3),     0 ,     0 ,  1 },
   1034 /* 3 : R+ON       */ { s(2,0),     2 ,    4 ,      4 ,     3 ,     3 , s(2,0),  1 },
   1035 /* 4 : R+EN/AN    */ {     0 ,     2 ,    4 ,      4 , s(1,3), s(1,3),     0 ,  2 }
   1036   };
   1037 static const ImpTabPair impTab_NUMBERS_SPECIAL = {{&impTabL_NUMBERS_SPECIAL,
   1038                                                    &impTabR_DEFAULT},
   1039                                                   {&impAct0, &impAct0}};
   1040 
   1041 static const ImpTab impTabL_GROUP_NUMBERS_WITH_R =
   1042 /*  In this table, EN/AN+ON sequences receive levels as if associated with R
   1043     until proven that there is L or sor/eor on both sides. AN is handled like EN.
   1044 */
   1045 {
   1046 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1047 /* 0 init         */ {     0 ,     3 , s(1,1), s(1,1),     0 ,     0 ,     0 ,  0 },
   1048 /* 1 EN/AN        */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  2 },
   1049 /* 2 EN/AN+ON     */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  1 },
   1050 /* 3 R            */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  1 },
   1051 /* 4 R+ON         */ { s(2,0),     3 ,     5 ,     5 ,     4 , s(2,0), s(2,0),  1 },
   1052 /* 5 R+EN/AN      */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  2 }
   1053 };
   1054 static const ImpTab impTabR_GROUP_NUMBERS_WITH_R =
   1055 /*  In this table, EN/AN+ON sequences receive levels as if associated with R
   1056     until proven that there is L on both sides. AN is handled like EN.
   1057 */
   1058 {
   1059 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1060 /* 0 init         */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
   1061 /* 1 EN/AN        */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
   1062 /* 2 L            */ {     2 ,     0 , s(1,4), s(1,4), s(1,3),     0 ,     0 ,  1 },
   1063 /* 3 L+ON         */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  0 },
   1064 /* 4 L+EN/AN      */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  1 }
   1065 };
   1066 static const ImpTabPair impTab_GROUP_NUMBERS_WITH_R = {
   1067                         {&impTabL_GROUP_NUMBERS_WITH_R,
   1068                          &impTabR_GROUP_NUMBERS_WITH_R},
   1069                         {&impAct0, &impAct0}};
   1070 
   1071 
   1072 static const ImpTab impTabL_INVERSE_NUMBERS_AS_L =
   1073 /*  This table is identical to the Default LTR table except that EN and AN are
   1074     handled like L.
   1075 */
   1076 {
   1077 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1078 /* 0 : init       */ {     0 ,     1 ,     0 ,     0 ,     0 ,     0 ,     0 ,  0 },
   1079 /* 1 : R          */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  1 },
   1080 /* 2 : AN         */ {     0 ,     1 ,     0 ,     0 , s(1,5), s(1,5),     0 ,  2 },
   1081 /* 3 : R+EN/AN    */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  2 },
   1082 /* 4 : R+ON       */ { s(2,0),     1 , s(2,0), s(2,0),     4 ,     4 , s(2,0),  1 },
   1083 /* 5 : AN+ON      */ { s(2,0),     1 , s(2,0), s(2,0),     5 ,     5 , s(2,0),  1 }
   1084 };
   1085 static const ImpTab impTabR_INVERSE_NUMBERS_AS_L =
   1086 /*  This table is identical to the Default RTL table except that EN and AN are
   1087     handled like L.
   1088 */
   1089 {
   1090 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1091 /* 0 : init       */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
   1092 /* 1 : L          */ {     1 ,     0 ,     1 ,     1 , s(1,4), s(1,4),     0 ,  1 },
   1093 /* 2 : EN/AN      */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
   1094 /* 3 : L+AN       */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  1 },
   1095 /* 4 : L+ON       */ { s(2,1),     0 , s(2,1), s(2,1),     4 ,     4 ,     0 ,  0 },
   1096 /* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  0 }
   1097 };
   1098 static const ImpTabPair impTab_INVERSE_NUMBERS_AS_L = {
   1099                         {&impTabL_INVERSE_NUMBERS_AS_L,
   1100                          &impTabR_INVERSE_NUMBERS_AS_L},
   1101                         {&impAct0, &impAct0}};
   1102 
   1103 static const ImpTab impTabR_INVERSE_LIKE_DIRECT =   /* Odd  paragraph level */
   1104 /*  In this table, conditional sequences receive the lower possible level
   1105     until proven otherwise.
   1106 */
   1107 {
   1108 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1109 /* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
   1110 /* 1 : L          */ {     1 ,     0 ,     1 ,     2 , s(1,3), s(1,3),     0 ,  1 },
   1111 /* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
   1112 /* 3 : L+ON       */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  0 },
   1113 /* 4 : L+ON+AN    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  3 },
   1114 /* 5 : L+AN+ON    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  2 },
   1115 /* 6 : L+ON+EN    */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  1 }
   1116 };
   1117 static const ImpAct impAct1 = {0,1,11,12};
   1118 /* FOOD FOR THOUGHT: in LTR table below, check case "JKL 123abc"
   1119  */
   1120 static const ImpTabPair impTab_INVERSE_LIKE_DIRECT = {
   1121                         {&impTabL_DEFAULT,
   1122                          &impTabR_INVERSE_LIKE_DIRECT},
   1123                         {&impAct0, &impAct1}};
   1124 
   1125 static const ImpTab impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS =
   1126 /*  The case handled in this table is (visually):  R EN L
   1127 */
   1128 {
   1129 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1130 /* 0 : init       */ {     0 , s(6,3),     0 ,     1 ,     0 ,     0 ,     0 ,  0 },
   1131 /* 1 : L+AN       */ {     0 , s(6,3),     0 ,     1 , s(1,2), s(3,0),     0 ,  4 },
   1132 /* 2 : L+AN+ON    */ { s(2,0), s(6,3), s(2,0),     1 ,     2 , s(3,0), s(2,0),  3 },
   1133 /* 3 : R          */ {     0 , s(6,3), s(5,5), s(5,6), s(1,4), s(3,0),     0 ,  3 },
   1134 /* 4 : R+ON       */ { s(3,0), s(4,3), s(5,5), s(5,6),     4 , s(3,0), s(3,0),  3 },
   1135 /* 5 : R+EN       */ { s(3,0), s(4,3),     5 , s(5,6), s(1,4), s(3,0), s(3,0),  4 },
   1136 /* 6 : R+AN       */ { s(3,0), s(4,3), s(5,5),     6 , s(1,4), s(3,0), s(3,0),  4 }
   1137 };
   1138 static const ImpTab impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS =
   1139 /*  The cases handled in this table are (visually):  R EN L
   1140                                                      R L AN L
   1141 */
   1142 {
   1143 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1144 /* 0 : init       */ { s(1,3),     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
   1145 /* 1 : R+EN/AN    */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  1 },
   1146 /* 2 : R+EN/AN+ON */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  0 },
   1147 /* 3 : L          */ {     3 ,     0 ,     3 , s(3,6), s(1,4), s(4,0),     0 ,  1 },
   1148 /* 4 : L+ON       */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  0 },
   1149 /* 5 : L+ON+EN    */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  1 },
   1150 /* 6 : L+AN       */ { s(5,3), s(4,0),     6 ,     6 ,     4 , s(4,0), s(4,0),  3 }
   1151 };
   1152 static const ImpAct impAct2 = {0,1,7,8,9,10};
   1153 static const ImpTabPair impTab_INVERSE_LIKE_DIRECT_WITH_MARKS = {
   1154                         {&impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS,
   1155                          &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
   1156                         {&impAct0, &impAct2}};
   1157 
   1158 static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL = {
   1159                         {&impTabL_NUMBERS_SPECIAL,
   1160                          &impTabR_INVERSE_LIKE_DIRECT},
   1161                         {&impAct0, &impAct1}};
   1162 
   1163 static const ImpTab impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS =
   1164 /*  The case handled in this table is (visually):  R EN L
   1165 */
   1166 {
   1167 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
   1168 /* 0 : init       */ {     0 , s(6,2),     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
   1169 /* 1 : L+EN/AN    */ {     0 , s(6,2),     1 ,     1 ,     0 , s(3,0),     0 ,  4 },
   1170 /* 2 : R          */ {     0 , s(6,2), s(5,4), s(5,4), s(1,3), s(3,0),     0 ,  3 },
   1171 /* 3 : R+ON       */ { s(3,0), s(4,2), s(5,4), s(5,4),     3 , s(3,0), s(3,0),  3 },
   1172 /* 4 : R+EN/AN    */ { s(3,0), s(4,2),     4 ,     4 , s(1,3), s(3,0), s(3,0),  4 }
   1173 };
   1174 static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS = {
   1175                         {&impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS,
   1176                          &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
   1177                         {&impAct0, &impAct2}};
   1178 
   1179 #undef s
   1180 
   1181 typedef struct {
   1182     const ImpTab * pImpTab;             /* level table pointer          */
   1183     const ImpAct * pImpAct;             /* action map array             */
   1184     int32_t startON;                    /* start of ON sequence         */
   1185     int32_t startL2EN;                  /* start of level 2 sequence    */
   1186     int32_t lastStrongRTL;              /* index of last found R or AL  */
   1187     int32_t state;                      /* current state                */
   1188     UBiDiLevel runLevel;                /* run level before implicit solving */
   1189 } LevState;
   1190 
   1191 /*------------------------------------------------------------------------*/
   1192 
   1193 static void
   1194 addPoint(UBiDi *pBiDi, int32_t pos, int32_t flag)
   1195   /* param pos:     position where to insert
   1196      param flag:    one of LRM_BEFORE, LRM_AFTER, RLM_BEFORE, RLM_AFTER
   1197   */
   1198 {
   1199 #define FIRSTALLOC  10
   1200     Point point;
   1201     InsertPoints * pInsertPoints=&(pBiDi->insertPoints);
   1202 
   1203     if (pInsertPoints->capacity == 0)
   1204     {
   1205         pInsertPoints->points=uprv_malloc(sizeof(Point)*FIRSTALLOC);
   1206         if (pInsertPoints->points == NULL)
   1207         {
   1208             pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
   1209             return;
   1210         }
   1211         pInsertPoints->capacity=FIRSTALLOC;
   1212     }
   1213     if (pInsertPoints->size >= pInsertPoints->capacity) /* no room for new point */
   1214     {
   1215         void * savePoints=pInsertPoints->points;
   1216         pInsertPoints->points=uprv_realloc(pInsertPoints->points,
   1217                                            pInsertPoints->capacity*2*sizeof(Point));
   1218         if (pInsertPoints->points == NULL)
   1219         {
   1220             pInsertPoints->points=savePoints;
   1221             pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
   1222             return;
   1223         }
   1224         else  pInsertPoints->capacity*=2;
   1225     }
   1226     point.pos=pos;
   1227     point.flag=flag;
   1228     pInsertPoints->points[pInsertPoints->size]=point;
   1229     pInsertPoints->size++;
   1230 #undef FIRSTALLOC
   1231 }
   1232 
   1233 /* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
   1234 
   1235 /*
   1236  * This implementation of the (Wn) rules applies all rules in one pass.
   1237  * In order to do so, it needs a look-ahead of typically 1 character
   1238  * (except for W5: sequences of ET) and keeps track of changes
   1239  * in a rule Wp that affect a later Wq (p<q).
   1240  *
   1241  * The (Nn) and (In) rules are also performed in that same single loop,
   1242  * but effectively one iteration behind for white space.
   1243  *
   1244  * Since all implicit rules are performed in one step, it is not necessary
   1245  * to actually store the intermediate directional properties in dirProps[].
   1246  */
   1247 
   1248 static void
   1249 processPropertySeq(UBiDi *pBiDi, LevState *pLevState, uint8_t _prop,
   1250                    int32_t start, int32_t limit) {
   1251     uint8_t cell, oldStateSeq, actionSeq;
   1252     const ImpTab * pImpTab=pLevState->pImpTab;
   1253     const ImpAct * pImpAct=pLevState->pImpAct;
   1254     UBiDiLevel * levels=pBiDi->levels;
   1255     UBiDiLevel level, addLevel;
   1256     InsertPoints * pInsertPoints;
   1257     int32_t start0, k;
   1258 
   1259     start0=start;                           /* save original start position */
   1260     oldStateSeq=(uint8_t)pLevState->state;
   1261     cell=(*pImpTab)[oldStateSeq][_prop];
   1262     pLevState->state=GET_STATE(cell);       /* isolate the new state */
   1263     actionSeq=(*pImpAct)[GET_ACTION(cell)]; /* isolate the action */
   1264     addLevel=(*pImpTab)[pLevState->state][IMPTABLEVELS_RES];
   1265 
   1266     if(actionSeq) {
   1267         switch(actionSeq) {
   1268         case 1:                         /* init ON seq */
   1269             pLevState->startON=start0;
   1270             break;
   1271 
   1272         case 2:                         /* prepend ON seq to current seq */
   1273             start=pLevState->startON;
   1274             break;
   1275 
   1276         case 3:                         /* L or S after possible relevant EN/AN */
   1277             /* check if we had EN after R/AL */
   1278             if (pLevState->startL2EN >= 0) {
   1279                 addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
   1280             }
   1281             pLevState->startL2EN=-1;  /* not within previous if since could also be -2 */
   1282             /* check if we had any relevant EN/AN after R/AL */
   1283             pInsertPoints=&(pBiDi->insertPoints);
   1284             if ((pInsertPoints->capacity == 0) ||
   1285                 (pInsertPoints->size <= pInsertPoints->confirmed))
   1286             {
   1287                 /* nothing, just clean up */
   1288                 pLevState->lastStrongRTL=-1;
   1289                 /* check if we have a pending conditional segment */
   1290                 level=(*pImpTab)[oldStateSeq][IMPTABLEVELS_RES];
   1291                 if ((level & 1) && (pLevState->startON > 0)) {  /* after ON */
   1292                     start=pLevState->startON;   /* reset to basic run level */
   1293                 }
   1294                 if (_prop == DirProp_S)                /* add LRM before S */
   1295                 {
   1296                     addPoint(pBiDi, start0, LRM_BEFORE);
   1297                     pInsertPoints->confirmed=pInsertPoints->size;
   1298                 }
   1299                 break;
   1300             }
   1301             /* reset previous RTL cont to level for LTR text */
   1302             for (k=pLevState->lastStrongRTL+1; k<start0; k++)
   1303             {
   1304                 /* reset odd level, leave runLevel+2 as is */
   1305                 levels[k]=(levels[k] - 2) & ~1;
   1306             }
   1307             /* mark insert points as confirmed */
   1308             pInsertPoints->confirmed=pInsertPoints->size;
   1309             pLevState->lastStrongRTL=-1;
   1310             if (_prop == DirProp_S)            /* add LRM before S */
   1311             {
   1312                 addPoint(pBiDi, start0, LRM_BEFORE);
   1313                 pInsertPoints->confirmed=pInsertPoints->size;
   1314             }
   1315             break;
   1316 
   1317         case 4:                         /* R/AL after possible relevant EN/AN */
   1318             /* just clean up */
   1319             pInsertPoints=&(pBiDi->insertPoints);
   1320             if (pInsertPoints->capacity > 0)
   1321                 /* remove all non confirmed insert points */
   1322                 pInsertPoints->size=pInsertPoints->confirmed;
   1323             pLevState->startON=-1;
   1324             pLevState->startL2EN=-1;
   1325             pLevState->lastStrongRTL=limit - 1;
   1326             break;
   1327 
   1328         case 5:                         /* EN/AN after R/AL + possible cont */
   1329             /* check for real AN */
   1330             if ((_prop == DirProp_AN) && (NO_CONTEXT_RTL(pBiDi->dirProps[start0]) == AN) &&
   1331                 (pBiDi->reorderingMode!=UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))
   1332             {
   1333                 /* real AN */
   1334                 if (pLevState->startL2EN == -1) /* if no relevant EN already found */
   1335                 {
   1336                     /* just note the righmost digit as a strong RTL */
   1337                     pLevState->lastStrongRTL=limit - 1;
   1338                     break;
   1339                 }
   1340                 if (pLevState->startL2EN >= 0)  /* after EN, no AN */
   1341                 {
   1342                     addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
   1343                     pLevState->startL2EN=-2;
   1344                 }
   1345                 /* note AN */
   1346                 addPoint(pBiDi, start0, LRM_BEFORE);
   1347                 break;
   1348             }
   1349             /* if first EN/AN after R/AL */
   1350             if (pLevState->startL2EN == -1) {
   1351                 pLevState->startL2EN=start0;
   1352             }
   1353             break;
   1354 
   1355         case 6:                         /* note location of latest R/AL */
   1356             pLevState->lastStrongRTL=limit - 1;
   1357             pLevState->startON=-1;
   1358             break;
   1359 
   1360         case 7:                         /* L after R+ON/EN/AN */
   1361             /* include possible adjacent number on the left */
   1362             for (k=start0-1; k>=0 && !(levels[k]&1); k--);
   1363             if(k>=0) {
   1364                 addPoint(pBiDi, k, RLM_BEFORE);             /* add RLM before */
   1365                 pInsertPoints=&(pBiDi->insertPoints);
   1366                 pInsertPoints->confirmed=pInsertPoints->size;   /* confirm it */
   1367             }
   1368             pLevState->startON=start0;
   1369             break;
   1370 
   1371         case 8:                         /* AN after L */
   1372             /* AN numbers between L text on both sides may be trouble. */
   1373             /* tentatively bracket with LRMs; will be confirmed if followed by L */
   1374             addPoint(pBiDi, start0, LRM_BEFORE);    /* add LRM before */
   1375             addPoint(pBiDi, start0, LRM_AFTER);     /* add LRM after  */
   1376             break;
   1377 
   1378         case 9:                         /* R after L+ON/EN/AN */
   1379             /* false alert, infirm LRMs around previous AN */
   1380             pInsertPoints=&(pBiDi->insertPoints);
   1381             pInsertPoints->size=pInsertPoints->confirmed;
   1382             if (_prop == DirProp_S)            /* add RLM before S */
   1383             {
   1384                 addPoint(pBiDi, start0, RLM_BEFORE);
   1385                 pInsertPoints->confirmed=pInsertPoints->size;
   1386             }
   1387             break;
   1388 
   1389         case 10:                        /* L after L+ON/AN */
   1390             level=pLevState->runLevel + addLevel;
   1391             for(k=pLevState->startON; k<start0; k++) {
   1392                 if (levels[k]<level)
   1393                     levels[k]=level;
   1394             }
   1395             pInsertPoints=&(pBiDi->insertPoints);
   1396             pInsertPoints->confirmed=pInsertPoints->size;   /* confirm inserts */
   1397             pLevState->startON=start0;
   1398             break;
   1399 
   1400         case 11:                        /* L after L+ON+EN/AN/ON */
   1401             level=pLevState->runLevel;
   1402             for(k=start0-1; k>=pLevState->startON; k--) {
   1403                 if(levels[k]==level+3) {
   1404                     while(levels[k]==level+3) {
   1405                         levels[k--]-=2;
   1406                     }
   1407                     while(levels[k]==level) {
   1408                         k--;
   1409                     }
   1410                 }
   1411                 if(levels[k]==level+2) {
   1412                     levels[k]=level;
   1413                     continue;
   1414                 }
   1415                 levels[k]=level+1;
   1416             }
   1417             break;
   1418 
   1419         case 12:                        /* R after L+ON+EN/AN/ON */
   1420             level=pLevState->runLevel+1;
   1421             for(k=start0-1; k>=pLevState->startON; k--) {
   1422                 if(levels[k]>level) {
   1423                     levels[k]-=2;
   1424                 }
   1425             }
   1426             break;
   1427 
   1428         default:                        /* we should never get here */
   1429             U_ASSERT(FALSE);
   1430             break;
   1431         }
   1432     }
   1433     if((addLevel) || (start < start0)) {
   1434         level=pLevState->runLevel + addLevel;
   1435         for(k=start; k<limit; k++) {
   1436             levels[k]=level;
   1437         }
   1438     }
   1439 }
   1440 
   1441 static DirProp
   1442 lastL_R_AL(UBiDi *pBiDi) {
   1443     /* return last strong char at the end of the prologue */
   1444     const UChar *text=pBiDi->prologue;
   1445     int32_t length=pBiDi->proLength;
   1446     int32_t i;
   1447     UChar32 uchar;
   1448     DirProp dirProp;
   1449     for(i=length; i>0; ) {
   1450         /* i is decremented by U16_PREV */
   1451         U16_PREV(text, 0, i, uchar);
   1452         dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
   1453         if(dirProp==L) {
   1454             return DirProp_L;
   1455         }
   1456         if(dirProp==R || dirProp==AL) {
   1457             return DirProp_R;
   1458         }
   1459         if(dirProp==B) {
   1460             return DirProp_ON;
   1461         }
   1462     }
   1463     return DirProp_ON;
   1464 }
   1465 
   1466 static DirProp
   1467 firstL_R_AL_EN_AN(UBiDi *pBiDi) {
   1468     /* return first strong char or digit in epilogue */
   1469     const UChar *text=pBiDi->epilogue;
   1470     int32_t length=pBiDi->epiLength;
   1471     int32_t i;
   1472     UChar32 uchar;
   1473     DirProp dirProp;
   1474     for(i=0; i<length; ) {
   1475         /* i is incremented by U16_NEXT */
   1476         U16_NEXT(text, i, length, uchar);
   1477         dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
   1478         if(dirProp==L) {
   1479             return DirProp_L;
   1480         }
   1481         if(dirProp==R || dirProp==AL) {
   1482             return DirProp_R;
   1483         }
   1484         if(dirProp==EN) {
   1485             return DirProp_EN;
   1486         }
   1487         if(dirProp==AN) {
   1488             return DirProp_AN;
   1489         }
   1490     }
   1491     return DirProp_ON;
   1492 }
   1493 
   1494 static void
   1495 resolveImplicitLevels(UBiDi *pBiDi,
   1496                       int32_t start, int32_t limit,
   1497                       DirProp sor, DirProp eor) {
   1498     const DirProp *dirProps=pBiDi->dirProps;
   1499 
   1500     LevState levState;
   1501     int32_t i, start1, start2;
   1502     uint8_t oldStateImp, stateImp, actionImp;
   1503     uint8_t gprop, resProp, cell;
   1504     UBool inverseRTL;
   1505     DirProp nextStrongProp=R;
   1506     int32_t nextStrongPos=-1;
   1507 
   1508     levState.startON = -1;  /* silence gcc flow analysis */
   1509 
   1510     /* check for RTL inverse BiDi mode */
   1511     /* FOOD FOR THOUGHT: in case of RTL inverse BiDi, it would make sense to
   1512      * loop on the text characters from end to start.
   1513      * This would need a different properties state table (at least different
   1514      * actions) and different levels state tables (maybe very similar to the
   1515      * LTR corresponding ones.
   1516      */
   1517     inverseRTL=(UBool)
   1518         ((start<pBiDi->lastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) &&
   1519          (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT  ||
   1520           pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL));
   1521     /* initialize for levels state table */
   1522     levState.startL2EN=-1;              /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
   1523     levState.lastStrongRTL=-1;          /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
   1524     levState.state=0;
   1525     levState.runLevel=pBiDi->levels[start];
   1526     levState.pImpTab=(const ImpTab*)((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel&1];
   1527     levState.pImpAct=(const ImpAct*)((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel&1];
   1528     if(start==0 && pBiDi->proLength>0) {
   1529         DirProp lastStrong=lastL_R_AL(pBiDi);
   1530         if(lastStrong!=DirProp_ON) {
   1531             sor=lastStrong;
   1532         }
   1533     }
   1534     processPropertySeq(pBiDi, &levState, sor, start, start);
   1535     /* initialize for property state table */
   1536     if(NO_CONTEXT_RTL(dirProps[start])==NSM) {
   1537         stateImp = 1 + sor;
   1538     } else {
   1539         stateImp=0;
   1540     }
   1541     start1=start;
   1542     start2=start;
   1543 
   1544     for(i=start; i<=limit; i++) {
   1545         if(i>=limit) {
   1546             gprop=eor;
   1547         } else {
   1548             DirProp prop, prop1;
   1549             prop=NO_CONTEXT_RTL(dirProps[i]);
   1550             if(inverseRTL) {
   1551                 if(prop==AL) {
   1552                     /* AL before EN does not make it AN */
   1553                     prop=R;
   1554                 } else if(prop==EN) {
   1555                     if(nextStrongPos<=i) {
   1556                         /* look for next strong char (L/R/AL) */
   1557                         int32_t j;
   1558                         nextStrongProp=R;   /* set default */
   1559                         nextStrongPos=limit;
   1560                         for(j=i+1; j<limit; j++) {
   1561                             prop1=NO_CONTEXT_RTL(dirProps[j]);
   1562                             if(prop1==L || prop1==R || prop1==AL) {
   1563                                 nextStrongProp=prop1;
   1564                                 nextStrongPos=j;
   1565                                 break;
   1566                             }
   1567                         }
   1568                     }
   1569                     if(nextStrongProp==AL) {
   1570                         prop=AN;
   1571                     }
   1572                 }
   1573             }
   1574             gprop=groupProp[prop];
   1575         }
   1576         oldStateImp=stateImp;
   1577         cell=impTabProps[oldStateImp][gprop];
   1578         stateImp=GET_STATEPROPS(cell);      /* isolate the new state */
   1579         actionImp=GET_ACTIONPROPS(cell);    /* isolate the action */
   1580         if((i==limit) && (actionImp==0)) {
   1581             /* there is an unprocessed sequence if its property == eor   */
   1582             actionImp=1;                    /* process the last sequence */
   1583         }
   1584         if(actionImp) {
   1585             resProp=impTabProps[oldStateImp][IMPTABPROPS_RES];
   1586             switch(actionImp) {
   1587             case 1:             /* process current seq1, init new seq1 */
   1588                 processPropertySeq(pBiDi, &levState, resProp, start1, i);
   1589                 start1=i;
   1590                 break;
   1591             case 2:             /* init new seq2 */
   1592                 start2=i;
   1593                 break;
   1594             case 3:             /* process seq1, process seq2, init new seq1 */
   1595                 processPropertySeq(pBiDi, &levState, resProp, start1, start2);
   1596                 processPropertySeq(pBiDi, &levState, DirProp_ON, start2, i);
   1597                 start1=i;
   1598                 break;
   1599             case 4:             /* process seq1, set seq1=seq2, init new seq2 */
   1600                 processPropertySeq(pBiDi, &levState, resProp, start1, start2);
   1601                 start1=start2;
   1602                 start2=i;
   1603                 break;
   1604             default:            /* we should never get here */
   1605                 U_ASSERT(FALSE);
   1606                 break;
   1607             }
   1608         }
   1609     }
   1610     /* flush possible pending sequence, e.g. ON */
   1611     if(limit==pBiDi->length && pBiDi->epiLength>0) {
   1612         DirProp firstStrong=firstL_R_AL_EN_AN(pBiDi);
   1613         if(firstStrong!=DirProp_ON) {
   1614             eor=firstStrong;
   1615         }
   1616     }
   1617     processPropertySeq(pBiDi, &levState, eor, limit, limit);
   1618 }
   1619 
   1620 /* perform (L1) and (X9) ---------------------------------------------------- */
   1621 
   1622 /*
   1623  * Reset the embedding levels for some non-graphic characters (L1).
   1624  * This function also sets appropriate levels for BN, and
   1625  * explicit embedding types that are supposed to have been removed
   1626  * from the paragraph in (X9).
   1627  */
   1628 static void
   1629 adjustWSLevels(UBiDi *pBiDi) {
   1630     const DirProp *dirProps=pBiDi->dirProps;
   1631     UBiDiLevel *levels=pBiDi->levels;
   1632     int32_t i;
   1633 
   1634     if(pBiDi->flags&MASK_WS) {
   1635         UBool orderParagraphsLTR=pBiDi->orderParagraphsLTR;
   1636         Flags flag;
   1637 
   1638         i=pBiDi->trailingWSStart;
   1639         while(i>0) {
   1640             /* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */
   1641             while(i>0 && (flag=DIRPROP_FLAG_NC(dirProps[--i]))&MASK_WS) {
   1642                 if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
   1643                     levels[i]=0;
   1644                 } else {
   1645                     levels[i]=GET_PARALEVEL(pBiDi, i);
   1646                 }
   1647             }
   1648 
   1649             /* reset BN to the next character's paraLevel until B/S, which restarts above loop */
   1650             /* here, i+1 is guaranteed to be <length */
   1651             while(i>0) {
   1652                 flag=DIRPROP_FLAG_NC(dirProps[--i]);
   1653                 if(flag&MASK_BN_EXPLICIT) {
   1654                     levels[i]=levels[i+1];
   1655                 } else if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
   1656                     levels[i]=0;
   1657                     break;
   1658                 } else if(flag&MASK_B_S) {
   1659                     levels[i]=GET_PARALEVEL(pBiDi, i);
   1660                     break;
   1661                 }
   1662             }
   1663         }
   1664     }
   1665 }
   1666 
   1667 U_CAPI void U_EXPORT2
   1668 ubidi_setContext(UBiDi *pBiDi,
   1669                  const UChar *prologue, int32_t proLength,
   1670                  const UChar *epilogue, int32_t epiLength,
   1671                  UErrorCode *pErrorCode) {
   1672     /* check the argument values */
   1673     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
   1674     if(pBiDi==NULL || proLength<-1 || epiLength<-1 ||
   1675        (prologue==NULL && proLength!=0) || (epilogue==NULL && epiLength!=0)) {
   1676         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
   1677         return;
   1678     }
   1679 
   1680     if(proLength==-1) {
   1681         pBiDi->proLength=u_strlen(prologue);
   1682     } else {
   1683         pBiDi->proLength=proLength;
   1684     }
   1685     if(epiLength==-1) {
   1686         pBiDi->epiLength=u_strlen(epilogue);
   1687     } else {
   1688         pBiDi->epiLength=epiLength;
   1689     }
   1690     pBiDi->prologue=prologue;
   1691     pBiDi->epilogue=epilogue;
   1692 }
   1693 
   1694 static void
   1695 setParaSuccess(UBiDi *pBiDi) {
   1696     pBiDi->proLength=0;                 /* forget the last context */
   1697     pBiDi->epiLength=0;
   1698     pBiDi->pParaBiDi=pBiDi;             /* mark successful setPara */
   1699 }
   1700 
   1701 #define BIDI_MIN(x, y)   ((x)<(y) ? (x) : (y))
   1702 #define BIDI_ABS(x)      ((x)>=0  ? (x) : (-(x)))
   1703 static void
   1704 setParaRunsOnly(UBiDi *pBiDi, const UChar *text, int32_t length,
   1705                 UBiDiLevel paraLevel, UErrorCode *pErrorCode) {
   1706     void *runsOnlyMemory;
   1707     int32_t *visualMap;
   1708     UChar *visualText;
   1709     int32_t saveLength, saveTrailingWSStart;
   1710     const UBiDiLevel *levels;
   1711     UBiDiLevel *saveLevels;
   1712     UBiDiDirection saveDirection;
   1713     UBool saveMayAllocateText;
   1714     Run *runs;
   1715     int32_t visualLength, i, j, visualStart, logicalStart,
   1716             runCount, runLength, addedRuns, insertRemove,
   1717             start, limit, step, indexOddBit, logicalPos,
   1718             index0, index1;
   1719     uint32_t saveOptions;
   1720 
   1721     pBiDi->reorderingMode=UBIDI_REORDER_DEFAULT;
   1722     if(length==0) {
   1723         ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
   1724         goto cleanup3;
   1725     }
   1726     /* obtain memory for mapping table and visual text */
   1727     runsOnlyMemory=uprv_malloc(length*(sizeof(int32_t)+sizeof(UChar)+sizeof(UBiDiLevel)));
   1728     if(runsOnlyMemory==NULL) {
   1729         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
   1730         goto cleanup3;
   1731     }
   1732     visualMap=runsOnlyMemory;
   1733     visualText=(UChar *)&visualMap[length];
   1734     saveLevels=(UBiDiLevel *)&visualText[length];
   1735     saveOptions=pBiDi->reorderingOptions;
   1736     if(saveOptions & UBIDI_OPTION_INSERT_MARKS) {
   1737         pBiDi->reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
   1738         pBiDi->reorderingOptions|=UBIDI_OPTION_REMOVE_CONTROLS;
   1739     }
   1740     paraLevel&=1;                       /* accept only 0 or 1 */
   1741     ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
   1742     if(U_FAILURE(*pErrorCode)) {
   1743         goto cleanup3;
   1744     }
   1745     /* we cannot access directly pBiDi->levels since it is not yet set if
   1746      * direction is not MIXED
   1747      */
   1748     levels=ubidi_getLevels(pBiDi, pErrorCode);
   1749     uprv_memcpy(saveLevels, levels, pBiDi->length*sizeof(UBiDiLevel));
   1750     saveTrailingWSStart=pBiDi->trailingWSStart;
   1751     saveLength=pBiDi->length;
   1752     saveDirection=pBiDi->direction;
   1753 
   1754     /* FOOD FOR THOUGHT: instead of writing the visual text, we could use
   1755      * the visual map and the dirProps array to drive the second call
   1756      * to ubidi_setPara (but must make provision for possible removal of
   1757      * BiDi controls.  Alternatively, only use the dirProps array via
   1758      * customized classifier callback.
   1759      */
   1760     visualLength=ubidi_writeReordered(pBiDi, visualText, length,
   1761                                       UBIDI_DO_MIRRORING, pErrorCode);
   1762     ubidi_getVisualMap(pBiDi, visualMap, pErrorCode);
   1763     if(U_FAILURE(*pErrorCode)) {
   1764         goto cleanup2;
   1765     }
   1766     pBiDi->reorderingOptions=saveOptions;
   1767 
   1768     pBiDi->reorderingMode=UBIDI_REORDER_INVERSE_LIKE_DIRECT;
   1769     paraLevel^=1;
   1770     /* Because what we did with reorderingOptions, visualText may be shorter
   1771      * than the original text. But we don't want the levels memory to be
   1772      * reallocated shorter than the original length, since we need to restore
   1773      * the levels as after the first call to ubidi_setpara() before returning.
   1774      * We will force mayAllocateText to FALSE before the second call to
   1775      * ubidi_setpara(), and will restore it afterwards.
   1776      */
   1777     saveMayAllocateText=pBiDi->mayAllocateText;
   1778     pBiDi->mayAllocateText=FALSE;
   1779     ubidi_setPara(pBiDi, visualText, visualLength, paraLevel, NULL, pErrorCode);
   1780     pBiDi->mayAllocateText=saveMayAllocateText;
   1781     ubidi_getRuns(pBiDi, pErrorCode);
   1782     if(U_FAILURE(*pErrorCode)) {
   1783         goto cleanup1;
   1784     }
   1785     /* check if some runs must be split, count how many splits */
   1786     addedRuns=0;
   1787     runCount=pBiDi->runCount;
   1788     runs=pBiDi->runs;
   1789     visualStart=0;
   1790     for(i=0; i<runCount; i++, visualStart+=runLength) {
   1791         runLength=runs[i].visualLimit-visualStart;
   1792         if(runLength<2) {
   1793             continue;
   1794         }
   1795         logicalStart=GET_INDEX(runs[i].logicalStart);
   1796         for(j=logicalStart+1; j<logicalStart+runLength; j++) {
   1797             index0=visualMap[j];
   1798             index1=visualMap[j-1];
   1799             if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
   1800                 addedRuns++;
   1801             }
   1802         }
   1803     }
   1804     if(addedRuns) {
   1805         if(getRunsMemory(pBiDi, runCount+addedRuns)) {
   1806             if(runCount==1) {
   1807                 /* because we switch from UBiDi.simpleRuns to UBiDi.runs */
   1808                 pBiDi->runsMemory[0]=runs[0];
   1809             }
   1810             runs=pBiDi->runs=pBiDi->runsMemory;
   1811             pBiDi->runCount+=addedRuns;
   1812         } else {
   1813             goto cleanup1;
   1814         }
   1815     }
   1816     /* split runs which are not consecutive in source text */
   1817     for(i=runCount-1; i>=0; i--) {
   1818         runLength= i==0 ? runs[0].visualLimit :
   1819                           runs[i].visualLimit-runs[i-1].visualLimit;
   1820         logicalStart=runs[i].logicalStart;
   1821         indexOddBit=GET_ODD_BIT(logicalStart);
   1822         logicalStart=GET_INDEX(logicalStart);
   1823         if(runLength<2) {
   1824             if(addedRuns) {
   1825                 runs[i+addedRuns]=runs[i];
   1826             }
   1827             logicalPos=visualMap[logicalStart];
   1828             runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
   1829                                             saveLevels[logicalPos]^indexOddBit);
   1830             continue;
   1831         }
   1832         if(indexOddBit) {
   1833             start=logicalStart;
   1834             limit=logicalStart+runLength-1;
   1835             step=1;
   1836         } else {
   1837             start=logicalStart+runLength-1;
   1838             limit=logicalStart;
   1839             step=-1;
   1840         }
   1841         for(j=start; j!=limit; j+=step) {
   1842             index0=visualMap[j];
   1843             index1=visualMap[j+step];
   1844             if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
   1845                 logicalPos=BIDI_MIN(visualMap[start], index0);
   1846                 runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
   1847                                             saveLevels[logicalPos]^indexOddBit);
   1848                 runs[i+addedRuns].visualLimit=runs[i].visualLimit;
   1849                 runs[i].visualLimit-=BIDI_ABS(j-start)+1;
   1850                 insertRemove=runs[i].insertRemove&(LRM_AFTER|RLM_AFTER);
   1851                 runs[i+addedRuns].insertRemove=insertRemove;
   1852                 runs[i].insertRemove&=~insertRemove;
   1853                 start=j+step;
   1854                 addedRuns--;
   1855             }
   1856         }
   1857         if(addedRuns) {
   1858             runs[i+addedRuns]=runs[i];
   1859         }
   1860         logicalPos=BIDI_MIN(visualMap[start], visualMap[limit]);
   1861         runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
   1862                                             saveLevels[logicalPos]^indexOddBit);
   1863     }
   1864 
   1865   cleanup1:
   1866     /* restore initial paraLevel */
   1867     pBiDi->paraLevel^=1;
   1868   cleanup2:
   1869     /* restore real text */
   1870     pBiDi->text=text;
   1871     pBiDi->length=saveLength;
   1872     pBiDi->originalLength=length;
   1873     pBiDi->direction=saveDirection;
   1874     /* the saved levels should never excess levelsSize, but we check anyway */
   1875     if(saveLength>pBiDi->levelsSize) {
   1876         saveLength=pBiDi->levelsSize;
   1877     }
   1878     uprv_memcpy(pBiDi->levels, saveLevels, saveLength*sizeof(UBiDiLevel));
   1879     pBiDi->trailingWSStart=saveTrailingWSStart;
   1880     /* free memory for mapping table and visual text */
   1881     uprv_free(runsOnlyMemory);
   1882     if(pBiDi->runCount>1) {
   1883         pBiDi->direction=UBIDI_MIXED;
   1884     }
   1885   cleanup3:
   1886     pBiDi->reorderingMode=UBIDI_REORDER_RUNS_ONLY;
   1887 }
   1888 
   1889 /* ubidi_setPara ------------------------------------------------------------ */
   1890 
   1891 U_CAPI void U_EXPORT2
   1892 ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length,
   1893               UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels,
   1894               UErrorCode *pErrorCode) {
   1895     UBiDiDirection direction;
   1896 
   1897     /* check the argument values */
   1898     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
   1899     if(pBiDi==NULL || text==NULL || length<-1 ||
   1900        (paraLevel>UBIDI_MAX_EXPLICIT_LEVEL && paraLevel<UBIDI_DEFAULT_LTR)) {
   1901         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
   1902         return;
   1903     }
   1904 
   1905     if(length==-1) {
   1906         length=u_strlen(text);
   1907     }
   1908 
   1909     /* special treatment for RUNS_ONLY mode */
   1910     if(pBiDi->reorderingMode==UBIDI_REORDER_RUNS_ONLY) {
   1911         setParaRunsOnly(pBiDi, text, length, paraLevel, pErrorCode);
   1912         return;
   1913     }
   1914 
   1915     /* initialize the UBiDi structure */
   1916     pBiDi->pParaBiDi=NULL;          /* mark unfinished setPara */
   1917     pBiDi->text=text;
   1918     pBiDi->length=pBiDi->originalLength=pBiDi->resultLength=length;
   1919     pBiDi->paraLevel=paraLevel;
   1920     pBiDi->direction=UBIDI_LTR;
   1921     pBiDi->paraCount=1;
   1922 
   1923     pBiDi->dirProps=NULL;
   1924     pBiDi->levels=NULL;
   1925     pBiDi->runs=NULL;
   1926     pBiDi->insertPoints.size=0;         /* clean up from last call */
   1927     pBiDi->insertPoints.confirmed=0;    /* clean up from last call */
   1928 
   1929     /*
   1930      * Save the original paraLevel if contextual; otherwise, set to 0.
   1931      */
   1932     if(IS_DEFAULT_LEVEL(paraLevel)) {
   1933         pBiDi->defaultParaLevel=paraLevel;
   1934     } else {
   1935         pBiDi->defaultParaLevel=0;
   1936     }
   1937 
   1938     if(length==0) {
   1939         /*
   1940          * For an empty paragraph, create a UBiDi object with the paraLevel and
   1941          * the flags and the direction set but without allocating zero-length arrays.
   1942          * There is nothing more to do.
   1943          */
   1944         if(IS_DEFAULT_LEVEL(paraLevel)) {
   1945             pBiDi->paraLevel&=1;
   1946             pBiDi->defaultParaLevel=0;
   1947         }
   1948         if(paraLevel&1) {
   1949             pBiDi->flags=DIRPROP_FLAG(R);
   1950             pBiDi->direction=UBIDI_RTL;
   1951         } else {
   1952             pBiDi->flags=DIRPROP_FLAG(L);
   1953             pBiDi->direction=UBIDI_LTR;
   1954         }
   1955 
   1956         pBiDi->runCount=0;
   1957         pBiDi->paraCount=0;
   1958         setParaSuccess(pBiDi);          /* mark successful setPara */
   1959         return;
   1960     }
   1961 
   1962     pBiDi->runCount=-1;
   1963 
   1964     /*
   1965      * Get the directional properties,
   1966      * the flags bit-set, and
   1967      * determine the paragraph level if necessary.
   1968      */
   1969     if(getDirPropsMemory(pBiDi, length)) {
   1970         pBiDi->dirProps=pBiDi->dirPropsMemory;
   1971         getDirProps(pBiDi);
   1972     } else {
   1973         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
   1974         return;
   1975     }
   1976     /* the processed length may have changed if UBIDI_OPTION_STREAMING */
   1977     length= pBiDi->length;
   1978     pBiDi->trailingWSStart=length;  /* the levels[] will reflect the WS run */
   1979     /* allocate paras memory */
   1980     if(pBiDi->paraCount>1) {
   1981         if(getInitialParasMemory(pBiDi, pBiDi->paraCount)) {
   1982             pBiDi->paras=pBiDi->parasMemory;
   1983             pBiDi->paras[pBiDi->paraCount-1]=length;
   1984         } else {
   1985             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
   1986             return;
   1987         }
   1988     } else {
   1989         /* initialize paras for single paragraph */
   1990         pBiDi->paras=pBiDi->simpleParas;
   1991         pBiDi->simpleParas[0]=length;
   1992     }
   1993 
   1994     /* are explicit levels specified? */
   1995     if(embeddingLevels==NULL) {
   1996         /* no: determine explicit levels according to the (Xn) rules */\
   1997         if(getLevelsMemory(pBiDi, length)) {
   1998             pBiDi->levels=pBiDi->levelsMemory;
   1999             direction=resolveExplicitLevels(pBiDi);
   2000         } else {
   2001             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
   2002             return;
   2003         }
   2004     } else {
   2005         /* set BN for all explicit codes, check that all levels are 0 or paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */
   2006         pBiDi->levels=embeddingLevels;
   2007         direction=checkExplicitLevels(pBiDi, pErrorCode);
   2008         if(U_FAILURE(*pErrorCode)) {
   2009             return;
   2010         }
   2011     }
   2012 
   2013     /*
   2014      * The steps after (X9) in the UBiDi algorithm are performed only if
   2015      * the paragraph text has mixed directionality!
   2016      */
   2017     pBiDi->direction=direction;
   2018     switch(direction) {
   2019     case UBIDI_LTR:
   2020         /* make sure paraLevel is even */
   2021         pBiDi->paraLevel=(UBiDiLevel)((pBiDi->paraLevel+1)&~1);
   2022 
   2023         /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
   2024         pBiDi->trailingWSStart=0;
   2025         break;
   2026     case UBIDI_RTL:
   2027         /* make sure paraLevel is odd */
   2028         pBiDi->paraLevel|=1;
   2029 
   2030         /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
   2031         pBiDi->trailingWSStart=0;
   2032         break;
   2033     default:
   2034         /*
   2035          *  Choose the right implicit state table
   2036          */
   2037         switch(pBiDi->reorderingMode) {
   2038         case UBIDI_REORDER_DEFAULT:
   2039             pBiDi->pImpTabPair=&impTab_DEFAULT;
   2040             break;
   2041         case UBIDI_REORDER_NUMBERS_SPECIAL:
   2042             pBiDi->pImpTabPair=&impTab_NUMBERS_SPECIAL;
   2043             break;
   2044         case UBIDI_REORDER_GROUP_NUMBERS_WITH_R:
   2045             pBiDi->pImpTabPair=&impTab_GROUP_NUMBERS_WITH_R;
   2046             break;
   2047         case UBIDI_REORDER_INVERSE_NUMBERS_AS_L:
   2048             pBiDi->pImpTabPair=&impTab_INVERSE_NUMBERS_AS_L;
   2049             break;
   2050         case UBIDI_REORDER_INVERSE_LIKE_DIRECT:
   2051             if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
   2052                 pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT_WITH_MARKS;
   2053             } else {
   2054                 pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT;
   2055             }
   2056             break;
   2057         case UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL:
   2058             if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
   2059                 pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS;
   2060             } else {
   2061                 pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL;
   2062             }
   2063             break;
   2064         default:
   2065             /* we should never get here */
   2066             U_ASSERT(FALSE);
   2067             break;
   2068         }
   2069         /*
   2070          * If there are no external levels specified and there
   2071          * are no significant explicit level codes in the text,
   2072          * then we can treat the entire paragraph as one run.
   2073          * Otherwise, we need to perform the following rules on runs of
   2074          * the text with the same embedding levels. (X10)
   2075          * "Significant" explicit level codes are ones that actually
   2076          * affect non-BN characters.
   2077          * Examples for "insignificant" ones are empty embeddings
   2078          * LRE-PDF, LRE-RLE-PDF-PDF, etc.
   2079          */
   2080         if(embeddingLevels==NULL && pBiDi->paraCount<=1 &&
   2081                                    !(pBiDi->flags&DIRPROP_FLAG_MULTI_RUNS)) {
   2082             resolveImplicitLevels(pBiDi, 0, length,
   2083                                     GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, 0)),
   2084                                     GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, length-1)));
   2085         } else {
   2086             /* sor, eor: start and end types of same-level-run */
   2087             UBiDiLevel *levels=pBiDi->levels;
   2088             int32_t start, limit=0;
   2089             UBiDiLevel level, nextLevel;
   2090             DirProp sor, eor;
   2091 
   2092             /* determine the first sor and set eor to it because of the loop body (sor=eor there) */
   2093             level=GET_PARALEVEL(pBiDi, 0);
   2094             nextLevel=levels[0];
   2095             if(level<nextLevel) {
   2096                 eor=GET_LR_FROM_LEVEL(nextLevel);
   2097             } else {
   2098                 eor=GET_LR_FROM_LEVEL(level);
   2099             }
   2100 
   2101             do {
   2102                 /* determine start and limit of the run (end points just behind the run) */
   2103 
   2104                 /* the values for this run's start are the same as for the previous run's end */
   2105                 start=limit;
   2106                 level=nextLevel;
   2107                 if((start>0) && (NO_CONTEXT_RTL(pBiDi->dirProps[start-1])==B)) {
   2108                     /* except if this is a new paragraph, then set sor = para level */
   2109                     sor=GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, start));
   2110                 } else {
   2111                     sor=eor;
   2112                 }
   2113 
   2114                 /* search for the limit of this run */
   2115                 while(++limit<length && levels[limit]==level) {}
   2116 
   2117                 /* get the correct level of the next run */
   2118                 if(limit<length) {
   2119                     nextLevel=levels[limit];
   2120                 } else {
   2121                     nextLevel=GET_PARALEVEL(pBiDi, length-1);
   2122                 }
   2123 
   2124                 /* determine eor from max(level, nextLevel); sor is last run's eor */
   2125                 if((level&~UBIDI_LEVEL_OVERRIDE)<(nextLevel&~UBIDI_LEVEL_OVERRIDE)) {
   2126                     eor=GET_LR_FROM_LEVEL(nextLevel);
   2127                 } else {
   2128                     eor=GET_LR_FROM_LEVEL(level);
   2129                 }
   2130 
   2131                 /* if the run consists of overridden directional types, then there
   2132                    are no implicit types to be resolved */
   2133                 if(!(level&UBIDI_LEVEL_OVERRIDE)) {
   2134                     resolveImplicitLevels(pBiDi, start, limit, sor, eor);
   2135                 } else {
   2136                     /* remove the UBIDI_LEVEL_OVERRIDE flags */
   2137                     do {
   2138                         levels[start++]&=~UBIDI_LEVEL_OVERRIDE;
   2139                     } while(start<limit);
   2140                 }
   2141             } while(limit<length);
   2142         }
   2143         /* check if we got any memory shortage while adding insert points */
   2144         if (U_FAILURE(pBiDi->insertPoints.errorCode))
   2145         {
   2146             *pErrorCode=pBiDi->insertPoints.errorCode;
   2147             return;
   2148         }
   2149         /* reset the embedding levels for some non-graphic characters (L1), (X9) */
   2150         adjustWSLevels(pBiDi);
   2151         break;
   2152     }
   2153     /* add RLM for inverse Bidi with contextual orientation resolving
   2154      * to RTL which would not round-trip otherwise
   2155      */
   2156     if((pBiDi->defaultParaLevel>0) &&
   2157        (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) &&
   2158        ((pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT) ||
   2159         (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))) {
   2160         int32_t i, j, start, last;
   2161         DirProp dirProp;
   2162         for(i=0; i<pBiDi->paraCount; i++) {
   2163             last=pBiDi->paras[i]-1;
   2164             if((pBiDi->dirProps[last] & CONTEXT_RTL)==0) {
   2165                 continue;           /* LTR paragraph */
   2166             }
   2167             start= i==0 ? 0 : pBiDi->paras[i - 1];
   2168             for(j=last; j>=start; j--) {
   2169                 dirProp=NO_CONTEXT_RTL(pBiDi->dirProps[j]);
   2170                 if(dirProp==L) {
   2171                     if(j<last) {
   2172                         while(NO_CONTEXT_RTL(pBiDi->dirProps[last])==B) {
   2173                             last--;
   2174                         }
   2175                     }
   2176                     addPoint(pBiDi, last, RLM_BEFORE);
   2177                     break;
   2178                 }
   2179                 if(DIRPROP_FLAG(dirProp) & MASK_R_AL) {
   2180                     break;
   2181                 }
   2182             }
   2183         }
   2184     }
   2185 
   2186     if(pBiDi->reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
   2187         pBiDi->resultLength -= pBiDi->controlCount;
   2188     } else {
   2189         pBiDi->resultLength += pBiDi->insertPoints.size;
   2190     }
   2191     setParaSuccess(pBiDi);              /* mark successful setPara */
   2192 }
   2193 
   2194 U_CAPI void U_EXPORT2
   2195 ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR) {
   2196     if(pBiDi!=NULL) {
   2197         pBiDi->orderParagraphsLTR=orderParagraphsLTR;
   2198     }
   2199 }
   2200 
   2201 U_CAPI UBool U_EXPORT2
   2202 ubidi_isOrderParagraphsLTR(UBiDi *pBiDi) {
   2203     if(pBiDi!=NULL) {
   2204         return pBiDi->orderParagraphsLTR;
   2205     } else {
   2206         return FALSE;
   2207     }
   2208 }
   2209 
   2210 U_CAPI UBiDiDirection U_EXPORT2
   2211 ubidi_getDirection(const UBiDi *pBiDi) {
   2212     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2213         return pBiDi->direction;
   2214     } else {
   2215         return UBIDI_LTR;
   2216     }
   2217 }
   2218 
   2219 U_CAPI const UChar * U_EXPORT2
   2220 ubidi_getText(const UBiDi *pBiDi) {
   2221     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2222         return pBiDi->text;
   2223     } else {
   2224         return NULL;
   2225     }
   2226 }
   2227 
   2228 U_CAPI int32_t U_EXPORT2
   2229 ubidi_getLength(const UBiDi *pBiDi) {
   2230     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2231         return pBiDi->originalLength;
   2232     } else {
   2233         return 0;
   2234     }
   2235 }
   2236 
   2237 U_CAPI int32_t U_EXPORT2
   2238 ubidi_getProcessedLength(const UBiDi *pBiDi) {
   2239     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2240         return pBiDi->length;
   2241     } else {
   2242         return 0;
   2243     }
   2244 }
   2245 
   2246 U_CAPI int32_t U_EXPORT2
   2247 ubidi_getResultLength(const UBiDi *pBiDi) {
   2248     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2249         return pBiDi->resultLength;
   2250     } else {
   2251         return 0;
   2252     }
   2253 }
   2254 
   2255 /* paragraphs API functions ------------------------------------------------- */
   2256 
   2257 U_CAPI UBiDiLevel U_EXPORT2
   2258 ubidi_getParaLevel(const UBiDi *pBiDi) {
   2259     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
   2260         return pBiDi->paraLevel;
   2261     } else {
   2262         return 0;
   2263     }
   2264 }
   2265 
   2266 U_CAPI int32_t U_EXPORT2
   2267 ubidi_countParagraphs(UBiDi *pBiDi) {
   2268     if(!IS_VALID_PARA_OR_LINE(pBiDi)) {
   2269         return 0;
   2270     } else {
   2271         return pBiDi->paraCount;
   2272     }
   2273 }
   2274 
   2275 U_CAPI void U_EXPORT2
   2276 ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex,
   2277                           int32_t *pParaStart, int32_t *pParaLimit,
   2278                           UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
   2279     int32_t paraStart;
   2280 
   2281     /* check the argument values */
   2282     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
   2283     RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode);
   2284     RETURN_VOID_IF_BAD_RANGE(paraIndex, 0, pBiDi->paraCount, *pErrorCode);
   2285 
   2286     pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
   2287     if(paraIndex) {
   2288         paraStart=pBiDi->paras[paraIndex-1];
   2289     } else {
   2290         paraStart=0;
   2291     }
   2292     if(pParaStart!=NULL) {
   2293         *pParaStart=paraStart;
   2294     }
   2295     if(pParaLimit!=NULL) {
   2296         *pParaLimit=pBiDi->paras[paraIndex];
   2297     }
   2298     if(pParaLevel!=NULL) {
   2299         *pParaLevel=GET_PARALEVEL(pBiDi, paraStart);
   2300     }
   2301 }
   2302 
   2303 U_CAPI int32_t U_EXPORT2
   2304 ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex,
   2305                           int32_t *pParaStart, int32_t *pParaLimit,
   2306                           UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
   2307     uint32_t paraIndex;
   2308 
   2309     /* check the argument values */
   2310     /* pErrorCode will be checked by the call to ubidi_getParagraphByIndex */
   2311     RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrorCode, -1);
   2312     RETURN_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode, -1);
   2313     pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
   2314     RETURN_IF_BAD_RANGE(charIndex, 0, pBiDi->length, *pErrorCode, -1);
   2315 
   2316     for(paraIndex=0; charIndex>=pBiDi->paras[paraIndex]; paraIndex++);
   2317     ubidi_getParagraphByIndex(pBiDi, paraIndex, pParaStart, pParaLimit, pParaLevel, pErrorCode);
   2318     return paraIndex;
   2319 }
   2320 
   2321 U_CAPI void U_EXPORT2
   2322 ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn,
   2323                        const void *newContext, UBiDiClassCallback **oldFn,
   2324                        const void **oldContext, UErrorCode *pErrorCode)
   2325 {
   2326     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
   2327     if(pBiDi==NULL) {
   2328         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
   2329         return;
   2330     }
   2331     if( oldFn )
   2332     {
   2333         *oldFn = pBiDi->fnClassCallback;
   2334     }
   2335     if( oldContext )
   2336     {
   2337         *oldContext = pBiDi->coClassCallback;
   2338     }
   2339     pBiDi->fnClassCallback = newFn;
   2340     pBiDi->coClassCallback = newContext;
   2341 }
   2342 
   2343 U_CAPI void U_EXPORT2
   2344 ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context)
   2345 {
   2346     if(pBiDi==NULL) {
   2347         return;
   2348     }
   2349     if( fn )
   2350     {
   2351         *fn = pBiDi->fnClassCallback;
   2352     }
   2353     if( context )
   2354     {
   2355         *context = pBiDi->coClassCallback;
   2356     }
   2357 }
   2358 
   2359 U_CAPI UCharDirection U_EXPORT2
   2360 ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c)
   2361 {
   2362     UCharDirection dir;
   2363 
   2364     if( pBiDi->fnClassCallback == NULL ||
   2365         (dir = (*pBiDi->fnClassCallback)(pBiDi->coClassCallback, c)) == U_BIDI_CLASS_DEFAULT )
   2366     {
   2367         return ubidi_getClass(pBiDi->bdp, c);
   2368     } else {
   2369         return dir;
   2370     }
   2371 }
   2372 
   2373