forked from sailfishos/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsBidi_noICU.cpp
2089 lines (1881 loc) · 71.7 KB
/
nsBidi_noICU.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsBidi.h"
#include "nsUnicodeProperties.h"
#include "nsCRTGlue.h"
using namespace mozilla::unicode;
static_assert(mozilla::kBidiLevelNone > NSBIDI_MAX_EXPLICIT_LEVEL + 1,
"The pseudo embedding level should be out-of-range");
// These are #defined in <sys/regset.h> under Solaris 10 x86
#undef CS
#undef ES
/* Comparing the description of the Bidi algorithm with this implementation
is easier with the same names for the Bidi types in the code as there.
*/
enum {
L = eCharType_LeftToRight,
R = eCharType_RightToLeft,
EN = eCharType_EuropeanNumber,
ES = eCharType_EuropeanNumberSeparator,
ET = eCharType_EuropeanNumberTerminator,
AN = eCharType_ArabicNumber,
CS = eCharType_CommonNumberSeparator,
B = eCharType_BlockSeparator,
S = eCharType_SegmentSeparator,
WS = eCharType_WhiteSpaceNeutral,
O_N = eCharType_OtherNeutral,
LRE = eCharType_LeftToRightEmbedding,
LRO = eCharType_LeftToRightOverride,
AL = eCharType_RightToLeftArabic,
RLE = eCharType_RightToLeftEmbedding,
RLO = eCharType_RightToLeftOverride,
PDF = eCharType_PopDirectionalFormat,
NSM = eCharType_DirNonSpacingMark,
BN = eCharType_BoundaryNeutral,
LRI = eCharType_LeftToRightIsolate,
RLI = eCharType_RightToLeftIsolate,
FSI = eCharType_FirstStrongIsolate,
PDI = eCharType_PopDirectionalIsolate,
ENL, /* EN after W7 */ /* 23 */
ENR, /* EN not subject to W7 */ /* 24 */
dirPropCount
};
#define IS_STRONG_TYPE(dirProp) ((dirProp) <= R || (dirProp) == AL)
/* to avoid some conditional statements, use tiny constant arrays */
static Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
static Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
static Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
#define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
#define DIRPROP_FLAG_E(level) flagE[(level)&1]
#define DIRPROP_FLAG_O(level) flagO[(level)&1]
#define NO_OVERRIDE(level) ((level)&~NSBIDI_LEVEL_OVERRIDE)
static inline uint8_t
DirFromStrong(uint8_t aDirProp)
{
MOZ_ASSERT(IS_STRONG_TYPE(aDirProp));
return aDirProp == L ? L : R;
}
/*
* General implementation notes:
*
* Throughout the implementation, there are comments like (W2) that refer to
* rules of the Bidi algorithm in its version 5, in this example to the second
* rule of the resolution of weak types.
*
* For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
* character according to UTF-16, the second UChar gets the directional property of
* the entire character assigned, while the first one gets a BN, a boundary
* neutral, type, which is ignored by most of the algorithm according to
* rule (X9) and the implementation suggestions of the Bidi algorithm.
*
* Later, AdjustWSLevels() will set the level for each BN to that of the
* following character (UChar), which results in surrogate pairs getting the
* same level on each of their surrogates.
*
* In a UTF-8 implementation, the same thing could be done: the last byte of
* a multi-byte sequence would get the "real" property, while all previous
* bytes of that sequence would get BN.
*
* It is not possible to assign all those parts of a character the same real
* property because this would fail in the resolution of weak types with rules
* that look at immediately surrounding types.
*
* As a related topic, this implementation does not remove Boundary Neutral
* types from the input, but ignores them whenever this is relevant.
* For example, the loop for the resolution of the weak types reads
* types until it finds a non-BN.
* Also, explicit embedding codes are neither changed into BN nor removed.
* They are only treated the same way real BNs are.
* As stated before, AdjustWSLevels() takes care of them at the end.
* For the purpose of conformance, the levels of all these codes
* do not matter.
*
* Note that this implementation never modifies the dirProps
* after the initial setup, except for FSI which is changed to either
* LRI or RLI in GetDirProps(), and paired brackets which may be changed
* to L or R according to N0.
*
*
* In this implementation, the resolution of weak types (Wn),
* neutrals (Nn), and the assignment of the resolved level (In)
* are all done in one single loop, in ResolveImplicitLevels().
* Changes of dirProp values are done on the fly, without writing
* them back to the dirProps array.
*
*
* This implementation contains code that allows to bypass steps of the
* algorithm that are not needed on the specific paragraph
* in order to speed up the most common cases considerably,
* like text that is entirely LTR, or RTL text without numbers.
*
* Most of this is done by setting a bit for each directional property
* in a flags variable and later checking for whether there are
* any LTR characters or any RTL characters, or both, whether
* there are any explicit embedding codes, etc.
*
* If the (Xn) steps are performed, then the flags are re-evaluated,
* because they will then not contain the embedding codes any more
* and will be adjusted for override codes, so that subsequently
* more bypassing may be possible than what the initial flags suggested.
*
* If the text is not mixed-directional, then the
* algorithm steps for the weak type resolution are not performed,
* and all levels are set to the paragraph level.
*
* If there are no explicit embedding codes, then the (Xn) steps
* are not performed.
*
* If embedding levels are supplied as a parameter, then all
* explicit embedding codes are ignored, and the (Xn) steps
* are not performed.
*
* White Space types could get the level of the run they belong to,
* and are checked with a test of (flags&MASK_EMBEDDING) to
* consider if the paragraph direction should be considered in
* the flags variable.
*
* If there are no White Space types in the paragraph, then
* (L1) is not necessary in AdjustWSLevels().
*/
nsBidi::nsBidi()
{
Init();
}
nsBidi::~nsBidi()
{
Free();
}
void nsBidi::Init()
{
/* reset the object, all pointers nullptr, all flags false, all sizes 0 */
mLength = 0;
mParaLevel = 0;
mFlags = 0;
mDirection = NSBIDI_LTR;
mTrailingWSStart = 0;
mDirPropsSize = 0;
mLevelsSize = 0;
mRunsSize = 0;
mIsolatesSize = 0;
mRunCount = -1;
mIsolateCount = -1;
mDirProps=nullptr;
mLevels=nullptr;
mRuns=nullptr;
mIsolates=nullptr;
mDirPropsMemory=nullptr;
mLevelsMemory=nullptr;
mRunsMemory=nullptr;
mIsolatesMemory=nullptr;
}
/*
* We are allowed to allocate memory if aMemory==nullptr
* for each array that we need.
* We also try to grow and shrink memory as needed if we
* allocate it.
*
* Assume aSizeNeeded>0.
* If *aMemory!=nullptr, then assume *aSize>0.
*
* ### this realloc() may unnecessarily copy the old data,
* which we know we don't need any more;
* is this the best way to do this??
*/
/*static*/
bool
nsBidi::GetMemory(void **aMemory, size_t *aSize, size_t aSizeNeeded)
{
/* check for existing memory */
if(*aMemory==nullptr) {
/* we need to allocate memory */
*aMemory=malloc(aSizeNeeded);
if (*aMemory!=nullptr) {
*aSize=aSizeNeeded;
return true;
} else {
*aSize=0;
return false;
}
} else {
/* there is some memory, is it enough or too much? */
if(aSizeNeeded!=*aSize) {
/* we may try to grow or shrink */
void *memory=realloc(*aMemory, aSizeNeeded);
if(memory!=nullptr) {
*aMemory=memory;
*aSize=aSizeNeeded;
return true;
} else {
/* we failed to grow */
return false;
}
} else {
/* we have at least enough memory and must not allocate */
return true;
}
}
}
void nsBidi::Free()
{
free(mDirPropsMemory);
mDirPropsMemory = nullptr;
free(mLevelsMemory);
mLevelsMemory = nullptr;
free(mRunsMemory);
mRunsMemory = nullptr;
free(mIsolatesMemory);
mIsolatesMemory = nullptr;
}
/* SetPara ------------------------------------------------------------ */
nsresult nsBidi::SetPara(const char16_t *aText, int32_t aLength,
nsBidiLevel aParaLevel)
{
nsBidiDirection direction;
/* check the argument values */
if(aText==nullptr ||
((NSBIDI_MAX_EXPLICIT_LEVEL<aParaLevel) && !IS_DEFAULT_LEVEL(aParaLevel)) ||
aLength<-1
) {
return NS_ERROR_INVALID_ARG;
}
if(aLength==-1) {
aLength = NS_strlen(aText);
}
/* initialize member data */
mLength = aLength;
mParaLevel=aParaLevel;
mDirection=aParaLevel & 1 ? NSBIDI_RTL : NSBIDI_LTR;
mTrailingWSStart=aLength; /* the levels[] will reflect the WS run */
mDirProps=nullptr;
mLevels=nullptr;
mRuns=nullptr;
if(aLength==0) {
/*
* For an empty paragraph, create an nsBidi object with the aParaLevel and
* the flags and the direction set but without allocating zero-length arrays.
* There is nothing more to do.
*/
if(IS_DEFAULT_LEVEL(aParaLevel)) {
mParaLevel&=1;
}
mFlags=DIRPROP_FLAG_LR(aParaLevel);
mRunCount=0;
return NS_OK;
}
mRunCount=-1;
/*
* Get the directional properties,
* the flags bit-set, and
* determine the partagraph level if necessary.
*/
if(GETDIRPROPSMEMORY(aLength)) {
mDirProps=mDirPropsMemory;
GetDirProps(aText);
} else {
return NS_ERROR_OUT_OF_MEMORY;
}
/* determine explicit levels according to the (Xn) rules */
if(GETLEVELSMEMORY(aLength)) {
mLevels=mLevelsMemory;
ResolveExplicitLevels(&direction, aText);
} else {
return NS_ERROR_OUT_OF_MEMORY;
}
/* allocate isolate memory */
if (mIsolateCount <= SIMPLE_ISOLATES_SIZE) {
mIsolates = mSimpleIsolates;
} else {
if (mIsolateCount * sizeof(Isolate) <= mIsolatesSize) {
mIsolates = mIsolatesMemory;
} else {
if (GETISOLATESMEMORY(mIsolateCount)) {
mIsolates = mIsolatesMemory;
} else {
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
mIsolateCount = -1; /* current isolates stack entry == none */
/*
* The steps after (X9) in the Bidi algorithm are performed only if
* the paragraph text has mixed directionality!
*/
mDirection = direction;
switch(direction) {
case NSBIDI_LTR:
/* make sure paraLevel is even */
mParaLevel=(mParaLevel+1)&~1;
/* all levels are implicitly at paraLevel (important for GetLevels()) */
mTrailingWSStart=0;
break;
case NSBIDI_RTL:
/* make sure paraLevel is odd */
mParaLevel|=1;
/* all levels are implicitly at paraLevel (important for GetLevels()) */
mTrailingWSStart=0;
break;
default:
/*
* If there are no external levels specified and there
* are no significant explicit level codes in the text,
* then we can treat the entire paragraph as one run.
* Otherwise, we need to perform the following rules on runs of
* the text with the same embedding levels. (X10)
* "Significant" explicit level codes are ones that actually
* affect non-BN characters.
* Examples for "insignificant" ones are empty embeddings
* LRE-PDF, LRE-RLE-PDF-PDF, etc.
*/
if(!(mFlags&DIRPROP_FLAG_MULTI_RUNS)) {
ResolveImplicitLevels(0, aLength,
GET_LR_FROM_LEVEL(mParaLevel),
GET_LR_FROM_LEVEL(mParaLevel));
} else {
/* sor, eor: start and end types of same-level-run */
nsBidiLevel *levels=mLevels;
int32_t start, limit=0;
nsBidiLevel level, nextLevel;
DirProp sor, eor;
/* determine the first sor and set eor to it because of the loop body (sor=eor there) */
level=mParaLevel;
nextLevel=levels[0];
if(level<nextLevel) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
do {
/* determine start and limit of the run (end points just behind the run) */
/* the values for this run's start are the same as for the previous run's end */
sor=eor;
start=limit;
level=nextLevel;
/* search for the limit of this run */
while(++limit<aLength &&
(levels[limit]==level ||
(DIRPROP_FLAG(mDirProps[limit])&MASK_BN_EXPLICIT))) {}
/* get the correct level of the next run */
if(limit<aLength) {
nextLevel=levels[limit];
} else {
nextLevel=mParaLevel;
}
/* determine eor from max(level, nextLevel); sor is last run's eor */
if((level&~NSBIDI_LEVEL_OVERRIDE)<(nextLevel&~NSBIDI_LEVEL_OVERRIDE)) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
/* if the run consists of overridden directional types, then there
are no implicit types to be resolved */
if(!(level&NSBIDI_LEVEL_OVERRIDE)) {
ResolveImplicitLevels(start, limit, sor, eor);
} else {
do {
levels[start++] &= ~NSBIDI_LEVEL_OVERRIDE;
} while (start < limit);
}
} while(limit<aLength);
}
/* reset the embedding levels for some non-graphic characters (L1), (X9) */
AdjustWSLevels();
break;
}
return NS_OK;
}
/* perform (P2)..(P3) ------------------------------------------------------- */
/*
* Get the directional properties for the text,
* calculate the flags bit-set, and
* determine the partagraph level if necessary.
*/
void nsBidi::GetDirProps(const char16_t *aText)
{
DirProp *dirProps=mDirPropsMemory; /* mDirProps is const */
int32_t i=0, length=mLength;
Flags flags=0; /* collect all directionalities in the text */
char16_t uchar;
DirProp dirProp;
bool isDefaultLevel = IS_DEFAULT_LEVEL(mParaLevel);
enum State {
NOT_SEEKING_STRONG, /* 0: not after FSI */
SEEKING_STRONG_FOR_PARA, /* 1: looking for first strong char in para */
SEEKING_STRONG_FOR_FSI, /* 2: looking for first strong after FSI */
LOOKING_FOR_PDI /* 3: found strong after FSI, looking for PDI */
};
State state;
/* The following stacks are used to manage isolate sequences. Those
sequences may be nested, but obviously never more deeply than the
maximum explicit embedding level.
lastStack is the index of the last used entry in the stack. A value of -1
means that there is no open isolate sequence. */
/* The following stack contains the position of the initiator of
each open isolate sequence */
int32_t isolateStartStack[NSBIDI_MAX_EXPLICIT_LEVEL + 1];
/* The following stack contains the last known state before
encountering the initiator of an isolate sequence */
State previousStateStack[NSBIDI_MAX_EXPLICIT_LEVEL + 1];
int32_t stackLast = -1;
if(isDefaultLevel) {
/*
* see comment in nsBidi.h:
* the DEFAULT_XXX values are designed so that
* their bit 0 alone yields the intended default
*/
mParaLevel &= 1;
state = SEEKING_STRONG_FOR_PARA;
} else {
state = NOT_SEEKING_STRONG;
}
/* determine the paragraph level (P2..P3) */
for(/* i = 0 above */; i < length;) {
uchar=aText[i];
if(!IS_FIRST_SURROGATE(uchar) || i+1==length || !IS_SECOND_SURROGATE(aText[i+1])) {
/* not a surrogate pair */
flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetBidiCat((uint32_t)uchar));
} else {
/* a surrogate pair */
dirProps[i++]=BN; /* first surrogate in the pair gets the BN type */
flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetBidiCat(GET_UTF_32(uchar, aText[i])))|DIRPROP_FLAG(BN);
}
++i;
switch (dirProp) {
case L:
if (state == SEEKING_STRONG_FOR_PARA) {
mParaLevel = 0;
state = NOT_SEEKING_STRONG;
} else if (state == SEEKING_STRONG_FOR_FSI) {
if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
dirProps[isolateStartStack[stackLast]] = LRI;
flags |= DIRPROP_FLAG(LRI);
}
state = LOOKING_FOR_PDI;
}
break;
case R: case AL:
if (state == SEEKING_STRONG_FOR_PARA) {
mParaLevel = 1;
state = NOT_SEEKING_STRONG;
} else if (state == SEEKING_STRONG_FOR_FSI) {
if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
dirProps[isolateStartStack[stackLast]] = RLI;
flags |= DIRPROP_FLAG(RLI);
}
state = LOOKING_FOR_PDI;
}
break;
case FSI: case LRI: case RLI:
stackLast++;
if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
isolateStartStack[stackLast] = i - 1;
previousStateStack[stackLast] = state;
}
if (dirProp == FSI) {
state = SEEKING_STRONG_FOR_FSI;
} else {
state = LOOKING_FOR_PDI;
}
break;
case PDI:
if (state == SEEKING_STRONG_FOR_FSI) {
if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
dirProps[isolateStartStack[stackLast]] = LRI;
flags |= DIRPROP_FLAG(LRI);
}
}
if (stackLast >= 0) {
if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
state = previousStateStack[stackLast];
}
stackLast--;
}
break;
case B:
// This shouldn't happen, since we don't support multiple paragraphs.
NS_NOTREACHED("Unexpected paragraph separator");
break;
default:
break;
}
}
/* Ignore still open isolate sequences with overflow */
if (stackLast > NSBIDI_MAX_EXPLICIT_LEVEL) {
stackLast = NSBIDI_MAX_EXPLICIT_LEVEL;
if (dirProps[previousStateStack[NSBIDI_MAX_EXPLICIT_LEVEL]] != FSI) {
state = LOOKING_FOR_PDI;
}
}
/* Resolve direction of still unresolved open FSI sequences */
while (stackLast >= 0) {
if (state == SEEKING_STRONG_FOR_FSI) {
dirProps[isolateStartStack[stackLast]] = LRI;
flags |= DIRPROP_FLAG(LRI);
}
state = previousStateStack[stackLast];
stackLast--;
}
flags|=DIRPROP_FLAG_LR(mParaLevel);
mFlags = flags;
}
/* Functions for handling paired brackets ----------------------------------- */
/* In the mIsoRuns array, the first entry is used for text outside of any
isolate sequence. Higher entries are used for each more deeply nested
isolate sequence.
mIsoRunLast is the index of the last used entry.
The mOpenings array is used to note the data of opening brackets not yet
matched by a closing bracket, or matched but still susceptible to change
level.
Each isoRun entry contains the index of the first and
one-after-last openings entries for pending opening brackets it
contains. The next mOpenings entry to use is the one-after-last of the
most deeply nested isoRun entry.
mIsoRuns entries also contain their current embedding level and the bidi
class of the last-encountered strong character, since these will be needed
to resolve the level of paired brackets. */
nsBidi::BracketData::BracketData(const nsBidi *aBidi)
{
mIsoRunLast = 0;
mIsoRuns[0].start = 0;
mIsoRuns[0].limit = 0;
mIsoRuns[0].level = aBidi->mParaLevel;
mIsoRuns[0].lastStrong = mIsoRuns[0].lastBase = mIsoRuns[0].contextDir =
GET_LR_FROM_LEVEL(aBidi->mParaLevel);
mIsoRuns[0].contextPos = 0;
mOpenings = mSimpleOpenings;
mOpeningsCount = SIMPLE_OPENINGS_COUNT;
mOpeningsMemory = nullptr;
}
nsBidi::BracketData::~BracketData()
{
free(mOpeningsMemory);
}
/* LRE, LRO, RLE, RLO, PDF */
void
nsBidi::BracketData::ProcessBoundary(int32_t aLastDirControlCharPos,
nsBidiLevel aContextLevel,
nsBidiLevel aEmbeddingLevel,
const DirProp* aDirProps)
{
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
if (DIRPROP_FLAG(aDirProps[aLastDirControlCharPos]) & MASK_ISO) { /* after an isolate */
return;
}
if (NO_OVERRIDE(aEmbeddingLevel) > NO_OVERRIDE(aContextLevel)) { /* not PDF */
aContextLevel = aEmbeddingLevel;
}
lastIsoRun.limit = lastIsoRun.start;
lastIsoRun.level = aEmbeddingLevel;
lastIsoRun.lastStrong = lastIsoRun.lastBase = lastIsoRun.contextDir =
GET_LR_FROM_LEVEL(aContextLevel);
lastIsoRun.contextPos = aLastDirControlCharPos;
}
/* LRI or RLI */
void
nsBidi::BracketData::ProcessLRI_RLI(nsBidiLevel aLevel)
{
MOZ_ASSERT(mIsoRunLast <= NSBIDI_MAX_EXPLICIT_LEVEL);
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
lastIsoRun.lastBase = O_N;
IsoRun& currIsoRun = mIsoRuns[++mIsoRunLast];
currIsoRun.start = currIsoRun.limit = lastIsoRun.limit;
currIsoRun.level = aLevel;
currIsoRun.lastStrong = currIsoRun.lastBase = currIsoRun.contextDir =
GET_LR_FROM_LEVEL(aLevel);
currIsoRun.contextPos = 0;
}
/* PDI */
void
nsBidi::BracketData::ProcessPDI()
{
MOZ_ASSERT(mIsoRunLast > 0);
mIsoRuns[--mIsoRunLast].lastBase = O_N;
}
/* newly found opening bracket: create an openings entry */
bool /* return true if success */
nsBidi::BracketData::AddOpening(char16_t aMatch, int32_t aPosition)
{
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
if (lastIsoRun.limit >= mOpeningsCount) { /* no available new entry */
if (!GETOPENINGSMEMORY(lastIsoRun.limit * 2)) {
return false;
}
if (mOpenings == mSimpleOpenings) {
memcpy(mOpeningsMemory, mSimpleOpenings,
SIMPLE_OPENINGS_COUNT * sizeof(Opening));
}
mOpenings = mOpeningsMemory; /* may have changed */
mOpeningsCount = mOpeningsSize / sizeof(Opening);
}
Opening& o = mOpenings[lastIsoRun.limit];
o.position = aPosition;
o.match = aMatch;
o.contextDir = lastIsoRun.contextDir;
o.contextPos = lastIsoRun.contextPos;
o.flags = 0;
lastIsoRun.limit++;
return true;
}
/* change N0c1 to N0c2 when a preceding bracket is assigned the embedding level */
void
nsBidi::BracketData::FixN0c(int32_t aOpeningIndex, int32_t aNewPropPosition,
DirProp aNewProp, DirProp* aDirProps)
{
/* This function calls itself recursively */
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
for (int32_t k = aOpeningIndex + 1; k < lastIsoRun.limit; k++) {
Opening& o = mOpenings[k];
if (o.match >= 0) { /* not an N0c match */
continue;
}
if (aNewPropPosition < o.contextPos) {
break;
}
int32_t openingPosition = o.position;
if (aNewPropPosition >= openingPosition) {
continue;
}
if (aNewProp == o.contextDir) {
break;
}
aDirProps[openingPosition] = aNewProp;
int32_t closingPosition = -(o.match);
aDirProps[closingPosition] = aNewProp;
o.match = 0; /* prevent further changes */
FixN0c(k, openingPosition, aNewProp, aDirProps);
FixN0c(k, closingPosition, aNewProp, aDirProps);
}
}
/* process closing bracket */
DirProp /* return L or R if N0b or N0c, ON if N0d */
nsBidi::BracketData::ProcessClosing(int32_t aOpenIdx, int32_t aPosition,
DirProp* aDirProps)
{
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
Opening& o = mOpenings[aOpenIdx];
DirProp newProp;
DirProp direction = GET_LR_FROM_LEVEL(lastIsoRun.level);
bool stable = true; // assume stable until proved otherwise
/* The stable flag is set when brackets are paired and their
level is resolved and cannot be changed by what will be
found later in the source string.
An unstable match can occur only when applying N0c, where
the resolved level depends on the preceding context, and
this context may be affected by text occurring later.
Example: RTL paragraph containing: abc[(latin) HEBREW]
When the closing parenthesis is encountered, it appears
that N0c1 must be applied since 'abc' sets an opposite
direction context and both parentheses receive level 2.
However, when the closing square bracket is processed,
N0b applies because of 'HEBREW' being included within the
brackets, thus the square brackets are treated like R and
receive level 1. However, this changes the preceding
context of the opening parenthesis, and it now appears
that N0c2 must be applied to the parentheses rather than
N0c1. */
if ((direction == 0 && o.flags & FOUND_L) ||
(direction == 1 && o.flags & FOUND_R)) { /* N0b */
newProp = direction;
} else if (o.flags & (FOUND_L|FOUND_R)) { /* N0c */
/* it is stable if there is no containing pair or in
conditions too complicated and not worth checking */
stable = (aOpenIdx == lastIsoRun.start);
if (direction != o.contextDir) {
newProp = o.contextDir; /* N0c1 */
} else {
newProp = direction; /* N0c2 */
}
} else {
/* forget this and any brackets nested within this pair */
lastIsoRun.limit = aOpenIdx;
return O_N; /* N0d */
}
aDirProps[o.position] = newProp;
aDirProps[aPosition] = newProp;
/* Update nested N0c pairs that may be affected */
FixN0c(aOpenIdx, o.position, newProp, aDirProps);
if (stable) {
/* forget any brackets nested within this pair */
lastIsoRun.limit = aOpenIdx;
} else {
int32_t k;
o.match = -aPosition;
/* neutralize any unmatched opening between the current pair */
for (k = aOpenIdx + 1; k < lastIsoRun.limit; k++) {
Opening& oo = mOpenings[k];
if (oo.position > aPosition) {
break;
}
if (oo.match > 0) {
oo.match = 0;
}
}
}
return newProp;
}
static inline bool
IsMatchingCloseBracket(char16_t aCh1, char16_t aCh2)
{
// U+232A RIGHT-POINTING ANGLE BRACKET and U+3009 RIGHT ANGLE BRACKET
// are canonical equivalents, so we special-case them here.
return (aCh1 == aCh2) ||
(aCh1 == 0x232A && aCh2 == 0x3009) ||
(aCh2 == 0x232A && aCh1 == 0x3009);
}
/* Handle strong characters, digits and candidates for closing brackets. */
/* Returns true if success. (The only failure mode is an OOM when trying
to allocate memory for the Openings array.) */
bool
nsBidi::BracketData::ProcessChar(int32_t aPosition, char16_t aCh,
DirProp* aDirProps, nsBidiLevel* aLevels)
{
IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
DirProp newProp;
DirProp dirProp = aDirProps[aPosition];
nsBidiLevel level = aLevels[aPosition];
if (dirProp == O_N) {
/* First see if it is a matching closing bracket. Hopefully, this is
more efficient than checking if it is a closing bracket at all */
for (int32_t idx = lastIsoRun.limit - 1; idx >= lastIsoRun.start; idx--) {
if (!IsMatchingCloseBracket(aCh, mOpenings[idx].match)) {
continue;
}
/* We have a match */
newProp = ProcessClosing(idx, aPosition, aDirProps);
if (newProp == O_N) { /* N0d */
aCh = 0; /* prevent handling as an opening */
break;
}
lastIsoRun.lastBase = O_N;
lastIsoRun.contextDir = newProp;
lastIsoRun.contextPos = aPosition;
if (level & NSBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
newProp = GET_LR_FROM_LEVEL(level);
lastIsoRun.lastStrong = newProp;
uint16_t flag = DIRPROP_FLAG(newProp);
for (int32_t i = lastIsoRun.start; i < idx; i++) {
mOpenings[i].flags |= flag;
}
/* matching brackets are not overridden by LRO/RLO */
aLevels[aPosition] &= ~NSBIDI_LEVEL_OVERRIDE;
}
/* matching brackets are not overridden by LRO/RLO */
aLevels[mOpenings[idx].position] &= ~NSBIDI_LEVEL_OVERRIDE;
return true;
}
/* We get here only if the ON character is not a matching closing
bracket or it is a case of N0d */
/* Now see if it is an opening bracket */
char16_t match = GetPairedBracket(aCh);
if (match != aCh && /* has a matching char */
GetPairedBracketType(aCh) == PAIRED_BRACKET_TYPE_OPEN) { /* opening bracket */
if (!AddOpening(match, aPosition)) {
return false;
}
}
}
if (level & NSBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
newProp = GET_LR_FROM_LEVEL(level);
if (dirProp != S && dirProp != WS && dirProp != O_N) {
aDirProps[aPosition] = newProp;
}
lastIsoRun.lastBase = newProp;
lastIsoRun.lastStrong = newProp;
lastIsoRun.contextDir = newProp;
lastIsoRun.contextPos = aPosition;
} else if (IS_STRONG_TYPE(dirProp)) {
newProp = DirFromStrong(dirProp);
lastIsoRun.lastBase = dirProp;
lastIsoRun.lastStrong = dirProp;
lastIsoRun.contextDir = newProp;
lastIsoRun.contextPos = aPosition;
} else if (dirProp == EN) {
lastIsoRun.lastBase = EN;
if (lastIsoRun.lastStrong == L) {
newProp = L; /* W7 */
aDirProps[aPosition] = ENL;
lastIsoRun.contextDir = L;
lastIsoRun.contextPos = aPosition;
} else {
newProp = R; /* N0 */
if (lastIsoRun.lastStrong == AL) {
aDirProps[aPosition] = AN; /* W2 */
} else {
aDirProps[aPosition] = ENR;
}
lastIsoRun.contextDir = R;
lastIsoRun.contextPos = aPosition;
}
} else if (dirProp == AN) {
newProp = R; /* N0 */
lastIsoRun.lastBase = AN;
lastIsoRun.contextDir = R;
lastIsoRun.contextPos = aPosition;
} else if (dirProp == NSM) {
/* if the last real char was ON, change NSM to ON so that it
will stay ON even if the last real char is a bracket which
may be changed to L or R */
newProp = lastIsoRun.lastBase;
if (newProp == O_N) {
aDirProps[aPosition] = newProp;
}
} else {
newProp = dirProp;
lastIsoRun.lastBase = dirProp;
}
if (IS_STRONG_TYPE(newProp)) {
uint16_t flag = DIRPROP_FLAG(DirFromStrong(newProp));
for (int32_t i = lastIsoRun.start; i < lastIsoRun.limit; i++) {
if (aPosition > mOpenings[i].position) {
mOpenings[i].flags |= flag;
}
}
}
return true;
}
/* perform (X1)..(X9) ------------------------------------------------------- */
/*
* Resolve the explicit levels as specified by explicit embedding codes.
* Recalculate the flags to have them reflect the real properties
* after taking the explicit embeddings into account.
*
* The Bidi algorithm is designed to result in the same behavior whether embedding
* levels are externally specified (from "styled text", supposedly the preferred
* method) or set by explicit embedding codes (LRx, RLx, PDF, FSI, PDI) in the plain text.
* That is why (X9) instructs to remove all not-isolate explicit codes (and BN).
* However, in a real implementation, this removal of these codes and their index
* positions in the plain text is undesirable since it would result in
* reallocated, reindexed text.
* Instead, this implementation leaves the codes in there and just ignores them
* in the subsequent processing.
* In order to get the same reordering behavior, positions with a BN or a not-isolate
* explicit embedding code just get the same level assigned as the last "real"
* character.
*
* Some implementations, not this one, then overwrite some of these
* directionality properties at "real" same-level-run boundaries by
* L or R codes so that the resolution of weak types can be performed on the
* entire paragraph at once instead of having to parse it once more and
* perform that resolution on same-level-runs.
* This limits the scope of the implicit rules in effectively
* the same way as the run limits.
*
* Instead, this implementation does not modify these codes.
* On one hand, the paragraph has to be scanned for same-level-runs, but
* on the other hand, this saves another loop to reset these codes,
* or saves making and modifying a copy of dirProps[].
*
*
* Note that (Pn) and (Xn) changed significantly from version 4 of the Bidi algorithm.
*
*
* Handling the stack of explicit levels (Xn):
*
* With the Bidi stack of explicit levels, as pushed with each
* LRE, RLE, LRO, and RLO, LRI, RLI, and FSI and popped with each PDF and PDI,
* the explicit level must never exceed NSBIDI_MAX_EXPLICIT_LEVEL.
*
* In order to have a correct push-pop semantics even in the case of overflows,
* overflow counters and a valid isolate counter are used as described in UAX#9
* section 3.3.2 "Explicit Levels and Direction".
*
* This implementation assumes that NSBIDI_MAX_EXPLICIT_LEVEL is odd.
*/
void nsBidi::ResolveExplicitLevels(nsBidiDirection *aDirection, const char16_t *aText)
{
DirProp *dirProps=mDirProps;
nsBidiLevel *levels=mLevels;
int32_t i=0, length=mLength;
Flags flags=mFlags; /* collect all directionalities in the text */
DirProp dirProp;
nsBidiLevel level=mParaLevel;
nsBidiDirection direction;
mIsolateCount = 0;
/* determine if the text is mixed-directional or single-directional */
direction=DirectionFromFlags(flags);
/* we may not need to resolve any explicit levels */
if(direction!=NSBIDI_MIXED) {
/* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
} else if(!(flags&(MASK_EXPLICIT|MASK_ISO))) {
BracketData bracketData(this);
/* no embeddings, set all levels to the paragraph level */
for(i=0; i<length; ++i) {
levels[i]=level;
if (dirProps[i] == BN) {
continue;
}
if (!bracketData.ProcessChar(i, aText[i], mDirProps, mLevels)) {
NS_WARNING("BracketData::ProcessChar failed, out of memory?");
// Ran out of memory for deeply-nested openings; give up and
// return LTR. This could presumably result in incorrect display,
// but in practice it won't happen except in some artificially-
// constructed torture test -- which is just as likely to die
// altogether with an OOM failure.
*aDirection = NSBIDI_LTR;
return;
}