Coverage Report

Created: 2026-12-01 06:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fribidi/lib/fribidi-bidi.c
Line
Count
Source
1
/* FriBidi
2
 * fribidi-bidi.c - bidirectional algorithm
3
 *
4
 * Authors:
5
 *   Behdad Esfahbod, 2001, 2002, 2004
6
 *   Dov Grobgeld, 1999, 2000, 2017
7
 *
8
 * Copyright (C) 2004 Sharif FarsiWeb, Inc
9
 * Copyright (C) 2001,2002 Behdad Esfahbod
10
 * Copyright (C) 1999,2000,2017 Dov Grobgeld
11
 *
12
 * This library is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU Lesser General Public
14
 * License as published by the Free Software Foundation; either
15
 * version 2.1 of the License, or (at your option) any later version.
16
 *
17
 * This library is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20
 * Lesser General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Lesser General Public License
23
 * along with this library, in a file named COPYING; if not, write to the
24
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25
 * Boston, MA 02110-1301, USA
26
 *
27
 * For licensing issues, contact <fribidi.license@gmail.com>.
28
 */
29
30
#include "common.h"
31
32
#include <fribidi-bidi.h>
33
#include <fribidi-mirroring.h>
34
#include <fribidi-brackets.h>
35
#include <fribidi-unicode.h>
36
37
#include "bidi-types.h"
38
#include "run.h"
39
40
/*
41
 * This file implements most of Unicode Standard Annex #9, Tracking Number 13.
42
 */
43
44
#ifndef MAX
45
1.22k
# define MAX(a,b) ((a) > (b) ? (a) : (b))
46
#endif /* !MAX */
47
48
/* Some convenience macros */
49
117M
#define RL_TYPE(list) ((list)->type)
50
16.4M
#define RL_LEN(list) ((list)->len)
51
100M
#define RL_LEVEL(list) ((list)->level)
52
53
/* "Within this scope, bidirectional types EN and AN are treated as R" */
54
4.04M
#define RL_TYPE_AN_EN_AS_RTL(list) ( \
55
4.04M
 (((list)->type == FRIBIDI_TYPE_AN) || ((list)->type == FRIBIDI_TYPE_EN) | ((list)->type == FRIBIDI_TYPE_RTL)) ? FRIBIDI_TYPE_RTL : (list)->type)
56
17.9M
#define RL_BRACKET_TYPE(list) ((list)->bracket_type)
57
70.8M
#define RL_ISOLATE_LEVEL(list) ((list)->isolate_level)
58
3.67M
#define RL_FSI_BASE_LEVEL(list) ((list)->fsi_base_level)
59
60
38.8k
#define LOCAL_BRACKET_SIZE 16
61
62
/* A pairing entry holds a pair of open/close brackets as described in
63
   BD16. They are collected (in an arbitrary order determined by the
64
   bracket-matching scan) into a flat, growable array rather than a
65
   malloc-per-pair linked list, then qsort()ed by the open bracket's
66
   position for the N0 pass below. Real-world text has few brackets, so
67
   the array typically stays within its small initial allocation.
68
   has_embedding_strong and has_isolate_strong tell whether the pair
69
   encloses a strong character matching the embedding direction (N0b),
70
   and any strong character of its own isolate level (N0c). */
71
typedef struct {
72
  FriBidiRun *open;
73
  FriBidiRun *close;
74
  fribidi_boolean has_embedding_strong;
75
  fribidi_boolean has_isolate_strong;
76
} FriBidiPairingNode;
77
78
typedef struct {
79
  FriBidiPairingNode *nodes;
80
  int count;
81
  int capacity;
82
} FriBidiPairingNodeArray;
83
84
340
#define FRIBIDI_PAIRING_ARRAY_MIN_CAPACITY 16
85
86
static FriBidiRun *
87
merge_with_prev (
88
  FriBidiRun *second
89
)
90
4.90M
{
91
4.90M
  FriBidiRun *first;
92
93
4.90M
  fribidi_assert (second);
94
4.90M
  fribidi_assert (second->next);
95
4.90M
  first = second->prev;
96
4.90M
  fribidi_assert (first);
97
98
4.90M
  first->next = second->next;
99
4.90M
  first->next->prev = first;
100
4.90M
  RL_LEN (first) += RL_LEN (second);
101
4.90M
  if (second->next_isolate)
102
4.89M
    second->next_isolate->prev_isolate = second->prev_isolate;
103
  /* The following edge case typically shouldn't happen, but fuzz
104
     testing shows it does, and the assignment protects against
105
     a dangling pointer. */
106
4.83k
  else if (second->next->prev_isolate == second)
107
0
    second->next->prev_isolate = second->prev_isolate;  
108
4.90M
  if (second->prev_isolate)
109
4.90M
    second->prev_isolate->next_isolate = second->next_isolate;
110
4.90M
  first->next_isolate = second->next_isolate;
111
112
  /* 'second' is pool-owned; it just becomes unreachable garbage within
113
     the pool instead of being freed individually (see run.h). */
114
4.90M
  return first;
115
4.90M
}
116
static void
117
compact_list (
118
  FriBidiRun *list
119
)
120
5.64k
{
121
5.64k
  fribidi_assert (list);
122
123
5.64k
  if (list->next)
124
5.64k
    for_run_list (list, list)
125
8.33M
      if (RL_TYPE (list->prev) == RL_TYPE (list)
126
4.77M
    && RL_LEVEL (list->prev) == RL_LEVEL (list)
127
4.70M
          && RL_ISOLATE_LEVEL (list->prev) == RL_ISOLATE_LEVEL (list)
128
4.70M
          && RL_BRACKET_TYPE(list) == FRIBIDI_NO_BRACKET /* Don't join brackets! */
129
2.70M
          && RL_BRACKET_TYPE(list->prev) == FRIBIDI_NO_BRACKET
130
8.33M
          )
131
2.69M
      list = merge_with_prev (list);
132
5.64k
}
133
134
static void
135
compact_neutrals (
136
  FriBidiRun *list
137
)
138
3.76k
{
139
3.76k
  fribidi_assert (list);
140
141
3.76k
  if (list->next)
142
3.76k
    {
143
3.76k
      for_run_list (list, list)
144
7.15M
      {
145
7.15M
  if (RL_LEVEL (list->prev) == RL_LEVEL (list)
146
7.08M
            && RL_ISOLATE_LEVEL (list->prev) == RL_ISOLATE_LEVEL (list)
147
7.08M
      &&
148
7.08M
      ((RL_TYPE (list->prev) == RL_TYPE (list)
149
3.07M
        || (FRIBIDI_IS_NEUTRAL (RL_TYPE (list->prev))
150
683k
      && FRIBIDI_IS_NEUTRAL (RL_TYPE (list)))))
151
4.05M
            && RL_BRACKET_TYPE(list) == FRIBIDI_NO_BRACKET /* Don't join brackets! */
152
2.05M
            && RL_BRACKET_TYPE(list->prev) == FRIBIDI_NO_BRACKET
153
7.15M
            )
154
2.04M
    list = merge_with_prev (list);
155
7.15M
      }
156
3.76k
    }
157
3.76k
}
158
159
/* Search for an adjacent run in the forward or backward direction.
160
   It uses the next_isolate and prev_isolate run for short circuited searching.
161
 */
162
163
/* The static sentinel is used to signal the end of an isolating
164
   sequence */
165
static FriBidiRun sentinel = { NULL, NULL, 0,0, FRIBIDI_TYPE_SENTINEL, -1,-1,FRIBIDI_NO_BRACKET, NULL, NULL, 0 };
166
167
static FriBidiRun *get_adjacent_run(FriBidiRun *list, fribidi_boolean forward, fribidi_boolean skip_neutral)
168
17.6M
{
169
17.6M
  FriBidiRun *ppp = forward ? list->next_isolate : list->prev_isolate;
170
17.6M
  if (!ppp)
171
166k
    return &sentinel;
172
173
17.5M
  while (ppp)
174
17.5M
    {
175
17.5M
      FriBidiCharType ppp_type = RL_TYPE (ppp);
176
177
17.5M
      if (ppp_type == FRIBIDI_TYPE_SENTINEL)
178
8.27k
        break;
179
180
      /* Note that when sweeping forward we continue one run
181
         beyond the PDI to see what lies behind. When looking
182
         backwards, this is not necessary as the leading isolate
183
         run has already been assigned the resolved level. */
184
17.5M
      if (ppp->isolate_level > list->isolate_level   /* <- How can this be true? */
185
17.5M
          || (forward && ppp_type == FRIBIDI_TYPE_PDI)
186
17.4M
          || (skip_neutral && !FRIBIDI_IS_STRONG(ppp_type)))
187
45.7k
        {
188
45.7k
          ppp = forward ? ppp->next_isolate : ppp->prev_isolate;
189
45.7k
          if (!ppp)
190
8.27k
            ppp = &sentinel;
191
192
45.7k
          continue;
193
45.7k
        }
194
17.4M
      break;
195
17.5M
    }
196
197
17.4M
  return ppp;
198
17.6M
}
199
200
/* Same as get_adjacent_run (list, true, false), for a loop that sweeps
201
   the run list forward and neither merges runs nor changes the type of
202
   a run it has not reached yet.
203
204
   The forward search skips runs of type PDI, and nothing bounds how many
205
   of them follow each other in an isolating run sequence: compact_neutrals
206
   folds "PDI, neutrals, isolate initiator" into one run of type PDI, and
207
   W1 folds an NSM into the PDI before it. Searching anew from every
208
   member of such a chain walks the rest of the chain each time, which
209
   made a paragraph of back-to-back isolates quadratic. But since a PDI
210
   run is skipped, the search from the run before it in the sequence
211
   continued exactly like a search from the PDI run itself, so its result
212
   can be reused. next_run holds the result for the last visited run of
213
   each isolate level; it has FRIBIDI_BIDI_MAX_RESOLVED_LEVELS entries,
214
   all NULL before the loop. */
215
static FriBidiRun *get_next_run_cached(FriBidiRun *list, FriBidiRun **next_run)
216
5.15M
{
217
5.15M
  FriBidiRun *ppp = NULL;
218
219
5.15M
  if (RL_TYPE (list) == FRIBIDI_TYPE_PDI && list->prev_isolate)
220
28.3k
    ppp = next_run[RL_ISOLATE_LEVEL (list)];
221
5.15M
  if (!ppp)
222
5.12M
    ppp = get_adjacent_run (list, true, false);
223
5.15M
  next_run[RL_ISOLATE_LEVEL (list)] = ppp;
224
225
5.15M
  return ppp;
226
5.15M
}
227
228
#ifdef DEBUG
229
/*======================================================================
230
 *  For debugging, define some functions for printing the types and the
231
 *  levels.
232
 *----------------------------------------------------------------------*/
233
234
static char char_from_level_array[] = {
235
  '$',        /* -1 == FRIBIDI_SENTINEL, indicating
236
         * start or end of string. */
237
  /* 0-61 == 0-9,a-z,A-Z are the the only valid levels before resolving
238
   * implicits.  after that the level @ may be appear too. */
239
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
240
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
241
  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
242
  'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
243
  'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
244
  'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
245
  'Y', 'Z',
246
247
  /* 62 and up, through FRIBIDI_BIDI_MAX_RESOLVED_LEVELS (127), are valid
248
   * levels too since the maximum explicit level was raised to 125; they have
249
   * no single-character representation and are printed as '*' by
250
   * fribidi_char_from_level.  See print_types_re for the numeric level. */
251
};
252
253
/* Map a level to its one-character representation, or '*' for any level
254
 * beyond the table above.  Resolved levels go up to 126, so the lookup
255
 * must not trust the table to cover them all. */
256
static char
257
fribidi_char_from_level (
258
  FriBidiLevel level
259
)
260
0
{
261
0
  int i = level + 1;
262
263
0
  if (i < 0 || i >= (int) sizeof (char_from_level_array))
264
0
    return '*';
265
266
0
  return char_from_level_array[i];
267
0
}
268
269
static void
270
print_types_re (
271
  const FriBidiRun *pp
272
)
273
0
{
274
0
  fribidi_assert (pp);
275
276
0
  MSG ("  Run types  : ");
277
0
  for_run_list (pp, pp)
278
0
  {
279
0
    MSG6 ("%d:%d(%s)[%d,%d] ",
280
0
    pp->pos, pp->len, fribidi_get_bidi_type_name (pp->type), pp->level, pp->isolate_level);
281
0
  }
282
0
  MSG ("\n");
283
0
}
284
285
static void
286
print_resolved_levels (
287
  const FriBidiRun *pp
288
)
289
0
{
290
0
  fribidi_assert (pp);
291
292
0
  MSG ("  Res. levels: ");
293
0
  for_run_list (pp, pp)
294
0
  {
295
0
    register FriBidiStrIndex i;
296
0
    for (i = RL_LEN (pp); i; i--)
297
0
      MSG2 ("%c", fribidi_char_from_level (RL_LEVEL (pp)));
298
0
  }
299
0
  MSG ("\n");
300
0
}
301
302
static void
303
print_resolved_types (
304
  const FriBidiRun *pp
305
)
306
0
{
307
0
  fribidi_assert (pp);
308
309
0
  MSG ("  Res. types : ");
310
0
  for_run_list (pp, pp)
311
0
  {
312
0
    FriBidiStrIndex i;
313
0
    for (i = RL_LEN (pp); i; i--)
314
0
      MSG2 ("%s ", fribidi_get_bidi_type_name (pp->type));
315
0
  }
316
0
  MSG ("\n");
317
0
}
318
319
static void
320
print_bidi_string (
321
  /* input */
322
  const FriBidiCharType *bidi_types,
323
  const FriBidiStrIndex len
324
)
325
0
{
326
0
  register FriBidiStrIndex i;
327
328
0
  fribidi_assert (bidi_types);
329
330
0
  MSG ("  Org. types : ");
331
0
  for (i = 0; i < len; i++)
332
0
    MSG2 ("%s ", fribidi_get_bidi_type_name (bidi_types[i]));
333
0
  MSG ("\n");
334
0
}
335
336
static void print_pairing_nodes(FriBidiPairingNodeArray *nodes)
337
0
{
338
0
  int i;
339
0
  MSG ("Pairs: ");
340
0
  for (i = 0; i < nodes->count; i++)
341
0
    MSG3 ("(%d, %d) ", nodes->nodes[i].open->pos, nodes->nodes[i].close->pos);
342
0
  MSG ("\n");
343
0
}
344
#endif /* DEBUG */
345
346
347
/*=========================================================================
348
 * define macros for push and pop the status in to / out of the stack
349
 *-------------------------------------------------------------------------*/
350
351
/* There are a few little points in pushing into and popping from the status
352
   stack:
353
   1. when the embedding level is not valid (more than
354
   FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL=125), you must reject it, and not to push
355
   into the stack, but when you see a PDF, you must find the matching code,
356
   and if it was pushed in the stack, pop it, it means you must pop if and
357
   only if you have pushed the matching code, the over_pushed var counts the
358
   number of rejected codes so far.
359
360
   2. there's a more confusing point too, when the embedding level is exactly
361
   FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL-1=124, an LRO, LRE, or LRI is rejected
362
   because the new level would be FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL+1=126, that
363
   is invalid; but an RLO, RLE, or RLI is accepted because the new level is
364
   FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL=125, that is valid, so the rejected codes
365
   may be not continuous in the logical order, in fact there are at most two
366
   continuous intervals of codes, with an RLO, RLE, or RLI between them.  To
367
   support this case, the first_interval var counts the number of rejected
368
   codes in the first interval, when it is 0, means that there is only one
369
   interval.
370
371
*/
372
373
/* a. If this new level would be valid, then this embedding code is valid.
374
   Remember (push) the current embedding level and override status.
375
   Reset current level to this new level, and reset the override status to
376
   new_override.
377
   b. If the new level would not be valid, then this code is invalid. Don't
378
   change the current level or override status.
379
*/
380
#define PUSH_STATUS \
381
3.17M
    FRIBIDI_BEGIN_STMT \
382
3.17M
      if LIKELY(over_pushed == 0 \
383
3.17M
                && isolate_overflow == 0 \
384
3.17M
                && new_level <= FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL)   \
385
3.17M
        { \
386
52.2k
          if UNLIKELY(level == FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL - 1) \
387
52.2k
            first_interval = over_pushed; \
388
52.2k
          status_stack[stack_size].level = level; \
389
52.2k
          status_stack[stack_size].isolate_level = isolate_level; \
390
52.2k
          status_stack[stack_size].isolate = isolate; \
391
52.2k
          status_stack[stack_size].override = override; \
392
52.2k
          stack_size++; \
393
52.2k
          level = new_level; \
394
52.2k
          override = new_override; \
395
3.12M
        } else if LIKELY(isolate_overflow == 0) \
396
3.12M
    over_pushed++; \
397
3.17M
    FRIBIDI_END_STMT
398
399
/* If there was a valid matching code, restore (pop) the last remembered
400
   (pushed) embedding level and directional override.
401
*/
402
#define POP_STATUS \
403
1.96M
    FRIBIDI_BEGIN_STMT \
404
1.96M
      if (stack_size) \
405
1.96M
      { \
406
459k
        if UNLIKELY(over_pushed > first_interval) \
407
459k
          over_pushed--; \
408
459k
        else \
409
459k
          { \
410
16.0k
            if LIKELY(over_pushed == first_interval) \
411
16.0k
              first_interval = 0; \
412
16.0k
            stack_size--; \
413
16.0k
            level = status_stack[stack_size].level; \
414
16.0k
            override = status_stack[stack_size].override; \
415
16.0k
            isolate = status_stack[stack_size].isolate; \
416
16.0k
            isolate_level = status_stack[stack_size].isolate_level; \
417
16.0k
          } \
418
459k
      } \
419
1.96M
    FRIBIDI_END_STMT
420
421
422
/* Return the type of previous run or the SOR, if already at the start of
423
   a level run. */
424
#define PREV_TYPE_OR_SOR(pp) \
425
3.58M
    ( \
426
3.58M
      RL_LEVEL(pp->prev) == RL_LEVEL(pp) ? \
427
3.58M
        RL_TYPE(pp->prev) : \
428
3.58M
        FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(pp->prev), RL_LEVEL(pp))) \
429
3.58M
    )
430
431
/* Return the type of next run or the EOR, if already at the end of
432
   a level run. */
433
#define NEXT_TYPE_OR_EOR(pp) \
434
    ( \
435
      RL_LEVEL(pp->next) == RL_LEVEL(pp) ? \
436
        RL_TYPE(pp->next) : \
437
        FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(pp->next), RL_LEVEL(pp))) \
438
    )
439
440
441
/* Return the embedding direction of a link. */
442
#define FRIBIDI_EMBEDDING_DIRECTION(link) \
443
16.6k
    FRIBIDI_LEVEL_TO_DIR(RL_LEVEL(link))
444
445
446
FRIBIDI_ENTRY FriBidiParType
447
fribidi_get_par_direction (
448
  /* input */
449
  const FriBidiCharType *bidi_types,
450
  const FriBidiStrIndex len
451
)
452
0
{
453
0
  int valid_isolate_count = 0;
454
0
  register FriBidiStrIndex i;
455
456
0
  fribidi_assert (bidi_types);
457
458
0
  for (i = 0; i < len; i++)
459
0
    {
460
0
      if (bidi_types[i] == FRIBIDI_TYPE_PDI)
461
0
        {
462
          /* Ignore if there is no matching isolate */
463
0
          if (valid_isolate_count>0)
464
0
            valid_isolate_count--;
465
0
        }
466
0
      else if (FRIBIDI_IS_ISOLATE(bidi_types[i]))
467
0
        valid_isolate_count++;
468
0
      else if (bidi_types[i] == FRIBIDI_TYPE_BS)
469
0
        valid_isolate_count = 0;
470
0
      else if (valid_isolate_count==0 && FRIBIDI_IS_LETTER (bidi_types[i]))
471
0
        return FRIBIDI_IS_RTL (bidi_types[i]) ? FRIBIDI_PAR_RTL :
472
0
          FRIBIDI_PAR_LTR;
473
0
    }
474
475
0
  return FRIBIDI_PAR_ON;
476
0
}
477
478
static void pairing_node_array_init(FriBidiPairingNodeArray *arr)
479
1.88k
{
480
1.88k
  arr->nodes = NULL;
481
1.88k
  arr->count = 0;
482
1.88k
  arr->capacity = 0;
483
1.88k
}
484
485
/* Append a new (open, close) pair, growing the backing array (by
486
   doubling, geometric growth) if needed. */
487
static fribidi_boolean pairing_node_array_push(FriBidiPairingNodeArray *arr,
488
                                               FriBidiRun *open,
489
                                               FriBidiRun *close,
490
                                               fribidi_boolean has_embedding_strong,
491
                                               fribidi_boolean has_isolate_strong)
492
784k
{
493
784k
  if UNLIKELY
494
784k
    (arr->count == arr->capacity)
495
1.13k
    {
496
1.13k
      int new_capacity = arr->capacity ? arr->capacity * 2 :
497
1.13k
        FRIBIDI_PAIRING_ARRAY_MIN_CAPACITY;
498
1.13k
      FriBidiPairingNode *new_nodes =
499
1.13k
        fribidi_malloc (new_capacity * sizeof (FriBidiPairingNode));
500
1.13k
      if UNLIKELY
501
1.13k
        (!new_nodes) return false;
502
1.13k
      if (arr->nodes)
503
797
        {
504
797
          memcpy (new_nodes, arr->nodes, arr->count * sizeof (FriBidiPairingNode));
505
797
          fribidi_free (arr->nodes);
506
797
        }
507
1.13k
      arr->nodes = new_nodes;
508
1.13k
      arr->capacity = new_capacity;
509
1.13k
    }
510
511
784k
  arr->nodes[arr->count].open = open;
512
784k
  arr->nodes[arr->count].close = close;
513
784k
  arr->nodes[arr->count].has_embedding_strong = has_embedding_strong;
514
784k
  arr->nodes[arr->count].has_isolate_strong = has_isolate_strong;
515
784k
  arr->count++;
516
784k
  return true;
517
784k
}
518
519
static int pairing_node_compare (const void *a, const void *b)
520
5.90M
{
521
5.90M
  const FriBidiPairingNode *na = a, *nb = b;
522
5.90M
  return (na->open->pos > nb->open->pos) - (na->open->pos < nb->open->pos);
523
5.90M
}
524
525
static void sort_pairing_nodes(FriBidiPairingNodeArray *arr)
526
1.88k
{
527
1.88k
  if (arr->count > 1)
528
225
    qsort (arr->nodes, arr->count, sizeof (FriBidiPairingNode), pairing_node_compare);
529
1.88k
}
530
531
static void free_pairing_nodes(FriBidiPairingNodeArray *arr)
532
1.88k
{
533
1.88k
  fribidi_free (arr->nodes);
534
1.88k
  arr->nodes = NULL;
535
1.88k
  arr->count = arr->capacity = 0;
536
1.88k
}
537
538
FRIBIDI_ENTRY FriBidiLevel
539
fribidi_get_par_embedding_levels_ex (
540
  /* input */
541
  const FriBidiCharType *bidi_types,
542
  const FriBidiBracketType *bracket_types,
543
  const FriBidiStrIndex len,
544
  /* input and output */
545
  FriBidiParType *pbase_dir,
546
  /* output */
547
  FriBidiLevel *embedding_levels
548
)
549
1.88k
{
550
1.88k
  FriBidiLevel base_level, max_level = 0;
551
1.88k
  FriBidiParType base_dir;
552
1.88k
  FriBidiRun *main_run_list = NULL, *explicits_list = NULL, *pp;
553
1.88k
  fribidi_boolean has_isolate = false;
554
1.88k
  FriBidiRunPool *run_pool = NULL;
555
1.88k
  fribidi_boolean status = false;
556
1.88k
  int max_iso_level = 0;
557
558
1.88k
  if UNLIKELY
559
1.88k
    (!len)
560
1
    {
561
1
      status = true;
562
1
      goto out;
563
1
    }
564
565
1.88k
  DBG ("in fribidi_get_par_embedding_levels");
566
567
1.88k
  fribidi_assert (bidi_types);
568
1.88k
  fribidi_assert (pbase_dir);
569
1.88k
  fribidi_assert (embedding_levels);
570
571
  /* All FriBidiRun nodes needed to resolve this paragraph's embedding
572
     levels are carved out of this single pool and released together at
573
     'out', rather than being malloc'd/freed one at a time. */
574
1.88k
  run_pool = fribidi_run_pool_new (len);
575
1.88k
  if UNLIKELY
576
1.88k
    (!run_pool) goto out;
577
578
  /* Determinate character types */
579
1.88k
  {
580
    /* Get run-length encoded character types */
581
1.88k
    main_run_list = run_list_encode_bidi_types (bidi_types, bracket_types, len, run_pool, &has_isolate);
582
1.88k
    if UNLIKELY
583
1.88k
      (!main_run_list) goto out;
584
1.88k
  }
585
586
  /* Find base level */
587
  /* If no strong base_dir was found, resort to the weak direction
588
     that was passed on input. */
589
1.88k
  base_level = FRIBIDI_DIR_TO_LEVEL (*pbase_dir);
590
1.88k
  if (!FRIBIDI_IS_STRONG (*pbase_dir))
591
    /* P2. P3. Search for first strong character and use its direction as
592
       base direction */
593
1.88k
    {
594
1.88k
      int valid_isolate_count = 0;
595
1.88k
      for_run_list (pp, main_run_list)
596
4.04M
        {
597
4.04M
          if (RL_TYPE(pp) == FRIBIDI_TYPE_PDI)
598
17.0k
            {
599
              /* Ignore if there is no matching isolate */
600
17.0k
              if (valid_isolate_count>0)
601
7.18k
                valid_isolate_count--;
602
17.0k
            }
603
4.03M
          else if (FRIBIDI_IS_ISOLATE(RL_TYPE(pp)))
604
1.79M
            valid_isolate_count++;
605
2.23M
          else if (valid_isolate_count==0 && FRIBIDI_IS_LETTER (RL_TYPE (pp)))
606
729
            {
607
729
              base_level = FRIBIDI_DIR_TO_LEVEL (RL_TYPE (pp));
608
729
              *pbase_dir = FRIBIDI_LEVEL_TO_DIR (base_level);
609
729
              break;
610
729
            }
611
4.04M
        }
612
1.88k
    }
613
1.88k
  base_dir = FRIBIDI_LEVEL_TO_DIR (base_level);
614
1.88k
  DBG2 ("  base level : %c", fribidi_char_from_level (base_level));
615
1.88k
  DBG2 ("  base dir   : %s", fribidi_get_bidi_type_name (base_dir));
616
617
1.88k
# if DEBUG
618
1.88k
  if UNLIKELY
619
1.88k
    (fribidi_debug_status ())
620
0
    {
621
0
      print_types_re (main_run_list);
622
0
    }
623
1.88k
# endif /* DEBUG */
624
625
  /* Explicit Levels and Directions */
626
1.88k
  DBG ("explicit levels and directions");
627
1.88k
  {
628
1.88k
    FriBidiLevel level, new_level = 0;
629
1.88k
    int isolate_level = 0;
630
1.88k
    FriBidiCharType override, new_override;
631
1.88k
    FriBidiStrIndex i;
632
1.88k
    int stack_size, over_pushed, first_interval;
633
1.88k
    int valid_isolate_count = 0;
634
1.88k
    int isolate_overflow = 0;
635
1.88k
    int isolate = 0; /* The isolate status flag */
636
1.88k
    struct
637
1.88k
    {
638
1.88k
      FriBidiCharType override; /* only LTR, RTL and ON are valid */
639
1.88k
      FriBidiLevel level;
640
1.88k
      int isolate;
641
1.88k
      int isolate_level;
642
1.88k
    } status_stack[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
643
1.88k
    FriBidiRun temp_link;
644
1.88k
    FriBidiRun *run_per_isolate_level[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
645
1.88k
    int prev_isolate_level = 0; /* When running over the isolate levels, remember the previous level */
646
647
1.88k
    memset(run_per_isolate_level, 0, sizeof(run_per_isolate_level[0])
648
1.88k
           * FRIBIDI_BIDI_MAX_RESOLVED_LEVELS);
649
650
/* explicits_list is a list like main_run_list, that holds the explicit
651
   codes that are removed from main_run_list, to reinsert them later by
652
   calling the shadow_run_list.
653
*/
654
1.88k
    explicits_list = new_run_list (run_pool);
655
1.88k
    if UNLIKELY
656
1.88k
      (!explicits_list) goto out;
657
658
    /* X5c preprocessing: resolve the effective direction of every FSI
659
       up front, in a single linear pass over the (still untouched)
660
       run list, using an explicit stack to skip over nested isolates.
661
       This replaces rescanning the tail of the run list from every FSI
662
       individually, which made paragraphs with many FSIs -- or with no
663
       strong character before an FSI's matching PDI -- quadratic. Only
664
       the direct content of each isolate initiator counts towards its
665
       own resolution; content of a nested isolate is skipped entirely,
666
       which a stack captures naturally: a strong character only ever
667
       resolves the isolate currently on top of the stack. Skipped
668
       entirely when the text has no isolate-initiator at all, which is
669
       the common case and would otherwise cost a full, pointless pass
670
       over the run list. */
671
1.88k
    if (has_isolate)
672
884
    {
673
884
      FriBidiRun *local_fsi_stack[LOCAL_BRACKET_SIZE];
674
884
      FriBidiRun **fsi_stack = local_fsi_stack;
675
884
      int fsi_stack_capacity = LOCAL_BRACKET_SIZE;
676
884
      int fsi_stack_size = 0;
677
884
      fribidi_boolean fsi_stack_heap = false;
678
884
      FriBidiRun *fsi_pp;
679
680
884
      for_run_list (fsi_pp, main_run_list)
681
7.68M
        {
682
7.68M
          FriBidiCharType fsi_this_type = RL_TYPE (fsi_pp);
683
684
7.68M
          if (fsi_this_type == FRIBIDI_TYPE_PDI)
685
40.3k
            {
686
40.3k
              if (fsi_stack_size)
687
17.2k
                fsi_stack_size--;
688
40.3k
            }
689
7.64M
          else if (FRIBIDI_IS_ISOLATE (fsi_this_type))
690
1.92M
            {
691
1.92M
              if UNLIKELY
692
1.92M
                (fsi_stack_size == fsi_stack_capacity)
693
1.50k
                {
694
1.50k
                  int new_capacity = fsi_stack_capacity * 2;
695
1.50k
                  FriBidiRun **new_stack =
696
1.50k
                    fribidi_malloc (new_capacity * sizeof (*new_stack));
697
1.50k
                  if UNLIKELY
698
1.50k
                    (!new_stack) break;
699
1.50k
                  memcpy (new_stack, fsi_stack,
700
1.50k
                          fsi_stack_size * sizeof (*new_stack));
701
1.50k
                  if (fsi_stack_heap)
702
1.10k
                    fribidi_free (fsi_stack);
703
1.50k
                  fsi_stack = new_stack;
704
1.50k
                  fsi_stack_capacity = new_capacity;
705
1.50k
                  fsi_stack_heap = true;
706
1.50k
                }
707
708
1.92M
              if (fsi_this_type == FRIBIDI_TYPE_FSI)
709
1.83M
                {
710
1.83M
                  RL_FSI_BASE_LEVEL (fsi_pp) = 0;
711
1.83M
                  fsi_stack[fsi_stack_size++] = fsi_pp;
712
1.83M
                }
713
81.9k
              else
714
81.9k
                fsi_stack[fsi_stack_size++] = NULL;
715
1.92M
            }
716
5.72M
          else if (fsi_stack_size && FRIBIDI_IS_LETTER (fsi_this_type))
717
383k
            {
718
383k
              FriBidiRun *pending = fsi_stack[fsi_stack_size - 1];
719
383k
              if (pending)
720
12.4k
                {
721
12.4k
                  RL_FSI_BASE_LEVEL (pending) =
722
12.4k
                    FRIBIDI_DIR_TO_LEVEL (fsi_this_type);
723
                  /* Found; stop this isolate from being resolved again
724
                     by a later, incorrect, character. */
725
12.4k
                  fsi_stack[fsi_stack_size - 1] = NULL;
726
12.4k
                }
727
383k
            }
728
7.68M
        }
729
730
884
      if (fsi_stack_heap)
731
397
        fribidi_free (fsi_stack);
732
884
    }
733
734
    /* X1. Begin by setting the current embedding level to the paragraph
735
       embedding level. Set the directional override status to neutral,
736
       and directional isolate status to false.
737
738
       Process each character iteratively, applying rules X2 through X8.
739
       Only embedding levels from 0 to 123 are valid in this phase. */
740
741
1.88k
    level = base_level;
742
1.88k
    override = FRIBIDI_TYPE_ON;
743
    /* stack */
744
1.88k
    stack_size = 0;
745
1.88k
    over_pushed = 0;
746
1.88k
    first_interval = 0;
747
1.88k
    valid_isolate_count = 0;
748
1.88k
    isolate_overflow = 0;
749
750
1.88k
    for_run_list (pp, main_run_list)
751
7.55M
    {
752
7.55M
      FriBidiCharType this_type = RL_TYPE (pp);
753
7.55M
      RL_ISOLATE_LEVEL (pp) = isolate_level;
754
755
7.55M
      if (FRIBIDI_IS_EXPLICIT_OR_BN (this_type))
756
3.15M
  {
757
3.15M
    if (FRIBIDI_IS_STRONG (this_type))
758
3.00M
      {     /* LRE, RLE, LRO, RLO */
759
        /* 1. Explicit Embeddings */
760
        /*   X2. With each RLE, compute the least greater odd
761
           embedding level. */
762
        /*   X3. With each LRE, compute the least greater even
763
           embedding level. */
764
        /* 2. Explicit Overrides */
765
        /*   X4. With each RLO, compute the least greater odd
766
           embedding level. */
767
        /*   X5. With each LRO, compute the least greater even
768
           embedding level. */
769
3.00M
        new_override = FRIBIDI_EXPLICIT_TO_OVERRIDE_DIR (this_type);
770
6.15M
        for (i = RL_LEN (pp); i; i--)
771
3.15M
    {
772
3.15M
      new_level =
773
3.15M
        ((level + FRIBIDI_DIR_TO_LEVEL (this_type) + 2) & ~1) -
774
3.15M
        FRIBIDI_DIR_TO_LEVEL (this_type);
775
3.15M
                  isolate = 0;
776
3.15M
      PUSH_STATUS;
777
3.15M
    }
778
3.00M
      }
779
146k
    else if (this_type == FRIBIDI_TYPE_PDF)
780
15.3k
      {
781
        /* 3. Terminating Embeddings and overrides */
782
        /*   X7. With each PDF, determine the matching embedding or
783
           override code. If the overflow isolate count is greater than
784
           zero, do nothing. Otherwise, if the overflow embedding count
785
           is greater than zero, decrement it. Otherwise pop the stack,
786
           unless the last entry is an isolate. */
787
551k
              for (i = RL_LEN (pp); i; i--)
788
543k
                {
789
543k
                  if (isolate_overflow > 0)
790
6.11k
                    break;
791
537k
                  if (over_pushed == 0
792
536k
                      && stack_size && status_stack[stack_size-1].isolate != 0)
793
947
                    break;
794
537k
                  POP_STATUS;
795
536k
                }
796
15.3k
      }
797
798
    /* X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes. */
799
    /* Remove element and add it to explicits_list */
800
3.15M
    RL_LEVEL (pp) = FRIBIDI_SENTINEL;
801
3.15M
    temp_link.next = pp->next;
802
3.15M
    move_node_before (pp, explicits_list);
803
3.15M
    pp = &temp_link;
804
3.15M
  }
805
4.39M
      else if (this_type == FRIBIDI_TYPE_PDI)
806
        /* X6a. pop the direction of the stack */
807
26.1k
        {
808
52.2k
          for (i = RL_LEN (pp); i; i--)
809
26.1k
            {
810
26.1k
              if (isolate_overflow > 0)
811
4.97k
                {
812
4.97k
                  isolate_overflow--;
813
4.97k
                  RL_LEVEL (pp) = level;
814
4.97k
                }
815
816
21.1k
              else if (valid_isolate_count > 0)
817
5.91k
                {
818
                  /* Pop away all LRE,RLE,LRO, RLO levels
819
                     from the stack, as these are implicitly
820
                     terminated by the PDI */
821
451k
                  while (stack_size && !status_stack[stack_size-1].isolate)
822
445k
                    POP_STATUS;
823
5.91k
                  over_pushed = 0; /* The PDI resets the overpushed! */
824
5.91k
                  POP_STATUS;
825
5.91k
                  if (isolate_level>0)
826
5.91k
                    isolate_level--;
827
5.91k
                  valid_isolate_count--;
828
5.91k
                  RL_LEVEL (pp) = level;
829
5.91k
                  RL_ISOLATE_LEVEL (pp) = isolate_level;
830
5.91k
                }
831
15.2k
              else
832
15.2k
                {
833
                  /* Ignore isolated PDI's by turning them into ON's */
834
15.2k
                  RL_TYPE (pp) = FRIBIDI_TYPE_ON;
835
15.2k
                  RL_LEVEL (pp) = level;
836
15.2k
                }
837
26.1k
            }
838
26.1k
        }
839
4.37M
      else if (FRIBIDI_IS_ISOLATE(this_type))
840
1.90M
        {
841
          /* TBD support RL_LEN > 1 */
842
1.90M
          new_override = FRIBIDI_TYPE_ON;
843
1.90M
          isolate = 1;
844
1.90M
          if (this_type == FRIBIDI_TYPE_LRI)
845
44.3k
            new_level = level + 2 - (level%2);
846
1.85M
          else if (this_type == FRIBIDI_TYPE_RLI)
847
30.0k
            new_level = level + 1 + (level%2);
848
1.82M
          else if (this_type == FRIBIDI_TYPE_FSI)
849
1.82M
            {
850
              /* The effective direction was already resolved by the
851
                 single-pass X5c preprocessing above; just look it up. */
852
1.82M
              FriBidiLevel fsi_base_level = RL_FSI_BASE_LEVEL (pp);
853
854
              /* Same behavior like RLI and LRI above */
855
1.82M
              if (FRIBIDI_LEVEL_IS_RTL (fsi_base_level))
856
920
                new_level = level + 1 + (level%2);
857
1.82M
              else
858
1.82M
                new_level = level + 2 - (level%2);
859
1.82M
            }
860
861
1.90M
    RL_LEVEL (pp) = level;
862
1.90M
          RL_ISOLATE_LEVEL (pp) = isolate_level;
863
864
1.90M
    if (!FRIBIDI_IS_NEUTRAL (override))
865
7.17k
      RL_TYPE (pp) = override;
866
867
          /* X5a-X5c. The isolate is valid only if the new level is valid
868
             and both the overflow isolate count and the overflow embedding
869
             count are zero; otherwise it is an overflow isolate and leaves
870
             the level, the isolate level and the stack unchanged. */
871
1.90M
          if (new_level <= FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL
872
52.6k
              && over_pushed == 0 && isolate_overflow == 0)
873
28.6k
            {
874
28.6k
              valid_isolate_count++;
875
28.6k
              if (isolate_level < FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL-1)
876
28.3k
                isolate_level++;
877
28.6k
              PUSH_STATUS;
878
28.6k
              level = new_level;
879
28.6k
            }
880
1.87M
          else
881
1.87M
            isolate_overflow += 1;
882
1.90M
        }
883
2.47M
      else if (this_type == FRIBIDI_TYPE_BS)
884
297
  {
885
    /* X8. All explicit directional embeddings and overrides are
886
       completely terminated at the end of each paragraph. Paragraph
887
       separators are not included in the embedding. */
888
297
    break;
889
297
  }
890
2.47M
      else
891
2.47M
  {
892
    /* X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
893
       a. Set the level of the current character to the current
894
       embedding level.
895
       b. Whenever the directional override status is not neutral,
896
       reset the current character type to the directional override
897
       status. */
898
2.47M
    RL_LEVEL (pp) = level;
899
2.47M
    if (!FRIBIDI_IS_NEUTRAL (override))
900
189k
      RL_TYPE (pp) = override;
901
2.47M
  }
902
7.55M
    }
903
904
    /* Build the isolate_level connections */
905
1.88k
    prev_isolate_level = 0;
906
1.88k
    for_run_list (pp, main_run_list)
907
5.83M
    {
908
5.83M
      int isolate_level = RL_ISOLATE_LEVEL (pp);
909
5.83M
      int i;
910
911
      /* When going from an upper to a lower level, zero out all higher levels
912
         in order not erroneous connections! */
913
5.83M
      if (isolate_level<prev_isolate_level)
914
10.4k
        for (i=isolate_level+1; i<=prev_isolate_level; i++)
915
5.98k
          run_per_isolate_level[i]=0;
916
5.83M
      prev_isolate_level = isolate_level;
917
      
918
5.83M
      if (run_per_isolate_level[isolate_level])
919
5.81M
        {
920
5.81M
          run_per_isolate_level[isolate_level]->next_isolate = pp;
921
5.81M
          pp->prev_isolate = run_per_isolate_level[isolate_level];
922
5.81M
        }
923
5.83M
      run_per_isolate_level[isolate_level] = pp;
924
5.83M
    }
925
926
    /* Implementing X8. It has no effect on a single paragraph! */
927
1.88k
    level = base_level;
928
1.88k
    override = FRIBIDI_TYPE_ON;
929
1.88k
    stack_size = 0;
930
1.88k
    over_pushed = 0;
931
1.88k
  }
932
  /* X10. The remaining rules are applied to each run of characters at the
933
     same level. For each run, determine the start-of-level-run (sor) and
934
     end-of-level-run (eor) type, either L or R. This depends on the
935
     higher of the two levels on either side of the boundary (at the start
936
     or end of the paragraph, the level of the 'other' run is the base
937
     embedding level). If the higher level is odd, the type is R, otherwise
938
     it is L. */
939
  /* Resolving Implicit Levels can be done out of X10 loop, so only change
940
     of Resolving Weak Types and Resolving Neutral Types is needed. */
941
942
0
  compact_list (main_run_list);
943
944
1.88k
# if DEBUG
945
1.88k
  if UNLIKELY
946
1.88k
    (fribidi_debug_status ())
947
0
    {
948
0
      print_types_re (main_run_list);
949
0
      print_bidi_string (bidi_types, len);
950
0
      print_resolved_levels (main_run_list);
951
0
      print_resolved_types (main_run_list);
952
0
    }
953
1.88k
# endif /* DEBUG */
954
955
  /* 4. Resolving weak types. Also calculate the maximum isolate level */
956
1.88k
  max_iso_level = 0;
957
1.88k
  DBG ("4a. resolving weak types");
958
1.88k
  {
959
1.88k
    int last_strong_stack[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
960
1.88k
    FriBidiRun *next_run[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
961
1.88k
    FriBidiCharType prev_type_orig;
962
1.88k
    fribidi_boolean w4;
963
964
1.88k
    last_strong_stack[0] = base_dir;
965
966
1.88k
    for_run_list (pp, main_run_list)
967
3.68M
    {
968
3.68M
      register FriBidiCharType prev_type, this_type, next_type;
969
3.68M
      FriBidiRun *ppp_prev, *ppp_next;
970
3.68M
      int iso_level;
971
972
3.68M
      ppp_prev = get_adjacent_run(pp, false, false);
973
3.68M
      ppp_next = get_adjacent_run(pp, true, false);
974
975
3.68M
      this_type = RL_TYPE (pp);
976
3.68M
      iso_level = RL_ISOLATE_LEVEL(pp);
977
978
3.68M
      if (iso_level > max_iso_level)
979
23.8k
        max_iso_level = iso_level;
980
981
3.68M
      if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
982
3.65M
        prev_type = RL_TYPE(ppp_prev);
983
32.3k
      else
984
32.3k
        prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
985
986
3.68M
      if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
987
3.64M
        next_type = RL_TYPE(ppp_next);
988
34.7k
      else
989
34.7k
        next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
990
991
3.68M
      if (FRIBIDI_IS_STRONG (prev_type))
992
1.00M
  last_strong_stack[iso_level] = prev_type;
993
994
      /* W1. NSM
995
         Examine each non-spacing mark (NSM) in the level run, and change the
996
         type of the NSM to the type of the previous character. If the NSM
997
         is at the start of the level run, it will get the type of sor. */
998
      /* Implementation note: it is important that if the previous character
999
         is not sor, then we should merge this run with the previous,
1000
         because of rules like W5, that we assume all of a sequence of
1001
         adjacent ETs are in one FriBidiRun. */
1002
3.68M
      if (this_type == FRIBIDI_TYPE_NSM)
1003
89.3k
  {
1004
          /* New rule in Unicode 6.3 */
1005
89.3k
          if (FRIBIDI_IS_ISOLATE (RL_TYPE (pp->prev)))
1006
4.83k
              RL_TYPE(pp) = FRIBIDI_TYPE_ON;
1007
1008
89.3k
    if (RL_LEVEL (ppp_prev) == RL_LEVEL (pp))
1009
88.5k
            {
1010
88.5k
              if (ppp_prev == pp->prev)
1011
88.5k
                pp = merge_with_prev (pp);
1012
88.5k
            }
1013
791
    else
1014
791
      RL_TYPE (pp) = prev_type;
1015
1016
89.3k
    if (prev_type == next_type && RL_LEVEL (pp) == RL_LEVEL (pp->next))
1017
76.7k
      {
1018
76.7k
              if (ppp_next == pp->next)
1019
76.5k
                pp = merge_with_prev (pp->next);
1020
76.7k
      }
1021
89.3k
    continue;   /* As we know the next condition cannot be true. */
1022
89.3k
  }
1023
1024
      /* W2: European numbers. */
1025
3.59M
      if (this_type == FRIBIDI_TYPE_EN && last_strong_stack[iso_level] == FRIBIDI_TYPE_AL)
1026
2.44k
  {
1027
2.44k
    RL_TYPE (pp) = FRIBIDI_TYPE_AN;
1028
1029
    /* Resolving dependency of loops for rules W1 and W2, so we
1030
       can merge them in one loop. */
1031
2.44k
    if (next_type == FRIBIDI_TYPE_NSM)
1032
566
      RL_TYPE (ppp_next) = FRIBIDI_TYPE_AN;
1033
2.44k
  }
1034
3.59M
    }
1035
1036
1.88k
# if DEBUG
1037
1.88k
  if UNLIKELY
1038
1.88k
    (fribidi_debug_status ())
1039
0
    {
1040
0
      print_resolved_levels (main_run_list);
1041
0
      print_resolved_types (main_run_list);
1042
0
    }
1043
1.88k
# endif /* DEBUG */
1044
1045
    /* The last iso level is used to invalidate the the last strong values when going from
1046
       a higher to a lower iso level. When this occur, all "last_strong" values are
1047
       set to the base_dir. */
1048
1.88k
    last_strong_stack[0] = base_dir;
1049
1050
1.88k
    DBG ("4b. resolving weak types. W4 and W5");
1051
1052
    /* Resolving dependency of loops for rules W4 and W5, W5 may
1053
       want to prevent W4 to take effect in the next turn, do this
1054
       through "w4". */
1055
1.88k
    w4 = true;
1056
    /* Resolving dependency of loops for rules W4 and W5 with W7,
1057
       W7 may change an EN to L but it sets the prev_type_orig if needed,
1058
       so W4 and W5 in next turn can still do their works. */
1059
1.88k
    prev_type_orig = FRIBIDI_TYPE_ON;
1060
1061
1.88k
    memset (next_run, 0, sizeof (next_run));
1062
1063
    /* Each isolate level has its own memory of the last strong character */
1064
1.88k
    for_run_list (pp, main_run_list)
1065
3.59M
    {
1066
3.59M
      register FriBidiCharType prev_type, this_type, next_type;
1067
3.59M
      int iso_level;
1068
3.59M
      FriBidiRun *ppp_prev, *ppp_next;
1069
1070
3.59M
      this_type = RL_TYPE (pp);
1071
3.59M
      iso_level = RL_ISOLATE_LEVEL(pp);
1072
1073
3.59M
      ppp_prev = get_adjacent_run(pp, false, false);
1074
3.59M
      ppp_next = get_next_run_cached(pp, next_run);
1075
1076
3.59M
      if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
1077
3.56M
        prev_type = RL_TYPE(ppp_prev);
1078
32.3k
      else
1079
32.3k
        prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
1080
1081
3.59M
      if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
1082
3.56M
        next_type = RL_TYPE(ppp_next);
1083
35.2k
      else
1084
35.2k
        next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
1085
1086
3.59M
      if (FRIBIDI_IS_STRONG (prev_type))
1087
937k
  last_strong_stack[iso_level] = prev_type;
1088
1089
      /* W2 ??? */
1090
1091
      /* W3: Change ALs to R. */
1092
3.59M
      if (this_type == FRIBIDI_TYPE_AL)
1093
4.26k
  {
1094
4.26k
    RL_TYPE (pp) = FRIBIDI_TYPE_RTL;
1095
4.26k
    w4 = true;
1096
4.26k
    prev_type_orig = FRIBIDI_TYPE_ON;
1097
4.26k
    continue;
1098
4.26k
  }
1099
1100
      /* W4. A single european separator changes to a european number.
1101
         A single common separator between two numbers of the same type
1102
         changes to that type. */
1103
3.59M
      if (w4
1104
3.58M
    && RL_LEN (pp) == 1 && FRIBIDI_IS_ES_OR_CS (this_type)
1105
9.77k
    && FRIBIDI_IS_NUMBER (prev_type_orig)
1106
3.96k
    && prev_type_orig == next_type
1107
2.98k
    && (prev_type_orig == FRIBIDI_TYPE_EN
1108
2.54k
        || this_type == FRIBIDI_TYPE_CS))
1109
2.47k
  {
1110
2.47k
    RL_TYPE (pp) = prev_type;
1111
2.47k
    this_type = RL_TYPE (pp);
1112
2.47k
  }
1113
3.59M
      w4 = true;
1114
1115
      /* W5. A sequence of European terminators adjacent to European
1116
         numbers changes to All European numbers. */
1117
3.59M
      if (this_type == FRIBIDI_TYPE_ET
1118
5.37k
    && (prev_type_orig == FRIBIDI_TYPE_EN
1119
4.66k
        || next_type == FRIBIDI_TYPE_EN))
1120
2.16k
  {
1121
2.16k
    RL_TYPE (pp) = FRIBIDI_TYPE_EN;
1122
2.16k
    w4 = false;
1123
2.16k
    this_type = RL_TYPE (pp);
1124
2.16k
  }
1125
1126
      /* W6. Otherwise change separators and terminators to other neutral. */
1127
3.59M
      if (FRIBIDI_IS_NUMBER_SEPARATOR_OR_TERMINATOR (this_type))
1128
10.5k
  RL_TYPE (pp) = FRIBIDI_TYPE_ON;
1129
1130
      /* W7. Change european numbers to L. */
1131
3.59M
      if (this_type == FRIBIDI_TYPE_EN && last_strong_stack[iso_level] == FRIBIDI_TYPE_LTR)
1132
9.14k
  {
1133
9.14k
    RL_TYPE (pp) = FRIBIDI_TYPE_LTR;
1134
9.14k
    prev_type_orig = (RL_LEVEL (pp) == RL_LEVEL (pp->next) ?
1135
8.91k
          FRIBIDI_TYPE_EN : FRIBIDI_TYPE_ON);
1136
9.14k
  }
1137
3.58M
      else
1138
3.58M
  prev_type_orig = PREV_TYPE_OR_SOR (pp->next);
1139
3.59M
    }
1140
1.88k
  }
1141
1142
1.88k
  compact_neutrals (main_run_list);
1143
1144
1.88k
# if DEBUG
1145
1.88k
  if UNLIKELY
1146
1.88k
    (fribidi_debug_status ())
1147
0
    {
1148
0
      print_resolved_levels (main_run_list);
1149
0
      print_resolved_types (main_run_list);
1150
0
    }
1151
1.88k
# endif /* DEBUG */
1152
1153
  /* 5. Resolving Neutral Types */
1154
1155
1.88k
  DBG ("5. resolving neutral types - N0");
1156
1.88k
  {
1157
    /*  BD16 - Build list of all pairs*/
1158
1.88k
    int num_iso_levels = max_iso_level + 1;
1159
1.88k
    FriBidiPairingNodeArray pairing_nodes;
1160
1.88k
    fribidi_boolean pairing_alloc_failed = false;
1161
    /* One full-size pair stack for each of the first LOCAL_BRACKET_SIZE
1162
       isolate levels; higher levels get theirs from the heap below. */
1163
1.88k
    FriBidiRun *local_bracket_stack[LOCAL_BRACKET_SIZE][FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS];
1164
1.88k
    FriBidiRun **bracket_stack[FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL];
1165
1.88k
    int bracket_stack_size[FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL];
1166
    /* Track the position of the most recently seen strong character, per
1167
       resolved level and per isolate level. When a bracket pair is closed,
1168
       it encloses such a character iff that position is past its opening
1169
       bracket. This lets N0b and N0c below know what a pair encloses
1170
       without rescanning it from the opening to the closing bracket, which
1171
       visited every run once per enclosing pair, and up to
1172
       FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS pairs can be open on each
1173
       isolate level at the same time. */
1174
1.88k
    FriBidiStrIndex last_strong_pos[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
1175
1.88k
    FriBidiStrIndex last_iso_strong_pos[FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL];
1176
1177
1.88k
    pairing_node_array_init (&pairing_nodes);
1178
1.88k
    memset(bracket_stack, 0, sizeof(bracket_stack[0])*num_iso_levels);
1179
1.88k
    memset(bracket_stack_size, 0, sizeof(bracket_stack_size[0])*num_iso_levels);
1180
1.88k
    memset(last_strong_pos, 0xFF, sizeof(last_strong_pos));
1181
1.88k
    memset(last_iso_strong_pos, 0xFF, sizeof(last_iso_strong_pos[0])*num_iso_levels);
1182
1183
    /* populate the bracket_size. The first LOCAL_BRACKET_SIZE entries
1184
       of the stack are one the stack. Allocate the rest of the entries.
1185
     */
1186
1.88k
    {
1187
1.88k
      int iso_level;
1188
31.9k
      for (iso_level=0; iso_level < LOCAL_BRACKET_SIZE; iso_level++)
1189
30.0k
        bracket_stack[iso_level] = local_bracket_stack[iso_level];
1190
1191
18.7k
      for (iso_level=LOCAL_BRACKET_SIZE; iso_level < num_iso_levels; iso_level++)
1192
16.8k
        bracket_stack[iso_level] = fribidi_malloc (sizeof (bracket_stack[0])
1193
16.8k
                                                       * FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS);
1194
1195
18.7k
      for (iso_level=LOCAL_BRACKET_SIZE; iso_level < num_iso_levels; iso_level++)
1196
16.8k
        if UNLIKELY
1197
16.8k
          (!bracket_stack[iso_level])
1198
0
          {
1199
0
            int i;
1200
0
            for (i=LOCAL_BRACKET_SIZE; i<num_iso_levels; i++)
1201
0
              fribidi_free(bracket_stack[i]);
1202
0
            free_pairing_nodes (&pairing_nodes);
1203
0
            status = false;
1204
0
            goto out;
1205
0
          }
1206
1.88k
    }
1207
1208
    /* Build the bd16 pair stack. */
1209
1.88k
    for_run_list (pp, main_run_list)
1210
3.56M
      {
1211
3.56M
        int level = RL_LEVEL(pp);
1212
3.56M
        int iso_level = RL_ISOLATE_LEVEL(pp);
1213
3.56M
        FriBidiBracketType brack_prop = RL_BRACKET_TYPE(pp);
1214
3.56M
        FriBidiCharType this_type = RL_TYPE_AN_EN_AS_RTL(pp);
1215
1216
        /* An isolating run sequence ends at a change in the level
1217
           between consecutive runs of an isolate chain, and when a new
1218
           chain starts (the first run of an isolate, also of a sibling
1219
           isolate at the same isolate level). Brackets do not pair
1220
           across sequences. */
1221
3.56M
        if (!pp->prev_isolate || RL_LEVEL (pp->prev_isolate) != level)
1222
32.3k
          bracket_stack_size[iso_level] = 0;
1223
1224
3.56M
        if (FRIBIDI_IS_STRONG (this_type))
1225
906k
          {
1226
            /* Calculate level like in resolve implicit levels below to prevent
1227
               embedded levels not to match the base_level */
1228
906k
            last_strong_pos[level +
1229
906k
              (FRIBIDI_LEVEL_IS_RTL (level) ^ FRIBIDI_DIR_TO_LEVEL (this_type))] = pp->pos;
1230
906k
            last_iso_strong_pos[iso_level] = pp->pos;
1231
906k
          }
1232
1233
3.56M
        if (brack_prop!= FRIBIDI_NO_BRACKET
1234
2.01M
            && RL_TYPE(pp)==FRIBIDI_TYPE_ON)
1235
1.93M
          {
1236
1.93M
            if (FRIBIDI_IS_BRACKET_OPEN(brack_prop))
1237
990k
              {
1238
                /* BD16: a full stack stops pairing for the remainder of
1239
                   this isolating run sequence only. A negative size marks
1240
                   the sequence as stopped until the size is reset above. */
1241
990k
                if (bracket_stack_size[iso_level]==FRIBIDI_BIDI_MAX_NESTED_BRACKET_PAIRS)
1242
366
                  bracket_stack_size[iso_level] = -1;
1243
989k
                else if (bracket_stack_size[iso_level] >= 0)
1244
                  /* push onto the pair stack */
1245
827k
                  bracket_stack[iso_level][bracket_stack_size[iso_level]++] = pp;
1246
990k
              }
1247
947k
            else
1248
947k
              {
1249
947k
                int stack_idx = bracket_stack_size[iso_level] - 1;
1250
1.04M
                while (stack_idx >= 0)
1251
883k
                  {
1252
883k
                    FriBidiRun *open = bracket_stack[iso_level][stack_idx];
1253
883k
                    FriBidiBracketType se_brack_prop = RL_BRACKET_TYPE(open);
1254
883k
                    if (FRIBIDI_BRACKET_ID(se_brack_prop) == FRIBIDI_BRACKET_ID(brack_prop))
1255
784k
                      {
1256
784k
                        bracket_stack_size[iso_level] = stack_idx;
1257
1258
784k
                        if UNLIKELY
1259
784k
                          (!pairing_node_array_push (&pairing_nodes,
1260
784k
                                                     open,
1261
784k
                                                     pp,
1262
784k
                                                     last_strong_pos[RL_LEVEL(open)] > open->pos,
1263
784k
                                                     last_iso_strong_pos[RL_ISOLATE_LEVEL(open)] > open->pos))
1264
0
                          pairing_alloc_failed = true;
1265
784k
                        break;
1266
784k
                    }
1267
99.3k
                    stack_idx--;
1268
99.3k
                  }
1269
947k
              }
1270
1.93M
          }
1271
3.56M
        if UNLIKELY
1272
3.56M
          (pairing_alloc_failed) break;
1273
3.56M
      }
1274
1275
1.88k
    if UNLIKELY
1276
1.88k
      (pairing_alloc_failed)
1277
0
      {
1278
0
        free_pairing_nodes (&pairing_nodes);
1279
0
        if (num_iso_levels >= LOCAL_BRACKET_SIZE)
1280
0
          {
1281
0
            int i;
1282
0
            for (i=LOCAL_BRACKET_SIZE; i<num_iso_levels; i++)
1283
0
              fribidi_free(bracket_stack[i]);
1284
0
          }
1285
0
        status = false;
1286
0
        goto out;
1287
0
      }
1288
1289
    /* The list must now be sorted for the next algo to work! */
1290
1.88k
    sort_pairing_nodes(&pairing_nodes);
1291
1292
1.88k
# if DEBUG
1293
1.88k
    if UNLIKELY
1294
1.88k
    (fribidi_debug_status ())
1295
0
      {
1296
0
        print_pairing_nodes (&pairing_nodes);
1297
0
      }
1298
1.88k
# endif /* DEBUG */
1299
1300
    /* Start the N0 */
1301
1.88k
    {
1302
1.88k
      int ppairs_idx;
1303
      /* Track, per isolate level, the level of the most recently seen
1304
         strong character while sweeping the run list forward exactly
1305
         once (strong_scan_pp only ever moves forward, it is never
1306
         rewound). This lets N0c below look up the preceding strong
1307
         character for each bracket pair in amortized O(1) instead of
1308
         rescanning backwards toward the start of the string for every
1309
         pair, which made runs of many bracket pairs with no strong
1310
         content quadratic. */
1311
1.88k
      int last_strong_level[FRIBIDI_BIDI_MAX_EXPLICIT_LEVEL];
1312
1.88k
      FriBidiRun *strong_scan_pp = main_run_list->next;
1313
1.88k
      memset (last_strong_level, 0xFF, sizeof (int) * num_iso_levels);
1314
1315
785k
      for (ppairs_idx = 0; ppairs_idx < pairing_nodes.count; ppairs_idx++)
1316
784k
        {
1317
784k
          FriBidiPairingNode *ppairs = &pairing_nodes.nodes[ppairs_idx];
1318
784k
          int embedding_level = ppairs->open->level;
1319
1320
784k
          if (ppairs->has_embedding_strong)
1321
4.79k
            {
1322
              /* N0b */
1323
4.79k
              RL_TYPE(ppairs->open) = RL_TYPE(ppairs->close) = embedding_level%2 ? FRIBIDI_TYPE_RTL : FRIBIDI_TYPE_LTR;
1324
4.79k
            }
1325
779k
          else if (ppairs->has_isolate_strong)
1326
1.11k
            {
1327
              /* N0c */
1328
              /* By constraint the strong type within the bracket pair is
1329
                 opposite the embedding direction, since we did not match
1330
                 the N0b rule. We must now compare with the preceding strong
1331
                 to establish whether to apply N0c1 (opposite) or N0c2
1332
                 embedding */
1333
1334
              /* Search for a preceding strong. Catch the sweep cursor up
1335
                 to this pair's opening bracket, recording the level of
1336
                 every strong character passed along the way, indexed by
1337
                 its isolate level. */
1338
1.11k
              int iso_level = RL_ISOLATE_LEVEL(ppairs->open);
1339
1.11k
              int prec_strong_level;
1340
1341
              /* The sweep includes the opening bracket's own run, so that
1342
                 a pair starting an isolating run sequence sees its sos. */
1343
479k
              for (; strong_scan_pp != ppairs->open->next; strong_scan_pp = strong_scan_pp->next)
1344
478k
                {
1345
478k
                  FriBidiCharType this_type = RL_TYPE_AN_EN_AS_RTL(strong_scan_pp);
1346
478k
                  int scan_iso_level = RL_ISOLATE_LEVEL(strong_scan_pp);
1347
478k
                  int scan_level = RL_LEVEL(strong_scan_pp);
1348
478k
                  FriBidiRun *scan_prev = strong_scan_pp->prev_isolate;
1349
1350
                  /* A run that does not continue the previous run of its
1351
                     isolate chain at the same level starts a new isolating
1352
                     run sequence. The strong type preceding it is then the
1353
                     sequence's sos (X10): the higher of its level and the
1354
                     level before it, which for the first run of an isolate
1355
                     (or of the paragraph) is never above its own. It is not
1356
                     the last strong character of an earlier sequence at the
1357
                     same isolate level, such as a preceding sibling isolate. */
1358
478k
                  if (!scan_prev)
1359
3.61k
                    last_strong_level[scan_iso_level] = scan_level;
1360
475k
                  else if (RL_LEVEL (scan_prev) != scan_level)
1361
1.22k
                    last_strong_level[scan_iso_level] = MAX (scan_level, RL_LEVEL (scan_prev));
1362
1363
478k
                  if (FRIBIDI_IS_STRONG (this_type))
1364
139k
                    {
1365
139k
                      last_strong_level[scan_iso_level] = scan_level +
1366
139k
                        (FRIBIDI_LEVEL_IS_RTL (scan_level) ^ FRIBIDI_DIR_TO_LEVEL (this_type));
1367
139k
                    }
1368
478k
                }
1369
1370
1.11k
              prec_strong_level = last_strong_level[iso_level] >= 0 ?
1371
1.11k
                last_strong_level[iso_level] : embedding_level;
1372
1373
1.11k
              RL_TYPE(ppairs->open) = RL_TYPE(ppairs->close) = prec_strong_level % 2 ? FRIBIDI_TYPE_RTL : FRIBIDI_TYPE_LTR;
1374
1.11k
            }
1375
784k
        }
1376
1377
1.88k
      free_pairing_nodes(&pairing_nodes);
1378
1379
1.88k
      if (num_iso_levels >= LOCAL_BRACKET_SIZE)
1380
391
        {
1381
391
          int i;
1382
          /* Only need to free the non static members */
1383
17.2k
          for (i=LOCAL_BRACKET_SIZE; i<num_iso_levels; i++)
1384
16.8k
            fribidi_free(bracket_stack[i]);
1385
391
        }
1386
1387
      /* Remove the bracket property and re-compact */
1388
1.88k
      {
1389
1.88k
        const FriBidiBracketType NoBracket = FRIBIDI_NO_BRACKET;
1390
1.88k
        for_run_list (pp, main_run_list)
1391
3.56M
          pp->bracket_type = NoBracket;
1392
1.88k
        compact_neutrals (main_run_list);
1393
1.88k
      }
1394
1.88k
    }
1395
1396
1.88k
# if DEBUG
1397
1.88k
  if UNLIKELY
1398
1.88k
    (fribidi_debug_status ())
1399
0
    {
1400
0
      print_resolved_levels (main_run_list);
1401
0
      print_resolved_types (main_run_list);
1402
0
    }
1403
1.88k
# endif /* DEBUG */
1404
1.88k
  }
1405
1406
1.88k
  DBG ("resolving neutral types - N1+N2");
1407
1.88k
  {
1408
1.88k
    FriBidiRun *next_run[FRIBIDI_BIDI_MAX_RESOLVED_LEVELS];
1409
1410
1.88k
    memset (next_run, 0, sizeof (next_run));
1411
1412
1.88k
    for_run_list (pp, main_run_list)
1413
1.55M
    {
1414
1.55M
      FriBidiCharType prev_type, this_type, next_type;
1415
1.55M
      FriBidiRun *ppp_prev, *ppp_next;
1416
1417
1.55M
      ppp_prev = get_adjacent_run(pp, false, false);
1418
1.55M
      ppp_next = get_next_run_cached(pp, next_run);
1419
1420
      /* "European and Arabic numbers are treated as though they were R"
1421
         FRIBIDI_CHANGE_NUMBER_TO_RTL does this. */
1422
1.55M
      this_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE (pp));
1423
1424
1.55M
      if (RL_LEVEL(ppp_prev) == RL_LEVEL(pp))
1425
1.52M
        prev_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE(ppp_prev));
1426
32.3k
      else
1427
32.3k
        prev_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_prev), RL_LEVEL(pp)));
1428
1429
1.55M
      if (RL_LEVEL(ppp_next) == RL_LEVEL(pp))
1430
1.52M
        next_type = FRIBIDI_CHANGE_NUMBER_TO_RTL (RL_TYPE(ppp_next));
1431
35.5k
      else
1432
35.5k
        next_type = FRIBIDI_LEVEL_TO_DIR(MAX(RL_LEVEL(ppp_next), RL_LEVEL(pp)));
1433
1434
1.55M
      if (FRIBIDI_IS_NEUTRAL (this_type))
1435
350k
  RL_TYPE (pp) = (prev_type == next_type) ?
1436
334k
    /* N1. */ prev_type :
1437
350k
    /* N2. */ FRIBIDI_EMBEDDING_DIRECTION (pp);
1438
1.55M
    }
1439
1.88k
  }
1440
1441
1.88k
  compact_list (main_run_list);
1442
1443
1.88k
# if DEBUG
1444
1.88k
  if UNLIKELY
1445
1.88k
    (fribidi_debug_status ())
1446
0
    {
1447
0
      print_resolved_levels (main_run_list);
1448
0
      print_resolved_types (main_run_list);
1449
0
    }
1450
1.88k
# endif /* DEBUG */
1451
1452
  /* 6. Resolving implicit levels */
1453
1.88k
  DBG ("resolving implicit levels");
1454
1.88k
  {
1455
1.88k
    max_level = base_level;
1456
1457
1.88k
    for_run_list (pp, main_run_list)
1458
936k
    {
1459
936k
      FriBidiCharType this_type;
1460
936k
      int level;
1461
1462
936k
      this_type = RL_TYPE (pp);
1463
936k
      level = RL_LEVEL (pp);
1464
1465
      /* I1. Even */
1466
      /* I2. Odd */
1467
936k
      if (FRIBIDI_IS_NUMBER (this_type))
1468
6.09k
  RL_LEVEL (pp) = (level + 2) & ~1;
1469
930k
      else
1470
930k
  RL_LEVEL (pp) =
1471
930k
    level +
1472
930k
    (FRIBIDI_LEVEL_IS_RTL (level) ^ FRIBIDI_DIR_TO_LEVEL (this_type));
1473
1474
936k
      if (RL_LEVEL (pp) > max_level)
1475
25.2k
  max_level = RL_LEVEL (pp);
1476
936k
    }
1477
1.88k
  }
1478
1479
1.88k
  compact_list (main_run_list);
1480
1481
1.88k
# if DEBUG
1482
1.88k
  if UNLIKELY
1483
1.88k
    (fribidi_debug_status ())
1484
0
    {
1485
0
      print_bidi_string (bidi_types, len);
1486
0
      print_resolved_levels (main_run_list);
1487
0
      print_resolved_types (main_run_list);
1488
0
    }
1489
1.88k
# endif /* DEBUG */
1490
1491
/* Reinsert the explicit codes & BN's that are already removed, from the
1492
   explicits_list to main_run_list. */
1493
1.88k
  DBG ("reinserting explicit codes");
1494
1.88k
  if UNLIKELY
1495
1.88k
    (explicits_list->next != explicits_list)
1496
848
    {
1497
848
      register FriBidiRun *p;
1498
848
      register fribidi_boolean stat =
1499
848
  shadow_run_list (main_run_list, explicits_list, true, run_pool);
1500
848
      explicits_list = NULL;
1501
848
      if UNLIKELY
1502
848
  (!stat) goto out;
1503
1504
      /* Set level of inserted explicit chars to that of their previous
1505
       * char, such that they do not affect reordering. */
1506
848
      p = main_run_list->next;
1507
848
      if (p != main_run_list && p->level == FRIBIDI_SENTINEL)
1508
363
  p->level = base_level;
1509
3.87M
      for_run_list (p, main_run_list) if (p->level == FRIBIDI_SENTINEL)
1510
3.15M
  p->level = p->prev->level;
1511
848
    }
1512
1513
1.88k
# if DEBUG
1514
1.88k
  if UNLIKELY
1515
1.88k
    (fribidi_debug_status ())
1516
0
    {
1517
0
      print_types_re (main_run_list);
1518
0
      print_resolved_levels (main_run_list);
1519
0
      print_resolved_types (main_run_list);
1520
0
    }
1521
1.88k
# endif /* DEBUG */
1522
1523
1.88k
  DBG ("reset the embedding levels, 1, 2, 3.");
1524
1.88k
  {
1525
1.88k
    register int j, state, pos;
1526
1.88k
    register FriBidiCharType char_type;
1527
1.88k
    register FriBidiRun *p, *q, *list;
1528
1529
    /* L1. Reset the embedding levels of some chars:
1530
       1. segment separators,
1531
       2. paragraph separators,
1532
       3. any sequence of whitespace characters preceding a segment
1533
          separator or paragraph separator, and
1534
       4. any sequence of whitespace characters and/or isolate formatting
1535
          characters at the end of the line.
1536
       ... (to be continued in fribidi_reorder_line()). */
1537
1.88k
    list = new_run_list (run_pool);
1538
1.88k
    if UNLIKELY
1539
1.88k
      (!list) goto out;
1540
1.88k
    q = list;
1541
1.88k
    state = 1;
1542
1.88k
    pos = len - 1;
1543
21.3M
    for (j = len - 1; j >= -1; j--)
1544
21.3M
      {
1545
  /* close up the open link at the end */
1546
21.3M
  if (j >= 0)
1547
21.3M
    char_type = bidi_types[j];
1548
1.88k
  else
1549
1.88k
    char_type = FRIBIDI_TYPE_ON;
1550
21.3M
  if (!state && FRIBIDI_IS_SEPARATOR (char_type))
1551
149k
    {
1552
149k
      state = 1;
1553
149k
      pos = j;
1554
149k
    }
1555
21.1M
  else if (state &&
1556
3.45M
                 !(FRIBIDI_IS_EXPLICIT_OR_SEPARATOR_OR_BN_OR_WS(char_type)
1557
216k
                   || FRIBIDI_IS_ISOLATE(char_type)))
1558
151k
    {
1559
151k
      state = 0;
1560
151k
      p = new_run (run_pool);
1561
151k
      if UNLIKELY
1562
151k
        (!p)
1563
0
        {
1564
0
    free_run_list (list);
1565
0
    goto out;
1566
0
        }
1567
151k
      p->pos = j + 1;
1568
151k
      p->len = pos - j;
1569
151k
      p->type = base_dir;
1570
151k
      p->level = base_level;
1571
151k
      move_node_before (p, q);
1572
151k
      q = p;
1573
151k
    }
1574
21.3M
      }
1575
1.88k
    if UNLIKELY
1576
1.88k
      (!shadow_run_list (main_run_list, list, false, run_pool)) goto out;
1577
1.88k
  }
1578
1579
1.88k
# if DEBUG
1580
1.88k
  if UNLIKELY
1581
1.88k
    (fribidi_debug_status ())
1582
0
    {
1583
0
      print_types_re (main_run_list);
1584
0
      print_resolved_levels (main_run_list);
1585
0
      print_resolved_types (main_run_list);
1586
0
    }
1587
1.88k
# endif /* DEBUG */
1588
1589
1.88k
  {
1590
1.88k
    FriBidiStrIndex pos = 0;
1591
1.88k
    for_run_list (pp, main_run_list)
1592
4.46M
    {
1593
4.46M
      register FriBidiStrIndex l;
1594
4.46M
      register FriBidiLevel level = pp->level;
1595
25.7M
      for (l = pp->len; l; l--)
1596
21.3M
  embedding_levels[pos++] = level;
1597
4.46M
    }
1598
1.88k
  }
1599
1600
1.88k
  status = true;
1601
1602
1.88k
out:
1603
1.88k
  DBG ("leaving fribidi_get_par_embedding_levels");
1604
1605
1.88k
  fribidi_run_pool_free (run_pool);
1606
1607
1.88k
  return status ? max_level + 1 : 0;
1608
1.88k
}
1609
1610
1611
static void
1612
bidi_string_reverse (
1613
  FriBidiChar *str,
1614
  const FriBidiStrIndex len
1615
)
1616
0
{
1617
0
  FriBidiStrIndex i;
1618
1619
0
  fribidi_assert (str);
1620
1621
0
  for (i = 0; i < len / 2; i++)
1622
0
    {
1623
0
      FriBidiChar tmp = str[i];
1624
0
      str[i] = str[len - 1 - i];
1625
0
      str[len - 1 - i] = tmp;
1626
0
    }
1627
0
}
1628
1629
static void
1630
index_array_reverse (
1631
  FriBidiStrIndex *arr,
1632
  const FriBidiStrIndex len
1633
)
1634
0
{
1635
0
  FriBidiStrIndex i;
1636
1637
0
  fribidi_assert (arr);
1638
1639
0
  for (i = 0; i < len / 2; i++)
1640
0
    {
1641
0
      FriBidiStrIndex tmp = arr[i];
1642
0
      arr[i] = arr[len - 1 - i];
1643
0
      arr[len - 1 - i] = tmp;
1644
0
    }
1645
0
}
1646
1647
/* A maximal run of consecutive characters that share the same resolved
1648
 * embedding level, as used by the linear-time implementation of L2 below. */
1649
typedef struct
1650
{
1651
  FriBidiStrIndex pos, len;
1652
  FriBidiLevel level;
1653
  FriBidiStrIndex next; /* index into the runs array, or -1 */
1654
} FriBidiL2Run;
1655
1656
/* A range groups one or more adjacent runs (in *visual* order) that have
1657
 * already been merged together, along with the highest level seen among
1658
 * the runs that produced it. */
1659
typedef struct
1660
{
1661
  FriBidiLevel level;
1662
  FriBidiStrIndex left, right;  /* indices into the runs array */
1663
  FriBidiStrIndex previous; /* index into the ranges array, or -1 */
1664
} FriBidiL2Range;
1665
1666
/* Merges ranges[top] with ranges[ranges[top].previous], frees the top
1667
 * range by returning its slot to the caller, and returns the index of
1668
 * the surviving (previous) range. */
1669
static FriBidiStrIndex
1670
fribidi_l2_merge_range_with_previous (
1671
  FriBidiL2Run *runs,
1672
  FriBidiL2Range *ranges,
1673
  FriBidiStrIndex top
1674
)
1675
0
{
1676
0
  FriBidiStrIndex previous = ranges[top].previous;
1677
0
  FriBidiStrIndex left, right;
1678
1679
0
  fribidi_assert (previous != -1);
1680
0
  fribidi_assert (ranges[previous].level < ranges[top].level);
1681
1682
0
  if (FRIBIDI_LEVEL_IS_RTL (ranges[previous].level))
1683
0
    {
1684
      /* Odd, previous goes to the right of range. */
1685
0
      left = top;
1686
0
      right = previous;
1687
0
    }
1688
0
  else
1689
0
    {
1690
      /* Even, previous goes to the left of range. */
1691
0
      left = previous;
1692
0
      right = top;
1693
0
    }
1694
  /* Stitch them. */
1695
0
  runs[ranges[left].right].next = ranges[right].left;
1696
1697
0
  ranges[previous].left = ranges[left].left;
1698
0
  ranges[previous].right = ranges[right].right;
1699
1700
0
  return previous;
1701
0
}
1702
1703
/* A one-pass linear-time implementation of UAX#9 rule L2, operating on
1704
 * maximal same-level runs instead of individual characters.  This avoids
1705
 * the O(len * max_level) cost of repeatedly rescanning the whole line for
1706
 * each embedding level from max_level down to 1.
1707
 *
1708
 * Reorders runs[0..num_runs-1], which must be given in logical order and
1709
 * linked via ->next accordingly, and returns the index of the left-most
1710
 * (i.e. first in visual order) run.  The runs array is used both as
1711
 * storage for the run list and as a preallocated stack for ranges sized
1712
 * to num_runs, since neither structure can exceed num_runs entries.
1713
 */
1714
static FriBidiStrIndex
1715
fribidi_l2_linear_reorder (
1716
  FriBidiL2Run *runs,
1717
  FriBidiL2Range *ranges,
1718
  const FriBidiStrIndex num_runs
1719
)
1720
0
{
1721
0
  FriBidiStrIndex top = -1;
1722
0
  FriBidiStrIndex range_count = 0;
1723
0
  FriBidiStrIndex i;
1724
1725
0
  for (i = 0; i < num_runs; i++)
1726
0
    {
1727
0
      while (top != -1 && ranges[top].level > runs[i].level &&
1728
0
       ranges[top].previous != -1 &&
1729
0
       ranges[ranges[top].previous].level >= runs[i].level)
1730
0
  top = fribidi_l2_merge_range_with_previous (runs, ranges, top);
1731
1732
0
      if (top != -1 && ranges[top].level >= runs[i].level)
1733
0
  {
1734
    /* Attach run to the range. */
1735
0
    if (FRIBIDI_LEVEL_IS_RTL (runs[i].level))
1736
0
      {
1737
        /* Odd, range goes to the right of run. */
1738
0
        runs[i].next = ranges[top].left;
1739
0
        ranges[top].left = i;
1740
0
      }
1741
0
    else
1742
0
      {
1743
        /* Even, range goes to the left of run. */
1744
0
        runs[ranges[top].right].next = i;
1745
0
        ranges[top].right = i;
1746
0
      }
1747
0
    ranges[top].level = runs[i].level;
1748
0
  }
1749
0
      else
1750
0
  {
1751
    /* Push new range for run. */
1752
0
    FriBidiStrIndex r = range_count++;
1753
0
    ranges[r].left = ranges[r].right = i;
1754
0
    ranges[r].level = runs[i].level;
1755
0
    ranges[r].previous = top;
1756
0
    top = r;
1757
0
  }
1758
0
    }
1759
1760
0
  fribidi_assert (top != -1);
1761
0
  while (ranges[top].previous != -1)
1762
0
    top = fribidi_l2_merge_range_with_previous (runs, ranges, top);
1763
1764
  /* Terminate. */
1765
0
  runs[ranges[top].right].next = -1;
1766
1767
0
  return ranges[top].left;
1768
0
}
1769
1770
1771
FRIBIDI_ENTRY FriBidiLevel
1772
fribidi_reorder_line (
1773
  /* input */
1774
  FriBidiFlags flags, /* reorder flags */
1775
  const FriBidiCharType *bidi_types,
1776
  const FriBidiStrIndex len,
1777
  const FriBidiStrIndex off,
1778
  const FriBidiParType base_dir,
1779
  /* input and output */
1780
  FriBidiLevel *embedding_levels,
1781
  FriBidiChar *visual_str,
1782
  /* output */
1783
  FriBidiStrIndex *map
1784
)
1785
0
{
1786
0
  fribidi_boolean status = false;
1787
0
  FriBidiLevel max_level = 0;
1788
1789
0
  if UNLIKELY
1790
0
    (len == 0)
1791
0
    {
1792
0
      status = true;
1793
0
      goto out;
1794
0
    }
1795
1796
0
  DBG ("in fribidi_reorder_line");
1797
1798
0
  fribidi_assert (bidi_types);
1799
0
  fribidi_assert (embedding_levels);
1800
1801
0
  DBG ("reset the embedding levels, 4. whitespace at the end of line");
1802
0
  {
1803
0
    register FriBidiStrIndex i;
1804
1805
    /* L1. Reset the embedding levels of some chars:
1806
       4. any sequence of white space characters at the end of the line. */
1807
0
    for (i = off + len - 1; i >= off &&
1808
0
   FRIBIDI_IS_EXPLICIT_OR_BN_OR_WS (bidi_types[i]); i--)
1809
0
      embedding_levels[i] = FRIBIDI_DIR_TO_LEVEL (base_dir);
1810
0
  }
1811
1812
  /* 7. Reordering resolved levels */
1813
0
  {
1814
0
    register FriBidiStrIndex i;
1815
1816
    /* Reorder both the outstring and the order array */
1817
0
    {
1818
0
      if (FRIBIDI_TEST_BITS (flags, FRIBIDI_FLAG_REORDER_NSM))
1819
0
  {
1820
0
    register FriBidiLevel level;
1821
1822
    /* L3. Reorder NSMs. */
1823
0
    for (i = off + len - 1; i >= off; i--)
1824
0
      if (FRIBIDI_LEVEL_IS_RTL (embedding_levels[i])
1825
0
    && bidi_types[i] == FRIBIDI_TYPE_NSM)
1826
0
        {
1827
0
    register FriBidiStrIndex seq_end = i;
1828
0
    level = embedding_levels[i];
1829
1830
0
    for (i--; i >= off &&
1831
0
         FRIBIDI_IS_EXPLICIT_OR_BN_OR_NSM (bidi_types[i])
1832
0
         && embedding_levels[i] == level; i--)
1833
0
      ;
1834
1835
0
    if (i < off || embedding_levels[i] != level)
1836
0
      {
1837
0
        i++;
1838
0
        DBG ("warning: NSM(s) at the beginning of level run");
1839
0
      }
1840
1841
0
    if (visual_str)
1842
0
      {
1843
0
        bidi_string_reverse (visual_str + i, seq_end - i + 1);
1844
0
      }
1845
0
    if (map)
1846
0
      {
1847
0
        index_array_reverse (map + i, seq_end - i + 1);
1848
0
      }
1849
0
        }
1850
0
  }
1851
1852
      /* L2. Reorder, and along the way find max_level of the line.  We
1853
       * don't reuse the paragraph max_level, both for a cleaner API, and
1854
       * that the line max_level may be far less than paragraph max_level.
1855
       *
1856
       * This is done in linear time by grouping the line into maximal
1857
       * same-level runs and reordering the runs, rather than repeatedly
1858
       * rescanning the whole line once per embedding level as the naive
1859
       * algorithm from the standard does. */
1860
0
      {
1861
  /* Count the runs first, so the runs/ranges arrays below can be
1862
   * sized to the actual run count rather than to len: real-world
1863
   * lines usually consist of a handful of long runs, so this keeps
1864
   * the common case cheap. */
1865
0
  FriBidiStrIndex num_runs = 0;
1866
0
  FriBidiStrIndex pos;
1867
1868
0
  for (pos = off; pos < off + len; num_runs++)
1869
0
    {
1870
0
      FriBidiStrIndex run_len = 1;
1871
0
      while (pos + run_len < off + len &&
1872
0
       embedding_levels[pos + run_len] == embedding_levels[pos])
1873
0
        run_len++;
1874
0
      pos += run_len;
1875
0
    }
1876
1877
0
  {
1878
0
    char *runs_and_ranges =
1879
0
      fribidi_malloc (num_runs * (sizeof (FriBidiL2Run) +
1880
0
           sizeof (FriBidiL2Range)));
1881
0
    if UNLIKELY
1882
0
      (!runs_and_ranges) goto out;
1883
0
    FriBidiL2Run *runs = (FriBidiL2Run *) runs_and_ranges;
1884
0
    FriBidiL2Range *ranges =
1885
0
      (FriBidiL2Range *) (runs_and_ranges +
1886
0
         num_runs * sizeof (FriBidiL2Run));
1887
0
    FriBidiStrIndex run_idx = 0;
1888
1889
0
    for (pos = off; pos < off + len; run_idx++)
1890
0
      {
1891
0
        FriBidiStrIndex run_len = 1;
1892
0
        while (pos + run_len < off + len &&
1893
0
         embedding_levels[pos + run_len] == embedding_levels[pos])
1894
0
    run_len++;
1895
1896
0
        runs[run_idx].pos = pos;
1897
0
        runs[run_idx].len = run_len;
1898
0
        runs[run_idx].level = embedding_levels[pos];
1899
0
        runs[run_idx].next = -1;
1900
1901
0
        if (runs[run_idx].level > max_level)
1902
0
    max_level = runs[run_idx].level;
1903
1904
        /* The run's own content must be reversed exactly once if it
1905
         * is an RTL run; further reordering only ever moves whole
1906
         * runs around, it never touches what is inside them. */
1907
0
        if (FRIBIDI_LEVEL_IS_RTL (runs[run_idx].level))
1908
0
    {
1909
0
      if (visual_str)
1910
0
        bidi_string_reverse (visual_str + pos, run_len);
1911
0
      if (map)
1912
0
        index_array_reverse (map + pos, run_len);
1913
0
    }
1914
1915
0
        pos += run_len;
1916
0
      }
1917
1918
0
    if (num_runs > 1)
1919
0
      {
1920
0
        FriBidiStrIndex left =
1921
0
    fribidi_l2_linear_reorder (runs, ranges, num_runs);
1922
1923
0
        if (visual_str || map)
1924
0
    {
1925
0
      char *tmp =
1926
0
        fribidi_malloc (len * ((visual_str ? sizeof (FriBidiChar) :
1927
0
               0) +
1928
0
              (map ? sizeof (FriBidiStrIndex) :
1929
0
               0)));
1930
0
      if UNLIKELY
1931
0
        (!tmp)
1932
0
          {
1933
0
      fribidi_free (runs_and_ranges);
1934
0
      goto out;
1935
0
          }
1936
0
      FriBidiChar *tmp_visual = visual_str ? (FriBidiChar *) tmp :
1937
0
        NULL;
1938
0
      FriBidiStrIndex *tmp_map =
1939
0
        map ? (FriBidiStrIndex *) (tmp +
1940
0
            (visual_str ?
1941
0
             len * sizeof (FriBidiChar) :
1942
0
             0)) : NULL;
1943
0
      FriBidiStrIndex out_pos = 0;
1944
0
      FriBidiStrIndex idx;
1945
1946
0
      for (idx = left; idx != -1; idx = runs[idx].next)
1947
0
        {
1948
0
          if (tmp_visual)
1949
0
      memcpy (tmp_visual + out_pos,
1950
0
        visual_str + runs[idx].pos,
1951
0
        runs[idx].len * sizeof (FriBidiChar));
1952
0
          if (tmp_map)
1953
0
      memcpy (tmp_map + out_pos, map + runs[idx].pos,
1954
0
        runs[idx].len * sizeof (FriBidiStrIndex));
1955
0
          out_pos += runs[idx].len;
1956
0
        }
1957
1958
0
      if (tmp_visual)
1959
0
        memcpy (visual_str + off, tmp_visual,
1960
0
          len * sizeof (FriBidiChar));
1961
0
      if (tmp_map)
1962
0
        memcpy (map + off, tmp_map, len * sizeof (FriBidiStrIndex));
1963
1964
0
      fribidi_free (tmp);
1965
0
    }
1966
0
      }
1967
1968
0
    fribidi_free (runs_and_ranges);
1969
0
  }
1970
0
      }
1971
0
    }
1972
1973
0
  }
1974
1975
0
  status = true;
1976
1977
0
out:
1978
1979
0
  return status ? max_level + 1 : 0;
1980
0
}
1981
1982
/* Editor directions:
1983
 * vim:textwidth=78:tabstop=8:shiftwidth=2:autoindent:cindent
1984
 */