Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/intl/icu/source/common/ubidi.cpp
Line
Count
Source (jump to first uncovered line)
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
******************************************************************************
5
*
6
*   Copyright (C) 1999-2015, International Business Machines
7
*   Corporation and others.  All Rights Reserved.
8
*
9
******************************************************************************
10
*   file name:  ubidi.c
11
*   encoding:   UTF-8
12
*   tab size:   8 (not used)
13
*   indentation:4
14
*
15
*   created on: 1999jul27
16
*   created by: Markus W. Scherer, updated by Matitiahu Allouche
17
*
18
*/
19
20
#include "cmemory.h"
21
#include "unicode/utypes.h"
22
#include "unicode/ustring.h"
23
#include "unicode/uchar.h"
24
#include "unicode/ubidi.h"
25
#include "unicode/utf16.h"
26
#include "ubidi_props.h"
27
#include "ubidiimp.h"
28
#include "uassert.h"
29
30
/*
31
 * General implementation notes:
32
 *
33
 * Throughout the implementation, there are comments like (W2) that refer to
34
 * rules of the BiDi algorithm, in this example to the second rule of the
35
 * resolution of weak types.
36
 *
37
 * For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
38
 * character according to UTF-16, the second UChar gets the directional property of
39
 * the entire character assigned, while the first one gets a BN, a boundary
40
 * neutral, type, which is ignored by most of the algorithm according to
41
 * rule (X9) and the implementation suggestions of the BiDi algorithm.
42
 *
43
 * Later, adjustWSLevels() will set the level for each BN to that of the
44
 * following character (UChar), which results in surrogate pairs getting the
45
 * same level on each of their surrogates.
46
 *
47
 * In a UTF-8 implementation, the same thing could be done: the last byte of
48
 * a multi-byte sequence would get the "real" property, while all previous
49
 * bytes of that sequence would get BN.
50
 *
51
 * It is not possible to assign all those parts of a character the same real
52
 * property because this would fail in the resolution of weak types with rules
53
 * that look at immediately surrounding types.
54
 *
55
 * As a related topic, this implementation does not remove Boundary Neutral
56
 * types from the input, but ignores them wherever this is relevant.
57
 * For example, the loop for the resolution of the weak types reads
58
 * types until it finds a non-BN.
59
 * Also, explicit embedding codes are neither changed into BN nor removed.
60
 * They are only treated the same way real BNs are.
61
 * As stated before, adjustWSLevels() takes care of them at the end.
62
 * For the purpose of conformance, the levels of all these codes
63
 * do not matter.
64
 *
65
 * Note that this implementation modifies the dirProps
66
 * after the initial setup, when applying X5c (replace FSI by LRI or RLI),
67
 * X6, N0 (replace paired brackets by L or R).
68
 *
69
 * In this implementation, the resolution of weak types (W1 to W6),
70
 * neutrals (N1 and N2), and the assignment of the resolved level (In)
71
 * are all done in one single loop, in resolveImplicitLevels().
72
 * Changes of dirProp values are done on the fly, without writing
73
 * them back to the dirProps array.
74
 *
75
 *
76
 * This implementation contains code that allows to bypass steps of the
77
 * algorithm that are not needed on the specific paragraph
78
 * in order to speed up the most common cases considerably,
79
 * like text that is entirely LTR, or RTL text without numbers.
80
 *
81
 * Most of this is done by setting a bit for each directional property
82
 * in a flags variable and later checking for whether there are
83
 * any LTR characters or any RTL characters, or both, whether
84
 * there are any explicit embedding codes, etc.
85
 *
86
 * If the (Xn) steps are performed, then the flags are re-evaluated,
87
 * because they will then not contain the embedding codes any more
88
 * and will be adjusted for override codes, so that subsequently
89
 * more bypassing may be possible than what the initial flags suggested.
90
 *
91
 * If the text is not mixed-directional, then the
92
 * algorithm steps for the weak type resolution are not performed,
93
 * and all levels are set to the paragraph level.
94
 *
95
 * If there are no explicit embedding codes, then the (Xn) steps
96
 * are not performed.
97
 *
98
 * If embedding levels are supplied as a parameter, then all
99
 * explicit embedding codes are ignored, and the (Xn) steps
100
 * are not performed.
101
 *
102
 * White Space types could get the level of the run they belong to,
103
 * and are checked with a test of (flags&MASK_EMBEDDING) to
104
 * consider if the paragraph direction should be considered in
105
 * the flags variable.
106
 *
107
 * If there are no White Space types in the paragraph, then
108
 * (L1) is not necessary in adjustWSLevels().
109
 */
110
111
/* to avoid some conditional statements, use tiny constant arrays */
112
static const Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
113
static const Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
114
static const Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
115
116
0
#define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
117
0
#define DIRPROP_FLAG_E(level)  flagE[(level)&1]
118
0
#define DIRPROP_FLAG_O(level)  flagO[(level)&1]
119
120
0
#define DIR_FROM_STRONG(strong) ((strong)==L ? L : R)
121
122
0
#define NO_OVERRIDE(level)  ((level)&~UBIDI_LEVEL_OVERRIDE)
123
124
/* UBiDi object management -------------------------------------------------- */
125
126
U_CAPI UBiDi * U_EXPORT2
127
ubidi_open(void)
128
0
{
129
0
    UErrorCode errorCode=U_ZERO_ERROR;
130
0
    return ubidi_openSized(0, 0, &errorCode);
131
0
}
132
133
U_CAPI UBiDi * U_EXPORT2
134
0
ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode) {
135
0
    UBiDi *pBiDi;
136
0
137
0
    /* check the argument values */
138
0
    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
139
0
        return NULL;
140
0
    } else if(maxLength<0 || maxRunCount<0) {
141
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
142
0
        return NULL;    /* invalid arguments */
143
0
    }
144
0
145
0
    /* allocate memory for the object */
146
0
    pBiDi=(UBiDi *)uprv_malloc(sizeof(UBiDi));
147
0
    if(pBiDi==NULL) {
148
0
        *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
149
0
        return NULL;
150
0
    }
151
0
152
0
    /* reset the object, all pointers NULL, all flags FALSE, all sizes 0 */
153
0
    uprv_memset(pBiDi, 0, sizeof(UBiDi));
154
0
155
0
    /* allocate memory for arrays as requested */
156
0
    if(maxLength>0) {
157
0
        if( !getInitialDirPropsMemory(pBiDi, maxLength) ||
158
0
            !getInitialLevelsMemory(pBiDi, maxLength)
159
0
        ) {
160
0
            *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
161
0
        }
162
0
    } else {
163
0
        pBiDi->mayAllocateText=TRUE;
164
0
    }
165
0
166
0
    if(maxRunCount>0) {
167
0
        if(maxRunCount==1) {
168
0
            /* use simpleRuns[] */
169
0
            pBiDi->runsSize=sizeof(Run);
170
0
        } else if(!getInitialRunsMemory(pBiDi, maxRunCount)) {
171
0
            *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
172
0
        }
173
0
    } else {
174
0
        pBiDi->mayAllocateRuns=TRUE;
175
0
    }
176
0
177
0
    if(U_SUCCESS(*pErrorCode)) {
178
0
        return pBiDi;
179
0
    } else {
180
0
        ubidi_close(pBiDi);
181
0
        return NULL;
182
0
    }
183
0
}
184
185
/*
186
 * We are allowed to allocate memory if memory==NULL or
187
 * mayAllocate==TRUE for each array that we need.
188
 * We also try to grow memory as needed if we
189
 * allocate it.
190
 *
191
 * Assume sizeNeeded>0.
192
 * If *pMemory!=NULL, then assume *pSize>0.
193
 *
194
 * ### this realloc() may unnecessarily copy the old data,
195
 * which we know we don't need any more;
196
 * is this the best way to do this??
197
 */
198
U_CFUNC UBool
199
0
ubidi_getMemory(BidiMemoryForAllocation *bidiMem, int32_t *pSize, UBool mayAllocate, int32_t sizeNeeded) {
200
0
    void **pMemory = (void **)bidiMem;
201
0
    /* check for existing memory */
202
0
    if(*pMemory==NULL) {
203
0
        /* we need to allocate memory */
204
0
        if(mayAllocate && (*pMemory=uprv_malloc(sizeNeeded))!=NULL) {
205
0
            *pSize=sizeNeeded;
206
0
            return TRUE;
207
0
        } else {
208
0
            return FALSE;
209
0
        }
210
0
    } else {
211
0
        if(sizeNeeded<=*pSize) {
212
0
            /* there is already enough memory */
213
0
            return TRUE;
214
0
        }
215
0
        else if(!mayAllocate) {
216
0
            /* not enough memory, and we must not allocate */
217
0
            return FALSE;
218
0
        } else {
219
0
            /* we try to grow */
220
0
            void *memory;
221
0
            /* in most cases, we do not need the copy-old-data part of
222
0
             * realloc, but it is needed when adding runs using getRunsMemory()
223
0
             * in setParaRunsOnly()
224
0
             */
225
0
            if((memory=uprv_realloc(*pMemory, sizeNeeded))!=NULL) {
226
0
                *pMemory=memory;
227
0
                *pSize=sizeNeeded;
228
0
                return TRUE;
229
0
            } else {
230
0
                /* we failed to grow */
231
0
                return FALSE;
232
0
            }
233
0
        }
234
0
    }
235
0
}
236
237
U_CAPI void U_EXPORT2
238
0
ubidi_close(UBiDi *pBiDi) {
239
0
    if(pBiDi!=NULL) {
240
0
        pBiDi->pParaBiDi=NULL;          /* in case one tries to reuse this block */
241
0
        if(pBiDi->dirPropsMemory!=NULL) {
242
0
            uprv_free(pBiDi->dirPropsMemory);
243
0
        }
244
0
        if(pBiDi->levelsMemory!=NULL) {
245
0
            uprv_free(pBiDi->levelsMemory);
246
0
        }
247
0
        if(pBiDi->openingsMemory!=NULL) {
248
0
            uprv_free(pBiDi->openingsMemory);
249
0
        }
250
0
        if(pBiDi->parasMemory!=NULL) {
251
0
            uprv_free(pBiDi->parasMemory);
252
0
        }
253
0
        if(pBiDi->runsMemory!=NULL) {
254
0
            uprv_free(pBiDi->runsMemory);
255
0
        }
256
0
        if(pBiDi->isolatesMemory!=NULL) {
257
0
            uprv_free(pBiDi->isolatesMemory);
258
0
        }
259
0
        if(pBiDi->insertPoints.points!=NULL) {
260
0
            uprv_free(pBiDi->insertPoints.points);
261
0
        }
262
0
263
0
        uprv_free(pBiDi);
264
0
    }
265
0
}
266
267
/* set to approximate "inverse BiDi" ---------------------------------------- */
268
269
U_CAPI void U_EXPORT2
270
0
ubidi_setInverse(UBiDi *pBiDi, UBool isInverse) {
271
0
    if(pBiDi!=NULL) {
272
0
        pBiDi->isInverse=isInverse;
273
0
        pBiDi->reorderingMode = isInverse ? UBIDI_REORDER_INVERSE_NUMBERS_AS_L
274
0
                                          : UBIDI_REORDER_DEFAULT;
275
0
    }
276
0
}
277
278
U_CAPI UBool U_EXPORT2
279
0
ubidi_isInverse(UBiDi *pBiDi) {
280
0
    if(pBiDi!=NULL) {
281
0
        return pBiDi->isInverse;
282
0
    } else {
283
0
        return FALSE;
284
0
    }
285
0
}
286
287
/* FOOD FOR THOUGHT: currently the reordering modes are a mixture of
288
 * algorithm for direct BiDi, algorithm for inverse BiDi and the bizarre
289
 * concept of RUNS_ONLY which is a double operation.
290
 * It could be advantageous to divide this into 3 concepts:
291
 * a) Operation: direct / inverse / RUNS_ONLY
292
 * b) Direct algorithm: default / NUMBERS_SPECIAL / GROUP_NUMBERS_WITH_R
293
 * c) Inverse algorithm: default / INVERSE_LIKE_DIRECT / NUMBERS_SPECIAL
294
 * This would allow combinations not possible today like RUNS_ONLY with
295
 * NUMBERS_SPECIAL.
296
 * Also allow to set INSERT_MARKS for the direct step of RUNS_ONLY and
297
 * REMOVE_CONTROLS for the inverse step.
298
 * Not all combinations would be supported, and probably not all do make sense.
299
 * This would need to document which ones are supported and what are the
300
 * fallbacks for unsupported combinations.
301
 */
302
U_CAPI void U_EXPORT2
303
0
ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode) {
304
0
    if ((pBiDi!=NULL) && (reorderingMode >= UBIDI_REORDER_DEFAULT)
305
0
                        && (reorderingMode < UBIDI_REORDER_COUNT)) {
306
0
        pBiDi->reorderingMode = reorderingMode;
307
0
        pBiDi->isInverse = (UBool)(reorderingMode == UBIDI_REORDER_INVERSE_NUMBERS_AS_L);
308
0
    }
309
0
}
310
311
U_CAPI UBiDiReorderingMode U_EXPORT2
312
0
ubidi_getReorderingMode(UBiDi *pBiDi) {
313
0
    if (pBiDi!=NULL) {
314
0
        return pBiDi->reorderingMode;
315
0
    } else {
316
0
        return UBIDI_REORDER_DEFAULT;
317
0
    }
318
0
}
319
320
U_CAPI void U_EXPORT2
321
0
ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions) {
322
0
    if (reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
323
0
        reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
324
0
    }
325
0
    if (pBiDi!=NULL) {
326
0
        pBiDi->reorderingOptions=reorderingOptions;
327
0
    }
328
0
}
329
330
U_CAPI uint32_t U_EXPORT2
331
0
ubidi_getReorderingOptions(UBiDi *pBiDi) {
332
0
    if (pBiDi!=NULL) {
333
0
        return pBiDi->reorderingOptions;
334
0
    } else {
335
0
        return 0;
336
0
    }
337
0
}
338
339
U_CAPI UBiDiDirection U_EXPORT2
340
ubidi_getBaseDirection(const UChar *text,
341
0
int32_t length){
342
0
343
0
    int32_t i;
344
0
    UChar32 uchar;
345
0
    UCharDirection dir;
346
0
347
0
    if( text==NULL || length<-1 ){
348
0
        return UBIDI_NEUTRAL;
349
0
    }
350
0
351
0
    if(length==-1) {
352
0
        length=u_strlen(text);
353
0
    }
354
0
355
0
    for( i = 0 ; i < length; ) {
356
0
        /* i is incremented by U16_NEXT */
357
0
        U16_NEXT(text, i, length, uchar);
358
0
        dir = u_charDirection(uchar);
359
0
        if( dir == U_LEFT_TO_RIGHT )
360
0
                return UBIDI_LTR;
361
0
        if( dir == U_RIGHT_TO_LEFT || dir ==U_RIGHT_TO_LEFT_ARABIC )
362
0
                return UBIDI_RTL;
363
0
    }
364
0
    return UBIDI_NEUTRAL;
365
0
}
366
367
/* perform (P2)..(P3) ------------------------------------------------------- */
368
369
/**
370
 * Returns the directionality of the first strong character
371
 * after the last B in prologue, if any.
372
 * Requires prologue!=null.
373
 */
374
static DirProp
375
0
firstL_R_AL(UBiDi *pBiDi) {
376
0
    const UChar *text=pBiDi->prologue;
377
0
    int32_t length=pBiDi->proLength;
378
0
    int32_t i;
379
0
    UChar32 uchar;
380
0
    DirProp dirProp, result=ON;
381
0
    for(i=0; i<length; ) {
382
0
        /* i is incremented by U16_NEXT */
383
0
        U16_NEXT(text, i, length, uchar);
384
0
        dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
385
0
        if(result==ON) {
386
0
            if(dirProp==L || dirProp==R || dirProp==AL) {
387
0
                result=dirProp;
388
0
            }
389
0
        } else {
390
0
            if(dirProp==B) {
391
0
                result=ON;
392
0
            }
393
0
        }
394
0
    }
395
0
    return result;
396
0
}
397
398
/*
399
 * Check that there are enough entries in the array pointed to by pBiDi->paras
400
 */
401
static UBool
402
0
checkParaCount(UBiDi *pBiDi) {
403
0
    int32_t count=pBiDi->paraCount;
404
0
    if(pBiDi->paras==pBiDi->simpleParas) {
405
0
        if(count<=SIMPLE_PARAS_COUNT)
406
0
            return TRUE;
407
0
        if(!getInitialParasMemory(pBiDi, SIMPLE_PARAS_COUNT * 2))
408
0
            return FALSE;
409
0
        pBiDi->paras=pBiDi->parasMemory;
410
0
        uprv_memcpy(pBiDi->parasMemory, pBiDi->simpleParas, SIMPLE_PARAS_COUNT * sizeof(Para));
411
0
        return TRUE;
412
0
    }
413
0
    if(!getInitialParasMemory(pBiDi, count * 2))
414
0
        return FALSE;
415
0
    pBiDi->paras=pBiDi->parasMemory;
416
0
    return TRUE;
417
0
}
418
419
/*
420
 * Get the directional properties for the text, calculate the flags bit-set, and
421
 * determine the paragraph level if necessary (in pBiDi->paras[i].level).
422
 * FSI initiators are also resolved and their dirProp replaced with LRI or RLI.
423
 * When encountering an FSI, it is initially replaced with an LRI, which is the
424
 * default. Only if a strong R or AL is found within its scope will the LRI be
425
 * replaced by an RLI.
426
 */
427
static UBool
428
0
getDirProps(UBiDi *pBiDi) {
429
0
    const UChar *text=pBiDi->text;
430
0
    DirProp *dirProps=pBiDi->dirPropsMemory;    /* pBiDi->dirProps is const */
431
0
432
0
    int32_t i=0, originalLength=pBiDi->originalLength;
433
0
    Flags flags=0;      /* collect all directionalities in the text */
434
0
    UChar32 uchar;
435
0
    DirProp dirProp=0, defaultParaLevel=0;  /* initialize to avoid compiler warnings */
436
0
    UBool isDefaultLevel=IS_DEFAULT_LEVEL(pBiDi->paraLevel);
437
0
    /* for inverse BiDi, the default para level is set to RTL if there is a
438
0
       strong R or AL character at either end of the text                            */
439
0
    UBool isDefaultLevelInverse=isDefaultLevel && (UBool)
440
0
            (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT ||
441
0
             pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL);
442
0
    int32_t lastArabicPos=-1;
443
0
    int32_t controlCount=0;
444
0
    UBool removeBiDiControls = (UBool)(pBiDi->reorderingOptions &
445
0
                                       UBIDI_OPTION_REMOVE_CONTROLS);
446
0
447
0
    enum State {
448
0
         NOT_SEEKING_STRONG,            /* 0: not contextual paraLevel, not after FSI */
449
0
         SEEKING_STRONG_FOR_PARA,       /* 1: looking for first strong char in para */
450
0
         SEEKING_STRONG_FOR_FSI,        /* 2: looking for first strong after FSI */
451
0
         LOOKING_FOR_PDI                /* 3: found strong after FSI, looking for PDI */
452
0
    };
453
0
    State state;
454
0
    DirProp lastStrong=ON;              /* for default level & inverse BiDi */
455
0
    /* The following stacks are used to manage isolate sequences. Those
456
0
       sequences may be nested, but obviously never more deeply than the
457
0
       maximum explicit embedding level.
458
0
       lastStack is the index of the last used entry in the stack. A value of -1
459
0
       means that there is no open isolate sequence.
460
0
       lastStack is reset to -1 on paragraph boundaries. */
461
0
    /* The following stack contains the position of the initiator of
462
0
       each open isolate sequence */
463
0
    int32_t isolateStartStack[UBIDI_MAX_EXPLICIT_LEVEL+1];
464
0
    /* The following stack contains the last known state before
465
0
       encountering the initiator of an isolate sequence */
466
0
    State  previousStateStack[UBIDI_MAX_EXPLICIT_LEVEL+1];
467
0
    int32_t stackLast=-1;
468
0
469
0
    if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING)
470
0
        pBiDi->length=0;
471
0
    defaultParaLevel=pBiDi->paraLevel&1;
472
0
    if(isDefaultLevel) {
473
0
        pBiDi->paras[0].level=defaultParaLevel;
474
0
        lastStrong=defaultParaLevel;
475
0
        if(pBiDi->proLength>0 &&                    /* there is a prologue */
476
0
           (dirProp=firstL_R_AL(pBiDi))!=ON) {  /* with a strong character */
477
0
            if(dirProp==L)
478
0
                pBiDi->paras[0].level=0;    /* set the default para level */
479
0
            else
480
0
                pBiDi->paras[0].level=1;    /* set the default para level */
481
0
            state=NOT_SEEKING_STRONG;
482
0
        } else {
483
0
            state=SEEKING_STRONG_FOR_PARA;
484
0
        }
485
0
    } else {
486
0
        pBiDi->paras[0].level=pBiDi->paraLevel;
487
0
        state=NOT_SEEKING_STRONG;
488
0
    }
489
0
    /* count paragraphs and determine the paragraph level (P2..P3) */
490
0
    /*
491
0
     * see comment in ubidi.h:
492
0
     * the UBIDI_DEFAULT_XXX values are designed so that
493
0
     * their bit 0 alone yields the intended default
494
0
     */
495
0
    for( /* i=0 above */ ; i<originalLength; ) {
496
0
        /* i is incremented by U16_NEXT */
497
0
        U16_NEXT(text, i, originalLength, uchar);
498
0
        flags|=DIRPROP_FLAG(dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar));
499
0
        dirProps[i-1]=dirProp;
500
0
        if(uchar>0xffff) {  /* set the lead surrogate's property to BN */
501
0
            flags|=DIRPROP_FLAG(BN);
502
0
            dirProps[i-2]=BN;
503
0
        }
504
0
        if(removeBiDiControls && IS_BIDI_CONTROL_CHAR(uchar))
505
0
            controlCount++;
506
0
        if(dirProp==L) {
507
0
            if(state==SEEKING_STRONG_FOR_PARA) {
508
0
                pBiDi->paras[pBiDi->paraCount-1].level=0;
509
0
                state=NOT_SEEKING_STRONG;
510
0
            }
511
0
            else if(state==SEEKING_STRONG_FOR_FSI) {
512
0
                if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
513
0
                    /* no need for next statement, already set by default */
514
0
                    /* dirProps[isolateStartStack[stackLast]]=LRI; */
515
0
                    flags|=DIRPROP_FLAG(LRI);
516
0
                }
517
0
                state=LOOKING_FOR_PDI;
518
0
            }
519
0
            lastStrong=L;
520
0
            continue;
521
0
        }
522
0
        if(dirProp==R || dirProp==AL) {
523
0
            if(state==SEEKING_STRONG_FOR_PARA) {
524
0
                pBiDi->paras[pBiDi->paraCount-1].level=1;
525
0
                state=NOT_SEEKING_STRONG;
526
0
            }
527
0
            else if(state==SEEKING_STRONG_FOR_FSI) {
528
0
                if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
529
0
                    dirProps[isolateStartStack[stackLast]]=RLI;
530
0
                    flags|=DIRPROP_FLAG(RLI);
531
0
                }
532
0
                state=LOOKING_FOR_PDI;
533
0
            }
534
0
            lastStrong=R;
535
0
            if(dirProp==AL)
536
0
                lastArabicPos=i-1;
537
0
            continue;
538
0
        }
539
0
        if(dirProp>=FSI && dirProp<=RLI) {  /* FSI, LRI or RLI */
540
0
            stackLast++;
541
0
            if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
542
0
                isolateStartStack[stackLast]=i-1;
543
0
                previousStateStack[stackLast]=state;
544
0
            }
545
0
            if(dirProp==FSI) {
546
0
                dirProps[i-1]=LRI;      /* default if no strong char */
547
0
                state=SEEKING_STRONG_FOR_FSI;
548
0
            }
549
0
            else
550
0
                state=LOOKING_FOR_PDI;
551
0
            continue;
552
0
        }
553
0
        if(dirProp==PDI) {
554
0
            if(state==SEEKING_STRONG_FOR_FSI) {
555
0
                if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
556
0
                    /* no need for next statement, already set by default */
557
0
                    /* dirProps[isolateStartStack[stackLast]]=LRI; */
558
0
                    flags|=DIRPROP_FLAG(LRI);
559
0
                }
560
0
            }
561
0
            if(stackLast>=0) {
562
0
                if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL)
563
0
                    state=previousStateStack[stackLast];
564
0
                stackLast--;
565
0
            }
566
0
            continue;
567
0
        }
568
0
        if(dirProp==B) {
569
0
            if(i<originalLength && uchar==CR && text[i]==LF) /* do nothing on the CR */
570
0
                continue;
571
0
            pBiDi->paras[pBiDi->paraCount-1].limit=i;
572
0
            if(isDefaultLevelInverse && lastStrong==R)
573
0
                pBiDi->paras[pBiDi->paraCount-1].level=1;
574
0
            if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
575
0
                /* When streaming, we only process whole paragraphs
576
0
                   thus some updates are only done on paragraph boundaries */
577
0
                pBiDi->length=i;        /* i is index to next character */
578
0
                pBiDi->controlCount=controlCount;
579
0
            }
580
0
            if(i<originalLength) {              /* B not last char in text */
581
0
                pBiDi->paraCount++;
582
0
                if(checkParaCount(pBiDi)==FALSE)    /* not enough memory for a new para entry */
583
0
                    return FALSE;
584
0
                if(isDefaultLevel) {
585
0
                    pBiDi->paras[pBiDi->paraCount-1].level=defaultParaLevel;
586
0
                    state=SEEKING_STRONG_FOR_PARA;
587
0
                    lastStrong=defaultParaLevel;
588
0
                } else {
589
0
                    pBiDi->paras[pBiDi->paraCount-1].level=pBiDi->paraLevel;
590
0
                    state=NOT_SEEKING_STRONG;
591
0
                }
592
0
                stackLast=-1;
593
0
            }
594
0
            continue;
595
0
        }
596
0
    }
597
0
    /* Ignore still open isolate sequences with overflow */
598
0
    if(stackLast>UBIDI_MAX_EXPLICIT_LEVEL) {
599
0
        stackLast=UBIDI_MAX_EXPLICIT_LEVEL;
600
0
        state=SEEKING_STRONG_FOR_FSI;   /* to be on the safe side */
601
0
    }
602
0
    /* Resolve direction of still unresolved open FSI sequences */
603
0
    while(stackLast>=0) {
604
0
        if(state==SEEKING_STRONG_FOR_FSI) {
605
0
            /* no need for next statement, already set by default */
606
0
            /* dirProps[isolateStartStack[stackLast]]=LRI; */
607
0
            flags|=DIRPROP_FLAG(LRI);
608
0
            break;
609
0
        }
610
0
        state=previousStateStack[stackLast];
611
0
        stackLast--;
612
0
    }
613
0
    /* When streaming, ignore text after the last paragraph separator */
614
0
    if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
615
0
        if(pBiDi->length<originalLength)
616
0
            pBiDi->paraCount--;
617
0
    } else {
618
0
        pBiDi->paras[pBiDi->paraCount-1].limit=originalLength;
619
0
        pBiDi->controlCount=controlCount;
620
0
    }
621
0
    /* For inverse bidi, default para direction is RTL if there is
622
0
       a strong R or AL at either end of the paragraph */
623
0
    if(isDefaultLevelInverse && lastStrong==R) {
624
0
        pBiDi->paras[pBiDi->paraCount-1].level=1;
625
0
    }
626
0
    if(isDefaultLevel) {
627
0
        pBiDi->paraLevel=pBiDi->paras[0].level;
628
0
    }
629
0
    /* The following is needed to resolve the text direction for default level
630
0
       paragraphs containing no strong character */
631
0
    for(i=0; i<pBiDi->paraCount; i++)
632
0
        flags|=DIRPROP_FLAG_LR(pBiDi->paras[i].level);
633
0
634
0
    if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
635
0
        flags|=DIRPROP_FLAG(L);
636
0
    }
637
0
    pBiDi->flags=flags;
638
0
    pBiDi->lastArabicPos=lastArabicPos;
639
0
    return TRUE;
640
0
}
641
642
/* determine the paragraph level at position index */
643
U_CFUNC UBiDiLevel
644
0
ubidi_getParaLevelAtIndex(const UBiDi *pBiDi, int32_t pindex) {
645
0
    int32_t i;
646
0
    for(i=0; i<pBiDi->paraCount; i++)
647
0
        if(pindex<pBiDi->paras[i].limit)
648
0
            break;
649
0
    if(i>=pBiDi->paraCount)
650
0
        i=pBiDi->paraCount-1;
651
0
    return (UBiDiLevel)(pBiDi->paras[i].level);
652
0
}
653
654
/* Functions for handling paired brackets ----------------------------------- */
655
656
/* In the isoRuns array, the first entry is used for text outside of any
657
   isolate sequence.  Higher entries are used for each more deeply nested
658
   isolate sequence. isoRunLast is the index of the last used entry.  The
659
   openings array is used to note the data of opening brackets not yet
660
   matched by a closing bracket, or matched but still susceptible to change
661
   level.
662
   Each isoRun entry contains the index of the first and
663
   one-after-last openings entries for pending opening brackets it
664
   contains.  The next openings entry to use is the one-after-last of the
665
   most deeply nested isoRun entry.
666
   isoRun entries also contain their current embedding level and the last
667
   encountered strong character, since these will be needed to resolve
668
   the level of paired brackets.  */
669
670
static void
671
0
bracketInit(UBiDi *pBiDi, BracketData *bd) {
672
0
    bd->pBiDi=pBiDi;
673
0
    bd->isoRunLast=0;
674
0
    bd->isoRuns[0].start=0;
675
0
    bd->isoRuns[0].limit=0;
676
0
    bd->isoRuns[0].level=GET_PARALEVEL(pBiDi, 0);
677
0
    UBiDiLevel t = GET_PARALEVEL(pBiDi, 0) & 1;
678
0
    bd->isoRuns[0].lastStrong = bd->isoRuns[0].lastBase = t;
679
0
    bd->isoRuns[0].contextDir = (UBiDiDirection)t;
680
0
    bd->isoRuns[0].contextPos=0;
681
0
    if(pBiDi->openingsMemory) {
682
0
        bd->openings=pBiDi->openingsMemory;
683
0
        bd->openingsCount=pBiDi->openingsSize / sizeof(Opening);
684
0
    } else {
685
0
        bd->openings=bd->simpleOpenings;
686
0
        bd->openingsCount=SIMPLE_OPENINGS_COUNT;
687
0
    }
688
0
    bd->isNumbersSpecial=bd->pBiDi->reorderingMode==UBIDI_REORDER_NUMBERS_SPECIAL ||
689
0
                         bd->pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL;
690
0
}
691
692
/* paragraph boundary */
693
static void
694
0
bracketProcessB(BracketData *bd, UBiDiLevel level) {
695
0
    bd->isoRunLast=0;
696
0
    bd->isoRuns[0].limit=0;
697
0
    bd->isoRuns[0].level=level;
698
0
    bd->isoRuns[0].lastStrong=bd->isoRuns[0].lastBase=level&1;
699
0
    bd->isoRuns[0].contextDir=(UBiDiDirection)(level&1);
700
0
    bd->isoRuns[0].contextPos=0;
701
0
}
702
703
/* LRE, LRO, RLE, RLO, PDF */
704
static void
705
bracketProcessBoundary(BracketData *bd, int32_t lastCcPos,
706
0
                       UBiDiLevel contextLevel, UBiDiLevel embeddingLevel) {
707
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
708
0
    DirProp *dirProps=bd->pBiDi->dirProps;
709
0
    if(DIRPROP_FLAG(dirProps[lastCcPos])&MASK_ISO)  /* after an isolate */
710
0
        return;
711
0
    if(NO_OVERRIDE(embeddingLevel)>NO_OVERRIDE(contextLevel))   /* not a PDF */
712
0
        contextLevel=embeddingLevel;
713
0
    pLastIsoRun->limit=pLastIsoRun->start;
714
0
    pLastIsoRun->level=embeddingLevel;
715
0
    pLastIsoRun->lastStrong=pLastIsoRun->lastBase=contextLevel&1;
716
0
    pLastIsoRun->contextDir=(UBiDiDirection)(contextLevel&1);
717
0
    pLastIsoRun->contextPos=(UBiDiDirection)lastCcPos;
718
0
}
719
720
/* LRI or RLI */
721
static void
722
0
bracketProcessLRI_RLI(BracketData *bd, UBiDiLevel level) {
723
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
724
0
    int16_t lastLimit;
725
0
    pLastIsoRun->lastBase=ON;
726
0
    lastLimit=pLastIsoRun->limit;
727
0
    bd->isoRunLast++;
728
0
    pLastIsoRun++;
729
0
    pLastIsoRun->start=pLastIsoRun->limit=lastLimit;
730
0
    pLastIsoRun->level=level;
731
0
    pLastIsoRun->lastStrong=pLastIsoRun->lastBase=level&1;
732
0
    pLastIsoRun->contextDir=(UBiDiDirection)(level&1);
733
0
    pLastIsoRun->contextPos=0;
734
0
}
735
736
/* PDI */
737
static void
738
0
bracketProcessPDI(BracketData *bd) {
739
0
    IsoRun *pLastIsoRun;
740
0
    bd->isoRunLast--;
741
0
    pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
742
0
    pLastIsoRun->lastBase=ON;
743
0
}
744
745
/* newly found opening bracket: create an openings entry */
746
static UBool                            /* return TRUE if success */
747
0
bracketAddOpening(BracketData *bd, UChar match, int32_t position) {
748
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
749
0
    Opening *pOpening;
750
0
    if(pLastIsoRun->limit>=bd->openingsCount) {  /* no available new entry */
751
0
        UBiDi *pBiDi=bd->pBiDi;
752
0
        if(!getInitialOpeningsMemory(pBiDi, pLastIsoRun->limit * 2))
753
0
            return FALSE;
754
0
        if(bd->openings==bd->simpleOpenings)
755
0
            uprv_memcpy(pBiDi->openingsMemory, bd->simpleOpenings,
756
0
                        SIMPLE_OPENINGS_COUNT * sizeof(Opening));
757
0
        bd->openings=pBiDi->openingsMemory;     /* may have changed */
758
0
        bd->openingsCount=pBiDi->openingsSize / sizeof(Opening);
759
0
    }
760
0
    pOpening=&bd->openings[pLastIsoRun->limit];
761
0
    pOpening->position=position;
762
0
    pOpening->match=match;
763
0
    pOpening->contextDir=pLastIsoRun->contextDir;
764
0
    pOpening->contextPos=pLastIsoRun->contextPos;
765
0
    pOpening->flags=0;
766
0
    pLastIsoRun->limit++;
767
0
    return TRUE;
768
0
}
769
770
/* change N0c1 to N0c2 when a preceding bracket is assigned the embedding level */
771
static void
772
0
fixN0c(BracketData *bd, int32_t openingIndex, int32_t newPropPosition, DirProp newProp) {
773
0
    /* This function calls itself recursively */
774
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
775
0
    Opening *qOpening;
776
0
    DirProp *dirProps=bd->pBiDi->dirProps;
777
0
    int32_t k, openingPosition, closingPosition;
778
0
    for(k=openingIndex+1, qOpening=&bd->openings[k]; k<pLastIsoRun->limit; k++, qOpening++) {
779
0
        if(qOpening->match>=0)      /* not an N0c match */
780
0
            continue;
781
0
        if(newPropPosition<qOpening->contextPos)
782
0
            break;
783
0
        if(newPropPosition>=qOpening->position)
784
0
            continue;
785
0
        if(newProp==qOpening->contextDir)
786
0
            break;
787
0
        openingPosition=qOpening->position;
788
0
        dirProps[openingPosition]=newProp;
789
0
        closingPosition=-(qOpening->match);
790
0
        dirProps[closingPosition]=newProp;
791
0
        qOpening->match=0;                      /* prevent further changes */
792
0
        fixN0c(bd, k, openingPosition, newProp);
793
0
        fixN0c(bd, k, closingPosition, newProp);
794
0
    }
795
0
}
796
797
/* process closing bracket */
798
static DirProp              /* return L or R if N0b or N0c, ON if N0d */
799
0
bracketProcessClosing(BracketData *bd, int32_t openIdx, int32_t position) {
800
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
801
0
    Opening *pOpening, *qOpening;
802
0
    UBiDiDirection direction;
803
0
    UBool stable;
804
0
    DirProp newProp;
805
0
    pOpening=&bd->openings[openIdx];
806
0
    direction=(UBiDiDirection)(pLastIsoRun->level&1);
807
0
    stable=TRUE;            /* assume stable until proved otherwise */
808
0
809
0
    /* The stable flag is set when brackets are paired and their
810
0
       level is resolved and cannot be changed by what will be
811
0
       found later in the source string.
812
0
       An unstable match can occur only when applying N0c, where
813
0
       the resolved level depends on the preceding context, and
814
0
       this context may be affected by text occurring later.
815
0
       Example: RTL paragraph containing:  abc[(latin) HEBREW]
816
0
       When the closing parenthesis is encountered, it appears
817
0
       that N0c1 must be applied since 'abc' sets an opposite
818
0
       direction context and both parentheses receive level 2.
819
0
       However, when the closing square bracket is processed,
820
0
       N0b applies because of 'HEBREW' being included within the
821
0
       brackets, thus the square brackets are treated like R and
822
0
       receive level 1. However, this changes the preceding
823
0
       context of the opening parenthesis, and it now appears
824
0
       that N0c2 must be applied to the parentheses rather than
825
0
       N0c1. */
826
0
827
0
    if((direction==0 && pOpening->flags&FOUND_L) ||
828
0
       (direction==1 && pOpening->flags&FOUND_R)) { /* N0b */
829
0
        newProp=direction;
830
0
    }
831
0
    else if(pOpening->flags&(FOUND_L|FOUND_R)) {    /* N0c */
832
0
        /* it is stable if there is no containing pair or in
833
0
           conditions too complicated and not worth checking */
834
0
        stable=(openIdx==pLastIsoRun->start);
835
0
        if(direction!=pOpening->contextDir)
836
0
            newProp=pOpening->contextDir;           /* N0c1 */
837
0
        else
838
0
            newProp=direction;                      /* N0c2 */
839
0
    } else {
840
0
        /* forget this and any brackets nested within this pair */
841
0
        pLastIsoRun->limit=openIdx;
842
0
        return ON;                                  /* N0d */
843
0
    }
844
0
    bd->pBiDi->dirProps[pOpening->position]=newProp;
845
0
    bd->pBiDi->dirProps[position]=newProp;
846
0
    /* Update nested N0c pairs that may be affected */
847
0
    fixN0c(bd, openIdx, pOpening->position, newProp);
848
0
    if(stable) {
849
0
        pLastIsoRun->limit=openIdx; /* forget any brackets nested within this pair */
850
0
        /* remove lower located synonyms if any */
851
0
        while(pLastIsoRun->limit>pLastIsoRun->start &&
852
0
              bd->openings[pLastIsoRun->limit-1].position==pOpening->position)
853
0
            pLastIsoRun->limit--;
854
0
    } else {
855
0
        int32_t k;
856
0
        pOpening->match=-position;
857
0
        /* neutralize lower located synonyms if any */
858
0
        k=openIdx-1;
859
0
        while(k>=pLastIsoRun->start &&
860
0
              bd->openings[k].position==pOpening->position)
861
0
            bd->openings[k--].match=0;
862
0
        /* neutralize any unmatched opening between the current pair;
863
0
           this will also neutralize higher located synonyms if any */
864
0
        for(k=openIdx+1; k<pLastIsoRun->limit; k++) {
865
0
            qOpening=&bd->openings[k];
866
0
            if(qOpening->position>=position)
867
0
                break;
868
0
            if(qOpening->match>0)
869
0
                qOpening->match=0;
870
0
        }
871
0
    }
872
0
    return newProp;
873
0
}
874
875
/* handle strong characters, digits and candidates for closing brackets */
876
static UBool                            /* return TRUE if success */
877
0
bracketProcessChar(BracketData *bd, int32_t position) {
878
0
    IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
879
0
    DirProp *dirProps, dirProp, newProp;
880
0
    UBiDiLevel level;
881
0
    dirProps=bd->pBiDi->dirProps;
882
0
    dirProp=dirProps[position];
883
0
    if(dirProp==ON) {
884
0
        UChar c, match;
885
0
        int32_t idx;
886
0
        /* First see if it is a matching closing bracket. Hopefully, this is
887
0
           more efficient than checking if it is a closing bracket at all */
888
0
        c=bd->pBiDi->text[position];
889
0
        for(idx=pLastIsoRun->limit-1; idx>=pLastIsoRun->start; idx--) {
890
0
            if(bd->openings[idx].match!=c)
891
0
                continue;
892
0
            /* We have a match */
893
0
            newProp=bracketProcessClosing(bd, idx, position);
894
0
            if(newProp==ON) {           /* N0d */
895
0
                c=0;        /* prevent handling as an opening */
896
0
                break;
897
0
            }
898
0
            pLastIsoRun->lastBase=ON;
899
0
            pLastIsoRun->contextDir=(UBiDiDirection)newProp;
900
0
            pLastIsoRun->contextPos=position;
901
0
            level=bd->pBiDi->levels[position];
902
0
            if(level&UBIDI_LEVEL_OVERRIDE) {    /* X4, X5 */
903
0
                uint16_t flag;
904
0
                int32_t i;
905
0
                newProp=level&1;
906
0
                pLastIsoRun->lastStrong=newProp;
907
0
                flag=DIRPROP_FLAG(newProp);
908
0
                for(i=pLastIsoRun->start; i<idx; i++)
909
0
                    bd->openings[i].flags|=flag;
910
0
                /* matching brackets are not overridden by LRO/RLO */
911
0
                bd->pBiDi->levels[position]&=~UBIDI_LEVEL_OVERRIDE;
912
0
            }
913
0
            /* matching brackets are not overridden by LRO/RLO */
914
0
            bd->pBiDi->levels[bd->openings[idx].position]&=~UBIDI_LEVEL_OVERRIDE;
915
0
            return TRUE;
916
0
        }
917
0
        /* We get here only if the ON character is not a matching closing
918
0
           bracket or it is a case of N0d */
919
0
        /* Now see if it is an opening bracket */
920
0
        if(c)
921
0
            match=u_getBidiPairedBracket(c);    /* get the matching char */
922
0
        else
923
0
            match=0;
924
0
        if(match!=c &&                  /* has a matching char */
925
0
           ubidi_getPairedBracketType(c)==U_BPT_OPEN) { /* opening bracket */
926
0
            /* special case: process synonyms
927
0
               create an opening entry for each synonym */
928
0
            if(match==0x232A) {     /* RIGHT-POINTING ANGLE BRACKET */
929
0
                if(!bracketAddOpening(bd, 0x3009, position))
930
0
                    return FALSE;
931
0
            }
932
0
            else if(match==0x3009) {         /* RIGHT ANGLE BRACKET */
933
0
                if(!bracketAddOpening(bd, 0x232A, position))
934
0
                    return FALSE;
935
0
            }
936
0
            if(!bracketAddOpening(bd, match, position))
937
0
                return FALSE;
938
0
        }
939
0
    }
940
0
    level=bd->pBiDi->levels[position];
941
0
    if(level&UBIDI_LEVEL_OVERRIDE) {    /* X4, X5 */
942
0
        newProp=level&1;
943
0
        if(dirProp!=S && dirProp!=WS && dirProp!=ON)
944
0
            dirProps[position]=newProp;
945
0
        pLastIsoRun->lastBase=newProp;
946
0
        pLastIsoRun->lastStrong=newProp;
947
0
        pLastIsoRun->contextDir=(UBiDiDirection)newProp;
948
0
        pLastIsoRun->contextPos=position;
949
0
    }
950
0
    else if(dirProp<=R || dirProp==AL) {
951
0
        newProp=DIR_FROM_STRONG(dirProp);
952
0
        pLastIsoRun->lastBase=dirProp;
953
0
        pLastIsoRun->lastStrong=dirProp;
954
0
        pLastIsoRun->contextDir=(UBiDiDirection)newProp;
955
0
        pLastIsoRun->contextPos=position;
956
0
    }
957
0
    else if(dirProp==EN) {
958
0
        pLastIsoRun->lastBase=EN;
959
0
        if(pLastIsoRun->lastStrong==L) {
960
0
            newProp=L;                  /* W7 */
961
0
            if(!bd->isNumbersSpecial)
962
0
                dirProps[position]=ENL;
963
0
            pLastIsoRun->contextDir=(UBiDiDirection)L;
964
0
            pLastIsoRun->contextPos=position;
965
0
        }
966
0
        else {
967
0
            newProp=R;                  /* N0 */
968
0
            if(pLastIsoRun->lastStrong==AL)
969
0
                dirProps[position]=AN;  /* W2 */
970
0
            else
971
0
                dirProps[position]=ENR;
972
0
            pLastIsoRun->contextDir=(UBiDiDirection)R;
973
0
            pLastIsoRun->contextPos=position;
974
0
        }
975
0
    }
976
0
    else if(dirProp==AN) {
977
0
        newProp=R;                      /* N0 */
978
0
        pLastIsoRun->lastBase=AN;
979
0
        pLastIsoRun->contextDir=(UBiDiDirection)R;
980
0
        pLastIsoRun->contextPos=position;
981
0
    }
982
0
    else if(dirProp==NSM) {
983
0
        /* if the last real char was ON, change NSM to ON so that it
984
0
           will stay ON even if the last real char is a bracket which
985
0
           may be changed to L or R */
986
0
        newProp=pLastIsoRun->lastBase;
987
0
        if(newProp==ON)
988
0
            dirProps[position]=newProp;
989
0
    }
990
0
    else {
991
0
        newProp=dirProp;
992
0
        pLastIsoRun->lastBase=dirProp;
993
0
    }
994
0
    if(newProp<=R || newProp==AL) {
995
0
        int32_t i;
996
0
        uint16_t flag=DIRPROP_FLAG(DIR_FROM_STRONG(newProp));
997
0
        for(i=pLastIsoRun->start; i<pLastIsoRun->limit; i++)
998
0
            if(position>bd->openings[i].position)
999
0
                bd->openings[i].flags|=flag;
1000
0
    }
1001
0
    return TRUE;
1002
0
}
1003
1004
/* perform (X1)..(X9) ------------------------------------------------------- */
1005
1006
/* determine if the text is mixed-directional or single-directional */
1007
static UBiDiDirection
1008
0
directionFromFlags(UBiDi *pBiDi) {
1009
0
    Flags flags=pBiDi->flags;
1010
0
    /* if the text contains AN and neutrals, then some neutrals may become RTL */
1011
0
    if(!(flags&MASK_RTL || ((flags&DIRPROP_FLAG(AN)) && (flags&MASK_POSSIBLE_N)))) {
1012
0
        return UBIDI_LTR;
1013
0
    } else if(!(flags&MASK_LTR)) {
1014
0
        return UBIDI_RTL;
1015
0
    } else {
1016
0
        return UBIDI_MIXED;
1017
0
    }
1018
0
}
1019
1020
/*
1021
 * Resolve the explicit levels as specified by explicit embedding codes.
1022
 * Recalculate the flags to have them reflect the real properties
1023
 * after taking the explicit embeddings into account.
1024
 *
1025
 * The BiDi algorithm is designed to result in the same behavior whether embedding
1026
 * levels are externally specified (from "styled text", supposedly the preferred
1027
 * method) or set by explicit embedding codes (LRx, RLx, PDF, FSI, PDI) in the plain text.
1028
 * That is why (X9) instructs to remove all not-isolate explicit codes (and BN).
1029
 * However, in a real implementation, the removal of these codes and their index
1030
 * positions in the plain text is undesirable since it would result in
1031
 * reallocated, reindexed text.
1032
 * Instead, this implementation leaves the codes in there and just ignores them
1033
 * in the subsequent processing.
1034
 * In order to get the same reordering behavior, positions with a BN or a not-isolate
1035
 * explicit embedding code just get the same level assigned as the last "real"
1036
 * character.
1037
 *
1038
 * Some implementations, not this one, then overwrite some of these
1039
 * directionality properties at "real" same-level-run boundaries by
1040
 * L or R codes so that the resolution of weak types can be performed on the
1041
 * entire paragraph at once instead of having to parse it once more and
1042
 * perform that resolution on same-level-runs.
1043
 * This limits the scope of the implicit rules in effectively
1044
 * the same way as the run limits.
1045
 *
1046
 * Instead, this implementation does not modify these codes, except for
1047
 * paired brackets whose properties (ON) may be replaced by L or R.
1048
 * On one hand, the paragraph has to be scanned for same-level-runs, but
1049
 * on the other hand, this saves another loop to reset these codes,
1050
 * or saves making and modifying a copy of dirProps[].
1051
 *
1052
 *
1053
 * Note that (Pn) and (Xn) changed significantly from version 4 of the BiDi algorithm.
1054
 *
1055
 *
1056
 * Handling the stack of explicit levels (Xn):
1057
 *
1058
 * With the BiDi stack of explicit levels, as pushed with each
1059
 * LRE, RLE, LRO, RLO, LRI, RLI and FSI and popped with each PDF and PDI,
1060
 * the explicit level must never exceed UBIDI_MAX_EXPLICIT_LEVEL.
1061
 *
1062
 * In order to have a correct push-pop semantics even in the case of overflows,
1063
 * overflow counters and a valid isolate counter are used as described in UAX#9
1064
 * section 3.3.2 "Explicit Levels and Directions".
1065
 *
1066
 * This implementation assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd.
1067
 *
1068
 * Returns normally the direction; -1 if there was a memory shortage
1069
 *
1070
 */
1071
static UBiDiDirection
1072
0
resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
1073
0
    DirProp *dirProps=pBiDi->dirProps;
1074
0
    UBiDiLevel *levels=pBiDi->levels;
1075
0
    const UChar *text=pBiDi->text;
1076
0
1077
0
    int32_t i=0, length=pBiDi->length;
1078
0
    Flags flags=pBiDi->flags;       /* collect all directionalities in the text */
1079
0
    DirProp dirProp;
1080
0
    UBiDiLevel level=GET_PARALEVEL(pBiDi, 0);
1081
0
    UBiDiDirection direction;
1082
0
    pBiDi->isolateCount=0;
1083
0
1084
0
    if(U_FAILURE(*pErrorCode)) { return UBIDI_LTR; }
1085
0
1086
0
    /* determine if the text is mixed-directional or single-directional */
1087
0
    direction=directionFromFlags(pBiDi);
1088
0
1089
0
    /* we may not need to resolve any explicit levels */
1090
0
    if((direction!=UBIDI_MIXED)) {
1091
0
        /* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
1092
0
        return direction;
1093
0
    }
1094
0
    if(pBiDi->reorderingMode > UBIDI_REORDER_LAST_LOGICAL_TO_VISUAL) {
1095
0
        /* inverse BiDi: mixed, but all characters are at the same embedding level */
1096
0
        /* set all levels to the paragraph level */
1097
0
        int32_t paraIndex, start, limit;
1098
0
        for(paraIndex=0; paraIndex<pBiDi->paraCount; paraIndex++) {
1099
0
            if(paraIndex==0)
1100
0
                start=0;
1101
0
            else
1102
0
                start=pBiDi->paras[paraIndex-1].limit;
1103
0
            limit=pBiDi->paras[paraIndex].limit;
1104
0
            level=pBiDi->paras[paraIndex].level;
1105
0
            for(i=start; i<limit; i++)
1106
0
                levels[i]=level;
1107
0
        }
1108
0
        return direction;   /* no bracket matching for inverse BiDi */
1109
0
    }
1110
0
    if(!(flags&(MASK_EXPLICIT|MASK_ISO))) {
1111
0
        /* no embeddings, set all levels to the paragraph level */
1112
0
        /* we still have to perform bracket matching */
1113
0
        int32_t paraIndex, start, limit;
1114
0
        BracketData bracketData;
1115
0
        bracketInit(pBiDi, &bracketData);
1116
0
        for(paraIndex=0; paraIndex<pBiDi->paraCount; paraIndex++) {
1117
0
            if(paraIndex==0)
1118
0
                start=0;
1119
0
            else
1120
0
                start=pBiDi->paras[paraIndex-1].limit;
1121
0
            limit=pBiDi->paras[paraIndex].limit;
1122
0
            level=pBiDi->paras[paraIndex].level;
1123
0
            for(i=start; i<limit; i++) {
1124
0
                levels[i]=level;
1125
0
                dirProp=dirProps[i];
1126
0
                if(dirProp==BN)
1127
0
                    continue;
1128
0
                if(dirProp==B) {
1129
0
                    if((i+1)<length) {
1130
0
                        if(text[i]==CR && text[i+1]==LF)
1131
0
                            continue;   /* skip CR when followed by LF */
1132
0
                        bracketProcessB(&bracketData, level);
1133
0
                    }
1134
0
                    continue;
1135
0
                }
1136
0
                if(!bracketProcessChar(&bracketData, i)) {
1137
0
                    *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
1138
0
                    return UBIDI_LTR;
1139
0
                }
1140
0
            }
1141
0
        }
1142
0
        return direction;
1143
0
    }
1144
0
    {
1145
0
        /* continue to perform (Xn) */
1146
0
1147
0
        /* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
1148
0
        /* both variables may carry the UBIDI_LEVEL_OVERRIDE flag to indicate the override status */
1149
0
        UBiDiLevel embeddingLevel=level, newLevel;
1150
0
        UBiDiLevel previousLevel=level;     /* previous level for regular (not CC) characters */
1151
0
        int32_t lastCcPos=0;                /* index of last effective LRx,RLx, PDx */
1152
0
1153
0
        /* The following stack remembers the embedding level and the ISOLATE flag of level runs.
1154
0
           stackLast points to its current entry. */
1155
0
        uint16_t stack[UBIDI_MAX_EXPLICIT_LEVEL+2];   /* we never push anything >=UBIDI_MAX_EXPLICIT_LEVEL
1156
0
                                                        but we need one more entry as base */
1157
0
        uint32_t stackLast=0;
1158
0
        int32_t overflowIsolateCount=0;
1159
0
        int32_t overflowEmbeddingCount=0;
1160
0
        int32_t validIsolateCount=0;
1161
0
        BracketData bracketData;
1162
0
        bracketInit(pBiDi, &bracketData);
1163
0
        stack[0]=level;     /* initialize base entry to para level, no override, no isolate */
1164
0
1165
0
        /* recalculate the flags */
1166
0
        flags=0;
1167
0
1168
0
        for(i=0; i<length; ++i) {
1169
0
            dirProp=dirProps[i];
1170
0
            switch(dirProp) {
1171
0
            case LRE:
1172
0
            case RLE:
1173
0
            case LRO:
1174
0
            case RLO:
1175
0
                /* (X2, X3, X4, X5) */
1176
0
                flags|=DIRPROP_FLAG(BN);
1177
0
                levels[i]=previousLevel;
1178
0
                if (dirProp==LRE || dirProp==LRO)
1179
0
                    /* least greater even level */
1180
0
                    newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1));
1181
0
                else
1182
0
                    /* least greater odd level */
1183
0
                    newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1);
1184
0
                if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 &&
1185
0
                                                         overflowEmbeddingCount==0) {
1186
0
                    lastCcPos=i;
1187
0
                    embeddingLevel=newLevel;
1188
0
                    if(dirProp==LRO || dirProp==RLO)
1189
0
                        embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
1190
0
                    stackLast++;
1191
0
                    stack[stackLast]=embeddingLevel;
1192
0
                    /* we don't need to set UBIDI_LEVEL_OVERRIDE off for LRE and RLE
1193
0
                       since this has already been done for newLevel which is
1194
0
                       the source for embeddingLevel.
1195
0
                     */
1196
0
                } else {
1197
0
                    if(overflowIsolateCount==0)
1198
0
                        overflowEmbeddingCount++;
1199
0
                }
1200
0
                break;
1201
0
            case PDF:
1202
0
                /* (X7) */
1203
0
                flags|=DIRPROP_FLAG(BN);
1204
0
                levels[i]=previousLevel;
1205
0
                /* handle all the overflow cases first */
1206
0
                if(overflowIsolateCount) {
1207
0
                    break;
1208
0
                }
1209
0
                if(overflowEmbeddingCount) {
1210
0
                    overflowEmbeddingCount--;
1211
0
                    break;
1212
0
                }
1213
0
                if(stackLast>0 && stack[stackLast]<ISOLATE) {   /* not an isolate entry */
1214
0
                    lastCcPos=i;
1215
0
                    stackLast--;
1216
0
                    embeddingLevel=(UBiDiLevel)stack[stackLast];
1217
0
                }
1218
0
                break;
1219
0
            case LRI:
1220
0
            case RLI:
1221
0
                flags|=(DIRPROP_FLAG(ON)|DIRPROP_FLAG_LR(embeddingLevel));
1222
0
                levels[i]=NO_OVERRIDE(embeddingLevel);
1223
0
                if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
1224
0
                    bracketProcessBoundary(&bracketData, lastCcPos,
1225
0
                                           previousLevel, embeddingLevel);
1226
0
                    flags|=DIRPROP_FLAG_MULTI_RUNS;
1227
0
                }
1228
0
                previousLevel=embeddingLevel;
1229
0
                /* (X5a, X5b) */
1230
0
                if(dirProp==LRI)
1231
0
                    /* least greater even level */
1232
0
                    newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1));
1233
0
                else
1234
0
                    /* least greater odd level */
1235
0
                    newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1);
1236
0
                if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 &&
1237
0
                                                         overflowEmbeddingCount==0) {
1238
0
                    flags|=DIRPROP_FLAG(dirProp);
1239
0
                    lastCcPos=i;
1240
0
                    validIsolateCount++;
1241
0
                    if(validIsolateCount>pBiDi->isolateCount)
1242
0
                        pBiDi->isolateCount=validIsolateCount;
1243
0
                    embeddingLevel=newLevel;
1244
0
                    /* we can increment stackLast without checking because newLevel
1245
0
                       will exceed UBIDI_MAX_EXPLICIT_LEVEL before stackLast overflows */
1246
0
                    stackLast++;
1247
0
                    stack[stackLast]=embeddingLevel+ISOLATE;
1248
0
                    bracketProcessLRI_RLI(&bracketData, embeddingLevel);
1249
0
                } else {
1250
0
                    /* make it WS so that it is handled by adjustWSLevels() */
1251
0
                    dirProps[i]=WS;
1252
0
                    overflowIsolateCount++;
1253
0
                }
1254
0
                break;
1255
0
            case PDI:
1256
0
                if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
1257
0
                    bracketProcessBoundary(&bracketData, lastCcPos,
1258
0
                                           previousLevel, embeddingLevel);
1259
0
                    flags|=DIRPROP_FLAG_MULTI_RUNS;
1260
0
                }
1261
0
                /* (X6a) */
1262
0
                if(overflowIsolateCount) {
1263
0
                    overflowIsolateCount--;
1264
0
                    /* make it WS so that it is handled by adjustWSLevels() */
1265
0
                    dirProps[i]=WS;
1266
0
                }
1267
0
                else if(validIsolateCount) {
1268
0
                    flags|=DIRPROP_FLAG(PDI);
1269
0
                    lastCcPos=i;
1270
0
                    overflowEmbeddingCount=0;
1271
0
                    while(stack[stackLast]<ISOLATE) /* pop embedding entries */
1272
0
                        stackLast--;                /* until the last isolate entry */
1273
0
                    stackLast--;                    /* pop also the last isolate entry */
1274
0
                    validIsolateCount--;
1275
0
                    bracketProcessPDI(&bracketData);
1276
0
                } else
1277
0
                    /* make it WS so that it is handled by adjustWSLevels() */
1278
0
                    dirProps[i]=WS;
1279
0
                embeddingLevel=(UBiDiLevel)stack[stackLast]&~ISOLATE;
1280
0
                flags|=(DIRPROP_FLAG(ON)|DIRPROP_FLAG_LR(embeddingLevel));
1281
0
                previousLevel=embeddingLevel;
1282
0
                levels[i]=NO_OVERRIDE(embeddingLevel);
1283
0
                break;
1284
0
            case B:
1285
0
                flags|=DIRPROP_FLAG(B);
1286
0
                levels[i]=GET_PARALEVEL(pBiDi, i);
1287
0
                if((i+1)<length) {
1288
0
                    if(text[i]==CR && text[i+1]==LF)
1289
0
                        break;          /* skip CR when followed by LF */
1290
0
                    overflowEmbeddingCount=overflowIsolateCount=0;
1291
0
                    validIsolateCount=0;
1292
0
                    stackLast=0;
1293
0
                    previousLevel=embeddingLevel=GET_PARALEVEL(pBiDi, i+1);
1294
0
                    stack[0]=embeddingLevel; /* initialize base entry to para level, no override, no isolate */
1295
0
                    bracketProcessB(&bracketData, embeddingLevel);
1296
0
                }
1297
0
                break;
1298
0
            case BN:
1299
0
                /* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
1300
0
                /* they will get their levels set correctly in adjustWSLevels() */
1301
0
                levels[i]=previousLevel;
1302
0
                flags|=DIRPROP_FLAG(BN);
1303
0
                break;
1304
0
            default:
1305
0
                /* all other types are normal characters and get the "real" level */
1306
0
                if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
1307
0
                    bracketProcessBoundary(&bracketData, lastCcPos,
1308
0
                                           previousLevel, embeddingLevel);
1309
0
                    flags|=DIRPROP_FLAG_MULTI_RUNS;
1310
0
                    if(embeddingLevel&UBIDI_LEVEL_OVERRIDE)
1311
0
                        flags|=DIRPROP_FLAG_O(embeddingLevel);
1312
0
                    else
1313
0
                        flags|=DIRPROP_FLAG_E(embeddingLevel);
1314
0
                }
1315
0
                previousLevel=embeddingLevel;
1316
0
                levels[i]=embeddingLevel;
1317
0
                if(!bracketProcessChar(&bracketData, i))
1318
0
                    return (UBiDiDirection)-1;
1319
0
                /* the dirProp may have been changed in bracketProcessChar() */
1320
0
                flags|=DIRPROP_FLAG(dirProps[i]);
1321
0
                break;
1322
0
            }
1323
0
        }
1324
0
        if(flags&MASK_EMBEDDING)
1325
0
            flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
1326
0
        if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B)))
1327
0
            flags|=DIRPROP_FLAG(L);
1328
0
        /* again, determine if the text is mixed-directional or single-directional */
1329
0
        pBiDi->flags=flags;
1330
0
        direction=directionFromFlags(pBiDi);
1331
0
    }
1332
0
    return direction;
1333
0
}
1334
1335
/*
1336
 * Use a pre-specified embedding levels array:
1337
 *
1338
 * Adjust the directional properties for overrides (->LEVEL_OVERRIDE),
1339
 * ignore all explicit codes (X9),
1340
 * and check all the preset levels.
1341
 *
1342
 * Recalculate the flags to have them reflect the real properties
1343
 * after taking the explicit embeddings into account.
1344
 */
1345
static UBiDiDirection
1346
0
checkExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
1347
0
    DirProp *dirProps=pBiDi->dirProps;
1348
0
    UBiDiLevel *levels=pBiDi->levels;
1349
0
    int32_t isolateCount=0;
1350
0
1351
0
    int32_t length=pBiDi->length;
1352
0
    Flags flags=0;  /* collect all directionalities in the text */
1353
0
    pBiDi->isolateCount=0;
1354
0
1355
0
    int32_t currentParaIndex = 0;
1356
0
    int32_t currentParaLimit = pBiDi->paras[0].limit;
1357
0
    int32_t currentParaLevel = pBiDi->paraLevel;
1358
0
1359
0
    for(int32_t i=0; i<length; ++i) {
1360
0
        UBiDiLevel level=levels[i];
1361
0
        DirProp dirProp=dirProps[i];
1362
0
        if(dirProp==LRI || dirProp==RLI) {
1363
0
            isolateCount++;
1364
0
            if(isolateCount>pBiDi->isolateCount)
1365
0
                pBiDi->isolateCount=isolateCount;
1366
0
        }
1367
0
        else if(dirProp==PDI)
1368
0
            isolateCount--;
1369
0
        else if(dirProp==B)
1370
0
            isolateCount=0;
1371
0
1372
0
        // optimized version of  int32_t currentParaLevel = GET_PARALEVEL(pBiDi, i);
1373
0
        if (pBiDi->defaultParaLevel != 0 &&
1374
0
                i == currentParaLimit && (currentParaIndex + 1) < pBiDi->paraCount) {
1375
0
            currentParaLevel = pBiDi->paras[++currentParaIndex].level;
1376
0
            currentParaLimit = pBiDi->paras[currentParaIndex].limit;
1377
0
        }
1378
0
1379
0
        UBiDiLevel overrideFlag = level & UBIDI_LEVEL_OVERRIDE;
1380
0
        level &= ~UBIDI_LEVEL_OVERRIDE;
1381
0
        if (level < currentParaLevel || UBIDI_MAX_EXPLICIT_LEVEL < level) {
1382
0
            if (level == 0) {
1383
0
                if (dirProp == B) {
1384
0
                    // Paragraph separators are ok with explicit level 0.
1385
0
                    // Prevents reordering of paragraphs.
1386
0
                } else {
1387
0
                    // Treat explicit level 0 as a wildcard for the paragraph level.
1388
0
                    // Avoid making the caller guess what the paragraph level would be.
1389
0
                    level = (UBiDiLevel)currentParaLevel;
1390
0
                    levels[i] = level | overrideFlag;
1391
0
                }
1392
0
            } else {
1393
0
                // 1 <= level < currentParaLevel or UBIDI_MAX_EXPLICIT_LEVEL < level
1394
0
                /* level out of bounds */
1395
0
                *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
1396
0
                return UBIDI_LTR;
1397
0
            }
1398
0
        }
1399
0
        if (overrideFlag != 0) {
1400
0
            /* keep the override flag in levels[i] but adjust the flags */
1401
0
            flags|=DIRPROP_FLAG_O(level);
1402
0
        } else {
1403
0
            /* set the flags */
1404
0
            flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG(dirProp);
1405
0
        }
1406
0
    }
1407
0
    if(flags&MASK_EMBEDDING)
1408
0
        flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
1409
0
    /* determine if the text is mixed-directional or single-directional */
1410
0
    pBiDi->flags=flags;
1411
0
    return directionFromFlags(pBiDi);
1412
0
}
1413
1414
/******************************************************************
1415
 The Properties state machine table
1416
*******************************************************************
1417
1418
 All table cells are 8 bits:
1419
      bits 0..4:  next state
1420
      bits 5..7:  action to perform (if > 0)
1421
1422
 Cells may be of format "n" where n represents the next state
1423
 (except for the rightmost column).
1424
 Cells may also be of format "s(x,y)" where x represents an action
1425
 to perform and y represents the next state.
1426
1427
*******************************************************************
1428
 Definitions and type for properties state table
1429
*******************************************************************
1430
*/
1431
0
#define IMPTABPROPS_COLUMNS 16
1432
0
#define IMPTABPROPS_RES (IMPTABPROPS_COLUMNS - 1)
1433
0
#define GET_STATEPROPS(cell) ((cell)&0x1f)
1434
0
#define GET_ACTIONPROPS(cell) ((cell)>>5)
1435
#define s(action, newState) ((uint8_t)(newState+(action<<5)))
1436
1437
static const uint8_t groupProp[] =          /* dirProp regrouped */
1438
{
1439
/*  L   R   EN  ES  ET  AN  CS  B   S   WS  ON  LRE LRO AL  RLE RLO PDF NSM BN  FSI LRI RLI PDI ENL ENR */
1440
    0,  1,  2,  7,  8,  3,  9,  6,  5,  4,  4,  10, 10, 12, 10, 10, 10, 11, 10, 4,  4,  4,  4,  13, 14
1441
};
1442
enum { DirProp_L=0, DirProp_R=1, DirProp_EN=2, DirProp_AN=3, DirProp_ON=4, DirProp_S=5, DirProp_B=6 }; /* reduced dirProp */
1443
1444
/******************************************************************
1445
1446
      PROPERTIES  STATE  TABLE
1447
1448
 In table impTabProps,
1449
      - the ON column regroups ON and WS, FSI, RLI, LRI and PDI
1450
      - the BN column regroups BN, LRE, RLE, LRO, RLO, PDF
1451
      - the Res column is the reduced property assigned to a run
1452
1453
 Action 1: process current run1, init new run1
1454
        2: init new run2
1455
        3: process run1, process run2, init new run1
1456
        4: process run1, set run1=run2, init new run2
1457
1458
 Notes:
1459
  1) This table is used in resolveImplicitLevels().
1460
  2) This table triggers actions when there is a change in the Bidi
1461
     property of incoming characters (action 1).
1462
  3) Most such property sequences are processed immediately (in
1463
     fact, passed to processPropertySeq().
1464
  4) However, numbers are assembled as one sequence. This means
1465
     that undefined situations (like CS following digits, until
1466
     it is known if the next char will be a digit) are held until
1467
     following chars define them.
1468
     Example: digits followed by CS, then comes another CS or ON;
1469
              the digits will be processed, then the CS assigned
1470
              as the start of an ON sequence (action 3).
1471
  5) There are cases where more than one sequence must be
1472
     processed, for instance digits followed by CS followed by L:
1473
     the digits must be processed as one sequence, and the CS
1474
     must be processed as an ON sequence, all this before starting
1475
     assembling chars for the opening L sequence.
1476
1477
1478
*/
1479
static const uint8_t impTabProps[][IMPTABPROPS_COLUMNS] =
1480
{
1481
/*                        L ,     R ,    EN ,    AN ,    ON ,     S ,     B ,    ES ,    ET ,    CS ,    BN ,   NSM ,    AL ,   ENL ,   ENR , Res */
1482
/* 0 Init        */ {     1 ,     2 ,     4 ,     5 ,     7 ,    15 ,    17 ,     7 ,     9 ,     7 ,     0 ,     7 ,     3 ,    18 ,    21 , DirProp_ON },
1483
/* 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),s(1,18),s(1,21),  DirProp_L },
1484
/* 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),s(1,18),s(1,21),  DirProp_R },
1485
/* 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 ,s(1,18),s(1,21),  DirProp_R },
1486
/* 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),    18 ,    21 , DirProp_EN },
1487
/* 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),s(1,18),s(1,21), DirProp_AN },
1488
/* 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),    18 ,    21 , DirProp_AN },
1489
/* 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),s(1,18),s(1,21), DirProp_ON },
1490
/* 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),s(1,18),s(1,21), DirProp_ON },
1491
/* 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),    18 ,    21 , DirProp_ON },
1492
/*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),    18 ,    21 , DirProp_EN },
1493
/*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),    18 ,    21 , DirProp_EN },
1494
/*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),s(3,18),s(3,21), DirProp_AN },
1495
/*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),    18 ,    21 , DirProp_AN },
1496
/*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),s(4,18),s(4,21), DirProp_ON },
1497
/*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),s(1,18),s(1,21),  DirProp_S },
1498
/*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),s(1,18),s(1,21),  DirProp_S },
1499
/*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),s(1,18),s(1,21),  DirProp_B },
1500
/*18 ENL         */ { s(1,1), s(1,2),    18 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,19),    20 ,s(2,19),    18 ,    18 , s(1,3),    18 ,    21 ,  DirProp_L },
1501
/*19 ENL+ES/CS   */ { s(3,1), s(3,2),    18 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    19 , s(4,7), s(3,3),    18 ,    21 ,  DirProp_L },
1502
/*20 ENL+ET      */ { s(1,1), s(1,2),    18 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7),    20 , s(1,7),    20 ,    20 , s(1,3),    18 ,    21 ,  DirProp_L },
1503
/*21 ENR         */ { s(1,1), s(1,2),    21 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,22),    23 ,s(2,22),    21 ,    21 , s(1,3),    18 ,    21 , DirProp_AN },
1504
/*22 ENR+ES/CS   */ { s(3,1), s(3,2),    21 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    22 , s(4,7), s(3,3),    18 ,    21 , DirProp_AN },
1505
/*23 ENR+ET      */ { s(1,1), s(1,2),    21 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7),    23 , s(1,7),    23 ,    23 , s(1,3),    18 ,    21 , DirProp_AN }
1506
};
1507
1508
/*  we must undef macro s because the levels tables have a different
1509
 *  structure (4 bits for action and 4 bits for next state.
1510
 */
1511
#undef s
1512
1513
/******************************************************************
1514
 The levels state machine tables
1515
*******************************************************************
1516
1517
 All table cells are 8 bits:
1518
      bits 0..3:  next state
1519
      bits 4..7:  action to perform (if > 0)
1520
1521
 Cells may be of format "n" where n represents the next state
1522
 (except for the rightmost column).
1523
 Cells may also be of format "s(x,y)" where x represents an action
1524
 to perform and y represents the next state.
1525
1526
 This format limits each table to 16 states each and to 15 actions.
1527
1528
*******************************************************************
1529
 Definitions and type for levels state tables
1530
*******************************************************************
1531
*/
1532
0
#define IMPTABLEVELS_COLUMNS (DirProp_B + 2)
1533
0
#define IMPTABLEVELS_RES (IMPTABLEVELS_COLUMNS - 1)
1534
0
#define GET_STATE(cell) ((cell)&0x0f)
1535
0
#define GET_ACTION(cell) ((cell)>>4)
1536
#define s(action, newState) ((uint8_t)(newState+(action<<4)))
1537
1538
typedef uint8_t ImpTab[][IMPTABLEVELS_COLUMNS];
1539
typedef uint8_t ImpAct[];
1540
1541
/* FOOD FOR THOUGHT: each ImpTab should have its associated ImpAct,
1542
 * instead of having a pair of ImpTab and a pair of ImpAct.
1543
 */
1544
typedef struct ImpTabPair {
1545
    const void * pImpTab[2];
1546
    const void * pImpAct[2];
1547
} ImpTabPair;
1548
1549
/******************************************************************
1550
1551
      LEVELS  STATE  TABLES
1552
1553
 In all levels state tables,
1554
      - state 0 is the initial state
1555
      - the Res column is the increment to add to the text level
1556
        for this property sequence.
1557
1558
 The impAct arrays for each table of a pair map the local action
1559
 numbers of the table to the total list of actions. For instance,
1560
 action 2 in a given table corresponds to the action number which
1561
 appears in entry [2] of the impAct array for that table.
1562
 The first entry of all impAct arrays must be 0.
1563
1564
 Action 1: init conditional sequence
1565
        2: prepend conditional sequence to current sequence
1566
        3: set ON sequence to new level - 1
1567
        4: init EN/AN/ON sequence
1568
        5: fix EN/AN/ON sequence followed by R
1569
        6: set previous level sequence to level 2
1570
1571
 Notes:
1572
  1) These tables are used in processPropertySeq(). The input
1573
     is property sequences as determined by resolveImplicitLevels.
1574
  2) Most such property sequences are processed immediately
1575
     (levels are assigned).
1576
  3) However, some sequences cannot be assigned a final level till
1577
     one or more following sequences are received. For instance,
1578
     ON following an R sequence within an even-level paragraph.
1579
     If the following sequence is R, the ON sequence will be
1580
     assigned basic run level+1, and so will the R sequence.
1581
  4) S is generally handled like ON, since its level will be fixed
1582
     to paragraph level in adjustWSLevels().
1583
1584
*/
1585
1586
static const ImpTab impTabL_DEFAULT =   /* Even paragraph level */
1587
/*  In this table, conditional sequences receive the lower possible level
1588
    until proven otherwise.
1589
*/
1590
{
1591
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1592
/* 0 : init       */ {     0 ,     1 ,     0 ,     2 ,     0 ,     0 ,     0 ,  0 },
1593
/* 1 : R          */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  1 },
1594
/* 2 : AN         */ {     0 ,     1 ,     0 ,     2 , s(1,5), s(1,5),     0 ,  2 },
1595
/* 3 : R+EN/AN    */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  2 },
1596
/* 4 : R+ON       */ {     0 , s(2,1), s(3,3), s(3,3),     4 ,     4 ,     0 ,  0 },
1597
/* 5 : AN+ON      */ {     0 , s(2,1),     0 , s(3,2),     5 ,     5 ,     0 ,  0 }
1598
};
1599
static const ImpTab impTabR_DEFAULT =   /* Odd  paragraph level */
1600
/*  In this table, conditional sequences receive the lower possible level
1601
    until proven otherwise.
1602
*/
1603
{
1604
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1605
/* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
1606
/* 1 : L          */ {     1 ,     0 ,     1 ,     3 , s(1,4), s(1,4),     0 ,  1 },
1607
/* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
1608
/* 3 : L+AN       */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  1 },
1609
/* 4 : L+ON       */ { s(2,1),     0 , s(2,1),     3 ,     4 ,     4 ,     0 ,  0 },
1610
/* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  0 }
1611
};
1612
static const ImpAct impAct0 = {0,1,2,3,4};
1613
static const ImpTabPair impTab_DEFAULT = {{&impTabL_DEFAULT,
1614
                                           &impTabR_DEFAULT},
1615
                                          {&impAct0, &impAct0}};
1616
1617
static const ImpTab impTabL_NUMBERS_SPECIAL =   /* Even paragraph level */
1618
/*  In this table, conditional sequences receive the lower possible level
1619
    until proven otherwise.
1620
*/
1621
{
1622
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1623
/* 0 : init       */ {     0 ,     2 , s(1,1), s(1,1),     0 ,     0 ,     0 ,  0 },
1624
/* 1 : L+EN/AN    */ {     0 , s(4,2),     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1625
/* 2 : R          */ {     0 ,     2 ,     4 ,     4 , s(1,3), s(1,3),     0 ,  1 },
1626
/* 3 : R+ON       */ {     0 , s(2,2), s(3,4), s(3,4),     3 ,     3 ,     0 ,  0 },
1627
/* 4 : R+EN/AN    */ {     0 ,     2 ,     4 ,     4 , s(1,3), s(1,3),     0 ,  2 }
1628
};
1629
static const ImpTabPair impTab_NUMBERS_SPECIAL = {{&impTabL_NUMBERS_SPECIAL,
1630
                                                   &impTabR_DEFAULT},
1631
                                                  {&impAct0, &impAct0}};
1632
1633
static const ImpTab impTabL_GROUP_NUMBERS_WITH_R =
1634
/*  In this table, EN/AN+ON sequences receive levels as if associated with R
1635
    until proven that there is L or sor/eor on both sides. AN is handled like EN.
1636
*/
1637
{
1638
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1639
/* 0 init         */ {     0 ,     3 , s(1,1), s(1,1),     0 ,     0 ,     0 ,  0 },
1640
/* 1 EN/AN        */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  2 },
1641
/* 2 EN/AN+ON     */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  1 },
1642
/* 3 R            */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  1 },
1643
/* 4 R+ON         */ { s(2,0),     3 ,     5 ,     5 ,     4 , s(2,0), s(2,0),  1 },
1644
/* 5 R+EN/AN      */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  2 }
1645
};
1646
static const ImpTab impTabR_GROUP_NUMBERS_WITH_R =
1647
/*  In this table, EN/AN+ON sequences receive levels as if associated with R
1648
    until proven that there is L on both sides. AN is handled like EN.
1649
*/
1650
{
1651
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1652
/* 0 init         */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1653
/* 1 EN/AN        */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
1654
/* 2 L            */ {     2 ,     0 , s(1,4), s(1,4), s(1,3),     0 ,     0 ,  1 },
1655
/* 3 L+ON         */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  0 },
1656
/* 4 L+EN/AN      */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  1 }
1657
};
1658
static const ImpTabPair impTab_GROUP_NUMBERS_WITH_R = {
1659
                        {&impTabL_GROUP_NUMBERS_WITH_R,
1660
                         &impTabR_GROUP_NUMBERS_WITH_R},
1661
                        {&impAct0, &impAct0}};
1662
1663
1664
static const ImpTab impTabL_INVERSE_NUMBERS_AS_L =
1665
/*  This table is identical to the Default LTR table except that EN and AN are
1666
    handled like L.
1667
*/
1668
{
1669
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1670
/* 0 : init       */ {     0 ,     1 ,     0 ,     0 ,     0 ,     0 ,     0 ,  0 },
1671
/* 1 : R          */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  1 },
1672
/* 2 : AN         */ {     0 ,     1 ,     0 ,     0 , s(1,5), s(1,5),     0 ,  2 },
1673
/* 3 : R+EN/AN    */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  2 },
1674
/* 4 : R+ON       */ { s(2,0),     1 , s(2,0), s(2,0),     4 ,     4 , s(2,0),  1 },
1675
/* 5 : AN+ON      */ { s(2,0),     1 , s(2,0), s(2,0),     5 ,     5 , s(2,0),  1 }
1676
};
1677
static const ImpTab impTabR_INVERSE_NUMBERS_AS_L =
1678
/*  This table is identical to the Default RTL table except that EN and AN are
1679
    handled like L.
1680
*/
1681
{
1682
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1683
/* 0 : init       */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1684
/* 1 : L          */ {     1 ,     0 ,     1 ,     1 , s(1,4), s(1,4),     0 ,  1 },
1685
/* 2 : EN/AN      */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
1686
/* 3 : L+AN       */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  1 },
1687
/* 4 : L+ON       */ { s(2,1),     0 , s(2,1), s(2,1),     4 ,     4 ,     0 ,  0 },
1688
/* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  0 }
1689
};
1690
static const ImpTabPair impTab_INVERSE_NUMBERS_AS_L = {
1691
                        {&impTabL_INVERSE_NUMBERS_AS_L,
1692
                         &impTabR_INVERSE_NUMBERS_AS_L},
1693
                        {&impAct0, &impAct0}};
1694
1695
static const ImpTab impTabR_INVERSE_LIKE_DIRECT =   /* Odd  paragraph level */
1696
/*  In this table, conditional sequences receive the lower possible level
1697
    until proven otherwise.
1698
*/
1699
{
1700
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1701
/* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
1702
/* 1 : L          */ {     1 ,     0 ,     1 ,     2 , s(1,3), s(1,3),     0 ,  1 },
1703
/* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
1704
/* 3 : L+ON       */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  0 },
1705
/* 4 : L+ON+AN    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  3 },
1706
/* 5 : L+AN+ON    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  2 },
1707
/* 6 : L+ON+EN    */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  1 }
1708
};
1709
static const ImpAct impAct1 = {0,1,13,14};
1710
/* FOOD FOR THOUGHT: in LTR table below, check case "JKL 123abc"
1711
 */
1712
static const ImpTabPair impTab_INVERSE_LIKE_DIRECT = {
1713
                        {&impTabL_DEFAULT,
1714
                         &impTabR_INVERSE_LIKE_DIRECT},
1715
                        {&impAct0, &impAct1}};
1716
1717
static const ImpTab impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS =
1718
/*  The case handled in this table is (visually):  R EN L
1719
*/
1720
{
1721
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1722
/* 0 : init       */ {     0 , s(6,3),     0 ,     1 ,     0 ,     0 ,     0 ,  0 },
1723
/* 1 : L+AN       */ {     0 , s(6,3),     0 ,     1 , s(1,2), s(3,0),     0 ,  4 },
1724
/* 2 : L+AN+ON    */ { s(2,0), s(6,3), s(2,0),     1 ,     2 , s(3,0), s(2,0),  3 },
1725
/* 3 : R          */ {     0 , s(6,3), s(5,5), s(5,6), s(1,4), s(3,0),     0 ,  3 },
1726
/* 4 : R+ON       */ { s(3,0), s(4,3), s(5,5), s(5,6),     4 , s(3,0), s(3,0),  3 },
1727
/* 5 : R+EN       */ { s(3,0), s(4,3),     5 , s(5,6), s(1,4), s(3,0), s(3,0),  4 },
1728
/* 6 : R+AN       */ { s(3,0), s(4,3), s(5,5),     6 , s(1,4), s(3,0), s(3,0),  4 }
1729
};
1730
static const ImpTab impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS =
1731
/*  The cases handled in this table are (visually):  R EN L
1732
                                                     R L AN L
1733
*/
1734
{
1735
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1736
/* 0 : init       */ { s(1,3),     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1737
/* 1 : R+EN/AN    */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  1 },
1738
/* 2 : R+EN/AN+ON */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  0 },
1739
/* 3 : L          */ {     3 ,     0 ,     3 , s(3,6), s(1,4), s(4,0),     0 ,  1 },
1740
/* 4 : L+ON       */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  0 },
1741
/* 5 : L+ON+EN    */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  1 },
1742
/* 6 : L+AN       */ { s(5,3), s(4,0),     6 ,     6 ,     4 , s(4,0), s(4,0),  3 }
1743
};
1744
static const ImpAct impAct2 = {0,1,2,5,6,7,8};
1745
static const ImpAct impAct3 = {0,1,9,10,11,12};
1746
static const ImpTabPair impTab_INVERSE_LIKE_DIRECT_WITH_MARKS = {
1747
                        {&impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS,
1748
                         &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
1749
                        {&impAct2, &impAct3}};
1750
1751
static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL = {
1752
                        {&impTabL_NUMBERS_SPECIAL,
1753
                         &impTabR_INVERSE_LIKE_DIRECT},
1754
                        {&impAct0, &impAct1}};
1755
1756
static const ImpTab impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS =
1757
/*  The case handled in this table is (visually):  R EN L
1758
*/
1759
{
1760
/*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1761
/* 0 : init       */ {     0 , s(6,2),     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1762
/* 1 : L+EN/AN    */ {     0 , s(6,2),     1 ,     1 ,     0 , s(3,0),     0 ,  4 },
1763
/* 2 : R          */ {     0 , s(6,2), s(5,4), s(5,4), s(1,3), s(3,0),     0 ,  3 },
1764
/* 3 : R+ON       */ { s(3,0), s(4,2), s(5,4), s(5,4),     3 , s(3,0), s(3,0),  3 },
1765
/* 4 : R+EN/AN    */ { s(3,0), s(4,2),     4 ,     4 , s(1,3), s(3,0), s(3,0),  4 }
1766
};
1767
static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS = {
1768
                        {&impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS,
1769
                         &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
1770
                        {&impAct2, &impAct3}};
1771
1772
#undef s
1773
1774
typedef struct {
1775
    const ImpTab * pImpTab;             /* level table pointer          */
1776
    const ImpAct * pImpAct;             /* action map array             */
1777
    int32_t startON;                    /* start of ON sequence         */
1778
    int32_t startL2EN;                  /* start of level 2 sequence    */
1779
    int32_t lastStrongRTL;              /* index of last found R or AL  */
1780
    int32_t state;                      /* current state                */
1781
    int32_t runStart;                   /* start position of the run    */
1782
    UBiDiLevel runLevel;                /* run level before implicit solving */
1783
} LevState;
1784
1785
/*------------------------------------------------------------------------*/
1786
1787
static void
1788
addPoint(UBiDi *pBiDi, int32_t pos, int32_t flag)
1789
  /* param pos:     position where to insert
1790
     param flag:    one of LRM_BEFORE, LRM_AFTER, RLM_BEFORE, RLM_AFTER
1791
  */
1792
0
{
1793
0
#define FIRSTALLOC  10
1794
0
    Point point;
1795
0
    InsertPoints * pInsertPoints=&(pBiDi->insertPoints);
1796
0
1797
0
    if (pInsertPoints->capacity == 0)
1798
0
    {
1799
0
        pInsertPoints->points=static_cast<Point *>(uprv_malloc(sizeof(Point)*FIRSTALLOC));
1800
0
        if (pInsertPoints->points == NULL)
1801
0
        {
1802
0
            pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
1803
0
            return;
1804
0
        }
1805
0
        pInsertPoints->capacity=FIRSTALLOC;
1806
0
    }
1807
0
    if (pInsertPoints->size >= pInsertPoints->capacity) /* no room for new point */
1808
0
    {
1809
0
        Point * savePoints=pInsertPoints->points;
1810
0
        pInsertPoints->points=static_cast<Point *>(uprv_realloc(pInsertPoints->points,
1811
0
                                           pInsertPoints->capacity*2*sizeof(Point)));
1812
0
        if (pInsertPoints->points == NULL)
1813
0
        {
1814
0
            pInsertPoints->points=savePoints;
1815
0
            pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
1816
0
            return;
1817
0
        }
1818
0
        else  pInsertPoints->capacity*=2;
1819
0
    }
1820
0
    point.pos=pos;
1821
0
    point.flag=flag;
1822
0
    pInsertPoints->points[pInsertPoints->size]=point;
1823
0
    pInsertPoints->size++;
1824
0
#undef FIRSTALLOC
1825
0
}
1826
1827
static void
1828
setLevelsOutsideIsolates(UBiDi *pBiDi, int32_t start, int32_t limit, UBiDiLevel level)
1829
0
{
1830
0
    DirProp *dirProps=pBiDi->dirProps, dirProp;
1831
0
    UBiDiLevel *levels=pBiDi->levels;
1832
0
    int32_t isolateCount=0, k;
1833
0
    for(k=start; k<limit; k++) {
1834
0
        dirProp=dirProps[k];
1835
0
        if(dirProp==PDI)
1836
0
            isolateCount--;
1837
0
        if(isolateCount==0)
1838
0
            levels[k]=level;
1839
0
        if(dirProp==LRI || dirProp==RLI)
1840
0
            isolateCount++;
1841
0
    }
1842
0
}
1843
1844
/* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
1845
1846
/*
1847
 * This implementation of the (Wn) rules applies all rules in one pass.
1848
 * In order to do so, it needs a look-ahead of typically 1 character
1849
 * (except for W5: sequences of ET) and keeps track of changes
1850
 * in a rule Wp that affect a later Wq (p<q).
1851
 *
1852
 * The (Nn) and (In) rules are also performed in that same single loop,
1853
 * but effectively one iteration behind for white space.
1854
 *
1855
 * Since all implicit rules are performed in one step, it is not necessary
1856
 * to actually store the intermediate directional properties in dirProps[].
1857
 */
1858
1859
static void
1860
processPropertySeq(UBiDi *pBiDi, LevState *pLevState, uint8_t _prop,
1861
0
                   int32_t start, int32_t limit) {
1862
0
    uint8_t cell, oldStateSeq, actionSeq;
1863
0
    const ImpTab * pImpTab=pLevState->pImpTab;
1864
0
    const ImpAct * pImpAct=pLevState->pImpAct;
1865
0
    UBiDiLevel * levels=pBiDi->levels;
1866
0
    UBiDiLevel level, addLevel;
1867
0
    InsertPoints * pInsertPoints;
1868
0
    int32_t start0, k;
1869
0
1870
0
    start0=start;                           /* save original start position */
1871
0
    oldStateSeq=(uint8_t)pLevState->state;
1872
0
    cell=(*pImpTab)[oldStateSeq][_prop];
1873
0
    pLevState->state=GET_STATE(cell);       /* isolate the new state */
1874
0
    actionSeq=(*pImpAct)[GET_ACTION(cell)]; /* isolate the action */
1875
0
    addLevel=(*pImpTab)[pLevState->state][IMPTABLEVELS_RES];
1876
0
1877
0
    if(actionSeq) {
1878
0
        switch(actionSeq) {
1879
0
        case 1:                         /* init ON seq */
1880
0
            pLevState->startON=start0;
1881
0
            break;
1882
0
1883
0
        case 2:                         /* prepend ON seq to current seq */
1884
0
            start=pLevState->startON;
1885
0
            break;
1886
0
1887
0
        case 3:                         /* EN/AN after R+ON */
1888
0
            level=pLevState->runLevel+1;
1889
0
            setLevelsOutsideIsolates(pBiDi, pLevState->startON, start0, level);
1890
0
            break;
1891
0
1892
0
        case 4:                         /* EN/AN before R for NUMBERS_SPECIAL */
1893
0
            level=pLevState->runLevel+2;
1894
0
            setLevelsOutsideIsolates(pBiDi, pLevState->startON, start0, level);
1895
0
            break;
1896
0
1897
0
        case 5:                         /* L or S after possible relevant EN/AN */
1898
0
            /* check if we had EN after R/AL */
1899
0
            if (pLevState->startL2EN >= 0) {
1900
0
                addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
1901
0
            }
1902
0
            pLevState->startL2EN=-1;  /* not within previous if since could also be -2 */
1903
0
            /* check if we had any relevant EN/AN after R/AL */
1904
0
            pInsertPoints=&(pBiDi->insertPoints);
1905
0
            if ((pInsertPoints->capacity == 0) ||
1906
0
                (pInsertPoints->size <= pInsertPoints->confirmed))
1907
0
            {
1908
0
                /* nothing, just clean up */
1909
0
                pLevState->lastStrongRTL=-1;
1910
0
                /* check if we have a pending conditional segment */
1911
0
                level=(*pImpTab)[oldStateSeq][IMPTABLEVELS_RES];
1912
0
                if ((level & 1) && (pLevState->startON > 0)) {  /* after ON */
1913
0
                    start=pLevState->startON;   /* reset to basic run level */
1914
0
                }
1915
0
                if (_prop == DirProp_S)                /* add LRM before S */
1916
0
                {
1917
0
                    addPoint(pBiDi, start0, LRM_BEFORE);
1918
0
                    pInsertPoints->confirmed=pInsertPoints->size;
1919
0
                }
1920
0
                break;
1921
0
            }
1922
0
            /* reset previous RTL cont to level for LTR text */
1923
0
            for (k=pLevState->lastStrongRTL+1; k<start0; k++)
1924
0
            {
1925
0
                /* reset odd level, leave runLevel+2 as is */
1926
0
                levels[k]=(levels[k] - 2) & ~1;
1927
0
            }
1928
0
            /* mark insert points as confirmed */
1929
0
            pInsertPoints->confirmed=pInsertPoints->size;
1930
0
            pLevState->lastStrongRTL=-1;
1931
0
            if (_prop == DirProp_S)            /* add LRM before S */
1932
0
            {
1933
0
                addPoint(pBiDi, start0, LRM_BEFORE);
1934
0
                pInsertPoints->confirmed=pInsertPoints->size;
1935
0
            }
1936
0
            break;
1937
0
1938
0
        case 6:                         /* R/AL after possible relevant EN/AN */
1939
0
            /* just clean up */
1940
0
            pInsertPoints=&(pBiDi->insertPoints);
1941
0
            if (pInsertPoints->capacity > 0)
1942
0
                /* remove all non confirmed insert points */
1943
0
                pInsertPoints->size=pInsertPoints->confirmed;
1944
0
            pLevState->startON=-1;
1945
0
            pLevState->startL2EN=-1;
1946
0
            pLevState->lastStrongRTL=limit - 1;
1947
0
            break;
1948
0
1949
0
        case 7:                         /* EN/AN after R/AL + possible cont */
1950
0
            /* check for real AN */
1951
0
            if ((_prop == DirProp_AN) && (pBiDi->dirProps[start0] == AN) &&
1952
0
                (pBiDi->reorderingMode!=UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))
1953
0
            {
1954
0
                /* real AN */
1955
0
                if (pLevState->startL2EN == -1) /* if no relevant EN already found */
1956
0
                {
1957
0
                    /* just note the righmost digit as a strong RTL */
1958
0
                    pLevState->lastStrongRTL=limit - 1;
1959
0
                    break;
1960
0
                }
1961
0
                if (pLevState->startL2EN >= 0)  /* after EN, no AN */
1962
0
                {
1963
0
                    addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
1964
0
                    pLevState->startL2EN=-2;
1965
0
                }
1966
0
                /* note AN */
1967
0
                addPoint(pBiDi, start0, LRM_BEFORE);
1968
0
                break;
1969
0
            }
1970
0
            /* if first EN/AN after R/AL */
1971
0
            if (pLevState->startL2EN == -1) {
1972
0
                pLevState->startL2EN=start0;
1973
0
            }
1974
0
            break;
1975
0
1976
0
        case 8:                         /* note location of latest R/AL */
1977
0
            pLevState->lastStrongRTL=limit - 1;
1978
0
            pLevState->startON=-1;
1979
0
            break;
1980
0
1981
0
        case 9:                         /* L after R+ON/EN/AN */
1982
0
            /* include possible adjacent number on the left */
1983
0
            for (k=start0-1; k>=0 && !(levels[k]&1); k--);
1984
0
            if(k>=0) {
1985
0
                addPoint(pBiDi, k, RLM_BEFORE);             /* add RLM before */
1986
0
                pInsertPoints=&(pBiDi->insertPoints);
1987
0
                pInsertPoints->confirmed=pInsertPoints->size;   /* confirm it */
1988
0
            }
1989
0
            pLevState->startON=start0;
1990
0
            break;
1991
0
1992
0
        case 10:                        /* AN after L */
1993
0
            /* AN numbers between L text on both sides may be trouble. */
1994
0
            /* tentatively bracket with LRMs; will be confirmed if followed by L */
1995
0
            addPoint(pBiDi, start0, LRM_BEFORE);    /* add LRM before */
1996
0
            addPoint(pBiDi, start0, LRM_AFTER);     /* add LRM after  */
1997
0
            break;
1998
0
1999
0
        case 11:                        /* R after L+ON/EN/AN */
2000
0
            /* false alert, infirm LRMs around previous AN */
2001
0
            pInsertPoints=&(pBiDi->insertPoints);
2002
0
            pInsertPoints->size=pInsertPoints->confirmed;
2003
0
            if (_prop == DirProp_S)            /* add RLM before S */
2004
0
            {
2005
0
                addPoint(pBiDi, start0, RLM_BEFORE);
2006
0
                pInsertPoints->confirmed=pInsertPoints->size;
2007
0
            }
2008
0
            break;
2009
0
2010
0
        case 12:                        /* L after L+ON/AN */
2011
0
            level=pLevState->runLevel + addLevel;
2012
0
            for(k=pLevState->startON; k<start0; k++) {
2013
0
                if (levels[k]<level)
2014
0
                    levels[k]=level;
2015
0
            }
2016
0
            pInsertPoints=&(pBiDi->insertPoints);
2017
0
            pInsertPoints->confirmed=pInsertPoints->size;   /* confirm inserts */
2018
0
            pLevState->startON=start0;
2019
0
            break;
2020
0
2021
0
        case 13:                        /* L after L+ON+EN/AN/ON */
2022
0
            level=pLevState->runLevel;
2023
0
            for(k=start0-1; k>=pLevState->startON; k--) {
2024
0
                if(levels[k]==level+3) {
2025
0
                    while(levels[k]==level+3) {
2026
0
                        levels[k--]-=2;
2027
0
                    }
2028
0
                    while(levels[k]==level) {
2029
0
                        k--;
2030
0
                    }
2031
0
                }
2032
0
                if(levels[k]==level+2) {
2033
0
                    levels[k]=level;
2034
0
                    continue;
2035
0
                }
2036
0
                levels[k]=level+1;
2037
0
            }
2038
0
            break;
2039
0
2040
0
        case 14:                        /* R after L+ON+EN/AN/ON */
2041
0
            level=pLevState->runLevel+1;
2042
0
            for(k=start0-1; k>=pLevState->startON; k--) {
2043
0
                if(levels[k]>level) {
2044
0
                    levels[k]-=2;
2045
0
                }
2046
0
            }
2047
0
            break;
2048
0
2049
0
        default:                        /* we should never get here */
2050
0
            U_ASSERT(FALSE);
2051
0
            break;
2052
0
        }
2053
0
    }
2054
0
    if((addLevel) || (start < start0)) {
2055
0
        level=pLevState->runLevel + addLevel;
2056
0
        if(start>=pLevState->runStart) {
2057
0
            for(k=start; k<limit; k++) {
2058
0
                levels[k]=level;
2059
0
            }
2060
0
        } else {
2061
0
            setLevelsOutsideIsolates(pBiDi, start, limit, level);
2062
0
        }
2063
0
    }
2064
0
}
2065
2066
/**
2067
 * Returns the directionality of the last strong character at the end of the prologue, if any.
2068
 * Requires prologue!=null.
2069
 */
2070
static DirProp
2071
0
lastL_R_AL(UBiDi *pBiDi) {
2072
0
    const UChar *text=pBiDi->prologue;
2073
0
    int32_t length=pBiDi->proLength;
2074
0
    int32_t i;
2075
0
    UChar32 uchar;
2076
0
    DirProp dirProp;
2077
0
    for(i=length; i>0; ) {
2078
0
        /* i is decremented by U16_PREV */
2079
0
        U16_PREV(text, 0, i, uchar);
2080
0
        dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
2081
0
        if(dirProp==L) {
2082
0
            return DirProp_L;
2083
0
        }
2084
0
        if(dirProp==R || dirProp==AL) {
2085
0
            return DirProp_R;
2086
0
        }
2087
0
        if(dirProp==B) {
2088
0
            return DirProp_ON;
2089
0
        }
2090
0
    }
2091
0
    return DirProp_ON;
2092
0
}
2093
2094
/**
2095
 * Returns the directionality of the first strong character, or digit, in the epilogue, if any.
2096
 * Requires epilogue!=null.
2097
 */
2098
static DirProp
2099
0
firstL_R_AL_EN_AN(UBiDi *pBiDi) {
2100
0
    const UChar *text=pBiDi->epilogue;
2101
0
    int32_t length=pBiDi->epiLength;
2102
0
    int32_t i;
2103
0
    UChar32 uchar;
2104
0
    DirProp dirProp;
2105
0
    for(i=0; i<length; ) {
2106
0
        /* i is incremented by U16_NEXT */
2107
0
        U16_NEXT(text, i, length, uchar);
2108
0
        dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
2109
0
        if(dirProp==L) {
2110
0
            return DirProp_L;
2111
0
        }
2112
0
        if(dirProp==R || dirProp==AL) {
2113
0
            return DirProp_R;
2114
0
        }
2115
0
        if(dirProp==EN) {
2116
0
            return DirProp_EN;
2117
0
        }
2118
0
        if(dirProp==AN) {
2119
0
            return DirProp_AN;
2120
0
        }
2121
0
    }
2122
0
    return DirProp_ON;
2123
0
}
2124
2125
static void
2126
resolveImplicitLevels(UBiDi *pBiDi,
2127
                      int32_t start, int32_t limit,
2128
0
                      DirProp sor, DirProp eor) {
2129
0
    const DirProp *dirProps=pBiDi->dirProps;
2130
0
    DirProp dirProp;
2131
0
    LevState levState;
2132
0
    int32_t i, start1, start2;
2133
0
    uint16_t oldStateImp, stateImp, actionImp;
2134
0
    uint8_t gprop, resProp, cell;
2135
0
    UBool inverseRTL;
2136
0
    DirProp nextStrongProp=R;
2137
0
    int32_t nextStrongPos=-1;
2138
0
2139
0
    /* check for RTL inverse BiDi mode */
2140
0
    /* FOOD FOR THOUGHT: in case of RTL inverse BiDi, it would make sense to
2141
0
     * loop on the text characters from end to start.
2142
0
     * This would need a different properties state table (at least different
2143
0
     * actions) and different levels state tables (maybe very similar to the
2144
0
     * LTR corresponding ones.
2145
0
     */
2146
0
    inverseRTL=(UBool)
2147
0
        ((start<pBiDi->lastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) &&
2148
0
         (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT  ||
2149
0
          pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL));
2150
0
2151
0
    /* initialize for property and levels state tables */
2152
0
    levState.startL2EN=-1;              /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
2153
0
    levState.lastStrongRTL=-1;          /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
2154
0
    levState.runStart=start;
2155
0
    levState.runLevel=pBiDi->levels[start];
2156
0
    levState.pImpTab=(const ImpTab*)((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel&1];
2157
0
    levState.pImpAct=(const ImpAct*)((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel&1];
2158
0
    if(start==0 && pBiDi->proLength>0) {
2159
0
        DirProp lastStrong=lastL_R_AL(pBiDi);
2160
0
        if(lastStrong!=DirProp_ON) {
2161
0
            sor=lastStrong;
2162
0
        }
2163
0
    }
2164
0
    /* The isolates[] entries contain enough information to
2165
0
       resume the bidi algorithm in the same state as it was
2166
0
       when it was interrupted by an isolate sequence. */
2167
0
    if(dirProps[start]==PDI  && pBiDi->isolateCount >= 0) {
2168
0
        levState.startON=pBiDi->isolates[pBiDi->isolateCount].startON;
2169
0
        start1=pBiDi->isolates[pBiDi->isolateCount].start1;
2170
0
        stateImp=pBiDi->isolates[pBiDi->isolateCount].stateImp;
2171
0
        levState.state=pBiDi->isolates[pBiDi->isolateCount].state;
2172
0
        pBiDi->isolateCount--;
2173
0
    } else {
2174
0
        levState.startON=-1;
2175
0
        start1=start;
2176
0
        if(dirProps[start]==NSM)
2177
0
            stateImp = 1 + sor;
2178
0
        else
2179
0
            stateImp=0;
2180
0
        levState.state=0;
2181
0
        processPropertySeq(pBiDi, &levState, sor, start, start);
2182
0
    }
2183
0
    start2=start;                       /* to make Java compiler happy */
2184
0
2185
0
    for(i=start; i<=limit; i++) {
2186
0
        if(i>=limit) {
2187
0
            int32_t k;
2188
0
            for(k=limit-1; k>start&&(DIRPROP_FLAG(dirProps[k])&MASK_BN_EXPLICIT); k--);
2189
0
            dirProp=dirProps[k];
2190
0
            if(dirProp==LRI || dirProp==RLI)
2191
0
                break;      /* no forced closing for sequence ending with LRI/RLI */
2192
0
            gprop=eor;
2193
0
        } else {
2194
0
            DirProp prop, prop1;
2195
0
            prop=dirProps[i];
2196
0
            if(prop==B) {
2197
0
                pBiDi->isolateCount=-1; /* current isolates stack entry == none */
2198
0
            }
2199
0
            if(inverseRTL) {
2200
0
                if(prop==AL) {
2201
0
                    /* AL before EN does not make it AN */
2202
0
                    prop=R;
2203
0
                } else if(prop==EN) {
2204
0
                    if(nextStrongPos<=i) {
2205
0
                        /* look for next strong char (L/R/AL) */
2206
0
                        int32_t j;
2207
0
                        nextStrongProp=R;   /* set default */
2208
0
                        nextStrongPos=limit;
2209
0
                        for(j=i+1; j<limit; j++) {
2210
0
                            prop1=dirProps[j];
2211
0
                            if(prop1==L || prop1==R || prop1==AL) {
2212
0
                                nextStrongProp=prop1;
2213
0
                                nextStrongPos=j;
2214
0
                                break;
2215
0
                            }
2216
0
                        }
2217
0
                    }
2218
0
                    if(nextStrongProp==AL) {
2219
0
                        prop=AN;
2220
0
                    }
2221
0
                }
2222
0
            }
2223
0
            gprop=groupProp[prop];
2224
0
        }
2225
0
        oldStateImp=stateImp;
2226
0
        cell=impTabProps[oldStateImp][gprop];
2227
0
        stateImp=GET_STATEPROPS(cell);      /* isolate the new state */
2228
0
        actionImp=GET_ACTIONPROPS(cell);    /* isolate the action */
2229
0
        if((i==limit) && (actionImp==0)) {
2230
0
            /* there is an unprocessed sequence if its property == eor   */
2231
0
            actionImp=1;                    /* process the last sequence */
2232
0
        }
2233
0
        if(actionImp) {
2234
0
            resProp=impTabProps[oldStateImp][IMPTABPROPS_RES];
2235
0
            switch(actionImp) {
2236
0
            case 1:             /* process current seq1, init new seq1 */
2237
0
                processPropertySeq(pBiDi, &levState, resProp, start1, i);
2238
0
                start1=i;
2239
0
                break;
2240
0
            case 2:             /* init new seq2 */
2241
0
                start2=i;
2242
0
                break;
2243
0
            case 3:             /* process seq1, process seq2, init new seq1 */
2244
0
                processPropertySeq(pBiDi, &levState, resProp, start1, start2);
2245
0
                processPropertySeq(pBiDi, &levState, DirProp_ON, start2, i);
2246
0
                start1=i;
2247
0
                break;
2248
0
            case 4:             /* process seq1, set seq1=seq2, init new seq2 */
2249
0
                processPropertySeq(pBiDi, &levState, resProp, start1, start2);
2250
0
                start1=start2;
2251
0
                start2=i;
2252
0
                break;
2253
0
            default:            /* we should never get here */
2254
0
                U_ASSERT(FALSE);
2255
0
                break;
2256
0
            }
2257
0
        }
2258
0
    }
2259
0
2260
0
    /* flush possible pending sequence, e.g. ON */
2261
0
    if(limit==pBiDi->length && pBiDi->epiLength>0) {
2262
0
        DirProp firstStrong=firstL_R_AL_EN_AN(pBiDi);
2263
0
        if(firstStrong!=DirProp_ON) {
2264
0
            eor=firstStrong;
2265
0
        }
2266
0
    }
2267
0
2268
0
    /* look for the last char not a BN or LRE/RLE/LRO/RLO/PDF */
2269
0
    for(i=limit-1; i>start&&(DIRPROP_FLAG(dirProps[i])&MASK_BN_EXPLICIT); i--);
2270
0
    dirProp=dirProps[i];
2271
0
    if((dirProp==LRI || dirProp==RLI) && limit<pBiDi->length) {
2272
0
        pBiDi->isolateCount++;
2273
0
        pBiDi->isolates[pBiDi->isolateCount].stateImp=stateImp;
2274
0
        pBiDi->isolates[pBiDi->isolateCount].state=levState.state;
2275
0
        pBiDi->isolates[pBiDi->isolateCount].start1=start1;
2276
0
        pBiDi->isolates[pBiDi->isolateCount].startON=levState.startON;
2277
0
    }
2278
0
    else
2279
0
        processPropertySeq(pBiDi, &levState, eor, limit, limit);
2280
0
}
2281
2282
/* perform (L1) and (X9) ---------------------------------------------------- */
2283
2284
/*
2285
 * Reset the embedding levels for some non-graphic characters (L1).
2286
 * This function also sets appropriate levels for BN, and
2287
 * explicit embedding types that are supposed to have been removed
2288
 * from the paragraph in (X9).
2289
 */
2290
static void
2291
0
adjustWSLevels(UBiDi *pBiDi) {
2292
0
    const DirProp *dirProps=pBiDi->dirProps;
2293
0
    UBiDiLevel *levels=pBiDi->levels;
2294
0
    int32_t i;
2295
0
2296
0
    if(pBiDi->flags&MASK_WS) {
2297
0
        UBool orderParagraphsLTR=pBiDi->orderParagraphsLTR;
2298
0
        Flags flag;
2299
0
2300
0
        i=pBiDi->trailingWSStart;
2301
0
        while(i>0) {
2302
0
            /* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */
2303
0
            while(i>0 && (flag=DIRPROP_FLAG(dirProps[--i]))&MASK_WS) {
2304
0
                if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
2305
0
                    levels[i]=0;
2306
0
                } else {
2307
0
                    levels[i]=GET_PARALEVEL(pBiDi, i);
2308
0
                }
2309
0
            }
2310
0
2311
0
            /* reset BN to the next character's paraLevel until B/S, which restarts above loop */
2312
0
            /* here, i+1 is guaranteed to be <length */
2313
0
            while(i>0) {
2314
0
                flag=DIRPROP_FLAG(dirProps[--i]);
2315
0
                if(flag&MASK_BN_EXPLICIT) {
2316
0
                    levels[i]=levels[i+1];
2317
0
                } else if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
2318
0
                    levels[i]=0;
2319
0
                    break;
2320
0
                } else if(flag&MASK_B_S) {
2321
0
                    levels[i]=GET_PARALEVEL(pBiDi, i);
2322
0
                    break;
2323
0
                }
2324
0
            }
2325
0
        }
2326
0
    }
2327
0
}
2328
2329
U_CAPI void U_EXPORT2
2330
ubidi_setContext(UBiDi *pBiDi,
2331
                 const UChar *prologue, int32_t proLength,
2332
                 const UChar *epilogue, int32_t epiLength,
2333
0
                 UErrorCode *pErrorCode) {
2334
0
    /* check the argument values */
2335
0
    RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2336
0
    if(pBiDi==NULL || proLength<-1 || epiLength<-1 ||
2337
0
       (prologue==NULL && proLength!=0) || (epilogue==NULL && epiLength!=0)) {
2338
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2339
0
        return;
2340
0
    }
2341
0
2342
0
    if(proLength==-1) {
2343
0
        pBiDi->proLength=u_strlen(prologue);
2344
0
    } else {
2345
0
        pBiDi->proLength=proLength;
2346
0
    }
2347
0
    if(epiLength==-1) {
2348
0
        pBiDi->epiLength=u_strlen(epilogue);
2349
0
    } else {
2350
0
        pBiDi->epiLength=epiLength;
2351
0
    }
2352
0
    pBiDi->prologue=prologue;
2353
0
    pBiDi->epilogue=epilogue;
2354
0
}
2355
2356
static void
2357
0
setParaSuccess(UBiDi *pBiDi) {
2358
0
    pBiDi->proLength=0;                 /* forget the last context */
2359
0
    pBiDi->epiLength=0;
2360
0
    pBiDi->pParaBiDi=pBiDi;             /* mark successful setPara */
2361
0
}
2362
2363
0
#define BIDI_MIN(x, y)   ((x)<(y) ? (x) : (y))
2364
0
#define BIDI_ABS(x)      ((x)>=0  ? (x) : (-(x)))
2365
2366
static void
2367
setParaRunsOnly(UBiDi *pBiDi, const UChar *text, int32_t length,
2368
0
                UBiDiLevel paraLevel, UErrorCode *pErrorCode) {
2369
0
    int32_t *runsOnlyMemory = NULL;
2370
0
    int32_t *visualMap;
2371
0
    UChar *visualText;
2372
0
    int32_t saveLength, saveTrailingWSStart;
2373
0
    const UBiDiLevel *levels;
2374
0
    UBiDiLevel *saveLevels;
2375
0
    UBiDiDirection saveDirection;
2376
0
    UBool saveMayAllocateText;
2377
0
    Run *runs;
2378
0
    int32_t visualLength, i, j, visualStart, logicalStart,
2379
0
            runCount, runLength, addedRuns, insertRemove,
2380
0
            start, limit, step, indexOddBit, logicalPos,
2381
0
            index0, index1;
2382
0
    uint32_t saveOptions;
2383
0
2384
0
    pBiDi->reorderingMode=UBIDI_REORDER_DEFAULT;
2385
0
    if(length==0) {
2386
0
        ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
2387
0
        goto cleanup3;
2388
0
    }
2389
0
    /* obtain memory for mapping table and visual text */
2390
0
    runsOnlyMemory=static_cast<int32_t *>(uprv_malloc(length*(sizeof(int32_t)+sizeof(UChar)+sizeof(UBiDiLevel))));
2391
0
    if(runsOnlyMemory==NULL) {
2392
0
        *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
2393
0
        goto cleanup3;
2394
0
    }
2395
0
    visualMap=runsOnlyMemory;
2396
0
    visualText=(UChar *)&visualMap[length];
2397
0
    saveLevels=(UBiDiLevel *)&visualText[length];
2398
0
    saveOptions=pBiDi->reorderingOptions;
2399
0
    if(saveOptions & UBIDI_OPTION_INSERT_MARKS) {
2400
0
        pBiDi->reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
2401
0
        pBiDi->reorderingOptions|=UBIDI_OPTION_REMOVE_CONTROLS;
2402
0
    }
2403
0
    paraLevel&=1;                       /* accept only 0 or 1 */
2404
0
    ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
2405
0
    if(U_FAILURE(*pErrorCode)) {
2406
0
        goto cleanup3;
2407
0
    }
2408
0
    /* we cannot access directly pBiDi->levels since it is not yet set if
2409
0
     * direction is not MIXED
2410
0
     */
2411
0
    levels=ubidi_getLevels(pBiDi, pErrorCode);
2412
0
    uprv_memcpy(saveLevels, levels, (size_t)pBiDi->length*sizeof(UBiDiLevel));
2413
0
    saveTrailingWSStart=pBiDi->trailingWSStart;
2414
0
    saveLength=pBiDi->length;
2415
0
    saveDirection=pBiDi->direction;
2416
0
2417
0
    /* FOOD FOR THOUGHT: instead of writing the visual text, we could use
2418
0
     * the visual map and the dirProps array to drive the second call
2419
0
     * to ubidi_setPara (but must make provision for possible removal of
2420
0
     * BiDi controls.  Alternatively, only use the dirProps array via
2421
0
     * customized classifier callback.
2422
0
     */
2423
0
    visualLength=ubidi_writeReordered(pBiDi, visualText, length,
2424
0
                                      UBIDI_DO_MIRRORING, pErrorCode);
2425
0
    ubidi_getVisualMap(pBiDi, visualMap, pErrorCode);
2426
0
    if(U_FAILURE(*pErrorCode)) {
2427
0
        goto cleanup2;
2428
0
    }
2429
0
    pBiDi->reorderingOptions=saveOptions;
2430
0
2431
0
    pBiDi->reorderingMode=UBIDI_REORDER_INVERSE_LIKE_DIRECT;
2432
0
    paraLevel^=1;
2433
0
    /* Because what we did with reorderingOptions, visualText may be shorter
2434
0
     * than the original text. But we don't want the levels memory to be
2435
0
     * reallocated shorter than the original length, since we need to restore
2436
0
     * the levels as after the first call to ubidi_setpara() before returning.
2437
0
     * We will force mayAllocateText to FALSE before the second call to
2438
0
     * ubidi_setpara(), and will restore it afterwards.
2439
0
     */
2440
0
    saveMayAllocateText=pBiDi->mayAllocateText;
2441
0
    pBiDi->mayAllocateText=FALSE;
2442
0
    ubidi_setPara(pBiDi, visualText, visualLength, paraLevel, NULL, pErrorCode);
2443
0
    pBiDi->mayAllocateText=saveMayAllocateText;
2444
0
    ubidi_getRuns(pBiDi, pErrorCode);
2445
0
    if(U_FAILURE(*pErrorCode)) {
2446
0
        goto cleanup1;
2447
0
    }
2448
0
    /* check if some runs must be split, count how many splits */
2449
0
    addedRuns=0;
2450
0
    runCount=pBiDi->runCount;
2451
0
    runs=pBiDi->runs;
2452
0
    visualStart=0;
2453
0
    for(i=0; i<runCount; i++, visualStart+=runLength) {
2454
0
        runLength=runs[i].visualLimit-visualStart;
2455
0
        if(runLength<2) {
2456
0
            continue;
2457
0
        }
2458
0
        logicalStart=GET_INDEX(runs[i].logicalStart);
2459
0
        for(j=logicalStart+1; j<logicalStart+runLength; j++) {
2460
0
            index0=visualMap[j];
2461
0
            index1=visualMap[j-1];
2462
0
            if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
2463
0
                addedRuns++;
2464
0
            }
2465
0
        }
2466
0
    }
2467
0
    if(addedRuns) {
2468
0
        if(getRunsMemory(pBiDi, runCount+addedRuns)) {
2469
0
            if(runCount==1) {
2470
0
                /* because we switch from UBiDi.simpleRuns to UBiDi.runs */
2471
0
                pBiDi->runsMemory[0]=runs[0];
2472
0
            }
2473
0
            runs=pBiDi->runs=pBiDi->runsMemory;
2474
0
            pBiDi->runCount+=addedRuns;
2475
0
        } else {
2476
0
            goto cleanup1;
2477
0
        }
2478
0
    }
2479
0
    /* split runs which are not consecutive in source text */
2480
0
    for(i=runCount-1; i>=0; i--) {
2481
0
        runLength= i==0 ? runs[0].visualLimit :
2482
0
                          runs[i].visualLimit-runs[i-1].visualLimit;
2483
0
        logicalStart=runs[i].logicalStart;
2484
0
        indexOddBit=GET_ODD_BIT(logicalStart);
2485
0
        logicalStart=GET_INDEX(logicalStart);
2486
0
        if(runLength<2) {
2487
0
            if(addedRuns) {
2488
0
                runs[i+addedRuns]=runs[i];
2489
0
            }
2490
0
            logicalPos=visualMap[logicalStart];
2491
0
            runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
2492
0
                                            saveLevels[logicalPos]^indexOddBit);
2493
0
            continue;
2494
0
        }
2495
0
        if(indexOddBit) {
2496
0
            start=logicalStart;
2497
0
            limit=logicalStart+runLength-1;
2498
0
            step=1;
2499
0
        } else {
2500
0
            start=logicalStart+runLength-1;
2501
0
            limit=logicalStart;
2502
0
            step=-1;
2503
0
        }
2504
0
        for(j=start; j!=limit; j+=step) {
2505
0
            index0=visualMap[j];
2506
0
            index1=visualMap[j+step];
2507
0
            if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
2508
0
                logicalPos=BIDI_MIN(visualMap[start], index0);
2509
0
                runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
2510
0
                                            saveLevels[logicalPos]^indexOddBit);
2511
0
                runs[i+addedRuns].visualLimit=runs[i].visualLimit;
2512
0
                runs[i].visualLimit-=BIDI_ABS(j-start)+1;
2513
0
                insertRemove=runs[i].insertRemove&(LRM_AFTER|RLM_AFTER);
2514
0
                runs[i+addedRuns].insertRemove=insertRemove;
2515
0
                runs[i].insertRemove&=~insertRemove;
2516
0
                start=j+step;
2517
0
                addedRuns--;
2518
0
            }
2519
0
        }
2520
0
        if(addedRuns) {
2521
0
            runs[i+addedRuns]=runs[i];
2522
0
        }
2523
0
        logicalPos=BIDI_MIN(visualMap[start], visualMap[limit]);
2524
0
        runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
2525
0
                                            saveLevels[logicalPos]^indexOddBit);
2526
0
    }
2527
0
2528
0
  cleanup1:
2529
0
    /* restore initial paraLevel */
2530
0
    pBiDi->paraLevel^=1;
2531
0
  cleanup2:
2532
0
    /* restore real text */
2533
0
    pBiDi->text=text;
2534
0
    pBiDi->length=saveLength;
2535
0
    pBiDi->originalLength=length;
2536
0
    pBiDi->direction=saveDirection;
2537
0
    /* the saved levels should never excess levelsSize, but we check anyway */
2538
0
    if(saveLength>pBiDi->levelsSize) {
2539
0
        saveLength=pBiDi->levelsSize;
2540
0
    }
2541
0
    uprv_memcpy(pBiDi->levels, saveLevels, (size_t)saveLength*sizeof(UBiDiLevel));
2542
0
    pBiDi->trailingWSStart=saveTrailingWSStart;
2543
0
    if(pBiDi->runCount>1) {
2544
0
        pBiDi->direction=UBIDI_MIXED;
2545
0
    }
2546
0
  cleanup3:
2547
0
    /* free memory for mapping table and visual text */
2548
0
    uprv_free(runsOnlyMemory);
2549
0
2550
0
    pBiDi->reorderingMode=UBIDI_REORDER_RUNS_ONLY;
2551
0
}
2552
2553
/* ubidi_setPara ------------------------------------------------------------ */
2554
2555
U_CAPI void U_EXPORT2
2556
ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length,
2557
              UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels,
2558
0
              UErrorCode *pErrorCode) {
2559
0
    UBiDiDirection direction;
2560
0
    DirProp *dirProps;
2561
0
2562
0
    /* check the argument values */
2563
0
    RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2564
0
    if(pBiDi==NULL || text==NULL || length<-1 ||
2565
0
       (paraLevel>UBIDI_MAX_EXPLICIT_LEVEL && paraLevel<UBIDI_DEFAULT_LTR)) {
2566
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2567
0
        return;
2568
0
    }
2569
0
2570
0
    if(length==-1) {
2571
0
        length=u_strlen(text);
2572
0
    }
2573
0
2574
0
    /* special treatment for RUNS_ONLY mode */
2575
0
    if(pBiDi->reorderingMode==UBIDI_REORDER_RUNS_ONLY) {
2576
0
        setParaRunsOnly(pBiDi, text, length, paraLevel, pErrorCode);
2577
0
        return;
2578
0
    }
2579
0
2580
0
    /* initialize the UBiDi structure */
2581
0
    pBiDi->pParaBiDi=NULL;          /* mark unfinished setPara */
2582
0
    pBiDi->text=text;
2583
0
    pBiDi->length=pBiDi->originalLength=pBiDi->resultLength=length;
2584
0
    pBiDi->paraLevel=paraLevel;
2585
0
    pBiDi->direction=(UBiDiDirection)(paraLevel&1);
2586
0
    pBiDi->paraCount=1;
2587
0
2588
0
    pBiDi->dirProps=NULL;
2589
0
    pBiDi->levels=NULL;
2590
0
    pBiDi->runs=NULL;
2591
0
    pBiDi->insertPoints.size=0;         /* clean up from last call */
2592
0
    pBiDi->insertPoints.confirmed=0;    /* clean up from last call */
2593
0
2594
0
    /*
2595
0
     * Save the original paraLevel if contextual; otherwise, set to 0.
2596
0
     */
2597
0
    pBiDi->defaultParaLevel=IS_DEFAULT_LEVEL(paraLevel);
2598
0
2599
0
    if(length==0) {
2600
0
        /*
2601
0
         * For an empty paragraph, create a UBiDi object with the paraLevel and
2602
0
         * the flags and the direction set but without allocating zero-length arrays.
2603
0
         * There is nothing more to do.
2604
0
         */
2605
0
        if(IS_DEFAULT_LEVEL(paraLevel)) {
2606
0
            pBiDi->paraLevel&=1;
2607
0
            pBiDi->defaultParaLevel=0;
2608
0
        }
2609
0
        pBiDi->flags=DIRPROP_FLAG_LR(paraLevel);
2610
0
        pBiDi->runCount=0;
2611
0
        pBiDi->paraCount=0;
2612
0
        setParaSuccess(pBiDi);          /* mark successful setPara */
2613
0
        return;
2614
0
    }
2615
0
2616
0
    pBiDi->runCount=-1;
2617
0
2618
0
    /* allocate paras memory */
2619
0
    if(pBiDi->parasMemory)
2620
0
        pBiDi->paras=pBiDi->parasMemory;
2621
0
    else
2622
0
        pBiDi->paras=pBiDi->simpleParas;
2623
0
2624
0
    /*
2625
0
     * Get the directional properties,
2626
0
     * the flags bit-set, and
2627
0
     * determine the paragraph level if necessary.
2628
0
     */
2629
0
    if(getDirPropsMemory(pBiDi, length)) {
2630
0
        pBiDi->dirProps=pBiDi->dirPropsMemory;
2631
0
        if(!getDirProps(pBiDi)) {
2632
0
            *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
2633
0
            return;
2634
0
        }
2635
0
    } else {
2636
0
        *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
2637
0
        return;
2638
0
    }
2639
0
    dirProps=pBiDi->dirProps;
2640
0
    /* the processed length may have changed if UBIDI_OPTION_STREAMING */
2641
0
    length= pBiDi->length;
2642
0
    pBiDi->trailingWSStart=length;  /* the levels[] will reflect the WS run */
2643
0
2644
0
    /* are explicit levels specified? */
2645
0
    if(embeddingLevels==NULL) {
2646
0
        /* no: determine explicit levels according to the (Xn) rules */\
2647
0
        if(getLevelsMemory(pBiDi, length)) {
2648
0
            pBiDi->levels=pBiDi->levelsMemory;
2649
0
            direction=resolveExplicitLevels(pBiDi, pErrorCode);
2650
0
            if(U_FAILURE(*pErrorCode)) {
2651
0
                return;
2652
0
            }
2653
0
        } else {
2654
0
            *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
2655
0
            return;
2656
0
        }
2657
0
    } else {
2658
0
        /* set BN for all explicit codes, check that all levels are 0 or paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */
2659
0
        pBiDi->levels=embeddingLevels;
2660
0
        direction=checkExplicitLevels(pBiDi, pErrorCode);
2661
0
        if(U_FAILURE(*pErrorCode)) {
2662
0
            return;
2663
0
        }
2664
0
    }
2665
0
2666
0
    /* allocate isolate memory */
2667
0
    if(pBiDi->isolateCount<=SIMPLE_ISOLATES_COUNT)
2668
0
        pBiDi->isolates=pBiDi->simpleIsolates;
2669
0
    else
2670
0
        if((int32_t)(pBiDi->isolateCount*sizeof(Isolate))<=pBiDi->isolatesSize)
2671
0
            pBiDi->isolates=pBiDi->isolatesMemory;
2672
0
        else {
2673
0
            if(getInitialIsolatesMemory(pBiDi, pBiDi->isolateCount)) {
2674
0
                pBiDi->isolates=pBiDi->isolatesMemory;
2675
0
            } else {
2676
0
                *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
2677
0
                return;
2678
0
            }
2679
0
        }
2680
0
    pBiDi->isolateCount=-1;             /* current isolates stack entry == none */
2681
0
2682
0
    /*
2683
0
     * The steps after (X9) in the UBiDi algorithm are performed only if
2684
0
     * the paragraph text has mixed directionality!
2685
0
     */
2686
0
    pBiDi->direction=direction;
2687
0
    switch(direction) {
2688
0
    case UBIDI_LTR:
2689
0
        /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
2690
0
        pBiDi->trailingWSStart=0;
2691
0
        break;
2692
0
    case UBIDI_RTL:
2693
0
        /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
2694
0
        pBiDi->trailingWSStart=0;
2695
0
        break;
2696
0
    default:
2697
0
        /*
2698
0
         *  Choose the right implicit state table
2699
0
         */
2700
0
        switch(pBiDi->reorderingMode) {
2701
0
        case UBIDI_REORDER_DEFAULT:
2702
0
            pBiDi->pImpTabPair=&impTab_DEFAULT;
2703
0
            break;
2704
0
        case UBIDI_REORDER_NUMBERS_SPECIAL:
2705
0
            pBiDi->pImpTabPair=&impTab_NUMBERS_SPECIAL;
2706
0
            break;
2707
0
        case UBIDI_REORDER_GROUP_NUMBERS_WITH_R:
2708
0
            pBiDi->pImpTabPair=&impTab_GROUP_NUMBERS_WITH_R;
2709
0
            break;
2710
0
        case UBIDI_REORDER_INVERSE_NUMBERS_AS_L:
2711
0
            pBiDi->pImpTabPair=&impTab_INVERSE_NUMBERS_AS_L;
2712
0
            break;
2713
0
        case UBIDI_REORDER_INVERSE_LIKE_DIRECT:
2714
0
            if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
2715
0
                pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT_WITH_MARKS;
2716
0
            } else {
2717
0
                pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT;
2718
0
            }
2719
0
            break;
2720
0
        case UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL:
2721
0
            if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
2722
0
                pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS;
2723
0
            } else {
2724
0
                pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL;
2725
0
            }
2726
0
            break;
2727
0
        default:
2728
0
            /* we should never get here */
2729
0
            U_ASSERT(FALSE);
2730
0
            break;
2731
0
        }
2732
0
        /*
2733
0
         * If there are no external levels specified and there
2734
0
         * are no significant explicit level codes in the text,
2735
0
         * then we can treat the entire paragraph as one run.
2736
0
         * Otherwise, we need to perform the following rules on runs of
2737
0
         * the text with the same embedding levels. (X10)
2738
0
         * "Significant" explicit level codes are ones that actually
2739
0
         * affect non-BN characters.
2740
0
         * Examples for "insignificant" ones are empty embeddings
2741
0
         * LRE-PDF, LRE-RLE-PDF-PDF, etc.
2742
0
         */
2743
0
        if(embeddingLevels==NULL && pBiDi->paraCount<=1 &&
2744
0
                                   !(pBiDi->flags&DIRPROP_FLAG_MULTI_RUNS)) {
2745
0
            resolveImplicitLevels(pBiDi, 0, length,
2746
0
                                    GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, 0)),
2747
0
                                    GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, length-1)));
2748
0
        } else {
2749
0
            /* sor, eor: start and end types of same-level-run */
2750
0
            UBiDiLevel *levels=pBiDi->levels;
2751
0
            int32_t start, limit=0;
2752
0
            UBiDiLevel level, nextLevel;
2753
0
            DirProp sor, eor;
2754
0
2755
0
            /* determine the first sor and set eor to it because of the loop body (sor=eor there) */
2756
0
            level=GET_PARALEVEL(pBiDi, 0);
2757
0
            nextLevel=levels[0];
2758
0
            if(level<nextLevel) {
2759
0
                eor=GET_LR_FROM_LEVEL(nextLevel);
2760
0
            } else {
2761
0
                eor=GET_LR_FROM_LEVEL(level);
2762
0
            }
2763
0
2764
0
            do {
2765
0
                /* determine start and limit of the run (end points just behind the run) */
2766
0
2767
0
                /* the values for this run's start are the same as for the previous run's end */
2768
0
                start=limit;
2769
0
                level=nextLevel;
2770
0
                if((start>0) && (dirProps[start-1]==B)) {
2771
0
                    /* except if this is a new paragraph, then set sor = para level */
2772
0
                    sor=GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, start));
2773
0
                } else {
2774
0
                    sor=eor;
2775
0
                }
2776
0
2777
0
                /* search for the limit of this run */
2778
0
                while((++limit<length) &&
2779
0
                      ((levels[limit]==level) ||
2780
0
                       (DIRPROP_FLAG(dirProps[limit])&MASK_BN_EXPLICIT))) {}
2781
0
2782
0
                /* get the correct level of the next run */
2783
0
                if(limit<length) {
2784
0
                    nextLevel=levels[limit];
2785
0
                } else {
2786
0
                    nextLevel=GET_PARALEVEL(pBiDi, length-1);
2787
0
                }
2788
0
2789
0
                /* determine eor from max(level, nextLevel); sor is last run's eor */
2790
0
                if(NO_OVERRIDE(level)<NO_OVERRIDE(nextLevel)) {
2791
0
                    eor=GET_LR_FROM_LEVEL(nextLevel);
2792
0
                } else {
2793
0
                    eor=GET_LR_FROM_LEVEL(level);
2794
0
                }
2795
0
2796
0
                /* if the run consists of overridden directional types, then there
2797
0
                   are no implicit types to be resolved */
2798
0
                if(!(level&UBIDI_LEVEL_OVERRIDE)) {
2799
0
                    resolveImplicitLevels(pBiDi, start, limit, sor, eor);
2800
0
                } else {
2801
0
                    /* remove the UBIDI_LEVEL_OVERRIDE flags */
2802
0
                    do {
2803
0
                        levels[start++]&=~UBIDI_LEVEL_OVERRIDE;
2804
0
                    } while(start<limit);
2805
0
                }
2806
0
            } while(limit<length);
2807
0
        }
2808
0
        /* check if we got any memory shortage while adding insert points */
2809
0
        if (U_FAILURE(pBiDi->insertPoints.errorCode))
2810
0
        {
2811
0
            *pErrorCode=pBiDi->insertPoints.errorCode;
2812
0
            return;
2813
0
        }
2814
0
        /* reset the embedding levels for some non-graphic characters (L1), (X9) */
2815
0
        adjustWSLevels(pBiDi);
2816
0
        break;
2817
0
    }
2818
0
    /* add RLM for inverse Bidi with contextual orientation resolving
2819
0
     * to RTL which would not round-trip otherwise
2820
0
     */
2821
0
    if((pBiDi->defaultParaLevel>0) &&
2822
0
       (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) &&
2823
0
       ((pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT) ||
2824
0
        (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))) {
2825
0
        int32_t i, j, start, last;
2826
0
        UBiDiLevel level;
2827
0
        DirProp dirProp;
2828
0
        for(i=0; i<pBiDi->paraCount; i++) {
2829
0
            last=(pBiDi->paras[i].limit)-1;
2830
0
            level=pBiDi->paras[i].level;
2831
0
            if(level==0)
2832
0
                continue;           /* LTR paragraph */
2833
0
            start= i==0 ? 0 : pBiDi->paras[i-1].limit;
2834
0
            for(j=last; j>=start; j--) {
2835
0
                dirProp=dirProps[j];
2836
0
                if(dirProp==L) {
2837
0
                    if(j<last) {
2838
0
                        while(dirProps[last]==B) {
2839
0
                            last--;
2840
0
                        }
2841
0
                    }
2842
0
                    addPoint(pBiDi, last, RLM_BEFORE);
2843
0
                    break;
2844
0
                }
2845
0
                if(DIRPROP_FLAG(dirProp) & MASK_R_AL) {
2846
0
                    break;
2847
0
                }
2848
0
            }
2849
0
        }
2850
0
    }
2851
0
2852
0
    if(pBiDi->reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
2853
0
        pBiDi->resultLength -= pBiDi->controlCount;
2854
0
    } else {
2855
0
        pBiDi->resultLength += pBiDi->insertPoints.size;
2856
0
    }
2857
0
    setParaSuccess(pBiDi);              /* mark successful setPara */
2858
0
}
2859
2860
U_CAPI void U_EXPORT2
2861
0
ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR) {
2862
0
    if(pBiDi!=NULL) {
2863
0
        pBiDi->orderParagraphsLTR=orderParagraphsLTR;
2864
0
    }
2865
0
}
2866
2867
U_CAPI UBool U_EXPORT2
2868
0
ubidi_isOrderParagraphsLTR(UBiDi *pBiDi) {
2869
0
    if(pBiDi!=NULL) {
2870
0
        return pBiDi->orderParagraphsLTR;
2871
0
    } else {
2872
0
        return FALSE;
2873
0
    }
2874
0
}
2875
2876
U_CAPI UBiDiDirection U_EXPORT2
2877
0
ubidi_getDirection(const UBiDi *pBiDi) {
2878
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2879
0
        return pBiDi->direction;
2880
0
    } else {
2881
0
        return UBIDI_LTR;
2882
0
    }
2883
0
}
2884
2885
U_CAPI const UChar * U_EXPORT2
2886
0
ubidi_getText(const UBiDi *pBiDi) {
2887
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2888
0
        return pBiDi->text;
2889
0
    } else {
2890
0
        return NULL;
2891
0
    }
2892
0
}
2893
2894
U_CAPI int32_t U_EXPORT2
2895
0
ubidi_getLength(const UBiDi *pBiDi) {
2896
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2897
0
        return pBiDi->originalLength;
2898
0
    } else {
2899
0
        return 0;
2900
0
    }
2901
0
}
2902
2903
U_CAPI int32_t U_EXPORT2
2904
0
ubidi_getProcessedLength(const UBiDi *pBiDi) {
2905
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2906
0
        return pBiDi->length;
2907
0
    } else {
2908
0
        return 0;
2909
0
    }
2910
0
}
2911
2912
U_CAPI int32_t U_EXPORT2
2913
0
ubidi_getResultLength(const UBiDi *pBiDi) {
2914
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2915
0
        return pBiDi->resultLength;
2916
0
    } else {
2917
0
        return 0;
2918
0
    }
2919
0
}
2920
2921
/* paragraphs API functions ------------------------------------------------- */
2922
2923
U_CAPI UBiDiLevel U_EXPORT2
2924
0
ubidi_getParaLevel(const UBiDi *pBiDi) {
2925
0
    if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2926
0
        return pBiDi->paraLevel;
2927
0
    } else {
2928
0
        return 0;
2929
0
    }
2930
0
}
2931
2932
U_CAPI int32_t U_EXPORT2
2933
0
ubidi_countParagraphs(UBiDi *pBiDi) {
2934
0
    if(!IS_VALID_PARA_OR_LINE(pBiDi)) {
2935
0
        return 0;
2936
0
    } else {
2937
0
        return pBiDi->paraCount;
2938
0
    }
2939
0
}
2940
2941
U_CAPI void U_EXPORT2
2942
ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex,
2943
                          int32_t *pParaStart, int32_t *pParaLimit,
2944
0
                          UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
2945
0
    int32_t paraStart;
2946
0
2947
0
    /* check the argument values */
2948
0
    RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2949
0
    RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode);
2950
0
    RETURN_VOID_IF_BAD_RANGE(paraIndex, 0, pBiDi->paraCount, *pErrorCode);
2951
0
2952
0
    pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
2953
0
    if(paraIndex) {
2954
0
        paraStart=pBiDi->paras[paraIndex-1].limit;
2955
0
    } else {
2956
0
        paraStart=0;
2957
0
    }
2958
0
    if(pParaStart!=NULL) {
2959
0
        *pParaStart=paraStart;
2960
0
    }
2961
0
    if(pParaLimit!=NULL) {
2962
0
        *pParaLimit=pBiDi->paras[paraIndex].limit;
2963
0
    }
2964
0
    if(pParaLevel!=NULL) {
2965
0
        *pParaLevel=GET_PARALEVEL(pBiDi, paraStart);
2966
0
    }
2967
0
}
2968
2969
U_CAPI int32_t U_EXPORT2
2970
ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex,
2971
                          int32_t *pParaStart, int32_t *pParaLimit,
2972
0
                          UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
2973
0
    int32_t paraIndex;
2974
0
2975
0
    /* check the argument values */
2976
0
    /* pErrorCode will be checked by the call to ubidi_getParagraphByIndex */
2977
0
    RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrorCode, -1);
2978
0
    RETURN_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode, -1);
2979
0
    pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
2980
0
    RETURN_IF_BAD_RANGE(charIndex, 0, pBiDi->length, *pErrorCode, -1);
2981
0
2982
0
    for(paraIndex=0; charIndex>=pBiDi->paras[paraIndex].limit; paraIndex++);
2983
0
    ubidi_getParagraphByIndex(pBiDi, paraIndex, pParaStart, pParaLimit, pParaLevel, pErrorCode);
2984
0
    return paraIndex;
2985
0
}
2986
2987
U_CAPI void U_EXPORT2
2988
ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn,
2989
                       const void *newContext, UBiDiClassCallback **oldFn,
2990
                       const void **oldContext, UErrorCode *pErrorCode)
2991
0
{
2992
0
    RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2993
0
    if(pBiDi==NULL) {
2994
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2995
0
        return;
2996
0
    }
2997
0
    if( oldFn )
2998
0
    {
2999
0
        *oldFn = pBiDi->fnClassCallback;
3000
0
    }
3001
0
    if( oldContext )
3002
0
    {
3003
0
        *oldContext = pBiDi->coClassCallback;
3004
0
    }
3005
0
    pBiDi->fnClassCallback = newFn;
3006
0
    pBiDi->coClassCallback = newContext;
3007
0
}
3008
3009
U_CAPI void U_EXPORT2
3010
ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context)
3011
0
{
3012
0
    if(pBiDi==NULL) {
3013
0
        return;
3014
0
    }
3015
0
    if( fn )
3016
0
    {
3017
0
        *fn = pBiDi->fnClassCallback;
3018
0
    }
3019
0
    if( context )
3020
0
    {
3021
0
        *context = pBiDi->coClassCallback;
3022
0
    }
3023
0
}
3024
3025
U_CAPI UCharDirection U_EXPORT2
3026
ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c)
3027
0
{
3028
0
    UCharDirection dir;
3029
0
3030
0
    if( pBiDi->fnClassCallback == NULL ||
3031
0
        (dir = (*pBiDi->fnClassCallback)(pBiDi->coClassCallback, c)) == U_BIDI_CLASS_DEFAULT )
3032
0
    {
3033
0
        dir = ubidi_getClass(c);
3034
0
    }
3035
0
    if(dir >= U_CHAR_DIRECTION_COUNT) {
3036
0
        dir = (UCharDirection)ON;
3037
0
    }
3038
0
    return dir;
3039
0
}