Coverage Report

Created: 2026-10-08 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/liblouis/liblouis/compileTranslationTable.c
Line
Count
Source
1
/* liblouis Braille Translation and Back-Translation Library
2
3
   Based on the Linux screenreader BRLTTY, copyright (C) 1999-2006 by The
4
   BRLTTY Team
5
6
   Copyright (C) 2004, 2005, 2006 ViewPlus Technologies, Inc. www.viewplus.com
7
   Copyright (C) 2004, 2005, 2006 JJB Software, Inc. www.jjb-software.com
8
   Copyright (C) 2016 Mike Gray, American Printing House for the Blind
9
   Copyright (C) 2016 Davy Kager, Dedicon
10
11
   This file is part of liblouis.
12
13
   liblouis is free software: you can redistribute it and/or modify it
14
   under the terms of the GNU Lesser General Public License as published
15
   by the Free Software Foundation, either version 2.1 of the License, or
16
   (at your option) any later version.
17
18
   liblouis is distributed in the hope that it will be useful, but
19
   WITHOUT ANY WARRANTY; without even the implied warranty of
20
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21
   Lesser General Public License for more details.
22
23
   You should have received a copy of the GNU Lesser General Public
24
   License along with liblouis. If not, see <http://www.gnu.org/licenses/>.
25
*/
26
27
/**
28
 * @file
29
 * @brief Read and compile translation tables
30
 */
31
32
#include "config.h"
33
34
#include <stddef.h>
35
#include <stdlib.h>
36
#include <stdio.h>
37
#include <stdarg.h>
38
#include <string.h>
39
#include <ctype.h>
40
#include <sys/stat.h>
41
42
#include "internal.h"
43
44
2.48k
#define QUOTESUB 28 /* Stand-in for double quotes in strings */
45
46
/* needed to make debuggin easier */
47
#ifdef DEBUG
48
wchar_t wchar;
49
#endif
50
51
/* The following variables and functions make it possible to specify the
52
 * path on which all tables for liblouis and all files for liblouisutdml,
53
 * in their proper directories, will be found.
54
 */
55
56
static char *dataPathPtr;
57
58
char *EXPORT_CALL
59
0
lou_setDataPath(const char *path) {
60
0
  _lou_logMessage(LOU_LOG_WARN, "warning: lou_setDataPath is deprecated.");
61
0
  static char dataPath[MAXSTRING];
62
0
  dataPathPtr = NULL;
63
0
  if (path == NULL || strlen(path) >= MAXSTRING) return NULL;
64
0
  strcpy(dataPath, path);
65
0
  dataPathPtr = dataPath;
66
0
  return dataPathPtr;
67
0
}
68
69
char *EXPORT_CALL
70
0
lou_getDataPath(void) {
71
0
  _lou_logMessage(LOU_LOG_WARN, "warning: lou_getDataPath is deprecated.");
72
0
  return dataPathPtr;
73
0
}
74
75
/* End of dataPath code. */
76
77
static int
78
12.0k
eqasc2uni(const unsigned char *a, const widechar *b, const int len) {
79
12.0k
  int k;
80
25.7k
  for (k = 0; k < len; k++)
81
23.9k
    if ((widechar)a[k] != b[k]) return 0;
82
1.75k
  return 1;
83
12.0k
}
84
85
typedef struct CharsString {
86
  widechar length;
87
  widechar chars[MAXSTRING];
88
} CharsString;
89
90
static int errorCount;
91
static int warningCount;
92
93
typedef struct TranslationTableChainEntry {
94
  struct TranslationTableChainEntry *next;
95
  TranslationTableHeader *table;
96
  int tableListLength;
97
  char tableList[1];
98
} TranslationTableChainEntry;
99
100
static TranslationTableChainEntry *translationTableChain = NULL;
101
102
typedef struct DisplayTableChainEntry {
103
  struct DisplayTableChainEntry *next;
104
  DisplayTableHeader *table;
105
  int tableListLength;
106
  char tableList[1];
107
} DisplayTableChainEntry;
108
109
static DisplayTableChainEntry *displayTableChain = NULL;
110
111
/* predefined character classes */
112
static const char *characterClassNames[] = {
113
  "space",
114
  "letter",
115
  "digit",
116
  "punctuation",
117
  "uppercase",
118
  "lowercase",
119
  "math",
120
  "sign",
121
  "litdigit",
122
  NULL,
123
};
124
125
// names that may not be used for custom attributes
126
static const char *reservedAttributeNames[] = {
127
  "numericnocontchars",
128
  "numericnocontchar",
129
  "numericnocont",
130
  "midendnumericmodechars",
131
  "midendnumericmodechar",
132
  "midendnumericmode",
133
  "numericmodechars",
134
  "numericmodechar",
135
  "numericmode",
136
  "capsmodechars",
137
  "capsmodechar",
138
  "capsmode",
139
  "emphmodechars",
140
  "emphmodechar",
141
  "emphmode",
142
  "noemphchars",
143
  "noemphchar",
144
  "noemph",
145
  "seqdelimiter",
146
  "seqbeforechars",
147
  "seqbeforechar",
148
  "seqbefore",
149
  "seqafterchars",
150
  "seqafterchar",
151
  "seqafter",
152
  "noletsign",
153
  "noletsignbefore",
154
  "noletsignafter",
155
  NULL,
156
};
157
158
static const char *opcodeNames[CTO_None] = {
159
  "include",
160
  "locale",
161
  "undefined",
162
  "capsletter",
163
  "begcapsword",
164
  "endcapsword",
165
  "begcaps",
166
  "endcaps",
167
  "begcapsphrase",
168
  "endcapsphrase",
169
  "lencapsphrase",
170
  "modeletter",
171
  "begmodeword",
172
  "endmodeword",
173
  "begmode",
174
  "endmode",
175
  "begmodephrase",
176
  "endmodephrase",
177
  "lenmodephrase",
178
  "letsign",
179
  "noletsignbefore",
180
  "noletsign",
181
  "noletsignafter",
182
  "numsign",
183
  "nonumsign",
184
  "numericmodechars",
185
  "midendnumericmodechars",
186
  "numericnocontchars",
187
  "seqdelimiter",
188
  "seqbeforechars",
189
  "seqafterchars",
190
  "seqafterpattern",
191
  "seqafterexpression",
192
  "emphclass",
193
  "emphletter",
194
  "begemphword",
195
  "endemphword",
196
  "begemph",
197
  "endemph",
198
  "begemphphrase",
199
  "endemphphrase",
200
  "lenemphphrase",
201
  "capsmodechars",
202
  "emphmodechars",
203
  "noemphchars",
204
  "begcomp",
205
  "endcomp",
206
  "nocontractsign",
207
  "multind",
208
  "compdots",
209
  "comp6",
210
  "class",
211
  "after",
212
  "before",
213
  "noback",
214
  "nofor",
215
  "empmatchbefore",
216
  "empmatchafter",
217
  "swapcc",
218
  "swapcd",
219
  "swapdd",
220
  "space",
221
  "digit",
222
  "punctuation",
223
  "math",
224
  "sign",
225
  "letter",
226
  "uppercase",
227
  "lowercase",
228
  "grouping",
229
  "uplow",
230
  "litdigit",
231
  "display",
232
  "replace",
233
  "context",
234
  "correct",
235
  "pass2",
236
  "pass3",
237
  "pass4",
238
  "repeated",
239
  "repword",
240
  "rependword",
241
  "capsnocont",
242
  "always",
243
  "exactdots",
244
  "nocross",
245
  "syllable",
246
  "nocont",
247
  "compbrl",
248
  "literal",
249
  "largesign",
250
  "word",
251
  "partword",
252
  "joinnum",
253
  "joinword",
254
  "lowword",
255
  "contraction",
256
  "sufword",
257
  "prfword",
258
  "begword",
259
  "begmidword",
260
  "midword",
261
  "midendword",
262
  "endword",
263
  "prepunc",
264
  "postpunc",
265
  "begnum",
266
  "midnum",
267
  "endnum",
268
  "decpoint",
269
  "hyphen",
270
  // "apostrophe",
271
  // "initial",
272
  "nobreak",
273
  "match",
274
  "backmatch",
275
  "attribute",
276
  "base",
277
  "macro",
278
};
279
280
static short opcodeLengths[CTO_None] = { 0 };
281
282
static void
283
compileError(const FileInfo *file, const char *format, ...);
284
285
static int
286
143k
getAChar(FileInfo *file) {
287
  /* Read a big endian, little endian or ASCII 8 file and convert it to
288
   * 16- or 32-bit unsigned integers */
289
143k
  int ch1 = 0, ch2 = 0;
290
143k
  widechar character;
291
143k
  if (file->encoding == ascii8)
292
142k
    if (file->status == 2) {
293
287
      file->status++;
294
287
      return file->checkencoding[1];
295
287
    }
296
143k
  while ((ch1 = fgetc(file->in)) != EOF) {
297
142k
    if (file->status < 2) file->checkencoding[file->status] = ch1;
298
142k
    file->status++;
299
142k
    if (file->status == 2) {
300
290
      if (file->checkencoding[0] == 0xfe && file->checkencoding[1] == 0xff)
301
0
        file->encoding = bigEndian;
302
290
      else if (file->checkencoding[0] == 0xff && file->checkencoding[1] == 0xfe)
303
3
        file->encoding = littleEndian;
304
287
      else if (file->checkencoding[0] < 128 && file->checkencoding[1] < 128) {
305
287
        file->encoding = ascii8;
306
287
        return file->checkencoding[0];
307
287
      } else {
308
0
        compileError(file,
309
0
            "encoding is neither big-endian, little-endian nor ASCII 8.");
310
0
        ch1 = EOF;
311
0
        break;
312
0
        ;
313
0
      }
314
3
      continue;
315
290
    }
316
142k
    switch (file->encoding) {
317
292
    case noEncoding:
318
292
      break;
319
141k
    case ascii8:
320
141k
      return ch1;
321
0
      break;
322
0
    case bigEndian:
323
0
      ch2 = fgetc(file->in);
324
0
      if (ch2 == EOF) break;
325
0
      character = (widechar)(ch1 << 8) | ch2;
326
0
      return (int)character;
327
0
      break;
328
765
    case littleEndian:
329
765
      ch2 = fgetc(file->in);
330
765
      if (ch2 == EOF) break;
331
765
      character = (widechar)(ch2 << 8) | ch1;
332
765
      return (int)character;
333
0
      break;
334
142k
    }
335
292
    if (ch1 == EOF || ch2 == EOF) break;
336
292
  }
337
566
  return EOF;
338
143k
}
339
340
int EXPORT_CALL
341
2.16k
_lou_getALine(FileInfo *file) {
342
  /* Read a line of widechar's from an input file */
343
2.16k
  int ch;
344
2.16k
  file->linelen = 0;
345
143k
  while ((ch = getAChar(file)) != EOF) {
346
142k
    if (ch == 13) continue;
347
142k
    if (ch == 10 || file->linelen >= MAXSTRING - 1) break;
348
140k
    file->line[file->linelen++] = (widechar)ch;
349
140k
  }
350
2.16k
  file->line[file->linelen] = 0;
351
2.16k
  file->linepos = 0;
352
2.16k
  if (ch == EOF && !file->linelen) return 0;
353
1.87k
  file->lineNumber++;
354
1.87k
  return 1;
355
2.16k
}
356
357
static inline int
358
66.3k
atEndOfLine(const FileInfo *file) {
359
66.3k
  return file->linepos >= file->linelen;
360
66.3k
}
361
362
static inline int
363
64.8k
atTokenDelimiter(const FileInfo *file) {
364
64.8k
  return file->line[file->linepos] <= 32;
365
64.8k
}
366
367
static int
368
4.55k
getToken(FileInfo *file, CharsString *result, const char *description) {
369
  /* Find the next string of contiguous non-whitespace characters. If this
370
   * is the last token on the line, return 2 instead of 1. */
371
9.87k
  while (!atEndOfLine(file) && atTokenDelimiter(file)) file->linepos++;
372
4.55k
  result->length = 0;
373
40.5k
  while (!atEndOfLine(file) && !atTokenDelimiter(file)) {
374
36.0k
    int maxlen = MAXSTRING;
375
36.0k
    if (result->length >= maxlen) {
376
0
      compileError(file, "more than %d characters (bytes)", maxlen);
377
0
      return 0;
378
0
    } else
379
36.0k
      result->chars[result->length++] = file->line[file->linepos++];
380
36.0k
  }
381
4.55k
  if (!result->length) {
382
    /* Not enough tokens */
383
365
    if (description) compileError(file, "%s not specified.", description);
384
365
    return 0;
385
365
  }
386
4.18k
  result->chars[result->length] = 0;
387
15.7k
  while (!atEndOfLine(file) && atTokenDelimiter(file)) file->linepos++;
388
4.18k
  return 1;
389
4.55k
}
390
391
static void
392
4.73k
compileError(const FileInfo *file, const char *format, ...) {
393
4.73k
#ifndef __SYMBIAN32__
394
4.73k
  char buffer[MAXSTRING];
395
4.73k
  va_list arguments;
396
4.73k
  va_start(arguments, format);
397
4.73k
  vsnprintf(buffer, sizeof(buffer), format, arguments);
398
4.73k
  va_end(arguments);
399
4.73k
  if (file)
400
49
    _lou_logMessage(LOU_LOG_ERROR, "%s:%d: error: %s", file->fileName,
401
49
        file->lineNumber, buffer);
402
4.68k
  else
403
4.68k
    _lou_logMessage(LOU_LOG_ERROR, "error: %s", buffer);
404
4.73k
  errorCount++;
405
4.73k
#endif
406
4.73k
}
407
408
static void
409
166k
compileWarning(const FileInfo *file, const char *format, ...) {
410
166k
#ifndef __SYMBIAN32__
411
166k
  char buffer[MAXSTRING];
412
166k
  va_list arguments;
413
166k
  va_start(arguments, format);
414
166k
  vsnprintf(buffer, sizeof(buffer), format, arguments);
415
166k
  va_end(arguments);
416
166k
  if (file)
417
24.0k
    _lou_logMessage(LOU_LOG_WARN, "%s:%d: warning: %s", file->fileName,
418
24.0k
        file->lineNumber, buffer);
419
142k
  else
420
142k
    _lou_logMessage(LOU_LOG_WARN, "warning: %s", buffer);
421
166k
  warningCount++;
422
166k
#endif
423
166k
}
424
425
static int
426
allocateSpaceInTranslationTable(const FileInfo *file, TranslationTableOffset *offset,
427
7.93k
    int size, TranslationTableHeader **table) {
428
  /* allocate memory for table and expand previously allocated memory if necessary */
429
7.93k
  int spaceNeeded = ((size + OFFSETSIZE - 1) / OFFSETSIZE) * OFFSETSIZE;
430
7.93k
  TranslationTableOffset newTableSize = (*table)->bytesUsed + spaceNeeded;
431
7.93k
  TranslationTableOffset tableSize = (*table)->tableSize;
432
7.93k
  if (newTableSize > tableSize) {
433
15
    TranslationTableHeader *newTable;
434
15
    newTableSize += (newTableSize / OFFSETSIZE);
435
15
    newTable = realloc(*table, newTableSize);
436
15
    if (!newTable) {
437
0
      compileError(file, "Not enough memory for translation table.");
438
0
      _lou_outOfMemory();
439
0
    }
440
15
    memset(((unsigned char *)newTable) + tableSize, 0, newTableSize - tableSize);
441
    /* update references to the old table */
442
15
    {
443
15
      TranslationTableChainEntry *entry;
444
15
      for (entry = translationTableChain; entry != NULL; entry = entry->next)
445
0
        if (entry->table == *table)
446
0
          entry->table = (TranslationTableHeader *)newTable;
447
15
    }
448
15
    newTable->tableSize = newTableSize;
449
15
    *table = newTable;
450
15
  }
451
7.93k
  if (offset != NULL) {
452
7.91k
    *offset = ((*table)->bytesUsed - sizeof(**table)) / OFFSETSIZE;
453
7.91k
    (*table)->bytesUsed += spaceNeeded;
454
7.91k
  }
455
7.93k
  return 1;
456
7.93k
}
457
458
static int
459
allocateSpaceInDisplayTable(const FileInfo *file, TranslationTableOffset *offset,
460
718
    int size, DisplayTableHeader **table) {
461
  /* allocate memory for table and expand previously allocated memory if necessary */
462
718
  int spaceNeeded = ((size + OFFSETSIZE - 1) / OFFSETSIZE) * OFFSETSIZE;
463
718
  TranslationTableOffset newTableSize = (*table)->bytesUsed + spaceNeeded;
464
718
  TranslationTableOffset tableSize = (*table)->tableSize;
465
718
  if (newTableSize > tableSize) {
466
0
    DisplayTableHeader *newTable;
467
0
    newTableSize += (newTableSize / OFFSETSIZE);
468
0
    newTable = realloc(*table, newTableSize);
469
0
    if (!newTable) {
470
0
      compileError(file, "Not enough memory for display table.");
471
0
      _lou_outOfMemory();
472
0
    }
473
0
    memset(((unsigned char *)newTable) + tableSize, 0, newTableSize - tableSize);
474
    /* update references to the old table */
475
0
    {
476
0
      DisplayTableChainEntry *entry;
477
0
      for (entry = displayTableChain; entry != NULL; entry = entry->next)
478
0
        if (entry->table == *table) entry->table = (DisplayTableHeader *)newTable;
479
0
    }
480
0
    newTable->tableSize = newTableSize;
481
0
    *table = newTable;
482
0
  }
483
718
  if (offset != NULL) {
484
718
    *offset = ((*table)->bytesUsed - sizeof(**table)) / OFFSETSIZE;
485
718
    (*table)->bytesUsed += spaceNeeded;
486
718
  }
487
718
  return 1;
488
718
}
489
490
static int
491
290
allocateTranslationTable(const FileInfo *file, TranslationTableHeader **table) {
492
  /* Allocate memory for the table and a guess on the number of rules */
493
290
  const TranslationTableOffset startSize = 2 * sizeof(**table);
494
290
  if (*table) return 1;
495
290
  TranslationTableOffset bytesUsed =
496
290
      sizeof(**table) + OFFSETSIZE; /* So no offset is ever zero */
497
290
  if (!(*table = malloc(startSize))) {
498
0
    compileError(file, "Not enough memory");
499
0
    if (*table != NULL) free(*table);
500
0
    *table = NULL;
501
0
    _lou_outOfMemory();
502
0
  }
503
290
  memset(*table, 0, startSize);
504
290
  (*table)->tableSize = startSize;
505
290
  (*table)->bytesUsed = bytesUsed;
506
290
  return 1;
507
290
}
508
509
static int
510
290
allocateDisplayTable(const FileInfo *file, DisplayTableHeader **table) {
511
  /* Allocate memory for the table and a guess on the number of rules */
512
290
  const TranslationTableOffset startSize = 2 * sizeof(**table);
513
290
  if (*table) return 1;
514
290
  TranslationTableOffset bytesUsed =
515
290
      sizeof(**table) + OFFSETSIZE; /* So no offset is ever zero */
516
290
  if (!(*table = malloc(startSize))) {
517
0
    compileError(file, "Not enough memory");
518
0
    if (*table != NULL) free(*table);
519
0
    *table = NULL;
520
0
    _lou_outOfMemory();
521
0
  }
522
290
  memset(*table, 0, startSize);
523
290
  (*table)->tableSize = startSize;
524
290
  (*table)->bytesUsed = bytesUsed;
525
290
  return 1;
526
290
}
527
528
/* Look up a character or dot pattern. Although the algorithms are almost identical,
529
 * different tables are needed for characters and dots because of the possibility of
530
 * conflicts. */
531
532
static TranslationTableCharacter *
533
getChar(widechar c, TranslationTableHeader *table,
534
13.9k
    TranslationTableOffset *characterOffset) {
535
13.9k
  const TranslationTableOffset bucket = table->characters[_lou_charHash(c)];
536
13.9k
  TranslationTableOffset offset = bucket;
537
14.1k
  while (offset) {
538
11.4k
    TranslationTableCharacter *character =
539
11.4k
        (TranslationTableCharacter *)&table->ruleArea[offset];
540
11.4k
    if (character->value == c) {
541
11.2k
      if (characterOffset) *characterOffset = offset;
542
11.2k
      return character;
543
11.2k
    }
544
210
    offset = character->next;
545
210
  }
546
2.71k
  return NULL;
547
13.9k
}
548
549
static TranslationTableCharacter *
550
1.36k
getDots(widechar d, TranslationTableHeader *table) {
551
1.36k
  const TranslationTableOffset bucket = table->dots[_lou_charHash(d)];
552
1.36k
  TranslationTableOffset offset = bucket;
553
1.36k
  while (offset) {
554
487
    TranslationTableCharacter *character =
555
487
        (TranslationTableCharacter *)&table->ruleArea[offset];
556
487
    if (character->value == d) return character;
557
0
    offset = character->next;
558
0
  }
559
880
  return NULL;
560
1.36k
}
561
562
static TranslationTableCharacter *
563
putChar(const FileInfo *file, widechar c, TranslationTableHeader **table,
564
12.1k
    TranslationTableOffset *characterOffset, int ruleIndex) {
565
  /* See if a character is in the appropriate table. If not, insert it. In either case,
566
   * return a pointer to it. */
567
12.1k
  TranslationTableCharacter *character;
568
12.1k
  TranslationTableOffset offset;
569
12.1k
  if ((character = getChar(c, *table, characterOffset))) return character;
570
2.71k
  if (!allocateSpaceInTranslationTable(file, &offset, sizeof(*character), table))
571
0
    return NULL;
572
2.71k
  character = (TranslationTableCharacter *)&(*table)->ruleArea[offset];
573
2.71k
  memset(character, 0, sizeof(*character));
574
2.71k
  character->sourceFile = file->sourceFile;
575
2.71k
  character->sourceLine = file->lineNumber;
576
2.71k
  character->ruleIndex = ruleIndex;
577
2.71k
  character->value = c;
578
2.71k
  const unsigned long int charHash = _lou_charHash(c);
579
2.71k
  const TranslationTableOffset bucket = (*table)->characters[charHash];
580
2.71k
  if (!bucket)
581
2.69k
    (*table)->characters[charHash] = offset;
582
21
  else {
583
21
    TranslationTableCharacter *oldchar =
584
21
        (TranslationTableCharacter *)&(*table)->ruleArea[bucket];
585
21
    while (oldchar->next)
586
0
      oldchar = (TranslationTableCharacter *)&(*table)->ruleArea[oldchar->next];
587
21
    oldchar->next = offset;
588
21
  }
589
2.71k
  if (characterOffset) *characterOffset = offset;
590
2.71k
  return character;
591
2.71k
}
592
593
static TranslationTableCharacter *
594
985
putDots(const FileInfo *file, widechar d, TranslationTableHeader **table, int ruleIndex) {
595
  /* See if a dot pattern is in the appropriate table. If not, insert it. In either
596
   * case, return a pointer to it. */
597
985
  TranslationTableCharacter *character;
598
985
  TranslationTableOffset offset;
599
985
  if ((character = getDots(d, *table))) return character;
600
556
  if (!allocateSpaceInTranslationTable(file, &offset, sizeof(*character), table))
601
0
    return NULL;
602
556
  character = (TranslationTableCharacter *)&(*table)->ruleArea[offset];
603
556
  memset(character, 0, sizeof(*character));
604
556
  character->sourceFile = file->sourceFile;
605
556
  character->sourceLine = file->lineNumber;
606
556
  character->ruleIndex = ruleIndex;
607
556
  character->value = d;
608
556
  const unsigned long int charHash = _lou_charHash(d);
609
556
  const TranslationTableOffset bucket = (*table)->dots[charHash];
610
556
  if (!bucket)
611
556
    (*table)->dots[charHash] = offset;
612
0
  else {
613
0
    TranslationTableCharacter *oldchar =
614
0
        (TranslationTableCharacter *)&(*table)->ruleArea[bucket];
615
0
    while (oldchar->next)
616
0
      oldchar = (TranslationTableCharacter *)&(*table)->ruleArea[oldchar->next];
617
0
    oldchar->next = offset;
618
0
  }
619
556
  return character;
620
556
}
621
622
/* Look up a character-dots mapping in a display table. */
623
624
static CharDotsMapping *
625
60.9k
getDotsForChar(widechar c, const DisplayTableHeader *table) {
626
60.9k
  if (table == NULL) return NULL;
627
60.9k
  CharDotsMapping *cdPtr;
628
60.9k
  const TranslationTableOffset bucket = table->charToDots[_lou_charHash(c)];
629
60.9k
  TranslationTableOffset offset = bucket;
630
60.9k
  while (offset) {
631
11.8k
    cdPtr = (CharDotsMapping *)&table->ruleArea[offset];
632
11.8k
    if (cdPtr->lookFor == c) return cdPtr;
633
1
    offset = cdPtr->next;
634
1
  }
635
49.0k
  return NULL;
636
60.9k
}
637
638
static CharDotsMapping *
639
25.9k
getCharForDots(widechar d, const DisplayTableHeader *table) {
640
25.9k
  if (table == NULL) return NULL;
641
25.9k
  CharDotsMapping *cdPtr;
642
25.9k
  const TranslationTableOffset bucket = table->dotsToChar[_lou_charHash(d)];
643
25.9k
  TranslationTableOffset offset = bucket;
644
25.9k
  while (offset) {
645
25.3k
    cdPtr = (CharDotsMapping *)&table->ruleArea[offset];
646
25.3k
    if (cdPtr->lookFor == d) return cdPtr;
647
0
    offset = cdPtr->next;
648
0
  }
649
530
  return NULL;
650
25.9k
}
651
652
widechar EXPORT_CALL
653
60.5k
_lou_getDotsForChar(widechar c, const DisplayTableHeader *table) {
654
60.5k
  CharDotsMapping *cdPtr = getDotsForChar(c, table);
655
60.5k
  if (cdPtr) return cdPtr->found;
656
48.6k
  return LOU_DOTS;
657
60.5k
}
658
659
widechar EXPORT_CALL
660
25.5k
_lou_getCharForDots(widechar d, const DisplayTableHeader *table) {
661
25.5k
  CharDotsMapping *cdPtr = getCharForDots(d, table);
662
25.5k
  if (cdPtr) return cdPtr->found;
663
170
  return '\0';
664
25.5k
}
665
666
static int
667
putCharDotsMapping(
668
371
    const FileInfo *file, widechar c, widechar d, DisplayTableHeader **table) {
669
371
  if (!getDotsForChar(c, *table)) {
670
358
    CharDotsMapping *cdPtr;
671
358
    TranslationTableOffset offset;
672
358
    if (!allocateSpaceInDisplayTable(file, &offset, sizeof(*cdPtr), table)) return 0;
673
358
    cdPtr = (CharDotsMapping *)&(*table)->ruleArea[offset];
674
358
    cdPtr->next = 0;
675
358
    cdPtr->lookFor = c;
676
358
    cdPtr->found = d;
677
358
    const unsigned long int charHash = _lou_charHash(c);
678
358
    const TranslationTableOffset bucket = (*table)->charToDots[charHash];
679
358
    if (!bucket)
680
357
      (*table)->charToDots[charHash] = offset;
681
1
    else {
682
1
      CharDotsMapping *oldcdPtr = (CharDotsMapping *)&(*table)->ruleArea[bucket];
683
1
      while (oldcdPtr->next)
684
0
        oldcdPtr = (CharDotsMapping *)&(*table)->ruleArea[oldcdPtr->next];
685
1
      oldcdPtr->next = offset;
686
1
    }
687
358
  }
688
371
  if (!getCharForDots(d, *table)) {
689
360
    CharDotsMapping *cdPtr;
690
360
    TranslationTableOffset offset;
691
360
    if (!allocateSpaceInDisplayTable(file, &offset, sizeof(*cdPtr), table)) return 0;
692
360
    cdPtr = (CharDotsMapping *)&(*table)->ruleArea[offset];
693
360
    cdPtr->next = 0;
694
360
    cdPtr->lookFor = d;
695
360
    cdPtr->found = c;
696
360
    const unsigned long int charHash = _lou_charHash(d);
697
360
    const TranslationTableOffset bucket = (*table)->dotsToChar[charHash];
698
360
    if (!bucket)
699
360
      (*table)->dotsToChar[charHash] = offset;
700
0
    else {
701
0
      CharDotsMapping *oldcdPtr = (CharDotsMapping *)&(*table)->ruleArea[bucket];
702
0
      while (oldcdPtr->next)
703
0
        oldcdPtr = (CharDotsMapping *)&(*table)->ruleArea[oldcdPtr->next];
704
0
      oldcdPtr->next = offset;
705
0
    }
706
360
  }
707
371
  return 1;
708
371
}
709
710
static inline const char *
711
0
getPartName(int actionPart) {
712
0
  return actionPart ? "action" : "test";
713
0
}
714
715
static int
716
passFindCharacters(const FileInfo *file, widechar *instructions, int end,
717
278
    widechar **characters, int *length) {
718
278
  int IC = 0;
719
278
  int lookback = 0;
720
721
278
  *characters = NULL;
722
278
  *length = 0;
723
724
545
  while (IC < end) {
725
545
    widechar instruction = instructions[IC];
726
727
545
    switch (instruction) {
728
1
    case pass_string:
729
8
    case pass_dots: {
730
8
      int count = instructions[IC + 1];
731
8
      IC += 2;
732
8
      if (count > lookback) {
733
8
        *characters = &instructions[IC + lookback];
734
8
        *length = count - lookback;
735
8
        return 1;
736
8
      } else {
737
0
        lookback -= count;
738
0
      }
739
0
      IC += count;
740
0
      continue;
741
8
    }
742
743
87
    case pass_attributes:
744
87
      IC += 7;
745
87
      if (instructions[IC - 2] == instructions[IC - 1] &&
746
47
          instructions[IC - 1] <= lookback) {
747
0
        lookback -= instructions[IC - 1];
748
0
        continue;
749
0
      }
750
87
      goto NO_CHARACTERS;
751
752
87
    case pass_swap:
753
2
      IC += 2;
754
      /* fall through */
755
756
18
    case pass_groupstart:
757
21
    case pass_groupend:
758
21
    case pass_groupreplace:
759
21
      IC += 3;
760
761
270
    NO_CHARACTERS: { return 1; }
762
763
1
    case pass_eq:
764
3
    case pass_lt:
765
3
    case pass_gt:
766
6
    case pass_lteq:
767
7
    case pass_gteq:
768
7
      IC += 3;
769
7
      continue;
770
771
126
    case pass_lookback:
772
126
      lookback += instructions[IC + 1];
773
126
      IC += 2;
774
126
      continue;
775
776
120
    case pass_not:
777
121
    case pass_startReplace:
778
122
    case pass_endReplace:
779
127
    case pass_first:
780
134
    case pass_last:
781
134
    case pass_copy:
782
134
    case pass_omit:
783
134
    case pass_plus:
784
134
    case pass_hyphen:
785
134
      IC += 1;
786
134
      continue;
787
788
162
    case pass_endTest:
789
162
      goto NO_CHARACTERS;
790
791
0
    default:
792
0
      compileError(file, "unhandled test suboperand: \\x%02x", instruction);
793
0
      return 0;
794
545
    }
795
545
  }
796
0
  goto NO_CHARACTERS;
797
278
}
798
799
static const char *
800
11
printSource(const char *currentFile, const char *sourceFile, int sourceLine) {
801
11
  static char scratchBuf[MAXSTRING];
802
11
  if (sourceFile) {
803
11
    if (currentFile && strcmp(currentFile, sourceFile) == 0)
804
11
      snprintf(scratchBuf, MAXSTRING, "line %d", sourceLine);
805
0
    else
806
0
      snprintf(scratchBuf, MAXSTRING, "%s:%d", sourceFile, sourceLine);
807
11
  } else
808
0
    snprintf(scratchBuf, MAXSTRING, "source unknown");
809
11
  return scratchBuf;
810
11
}
811
812
/* The following functions are called by addRule to handle various cases. */
813
814
static void
815
addForwardRuleWithSingleChar(const FileInfo *file, TranslationTableOffset ruleOffset,
816
495
    TranslationTableRule **rule, TranslationTableHeader **table) {
817
  /* direction = 0, rule->charslen = 1 */
818
495
  TranslationTableCharacter *character;
819
  // get the character from the table, or if the character is not defined yet, define it
820
  // (without adding attributes)
821
495
  character = putChar(file, (*rule)->charsdots[0], table, NULL, (*rule)->index);
822
  // putChar may have moved table, so make sure rule is still valid
823
495
  *rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
824
495
  if ((*rule)->opcode == CTO_CompDots || (*rule)->opcode == CTO_Comp6) {
825
25
    character->compRule = ruleOffset;
826
25
    return;
827
470
  } else {
828
    // if the new rule is a character definition rule, set the main definition rule of
829
    // this character to it, but don't override existing character definitions rules
830
    // or base rules
831
    // adding the attributes to the character has already been done elsewhere
832
470
    if ((*rule)->opcode >= CTO_Space && (*rule)->opcode < CTO_UpLow) {
833
369
      if (character->definitionRule) {
834
11
        TranslationTableRule *prevRule =
835
11
            (TranslationTableRule *)&(*table)
836
11
                ->ruleArea[character->definitionRule];
837
11
        char *prevOpcodeName = strdup(_lou_findOpcodeName(prevRule->opcode));
838
11
        char *newOpcodeName = strdup(_lou_findOpcodeName((*rule)->opcode));
839
11
        _lou_logMessage(LOU_LOG_DEBUG,
840
11
            "%s:%d: Character already defined (%s). The existing %s rule "
841
11
            "will take precedence over the new %s rule.",
842
11
            file->fileName, file->lineNumber,
843
11
            printSource(file->sourceFile, prevRule->sourceFile,
844
11
                prevRule->sourceLine),
845
11
            prevOpcodeName, newOpcodeName);
846
11
        free(prevOpcodeName);
847
11
        free(newOpcodeName);
848
358
      } else {
849
358
        character->definitionRule = ruleOffset;
850
358
      }
851
369
    }
852
470
  }
853
  // add the new rule to the list of rules associated with this character
854
  // if the new rule is a character definition rule, it is inserted at the end of the
855
  // list, otherwise it is inserted before the first character definition rule
856
  // in other words, rules are considered in the order in which they are defined in the
857
  // table
858
470
  TranslationTableOffset *otherRule = &character->otherRules;
859
539
  while (*otherRule) {
860
86
    TranslationTableRule *r = (TranslationTableRule *)&(*table)->ruleArea[*otherRule];
861
86
    if (r->charslen == 0) break;
862
86
    if (r->opcode >= CTO_Space && r->opcode < CTO_UpLow)
863
34
      if (!((*rule)->opcode >= CTO_Space && (*rule)->opcode < CTO_UpLow)) break;
864
69
    otherRule = &r->charsnext;
865
69
  }
866
470
  (*rule)->charsnext = *otherRule;
867
470
  *otherRule = ruleOffset;
868
470
}
869
870
static void
871
addForwardRuleWithMultipleChars(TranslationTableOffset ruleOffset,
872
143
    TranslationTableRule *rule, TranslationTableHeader *table) {
873
  /* direction = 0 rule->charslen > 1 */
874
143
  TranslationTableOffset *forRule =
875
143
      &table->forRules[_lou_stringHash(&rule->charsdots[0], 0, NULL)];
876
199
  while (*forRule) {
877
61
    TranslationTableRule *r = (TranslationTableRule *)&table->ruleArea[*forRule];
878
61
    if (rule->charslen > r->charslen) break;
879
56
    if (rule->charslen == r->charslen)
880
49
      if ((r->opcode == CTO_Always) && (rule->opcode != CTO_Always)) break;
881
56
    forRule = &r->charsnext;
882
56
  }
883
143
  rule->charsnext = *forRule;
884
143
  *forRule = ruleOffset;
885
143
}
886
887
static void
888
addBackwardRuleWithSingleCell(const FileInfo *file, widechar cell,
889
    TranslationTableOffset ruleOffset, TranslationTableRule **rule,
890
632
    TranslationTableHeader **table) {
891
  /* direction = 1, rule->dotslen = 1 */
892
632
  TranslationTableCharacter *dots;
893
632
  if ((*rule)->opcode == CTO_SwapCc || (*rule)->opcode == CTO_Repeated)
894
1
    return; /* too ambiguous */
895
  // get the cell from the table, or if the cell is not defined yet, define it (without
896
  // adding attributes)
897
631
  dots = putDots(file, cell, table, (*rule)->index);
898
  // putDots may have moved table, so make sure rule is still valid
899
631
  *rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
900
631
  if ((*rule)->opcode >= CTO_Space && (*rule)->opcode < CTO_UpLow)
901
336
    dots->definitionRule = ruleOffset;
902
631
  TranslationTableOffset *otherRule = &dots->otherRules;
903
1.05k
  while (*otherRule) {
904
465
    TranslationTableRule *r = (TranslationTableRule *)&(*table)->ruleArea[*otherRule];
905
465
    if ((*rule)->charslen > r->charslen || r->dotslen == 0) break;
906
429
    if (r->opcode >= CTO_Space && r->opcode < CTO_UpLow)
907
8
      if (!((*rule)->opcode >= CTO_Space && (*rule)->opcode < CTO_UpLow)) break;
908
428
    otherRule = &r->dotsnext;
909
428
  }
910
631
  (*rule)->dotsnext = *otherRule;
911
631
  *otherRule = ruleOffset;
912
631
}
913
914
static void
915
addBackwardRuleWithMultipleCells(widechar *cells, int dotslen,
916
    TranslationTableOffset ruleOffset, TranslationTableRule *rule,
917
88
    TranslationTableHeader *table) {
918
  /* direction = 1, dotslen > 1 */
919
88
  TranslationTableOffset *backRule = &table->backRules[_lou_stringHash(cells, 0, NULL)];
920
88
  if (rule->opcode == CTO_SwapCc) return;
921
88
  int ruleLength = dotslen + rule->charslen;
922
115
  while (*backRule) {
923
28
    TranslationTableRule *r = (TranslationTableRule *)&table->ruleArea[*backRule];
924
28
    int rLength = r->dotslen + r->charslen;
925
28
    if (ruleLength > rLength) break;
926
27
    if (rLength == ruleLength)
927
19
      if ((r->opcode == CTO_Always) && (rule->opcode != CTO_Always)) break;
928
27
    backRule = &r->dotsnext;
929
27
  }
930
88
  rule->dotsnext = *backRule;
931
88
  *backRule = ruleOffset;
932
88
}
933
934
static int
935
addForwardPassRule(TranslationTableOffset ruleOffset, TranslationTableRule *rule,
936
233
    TranslationTableHeader *table) {
937
233
  TranslationTableOffset *forPassRule;
938
233
  switch (rule->opcode) {
939
160
  case CTO_Correct:
940
160
    forPassRule = &table->forPassRules[0];
941
160
    break;
942
50
  case CTO_Context:
943
50
    forPassRule = &table->forPassRules[1];
944
50
    break;
945
11
  case CTO_Pass2:
946
11
    forPassRule = &table->forPassRules[2];
947
11
    break;
948
3
  case CTO_Pass3:
949
3
    forPassRule = &table->forPassRules[3];
950
3
    break;
951
9
  case CTO_Pass4:
952
9
    forPassRule = &table->forPassRules[4];
953
9
    break;
954
0
  default:
955
0
    return 0;
956
233
  }
957
330
  while (*forPassRule) {
958
97
    TranslationTableRule *r = (TranslationTableRule *)&table->ruleArea[*forPassRule];
959
97
    if (rule->charslen > r->charslen) break;
960
97
    forPassRule = &r->charsnext;
961
97
  }
962
233
  rule->charsnext = *forPassRule;
963
233
  *forPassRule = ruleOffset;
964
233
  return 1;
965
233
}
966
967
static int
968
addBackwardPassRule(TranslationTableOffset ruleOffset, TranslationTableRule *rule,
969
43
    TranslationTableHeader *table) {
970
43
  TranslationTableOffset *backPassRule;
971
43
  switch (rule->opcode) {
972
7
  case CTO_Correct:
973
7
    backPassRule = &table->backPassRules[0];
974
7
    break;
975
3
  case CTO_Context:
976
3
    backPassRule = &table->backPassRules[1];
977
3
    break;
978
7
  case CTO_Pass2:
979
7
    backPassRule = &table->backPassRules[2];
980
7
    break;
981
5
  case CTO_Pass3:
982
5
    backPassRule = &table->backPassRules[3];
983
5
    break;
984
21
  case CTO_Pass4:
985
21
    backPassRule = &table->backPassRules[4];
986
21
    break;
987
0
  default:
988
0
    return 0;
989
43
  }
990
47
  while (*backPassRule) {
991
4
    TranslationTableRule *r = (TranslationTableRule *)&table->ruleArea[*backPassRule];
992
4
    if (rule->charslen > r->charslen) break;
993
4
    backPassRule = &r->dotsnext;
994
4
  }
995
43
  rule->dotsnext = *backPassRule;
996
43
  *backPassRule = ruleOffset;
997
43
  return 1;
998
43
}
999
1000
static int
1001
addRule(const FileInfo *file, TranslationTableOpcode opcode, const CharsString *ruleChars,
1002
    const CharsString *ruleDots, TranslationTableCharacterAttributes after,
1003
    TranslationTableCharacterAttributes before, TranslationTableOffset *ruleOffset,
1004
    TranslationTableRule **rule, int noback, int nofor,
1005
1.07k
    TranslationTableHeader **table) {
1006
  /* Add a rule to the table, using the hash function to find the start of
1007
   * chains and chaining both the chars and dots strings */
1008
1.07k
  TranslationTableOffset offset;
1009
1.07k
  int ruleSize = sizeof(TranslationTableRule) - (DEFAULTRULESIZE * CHARSIZE);
1010
1.07k
  if (ruleChars) ruleSize += CHARSIZE * ruleChars->length;
1011
1.07k
  if (ruleDots) ruleSize += CHARSIZE * ruleDots->length;
1012
1.07k
  if (!allocateSpaceInTranslationTable(file, &offset, ruleSize, table)) return 0;
1013
1.07k
  TranslationTableRule *r = (TranslationTableRule *)&(*table)->ruleArea[offset];
1014
1.07k
  if (rule) *rule = r;
1015
1.07k
  if (ruleOffset) *ruleOffset = offset;
1016
1.07k
  r->sourceFile = file->sourceFile;
1017
1.07k
  r->sourceLine = file->lineNumber;
1018
1.07k
  r->index = (*table)->ruleCounter++;
1019
1.07k
  r->opcode = opcode;
1020
1.07k
  r->after = after;
1021
1.07k
  r->before = before;
1022
1.07k
  r->nocross = 0;
1023
1.07k
  if (ruleChars)
1024
925
    memcpy(&r->charsdots[0], &ruleChars->chars[0],
1025
925
        CHARSIZE * (r->charslen = ruleChars->length));
1026
153
  else
1027
153
    r->charslen = 0;
1028
1.07k
  if (ruleDots)
1029
1.06k
    memcpy(&r->charsdots[r->charslen], &ruleDots->chars[0],
1030
1.06k
        CHARSIZE * (r->dotslen = ruleDots->length));
1031
14
  else
1032
14
    r->dotslen = 0;
1033
1034
  /* link new rule into table. */
1035
1.07k
  if (opcode == CTO_SwapCc || opcode == CTO_SwapCd || opcode == CTO_SwapDd) return 1;
1036
1.07k
  if (opcode >= CTO_Context && opcode <= CTO_Pass4)
1037
278
    if (!(opcode == CTO_Context && r->charslen > 0)) {
1038
276
      if (!nofor)
1039
233
        if (!addForwardPassRule(offset, r, *table)) return 0;
1040
276
      if (!noback)
1041
43
        if (!addBackwardPassRule(offset, r, *table)) return 0;
1042
276
      return 1;
1043
276
    }
1044
796
  if (!nofor) {
1045
791
    if (r->charslen == 1)
1046
495
      addForwardRuleWithSingleChar(file, offset, &r, table);
1047
296
    else if (r->charslen > 1)
1048
143
      addForwardRuleWithMultipleChars(offset, r, *table);
1049
791
  }
1050
796
  if (!noback) {
1051
741
    widechar *cells;
1052
741
    int dotslen;
1053
1054
741
    if (r->opcode == CTO_Context) {
1055
2
      cells = &r->charsdots[0];
1056
2
      dotslen = r->charslen;
1057
739
    } else {
1058
739
      cells = &r->charsdots[r->charslen];
1059
739
      dotslen = r->dotslen;
1060
739
    }
1061
741
    if (dotslen == 1) {
1062
632
      addBackwardRuleWithSingleCell(file, *cells, offset, &r, table);
1063
632
    } else if (dotslen > 1)
1064
88
      addBackwardRuleWithMultipleCells(cells, dotslen, offset, r, *table);
1065
741
  }
1066
796
  return 1;
1067
1.07k
}
1068
1069
static const CharacterClass *
1070
223
findCharacterClass(const CharsString *name, const TranslationTableHeader *table) {
1071
  /* Find a character class, whether predefined or user-defined */
1072
223
  const CharacterClass *class = table->characterClasses;
1073
1.62k
  while (class) {
1074
1.53k
    if ((name->length == class->length) &&
1075
284
        (memcmp(&name->chars[0], class->name, CHARSIZE * name->length) == 0))
1076
139
      return class;
1077
1.40k
    class = class->next;
1078
1.40k
  }
1079
84
  return NULL;
1080
223
}
1081
1082
static TranslationTableCharacterAttributes
1083
0
getNextNumberedAttribute(TranslationTableHeader *table) {
1084
  /* Get the next attribute value for numbered attributes, or 0 if there is no more
1085
   * space in the table. */
1086
0
  TranslationTableCharacterAttributes next = table->nextNumberedCharacterClassAttribute;
1087
0
  if (next > CTC_UserDefined8) return 0;
1088
0
  table->nextNumberedCharacterClassAttribute <<= 1;
1089
0
  return next;
1090
0
}
1091
1092
static TranslationTableCharacterAttributes
1093
946
getNextAttribute(TranslationTableHeader *table) {
1094
  /* Get the next attribute value, or 0 if there is no more space in the table. */
1095
946
  TranslationTableCharacterAttributes next = table->nextCharacterClassAttribute;
1096
946
  if (next) {
1097
946
    if (next == CTC_LitDigit)
1098
96
      table->nextCharacterClassAttribute = CTC_UserDefined9;
1099
850
    else
1100
850
      table->nextCharacterClassAttribute <<= 1;
1101
946
    return next;
1102
946
  } else
1103
0
    return getNextNumberedAttribute(table);
1104
946
}
1105
1106
static CharacterClass *
1107
addCharacterClass(const FileInfo *file, const widechar *name, int length,
1108
946
    TranslationTableHeader *table, int validate) {
1109
  /* Define a character class, Whether predefined or user-defined */
1110
946
  if (validate) {
1111
572
    for (int i = 0; i < length; i++) {
1112
490
      if (!((name[i] >= 'a' && name[i] <= 'z') ||
1113
102
            (name[i] >= 'A' && name[i] <= 'Z'))) {
1114
2
        compileError(file,
1115
2
            "Invalid attribute name: must be a digit between "
1116
2
            "0 and 7 or a word containing only letters");
1117
2
      }
1118
490
    }
1119
    // check that name is not reserved
1120
82
    int k = 0;
1121
2.37k
    while (reservedAttributeNames[k]) {
1122
2.29k
      if (strlen(reservedAttributeNames[k]) == (size_t)length) {
1123
45
        int i;
1124
56
        for (i = 0; i < length; i++)
1125
56
          if (reservedAttributeNames[k][i] != name[i]) break;
1126
45
        if (i == length) {
1127
0
          compileError(file, "Attribute name is reserved: %s",
1128
0
              reservedAttributeNames[k]);
1129
0
          return NULL;
1130
0
        }
1131
45
      }
1132
2.29k
      k++;
1133
2.29k
    }
1134
82
  }
1135
946
  CharacterClass **classes = &table->characterClasses;
1136
946
  TranslationTableCharacterAttributes attribute = getNextAttribute(table);
1137
946
  CharacterClass *class;
1138
946
  if (attribute) {
1139
946
    if (!(class = malloc(sizeof(*class) + CHARSIZE * (length - 1))))
1140
0
      _lou_outOfMemory();
1141
946
    else {
1142
946
      memset(class, 0, sizeof(*class));
1143
946
      memcpy(class->name, name, CHARSIZE * (class->length = length));
1144
946
      class->attribute = attribute;
1145
946
      class->next = *classes;
1146
946
      *classes = class;
1147
946
      return class;
1148
946
    }
1149
946
  }
1150
0
  compileError(file, "character class table overflow.");
1151
0
  return NULL;
1152
946
}
1153
1154
static void
1155
96
deallocateCharacterClasses(TranslationTableHeader *table) {
1156
96
  CharacterClass **classes = &table->characterClasses;
1157
1.04k
  while (*classes) {
1158
946
    CharacterClass *class = *classes;
1159
946
    *classes = (*classes)->next;
1160
946
    if (class) free(class);
1161
946
  }
1162
96
}
1163
1164
static int
1165
96
allocateCharacterClasses(TranslationTableHeader *table) {
1166
  /* Allocate memory for predefined character classes */
1167
96
  int k = 0;
1168
96
  table->characterClasses = NULL;
1169
96
  table->nextCharacterClassAttribute = 1;  // CTC_Space
1170
96
  table->nextNumberedCharacterClassAttribute = CTC_UserDefined1;
1171
960
  while (characterClassNames[k]) {
1172
864
    widechar wname[MAXSTRING];
1173
864
    int length = (int)strlen(characterClassNames[k]);
1174
864
    int kk;
1175
6.72k
    for (kk = 0; kk < length; kk++) wname[kk] = (widechar)characterClassNames[k][kk];
1176
864
    if (!addCharacterClass(NULL, wname, length, table, 0)) {
1177
0
      deallocateCharacterClasses(table);
1178
0
      return 0;
1179
0
    }
1180
864
    k++;
1181
864
  }
1182
96
  return 1;
1183
96
}
1184
1185
static TranslationTableOpcode
1186
1.75k
getOpcode(const FileInfo *file, const CharsString *token) {
1187
1.75k
  static TranslationTableOpcode lastOpcode = 0;
1188
1.75k
  TranslationTableOpcode opcode = lastOpcode;
1189
1190
92.5k
  do {
1191
92.5k
    if (token->length == opcodeLengths[opcode])
1192
10.6k
      if (eqasc2uni((unsigned char *)opcodeNames[opcode], &token->chars[0],
1193
10.6k
            token->length)) {
1194
1.74k
        lastOpcode = opcode;
1195
1.74k
        return opcode;
1196
1.74k
      }
1197
90.7k
    opcode++;
1198
90.7k
    if (opcode >= CTO_None) opcode = 0;
1199
90.7k
  } while (opcode != lastOpcode);
1200
12
  return CTO_None;
1201
1.75k
}
1202
1203
TranslationTableOpcode EXPORT_CALL
1204
0
_lou_findOpcodeNumber(const char *toFind) {
1205
  /* Used by tools such as lou_debug */
1206
0
  static TranslationTableOpcode lastOpcode = 0;
1207
0
  TranslationTableOpcode opcode = lastOpcode;
1208
0
  int length = (int)strlen(toFind);
1209
0
  do {
1210
0
    if (length == opcodeLengths[opcode] &&
1211
0
        strcasecmp(toFind, opcodeNames[opcode]) == 0) {
1212
0
      lastOpcode = opcode;
1213
0
      return opcode;
1214
0
    }
1215
0
    opcode++;
1216
0
    if (opcode >= CTO_None) opcode = 0;
1217
0
  } while (opcode != lastOpcode);
1218
0
  return CTO_None;
1219
0
}
1220
1221
const char *EXPORT_CALL
1222
22
_lou_findOpcodeName(TranslationTableOpcode opcode) {
1223
22
  static char scratchBuf[MAXSTRING];
1224
  /* Used by tools such as lou_debug */
1225
22
  if (opcode < 0 || opcode >= CTO_None) {
1226
0
    sprintf(scratchBuf, "%u", opcode);
1227
0
    return scratchBuf;
1228
0
  }
1229
22
  return opcodeNames[opcode];
1230
22
}
1231
1232
static widechar
1233
4.48k
hexValue(const FileInfo *file, const widechar *digits, int length) {
1234
4.48k
  int k;
1235
4.48k
  unsigned int binaryValue = 0;
1236
14.8k
  for (k = 0; k < length; k++) {
1237
13.9k
    unsigned int hexDigit = 0;
1238
13.9k
    if (digits[k] >= '0' && digits[k] <= '9')
1239
896
      hexDigit = digits[k] - '0';
1240
13.0k
    else if (digits[k] >= 'a' && digits[k] <= 'f')
1241
6.53k
      hexDigit = digits[k] - 'a' + 10;
1242
6.53k
    else if (digits[k] >= 'A' && digits[k] <= 'F')
1243
2.96k
      hexDigit = digits[k] - 'A' + 10;
1244
3.56k
    else {
1245
3.56k
      compileError(file, "invalid %d-digit hexadecimal number", length);
1246
3.56k
      return (widechar)0xffffffff;
1247
3.56k
    }
1248
10.3k
    binaryValue |= hexDigit << (4 * (length - 1 - k));
1249
10.3k
  }
1250
919
  return (widechar)binaryValue;
1251
4.48k
}
1252
1253
40.4k
#define MAXBYTES 7
1254
static const unsigned int first0Bit[MAXBYTES] = { 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC,
1255
  0XFE };
1256
1257
static bool
1258
8.01k
isMatchPatternEscape(unsigned int ch, bool inMatchPattern) {
1259
8.01k
  return inMatchPattern && (ch == '(' || ch == ')' || ch == ']');
1260
8.01k
}
1261
1262
static int
1263
parseCharsInternal(const FileInfo *file, CharsString *result, CharsString *token,
1264
1.67k
    bool inMatchPattern) {
1265
1.67k
  int in = 0;
1266
1.67k
  int out = 0;
1267
1.67k
  int lastOutSize = 0;
1268
210k
  while (in < token->length) {
1269
208k
    unsigned int ch = token->chars[in++] & 0xff;
1270
208k
    if (ch < 128) {
1271
167k
      if (ch == '\\' &&
1272
8.01k
          !isMatchPatternEscape(
1273
8.01k
              token->chars[in], inMatchPattern)) { /* escape sequence */
1274
8.01k
        switch (ch = token->chars[in]) {
1275
106
        case '\\':
1276
106
          break;
1277
17
        case 'e':
1278
17
          ch = 0x1b;
1279
17
          break;
1280
162
        case 'f':
1281
162
          ch = 12;
1282
162
          break;
1283
281
        case 'n':
1284
281
          ch = 10;
1285
281
          break;
1286
305
        case 'r':
1287
305
          ch = 13;
1288
305
          break;
1289
23
        case 's':
1290
23
          ch = ' ';
1291
23
          break;
1292
234
        case 't':
1293
234
          ch = 9;
1294
234
          break;
1295
567
        case 'v':
1296
567
          ch = 11;
1297
567
          break;
1298
417
        case 'w':
1299
417
          ch = LOU_ENDSEGMENT;
1300
417
          break;
1301
288
        case 34:
1302
288
          ch = QUOTESUB;
1303
288
          break;
1304
2.09k
        case 'X':
1305
2.09k
          compileWarning(file, "\\Xhhhh (with a capital 'X') is deprecated.");
1306
4.50k
        case 'x':
1307
4.50k
          if (token->length - in > 4) {
1308
4.48k
            ch = hexValue(file, &token->chars[in + 1], 4);
1309
4.48k
            in += 4;
1310
4.48k
          }
1311
4.50k
          break;
1312
170
        case 'Y':
1313
170
          compileWarning(file, "\\Yhhhhh (with a capital 'Y') is deprecated.");
1314
684
        case 'y':
1315
684
          if (CHARSIZE == 2) {
1316
1.10k
          not32:
1317
1.10k
            compileError(file,
1318
1.10k
                "liblouis has not been compiled for 32-bit Unicode");
1319
1.10k
            break;
1320
684
          }
1321
0
          if (token->length - in > 5) {
1322
0
            ch = hexValue(file, &token->chars[in + 1], 5);
1323
0
            in += 5;
1324
0
          }
1325
0
          break;
1326
295
        case 'Z':
1327
295
          compileWarning(
1328
295
              file, "\\Zhhhhhhhh (with a capital 'Z') is deprecated.");
1329
424
        case 'z':
1330
424
          if (CHARSIZE == 2) goto not32;
1331
0
          if (token->length - in > 8) {
1332
0
            ch = hexValue(file, &token->chars[in + 1], 8);
1333
0
            in += 8;
1334
0
          }
1335
0
          break;
1336
3
        default:
1337
3
          compileError(file, "invalid escape sequence '\\%c'", ch);
1338
3
          result->length = lastOutSize;
1339
3
          return 0;
1340
8.01k
        }
1341
8.00k
        in++;
1342
8.00k
      }
1343
167k
      if (out >= MAXSTRING - 1) {
1344
2
        compileError(file, "Token too long");
1345
2
        result->length = MAXSTRING - 1;
1346
2
        return 0;
1347
2
      }
1348
167k
      result->chars[out++] = (widechar)ch;
1349
167k
      continue;
1350
167k
    }
1351
40.4k
    lastOutSize = out;
1352
40.4k
    int lastIn = in;
1353
40.4k
    int numBytes = 0;
1354
116k
    for (numBytes = MAXBYTES - 1; numBytes > 0; numBytes--)
1355
107k
      if (ch >= first0Bit[numBytes]) break;
1356
40.4k
    unsigned int utf32 = ch & (0XFF - first0Bit[numBytes]);
1357
205k
    for (int k = 0; k < numBytes; k++) {
1358
165k
      if (in >= MAXSTRING - 1 || in >= token->length) break;
1359
164k
      if (out >= MAXSTRING - 1) {
1360
2
        compileError(file, "Token too long");
1361
2
        result->length = lastOutSize;
1362
2
        return 0;
1363
2
      }
1364
164k
      if (token->chars[in] < 128 || (token->chars[in] & 0x0040)) {
1365
163k
        compileWarning(file, "invalid UTF-8. Assuming Latin-1.");
1366
163k
        result->chars[out++] = token->chars[lastIn];
1367
163k
        in = lastIn + 1;
1368
163k
        continue;
1369
163k
      }
1370
947
      utf32 = (utf32 << 6) + (token->chars[in++] & 0x3f);
1371
947
    }
1372
40.4k
    if (out >= MAXSTRING - 1) {
1373
2
      compileError(file, "Token too long");
1374
2
      result->length = lastOutSize;
1375
2
      return 0;
1376
2
    }
1377
40.4k
    if (CHARSIZE == 2 && utf32 > 0xffff) {
1378
6
      compileError(file, "liblouis has not been compiled for 32-bit Unicode");
1379
6
      result->length = lastOutSize;
1380
6
      return 0;
1381
6
    }
1382
40.4k
    result->chars[out++] = (widechar)utf32;
1383
40.4k
  }
1384
1.65k
  result->length = out;
1385
1.65k
  return 1;
1386
1.67k
}
1387
1388
static int
1389
1.65k
parseChars(const FileInfo *file, CharsString *result, CharsString *token) {
1390
1.65k
  return parseCharsInternal(file, result, token, false);
1391
1.65k
}
1392
1393
static int
1394
18
parseMatchPatternChars(const FileInfo *file, CharsString *result, CharsString *token) {
1395
18
  return parseCharsInternal(file, result, token, true);
1396
18
}
1397
1398
int EXPORT_CALL
1399
271
_lou_extParseChars(const char *inString, widechar *outString) {
1400
  /* Parse external character strings */
1401
271
  CharsString wideIn;
1402
271
  CharsString result;
1403
271
  int k;
1404
230k
  for (k = 0; inString[k] && k < MAXSTRING - 1; k++) wideIn.chars[k] = inString[k];
1405
271
  wideIn.chars[k] = 0;
1406
271
  wideIn.length = k;
1407
271
  if (!parseChars(NULL, &result, &wideIn)) return 0;
1408
297k
  for (k = 0; k < result.length; k++) outString[k] = result.chars[k];
1409
256
  return result.length;
1410
271
}
1411
1412
static int
1413
711
parseDots(const FileInfo *file, CharsString *cells, const CharsString *token) {
1414
  /* get dot patterns */
1415
711
  widechar cell = 0; /* assembly place for dots */
1416
711
  int cellCount = 0;
1417
711
  int index;
1418
711
  int start = 0;
1419
1420
5.74k
  for (index = 0; index < token->length; index++) {
1421
5.05k
    int started = index != start;
1422
5.05k
    widechar character = token->chars[index];
1423
5.05k
    switch (character) { /* or dots to make up Braille cell */
1424
0
      {
1425
0
        int dot;
1426
329
      case '1':
1427
329
        dot = LOU_DOT_1;
1428
329
        goto haveDot;
1429
321
      case '2':
1430
321
        dot = LOU_DOT_2;
1431
321
        goto haveDot;
1432
304
      case '3':
1433
304
        dot = LOU_DOT_3;
1434
304
        goto haveDot;
1435
301
      case '4':
1436
301
        dot = LOU_DOT_4;
1437
301
        goto haveDot;
1438
336
      case '5':
1439
336
        dot = LOU_DOT_5;
1440
336
        goto haveDot;
1441
305
      case '6':
1442
305
        dot = LOU_DOT_6;
1443
305
        goto haveDot;
1444
301
      case '7':
1445
301
        dot = LOU_DOT_7;
1446
301
        goto haveDot;
1447
326
      case '8':
1448
326
        dot = LOU_DOT_8;
1449
326
        goto haveDot;
1450
297
      case '9':
1451
297
        dot = LOU_DOT_9;
1452
297
        goto haveDot;
1453
335
      case 'a':
1454
335
        dot = LOU_DOT_10;
1455
335
        goto haveDot;
1456
300
      case 'b':
1457
300
        dot = LOU_DOT_11;
1458
300
        goto haveDot;
1459
296
      case 'c':
1460
296
        dot = LOU_DOT_12;
1461
296
        goto haveDot;
1462
406
      case 'd':
1463
406
        dot = LOU_DOT_13;
1464
406
        goto haveDot;
1465
388
      case 'e':
1466
388
        dot = LOU_DOT_14;
1467
388
        goto haveDot;
1468
304
      case 'f':
1469
304
        dot = LOU_DOT_15;
1470
304
        goto haveDot;
1471
0
      case 'A':
1472
1
      case 'B':
1473
17
      case 'C':
1474
17
      case 'D':
1475
17
      case 'E':
1476
19
      case 'F':
1477
19
        compileError(file, "Uppercase virtual dots are not allowed.");
1478
19
        return 0;
1479
4.84k
      haveDot:
1480
4.84k
        if (started && !cell) goto invalid;
1481
4.84k
        if (cell & dot) {
1482
0
          compileError(file, "dot specified more than once.");
1483
0
          return 0;
1484
0
        }
1485
4.84k
        cell |= dot;
1486
4.84k
        break;
1487
4.84k
      }
1488
109
    case '0': /* blank */
1489
109
      if (started) goto invalid;
1490
109
      break;
1491
109
    case '-': /* got all dots for this cell */
1492
74
      if (!started) {
1493
0
        compileError(file, "missing cell specification.");
1494
0
        return 0;
1495
0
      }
1496
74
      cells->chars[cellCount++] = cell | LOU_DOTS;
1497
74
      cell = 0;
1498
74
      start = index + 1;
1499
74
      break;
1500
0
    default:
1501
0
    invalid:
1502
0
      compileError(
1503
0
          file, "invalid dot number %s.", _lou_showString(&character, 1, 0));
1504
0
      return 0;
1505
5.05k
    }
1506
5.05k
  }
1507
692
  if (index == start) {
1508
1
    compileError(file, "missing cell specification.");
1509
1
    return 0;
1510
1
  }
1511
691
  cells->chars[cellCount++] = cell | LOU_DOTS; /* last cell */
1512
691
  cells->length = cellCount;
1513
691
  return 1;
1514
692
}
1515
1516
int EXPORT_CALL
1517
0
_lou_extParseDots(const char *inString, widechar *outString) {
1518
  /* Parse external dot patterns */
1519
0
  CharsString wideIn;
1520
0
  CharsString result;
1521
0
  int k;
1522
0
  for (k = 0; inString[k] && k < MAXSTRING - 1; k++) wideIn.chars[k] = inString[k];
1523
0
  wideIn.chars[k] = 0;
1524
0
  wideIn.length = k;
1525
0
  parseDots(NULL, &result, &wideIn);
1526
0
  if (errorCount) {
1527
0
    errorCount = 0;
1528
0
    return 0;
1529
0
  }
1530
0
  for (k = 0; k < result.length; k++) outString[k] = result.chars[k];
1531
0
  outString[k] = 0;
1532
0
  return result.length;
1533
0
}
1534
1535
static int
1536
172
getCharacters(FileInfo *file, CharsString *characters) {
1537
  /* Get ruleChars string */
1538
172
  CharsString token;
1539
172
  if (!getToken(file, &token, "characters")) return 0;
1540
172
  return parseChars(file, characters, &token);
1541
172
}
1542
1543
static int
1544
18
getMatchPatternCharacters(FileInfo *file, CharsString *characters) {
1545
  /* Get match pattern string */
1546
18
  CharsString token;
1547
18
  if (!getToken(file, &token, "characters")) return 0;
1548
18
  return parseMatchPatternChars(file, characters, &token);
1549
18
}
1550
1551
static int
1552
757
getRuleCharsText(FileInfo *file, CharsString *ruleChars) {
1553
757
  CharsString token;
1554
757
  if (!getToken(file, &token, "Characters operand")) return 0;
1555
756
  return parseChars(file, ruleChars, &token);
1556
757
}
1557
1558
static int
1559
96
getRuleDotsText(FileInfo *file, CharsString *ruleDots) {
1560
96
  CharsString token;
1561
96
  if (!getToken(file, &token, "characters")) return 0;
1562
96
  return parseChars(file, ruleDots, &token);
1563
96
}
1564
1565
static int
1566
479
getRuleDotsPattern(FileInfo *file, CharsString *ruleDots) {
1567
  /* Interpret the dets operand */
1568
479
  CharsString token;
1569
479
  if (!getToken(file, &token, "Dots operand")) return 0;
1570
479
  if (token.length == 1 && token.chars[0] == '=') {
1571
2
    ruleDots->length = 0;
1572
2
    return 1;
1573
2
  } else
1574
477
    return parseDots(file, ruleDots, &token);
1575
479
}
1576
1577
static int
1578
includeFile(const FileInfo *file, CharsString *includedFile,
1579
    TranslationTableHeader **table, DisplayTableHeader **displayTable);
1580
1581
static TranslationTableOffset
1582
80
findRuleName(const CharsString *name, const TranslationTableHeader *table) {
1583
80
  const RuleName *ruleName = table->ruleNames;
1584
132
  while (ruleName) {
1585
84
    if ((name->length == ruleName->length) &&
1586
33
        (memcmp(&name->chars[0], ruleName->name, CHARSIZE * name->length) == 0))
1587
32
      return ruleName->ruleOffset;
1588
52
    ruleName = ruleName->next;
1589
52
  }
1590
48
  return 0;
1591
80
}
1592
1593
static int
1594
addRuleName(const FileInfo *file, CharsString *name, TranslationTableOffset ruleOffset,
1595
21
    TranslationTableHeader *table) {
1596
21
  int k;
1597
21
  RuleName *ruleName;
1598
21
  if (!(ruleName = malloc(sizeof(*ruleName) + CHARSIZE * (name->length - 1)))) {
1599
0
    compileError(file, "not enough memory");
1600
0
    _lou_outOfMemory();
1601
0
  }
1602
21
  memset(ruleName, 0, sizeof(*ruleName));
1603
  // a name is a sequence of characters in the ranges 'a'..'z' and 'A'..'Z'
1604
83
  for (k = 0; k < name->length; k++) {
1605
62
    widechar c = name->chars[k];
1606
62
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
1607
62
      ruleName->name[k] = c;
1608
0
    else {
1609
0
      compileError(file, "a name may contain only letters");
1610
0
      free(ruleName);
1611
0
      return 0;
1612
0
    }
1613
62
  }
1614
21
  ruleName->length = name->length;
1615
21
  ruleName->ruleOffset = ruleOffset;
1616
21
  ruleName->next = table->ruleNames;
1617
21
  table->ruleNames = ruleName;
1618
21
  return 1;
1619
21
}
1620
1621
static void
1622
18
deallocateRuleNames(TranslationTableHeader *table) {
1623
18
  RuleName **ruleName = &table->ruleNames;
1624
39
  while (*ruleName) {
1625
21
    RuleName *rn = *ruleName;
1626
21
    *ruleName = rn->next;
1627
21
    free(rn);
1628
21
  }
1629
18
}
1630
1631
static int
1632
5
compileSwapDots(const FileInfo *file, CharsString *source, CharsString *dest) {
1633
5
  int k = 0;
1634
5
  int kk = 0;
1635
5
  CharsString dotsSource;
1636
5
  CharsString dotsDest;
1637
5
  dest->length = 0;
1638
5
  dotsSource.length = 0;
1639
27
  while (k <= source->length) {
1640
22
    if (source->chars[k] != ',' && k != source->length)
1641
16
      dotsSource.chars[dotsSource.length++] = source->chars[k];
1642
6
    else {
1643
6
      if (!parseDots(file, &dotsDest, &dotsSource)) return 0;
1644
6
      dest->chars[dest->length++] = dotsDest.length + 1;
1645
16
      for (kk = 0; kk < dotsDest.length; kk++)
1646
10
        dest->chars[dest->length++] = dotsDest.chars[kk];
1647
6
      dotsSource.length = 0;
1648
6
    }
1649
22
    k++;
1650
22
  }
1651
5
  return 1;
1652
5
}
1653
1654
static int
1655
compileSwap(FileInfo *file, TranslationTableOpcode opcode, int noback, int nofor,
1656
6
    TranslationTableHeader **table) {
1657
6
  CharsString ruleChars;
1658
6
  CharsString ruleDots;
1659
6
  CharsString name;
1660
6
  CharsString matches;
1661
6
  CharsString replacements;
1662
6
  TranslationTableOffset ruleOffset;
1663
6
  if (!getToken(file, &name, "name operand")) return 0;
1664
6
  if (!getToken(file, &matches, "matches operand")) return 0;
1665
6
  if (!getToken(file, &replacements, "replacements operand")) return 0;
1666
6
  if (opcode == CTO_SwapCc || opcode == CTO_SwapCd) {
1667
5
    if (!parseChars(file, &ruleChars, &matches)) return 0;
1668
5
  } else {
1669
1
    if (!compileSwapDots(file, &matches, &ruleChars)) return 0;
1670
1
  }
1671
6
  if (opcode == CTO_SwapCc) {
1672
2
    if (!parseChars(file, &ruleDots, &replacements)) return 0;
1673
4
  } else {
1674
4
    if (!compileSwapDots(file, &replacements, &ruleDots)) return 0;
1675
4
  }
1676
6
  if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, NULL, noback,
1677
6
        nofor, table))
1678
0
    return 0;
1679
6
  if (!addRuleName(file, &name, ruleOffset, *table)) return 0;
1680
6
  return 1;
1681
6
}
1682
1683
static int
1684
17
getNumber(widechar *string, widechar *number) {
1685
  /* Convert a string of wide character digits to an integer */
1686
17
  int k = 0;
1687
17
  *number = 0;
1688
51
  while (string[k] >= '0' && string[k] <= '9')
1689
34
    *number = 10 * *number + (string[k++] - '0');
1690
17
  return k;
1691
17
}
1692
1693
/* Start of multipass compiler */
1694
1695
static int
1696
passGetAttributes(CharsString *passLine, int *passLinepos,
1697
111
    TranslationTableCharacterAttributes *attributes, const FileInfo *file) {
1698
111
  int more = 1;
1699
111
  *attributes = 0;
1700
532
  while (more) {
1701
421
    switch (passLine->chars[*passLinepos]) {
1702
68
    case pass_any:
1703
68
      *attributes = 0xffffffff;
1704
68
      break;
1705
25
    case pass_digit:
1706
25
      *attributes |= CTC_Digit;
1707
25
      break;
1708
8
    case pass_litDigit:
1709
8
      *attributes |= CTC_LitDigit;
1710
8
      break;
1711
0
    case pass_letter:
1712
0
      *attributes |= CTC_Letter;
1713
0
      break;
1714
0
    case pass_math:
1715
0
      *attributes |= CTC_Math;
1716
0
      break;
1717
51
    case pass_punctuation:
1718
51
      *attributes |= CTC_Punctuation;
1719
51
      break;
1720
19
    case pass_sign:
1721
19
      *attributes |= CTC_Sign;
1722
19
      break;
1723
68
    case pass_space:
1724
68
      *attributes |= CTC_Space;
1725
68
      break;
1726
0
    case pass_uppercase:
1727
0
      *attributes |= CTC_UpperCase;
1728
0
      break;
1729
23
    case pass_lowercase:
1730
23
      *attributes |= CTC_LowerCase;
1731
23
      break;
1732
8
    case pass_class1:
1733
8
      *attributes |= CTC_UserDefined9;
1734
8
      break;
1735
8
    case pass_class2:
1736
8
      *attributes |= CTC_UserDefined10;
1737
8
      break;
1738
31
    case pass_class3:
1739
31
      *attributes |= CTC_UserDefined11;
1740
31
      break;
1741
1
    case pass_class4:
1742
1
      *attributes |= CTC_UserDefined12;
1743
1
      break;
1744
111
    default:
1745
111
      more = 0;
1746
111
      break;
1747
421
    }
1748
421
    if (more) (*passLinepos)++;
1749
421
  }
1750
111
  if (!*attributes) {
1751
0
    compileError(file, "missing attribute");
1752
0
    (*passLinepos)--;
1753
0
    return 0;
1754
0
  }
1755
111
  return 1;
1756
111
}
1757
1758
static int
1759
passGetDots(CharsString *passLine, int *passLinepos, CharsString *dots,
1760
53
    const FileInfo *file) {
1761
53
  CharsString collectDots;
1762
53
  collectDots.length = 0;
1763
189
  while (*passLinepos < passLine->length &&
1764
189
      (passLine->chars[*passLinepos] == '-' ||
1765
188
          (passLine->chars[*passLinepos] >= '0' &&
1766
145
              passLine->chars[*passLinepos] <= '9') ||
1767
122
          ((passLine->chars[*passLinepos] | 32) >= 'a' &&
1768
70
              (passLine->chars[*passLinepos] | 32) <= 'f')))
1769
136
    collectDots.chars[collectDots.length++] = passLine->chars[(*passLinepos)++];
1770
53
  if (!parseDots(file, dots, &collectDots)) return 0;
1771
34
  return 1;
1772
53
}
1773
1774
static int
1775
passGetString(CharsString *passLine, int *passLinepos, CharsString *string,
1776
131
    const FileInfo *file) {
1777
131
  string->length = 0;
1778
2.33k
  while (1) {
1779
2.33k
    if ((*passLinepos >= passLine->length) || !passLine->chars[*passLinepos]) {
1780
9
      compileError(file, "unterminated string");
1781
9
      return 0;
1782
9
    }
1783
2.32k
    if (passLine->chars[*passLinepos] == 34) break;
1784
2.20k
    if (passLine->chars[*passLinepos] == QUOTESUB)
1785
22
      string->chars[string->length++] = 34;
1786
2.17k
    else
1787
2.17k
      string->chars[string->length++] = passLine->chars[*passLinepos];
1788
2.20k
    (*passLinepos)++;
1789
2.20k
  }
1790
122
  string->chars[string->length] = 0;
1791
122
  (*passLinepos)++;
1792
122
  return 1;
1793
131
}
1794
1795
static int
1796
308
passGetNumber(CharsString *passLine, int *passLinepos, widechar *number) {
1797
  /* Convert a string of wide character digits to an integer */
1798
308
  *number = 0;
1799
542
  while ((*passLinepos < passLine->length) && (passLine->chars[*passLinepos] >= '0') &&
1800
412
      (passLine->chars[*passLinepos] <= '9'))
1801
234
    *number = 10 * (*number) + (passLine->chars[(*passLinepos)++] - '0');
1802
308
  return 1;
1803
308
}
1804
1805
static int
1806
passGetVariableNumber(
1807
24
    const FileInfo *file, CharsString *passLine, int *passLinepos, widechar *number) {
1808
24
  if (!passGetNumber(passLine, passLinepos, number)) {
1809
0
    compileError(file, "missing variable number");
1810
0
    return 0;
1811
0
  }
1812
24
  if ((*number >= 0) && (*number < NUMVAR)) return 1;
1813
0
  compileError(file, "variable number out of range");
1814
0
  return 0;
1815
24
}
1816
1817
static int
1818
80
passGetName(CharsString *passLine, int *passLinepos, CharsString *name) {
1819
80
  name->length = 0;
1820
  // a name is a sequence of characters in the ranges 'a'..'z' and 'A'..'Z'
1821
314
  do {
1822
314
    widechar c = passLine->chars[*passLinepos];
1823
314
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
1824
234
      name->chars[name->length++] = c;
1825
234
      (*passLinepos)++;
1826
234
    } else {
1827
80
      break;
1828
80
    }
1829
314
  } while (*passLinepos < passLine->length);
1830
80
  return 1;
1831
80
}
1832
1833
static inline int
1834
184
wantsString(TranslationTableOpcode opcode, int actionPart, int nofor) {
1835
184
  if (opcode == CTO_Correct) return 1;
1836
56
  if (opcode != CTO_Context) return 0;
1837
8
  return !nofor == !actionPart;
1838
56
}
1839
1840
static int
1841
verifyStringOrDots(const FileInfo *file, TranslationTableOpcode opcode, int isString,
1842
184
    int actionPart, int nofor) {
1843
184
  if (!wantsString(opcode, actionPart, nofor) == !isString) return 1;
1844
1845
0
  compileError(file, "%s are not allowed in the %s part of a %s translation %s rule.",
1846
0
      isString ? "strings" : "dots", getPartName(actionPart),
1847
0
      nofor ? "backward" : "forward", _lou_findOpcodeName(opcode));
1848
1849
0
  return 0;
1850
184
}
1851
1852
static int
1853
appendInstructionChar(
1854
6.79k
    const FileInfo *file, widechar *passInstructions, int *passIC, widechar ch) {
1855
6.79k
  if (*passIC >= MAXSTRING) {
1856
0
    compileError(file, "multipass operand too long");
1857
0
    return 0;
1858
0
  }
1859
6.79k
  passInstructions[(*passIC)++] = ch;
1860
6.79k
  return 1;
1861
6.79k
}
1862
1863
static int
1864
compilePassOpcode(const FileInfo *file, TranslationTableOpcode opcode, int noback,
1865
280
    int nofor, TranslationTableHeader **table) {
1866
280
  static CharsString passRuleChars;
1867
280
  static CharsString passRuleDots;
1868
  /* Compile the operands of a pass opcode */
1869
280
  widechar passSubOp;
1870
280
  const CharacterClass *class;
1871
280
  TranslationTableRule *rule = NULL;
1872
280
  int k;
1873
280
  int kk = 0;
1874
280
  int endTest = 0;
1875
280
  widechar *passInstructions = passRuleDots.chars;
1876
280
  int passIC = 0; /* Instruction counter */
1877
280
  passRuleChars.length = 0;
1878
280
  CharsString passHoldString;
1879
280
  widechar passHoldNumber;
1880
280
  CharsString passLine;
1881
280
  int passLinepos = 0;
1882
280
  TranslationTableCharacterAttributes passAttributes;
1883
280
  int replacing = 0;
1884
280
  passHoldString.length = 0;
1885
26.3k
  for (k = file->linepos; k < file->linelen; k++)
1886
26.1k
    passHoldString.chars[passHoldString.length++] = file->line[k];
1887
2.00k
#define SEPCHAR 0x0001
1888
  /* FIXME: The separation of the test and the action operand works by testing for a
1889
     space character. We can do this because the operands are not allowed to contain
1890
     spaces (as per the documentation). (We are doing this for consistency and
1891
     compatibility with louis-rs.) We are however not actually checking that the action
1892
     operand does not contain spaces. It is not trivial to implent because: We can not
1893
     simply check the remainder of `passHoldString` after the first space, since we need
1894
     to allow comments. We can also not simply adapt `passGetString`: it needs to handle
1895
     spaces as any escaped spaces (\s) have been expanded by `parseChars`. */
1896
1.81k
  for (k = 0; k < passHoldString.length && passHoldString.chars[k] > 32; k++);
1897
280
  if (k < passHoldString.length)
1898
280
    passHoldString.chars[k] = SEPCHAR;
1899
0
  else {
1900
0
    compileError(file, "Invalid multipass operands");
1901
0
    return 0;
1902
0
  }
1903
280
  parseChars(file, &passLine, &passHoldString);
1904
  /* Compile test part */
1905
1.72k
  for (k = 0; k < passLine.length && passLine.chars[k] != SEPCHAR; k++);
1906
280
  endTest = k;
1907
280
  passLine.chars[endTest] = pass_endTest;
1908
280
  passLinepos = 0;
1909
1.24k
  while (passLinepos <= endTest) {
1910
961
    switch ((passSubOp = passLine.chars[passLinepos])) {
1911
214
    case pass_lookback:
1912
214
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_lookback))
1913
0
        return 0;
1914
214
      passLinepos++;
1915
214
      passGetNumber(&passLine, &passLinepos, &passHoldNumber);
1916
214
      if (passHoldNumber == 0) passHoldNumber = 1;
1917
214
      if (!appendInstructionChar(file, passInstructions, &passIC, passHoldNumber))
1918
0
        return 0;
1919
214
      break;
1920
214
    case pass_not:
1921
147
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_not))
1922
0
        return 0;
1923
147
      passLinepos++;
1924
147
      break;
1925
39
    case pass_first:
1926
39
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_first))
1927
0
        return 0;
1928
39
      passLinepos++;
1929
39
      break;
1930
7
    case pass_last:
1931
7
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_last))
1932
0
        return 0;
1933
7
      passLinepos++;
1934
7
      break;
1935
25
    case pass_search:
1936
25
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_search))
1937
0
        return 0;
1938
25
      passLinepos++;
1939
25
      break;
1940
4
    case pass_string:
1941
4
      if (!verifyStringOrDots(file, opcode, 1, 0, nofor)) {
1942
0
        return 0;
1943
0
      }
1944
4
      passLinepos++;
1945
4
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_string))
1946
0
        return 0;
1947
4
      passGetString(&passLine, &passLinepos, &passHoldString, file);
1948
4
      if (passHoldString.length == 0) {
1949
0
        compileError(file, "empty string in test part");
1950
0
        return 0;
1951
0
      }
1952
4
      goto testDoCharsDots;
1953
25
    case pass_dots:
1954
25
      if (!verifyStringOrDots(file, opcode, 0, 0, nofor)) {
1955
0
        return 0;
1956
0
      }
1957
25
      passLinepos++;
1958
25
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_dots))
1959
0
        return 0;
1960
25
      passGetDots(&passLine, &passLinepos, &passHoldString, file);
1961
25
      if (passHoldString.length == 0) {
1962
0
        compileError(file, "expected dot pattern after @ operand in test part");
1963
0
        return 0;
1964
0
      }
1965
29
    testDoCharsDots:
1966
29
      if (passIC >= MAXSTRING) {
1967
0
        compileError(
1968
0
            file, "@ operand in test part of multipass operand too long");
1969
0
        return 0;
1970
0
      }
1971
29
      if (!appendInstructionChar(
1972
29
            file, passInstructions, &passIC, passHoldString.length))
1973
0
        return 0;
1974
559
      for (kk = 0; kk < passHoldString.length; kk++) {
1975
530
        if (passIC >= MAXSTRING) {
1976
0
          compileError(
1977
0
              file, "@ operand in test part of multipass operand too long");
1978
0
          return 0;
1979
0
        }
1980
530
        if (!appendInstructionChar(
1981
530
              file, passInstructions, &passIC, passHoldString.chars[kk]))
1982
0
          return 0;
1983
530
      }
1984
29
      break;
1985
39
    case pass_startReplace:
1986
39
      if (replacing) {
1987
0
        compileError(file, "nested replacement statements");
1988
0
        return 0;
1989
0
      }
1990
39
      if (!appendInstructionChar(
1991
39
            file, passInstructions, &passIC, pass_startReplace))
1992
0
        return 0;
1993
39
      replacing = 1;
1994
39
      passLinepos++;
1995
39
      break;
1996
37
    case pass_endReplace:
1997
37
      if (!replacing) {
1998
0
        compileError(file, "unexpected end of replacement");
1999
0
        return 0;
2000
0
      }
2001
37
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_endReplace))
2002
0
        return 0;
2003
37
      replacing = 0;
2004
37
      passLinepos++;
2005
37
      break;
2006
8
    case pass_variable:
2007
8
      passLinepos++;
2008
8
      if (!passGetVariableNumber(file, &passLine, &passLinepos, &passHoldNumber))
2009
0
        return 0;
2010
8
      switch (passLine.chars[passLinepos]) {
2011
1
      case pass_eq:
2012
1
        if (!appendInstructionChar(file, passInstructions, &passIC, pass_eq))
2013
0
          return 0;
2014
1
        goto doComp;
2015
6
      case pass_lt:
2016
6
        if (passLine.chars[passLinepos + 1] == pass_eq) {
2017
4
          passLinepos++;
2018
4
          if (!appendInstructionChar(
2019
4
                file, passInstructions, &passIC, pass_lteq))
2020
0
            return 0;
2021
4
        } else if (!appendInstructionChar(
2022
2
                   file, passInstructions, &passIC, pass_lt))
2023
0
          return 0;
2024
6
        goto doComp;
2025
6
      case pass_gt:
2026
1
        if (passLine.chars[passLinepos + 1] == pass_eq) {
2027
1
          passLinepos++;
2028
1
          if (!appendInstructionChar(
2029
1
                file, passInstructions, &passIC, pass_gteq))
2030
0
            return 0;
2031
1
        } else if (!appendInstructionChar(
2032
0
                   file, passInstructions, &passIC, pass_gt))
2033
0
          return 0;
2034
8
      doComp:
2035
8
        if (!appendInstructionChar(
2036
8
              file, passInstructions, &passIC, passHoldNumber))
2037
0
          return 0;
2038
8
        passLinepos++;
2039
8
        passGetNumber(&passLine, &passLinepos, &passHoldNumber);
2040
8
        if (!appendInstructionChar(
2041
8
              file, passInstructions, &passIC, passHoldNumber))
2042
0
          return 0;
2043
8
        break;
2044
8
      default:
2045
0
        compileError(file, "incorrect comparison operator");
2046
0
        return 0;
2047
8
      }
2048
8
      break;
2049
111
    case pass_attributes:
2050
111
      passLinepos++;
2051
111
      if (!passGetAttributes(&passLine, &passLinepos, &passAttributes, file))
2052
0
        return 0;
2053
111
    insertAttributes:
2054
111
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_attributes))
2055
0
        return 0;
2056
111
      if (!appendInstructionChar(
2057
111
            file, passInstructions, &passIC, (passAttributes >> 48) & 0xffff))
2058
0
        return 0;
2059
111
      if (!appendInstructionChar(
2060
111
            file, passInstructions, &passIC, (passAttributes >> 32) & 0xffff))
2061
0
        return 0;
2062
111
      if (!appendInstructionChar(
2063
111
            file, passInstructions, &passIC, (passAttributes >> 16) & 0xffff))
2064
0
        return 0;
2065
111
      if (!appendInstructionChar(
2066
111
            file, passInstructions, &passIC, passAttributes & 0xffff))
2067
0
        return 0;
2068
113
    getRange:
2069
113
      if (passLine.chars[passLinepos] == pass_until) {
2070
53
        passLinepos++;
2071
53
        if (!appendInstructionChar(file, passInstructions, &passIC, 1)) return 0;
2072
53
        if (!appendInstructionChar(file, passInstructions, &passIC, 0xffff))
2073
0
          return 0;
2074
53
        break;
2075
53
      }
2076
60
      passGetNumber(&passLine, &passLinepos, &passHoldNumber);
2077
60
      if (passHoldNumber == 0) {
2078
45
        if (!appendInstructionChar(file, passInstructions, &passIC, 1)) return 0;
2079
45
        if (!appendInstructionChar(file, passInstructions, &passIC, 1)) return 0;
2080
45
        break;
2081
45
      }
2082
15
      if (!appendInstructionChar(file, passInstructions, &passIC, passHoldNumber))
2083
0
        return 0;
2084
15
      if (passLine.chars[passLinepos] != pass_hyphen) {
2085
14
        if (!appendInstructionChar(
2086
14
              file, passInstructions, &passIC, passHoldNumber))
2087
0
          return 0;
2088
14
        break;
2089
14
      }
2090
1
      passLinepos++;
2091
1
      passGetNumber(&passLine, &passLinepos, &passHoldNumber);
2092
1
      if (passHoldNumber == 0) {
2093
0
        compileError(file, "invalid range");
2094
0
        return 0;
2095
0
      }
2096
1
      if (!appendInstructionChar(file, passInstructions, &passIC, passHoldNumber))
2097
0
        return 0;
2098
1
      break;
2099
17
    case pass_groupstart:
2100
22
    case pass_groupend: {
2101
22
      passLinepos++;
2102
22
      passGetName(&passLine, &passLinepos, &passHoldString);
2103
22
      TranslationTableOffset ruleOffset = findRuleName(&passHoldString, *table);
2104
22
      if (ruleOffset)
2105
22
        rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
2106
22
      if (rule && rule->opcode == CTO_Grouping) {
2107
22
        if (!appendInstructionChar(file, passInstructions, &passIC, passSubOp))
2108
0
          return 0;
2109
22
        if (!appendInstructionChar(
2110
22
              file, passInstructions, &passIC, ruleOffset >> 16))
2111
0
          return 0;
2112
22
        if (!appendInstructionChar(
2113
22
              file, passInstructions, &passIC, ruleOffset & 0xffff))
2114
0
          return 0;
2115
22
        break;
2116
22
      } else {
2117
0
        compileError(file, "%s is not a grouping name",
2118
0
            _lou_showString(
2119
0
                &passHoldString.chars[0], passHoldString.length, 0));
2120
0
        return 0;
2121
0
      }
2122
0
      break;
2123
22
    }
2124
2
    case pass_swap: {
2125
2
      passLinepos++;
2126
2
      passGetName(&passLine, &passLinepos, &passHoldString);
2127
2
      if ((class = findCharacterClass(&passHoldString, *table))) {
2128
0
        passAttributes = class->attribute;
2129
0
        goto insertAttributes;
2130
0
      }
2131
2
      TranslationTableOffset ruleOffset = findRuleName(&passHoldString, *table);
2132
2
      if (ruleOffset)
2133
2
        rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
2134
2
      if (rule &&
2135
2
          (rule->opcode == CTO_SwapCc || rule->opcode == CTO_SwapCd ||
2136
2
              rule->opcode == CTO_SwapDd)) {
2137
2
        if (!appendInstructionChar(file, passInstructions, &passIC, pass_swap))
2138
0
          return 0;
2139
2
        if (!appendInstructionChar(
2140
2
              file, passInstructions, &passIC, ruleOffset >> 16))
2141
0
          return 0;
2142
2
        if (!appendInstructionChar(
2143
2
              file, passInstructions, &passIC, ruleOffset & 0xffff))
2144
0
          return 0;
2145
2
        goto getRange;
2146
2
      }
2147
0
      compileError(file, "%s is neither a class name nor a swap name.",
2148
0
          _lou_showString(&passHoldString.chars[0], passHoldString.length, 0));
2149
0
      return 0;
2150
2
    }
2151
280
    case pass_endTest:
2152
280
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_endTest))
2153
0
        return 0;
2154
280
      if (replacing) {
2155
0
        compileError(file, "expected end of replacement");
2156
0
        return 0;
2157
0
      }
2158
280
      passLinepos++;
2159
280
      break;
2160
1
    default:
2161
1
      compileError(file, "incorrect operator '%c ' in test part",
2162
1
          passLine.chars[passLinepos]);
2163
1
      return 0;
2164
961
    }
2165
2166
961
  } /* Compile action part */
2167
2168
  /* Compile action part */
2169
1.55k
  while (passLinepos < passLine.length && passLine.chars[passLinepos] <= 32)
2170
1.27k
    passLinepos++;
2171
755
  while (passLinepos < passLine.length && passLine.chars[passLinepos] > 32) {
2172
477
    if (passIC >= MAXSTRING) {
2173
0
      compileError(file, "Action part in multipass operand too long");
2174
0
      return 0;
2175
0
    }
2176
477
    switch ((passSubOp = passLine.chars[passLinepos])) {
2177
127
    case pass_string:
2178
127
      if (!verifyStringOrDots(file, opcode, 1, 1, nofor)) {
2179
0
        return 0;
2180
0
      }
2181
127
      passLinepos++;
2182
127
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_string))
2183
0
        return 0;
2184
127
      passGetString(&passLine, &passLinepos, &passHoldString, file);
2185
127
      goto actionDoCharsDots;
2186
28
    case pass_dots:
2187
28
      if (!verifyStringOrDots(file, opcode, 0, 1, nofor)) {
2188
0
        return 0;
2189
0
      }
2190
28
      passLinepos++;
2191
28
      passGetDots(&passLine, &passLinepos, &passHoldString, file);
2192
28
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_dots))
2193
0
        return 0;
2194
28
      if (passHoldString.length == 0) {
2195
0
        compileError(file, "expected dot pattern after @ operand in action part");
2196
0
        return 0;
2197
0
      }
2198
155
    actionDoCharsDots:
2199
155
      if (passIC >= MAXSTRING) {
2200
0
        compileError(
2201
0
            file, "@ operand in action part of multipass operand too long");
2202
0
        return 0;
2203
0
      }
2204
155
      if (!appendInstructionChar(
2205
155
            file, passInstructions, &passIC, passHoldString.length))
2206
0
        return 0;
2207
3.72k
      for (kk = 0; kk < passHoldString.length; kk++) {
2208
3.57k
        if (passIC >= MAXSTRING) {
2209
0
          compileError(file,
2210
0
              "@ operand in action part of multipass operand too long");
2211
0
          return 0;
2212
0
        }
2213
3.57k
        if (!appendInstructionChar(
2214
3.57k
              file, passInstructions, &passIC, passHoldString.chars[kk]))
2215
0
          return 0;
2216
3.57k
      }
2217
155
      break;
2218
155
    case pass_variable:
2219
16
      passLinepos++;
2220
16
      if (!passGetVariableNumber(file, &passLine, &passLinepos, &passHoldNumber))
2221
0
        return 0;
2222
16
      switch (passLine.chars[passLinepos]) {
2223
1
      case pass_eq:
2224
1
        if (!appendInstructionChar(file, passInstructions, &passIC, pass_eq))
2225
0
          return 0;
2226
1
        if (!appendInstructionChar(
2227
1
              file, passInstructions, &passIC, passHoldNumber))
2228
0
          return 0;
2229
1
        passLinepos++;
2230
1
        passGetNumber(&passLine, &passLinepos, &passHoldNumber);
2231
1
        if (!appendInstructionChar(
2232
1
              file, passInstructions, &passIC, passHoldNumber))
2233
0
          return 0;
2234
1
        break;
2235
15
      case pass_plus:
2236
15
      case pass_hyphen:
2237
15
        if (!appendInstructionChar(file, passInstructions, &passIC,
2238
15
              passLine.chars[passLinepos++]))
2239
0
          return 0;
2240
15
        if (!appendInstructionChar(
2241
15
              file, passInstructions, &passIC, passHoldNumber))
2242
0
          return 0;
2243
15
        break;
2244
15
      default:
2245
0
        compileError(file, "incorrect variable operator in action part");
2246
0
        return 0;
2247
16
      }
2248
16
      break;
2249
197
    case pass_copy:
2250
197
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_copy))
2251
0
        return 0;
2252
197
      passLinepos++;
2253
197
      break;
2254
52
    case pass_omit:
2255
52
      if (!appendInstructionChar(file, passInstructions, &passIC, pass_omit))
2256
0
        return 0;
2257
52
      passLinepos++;
2258
52
      break;
2259
34
    case pass_groupreplace:
2260
36
    case pass_groupstart:
2261
41
    case pass_groupend: {
2262
41
      passLinepos++;
2263
41
      passGetName(&passLine, &passLinepos, &passHoldString);
2264
41
      TranslationTableOffset ruleOffset = findRuleName(&passHoldString, *table);
2265
41
      if (ruleOffset)
2266
4
        rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
2267
41
      if (rule && rule->opcode == CTO_Grouping) {
2268
41
        if (!appendInstructionChar(file, passInstructions, &passIC, passSubOp))
2269
0
          return 0;
2270
41
        if (!appendInstructionChar(
2271
41
              file, passInstructions, &passIC, ruleOffset >> 16))
2272
0
          return 0;
2273
41
        if (!appendInstructionChar(
2274
41
              file, passInstructions, &passIC, ruleOffset & 0xffff))
2275
0
          return 0;
2276
41
        break;
2277
41
      }
2278
0
      compileError(file, "%s is not a grouping name",
2279
0
          _lou_showString(&passHoldString.chars[0], passHoldString.length, 0));
2280
0
      return 0;
2281
41
    }
2282
15
    case pass_swap: {
2283
15
      passLinepos++;
2284
15
      passGetName(&passLine, &passLinepos, &passHoldString);
2285
15
      TranslationTableOffset ruleOffset = findRuleName(&passHoldString, *table);
2286
15
      if (ruleOffset)
2287
4
        rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
2288
15
      if (rule &&
2289
15
          (rule->opcode == CTO_SwapCc || rule->opcode == CTO_SwapCd ||
2290
15
              rule->opcode == CTO_SwapDd)) {
2291
15
        if (!appendInstructionChar(file, passInstructions, &passIC, pass_swap))
2292
0
          return 0;
2293
15
        if (!appendInstructionChar(
2294
15
              file, passInstructions, &passIC, ruleOffset >> 16))
2295
0
          return 0;
2296
15
        if (!appendInstructionChar(
2297
15
              file, passInstructions, &passIC, ruleOffset & 0xffff))
2298
0
          return 0;
2299
15
        break;
2300
15
      }
2301
0
      compileError(file, "%s is not a swap name.",
2302
0
          _lou_showString(&passHoldString.chars[0], passHoldString.length, 0));
2303
0
      return 0;
2304
0
      break;
2305
15
    }
2306
1
    default:
2307
1
      compileError(file, "incorrect operator in action part");
2308
1
      return 0;
2309
477
    }
2310
477
  }
2311
2312
  /* Analyze and add rule */
2313
278
  passRuleDots.length = passIC;
2314
2315
278
  {
2316
278
    widechar *characters;
2317
278
    int length;
2318
278
    int found = passFindCharacters(
2319
278
        file, passInstructions, passRuleDots.length, &characters, &length);
2320
2321
278
    if (!found) return 0;
2322
2323
278
    if (characters) {
2324
25
      for (k = 0; k < length; k += 1) passRuleChars.chars[k] = characters[k];
2325
8
      passRuleChars.length = k;
2326
8
    }
2327
278
  }
2328
2329
278
  if (!addRule(file, opcode, &passRuleChars, &passRuleDots, 0, 0, NULL, NULL, noback,
2330
278
        nofor, table))
2331
0
    return 0;
2332
278
  return 1;
2333
278
}
2334
2335
/* End of multipass compiler */
2336
2337
static int
2338
compileBrailleIndicator(FileInfo *file, const char *ermsg, TranslationTableOpcode opcode,
2339
    TranslationTableOffset *ruleOffset, int noback, int nofor,
2340
153
    TranslationTableHeader **table) {
2341
153
  CharsString token;
2342
153
  CharsString cells;
2343
153
  if (!getToken(file, &token, ermsg)) return 0;
2344
153
  if (!parseDots(file, &cells, &token)) return 0;
2345
153
  return addRule(
2346
153
      file, opcode, NULL, &cells, 0, 0, ruleOffset, NULL, noback, nofor, table);
2347
153
}
2348
2349
static int
2350
17
compileNumber(FileInfo *file) {
2351
17
  CharsString token;
2352
17
  widechar number;
2353
17
  if (!getToken(file, &token, "number")) return 0;
2354
17
  getNumber(&token.chars[0], &number);
2355
17
  if (!(number > 0)) {
2356
0
    compileError(file, "a nonzero positive number is required");
2357
0
    return 0;
2358
0
  }
2359
17
  return number;
2360
17
}
2361
2362
static int
2363
compileGrouping(FileInfo *file, int noback, int nofor, TranslationTableHeader **table,
2364
15
    DisplayTableHeader **displayTable) {
2365
15
  int k;
2366
15
  CharsString name;
2367
15
  CharsString groupChars;
2368
15
  CharsString groupDots;
2369
15
  CharsString dotsParsed;
2370
15
  if (!getToken(file, &name, "name operand")) return 0;
2371
15
  if (!getRuleCharsText(file, &groupChars)) return 0;
2372
15
  if (!getToken(file, &groupDots, "dots operand")) return 0;
2373
40
  for (k = 0; k < groupDots.length && groupDots.chars[k] != ','; k++);
2374
15
  if (k == groupDots.length) {
2375
0
    compileError(file, "Dots operand must consist of two cells separated by a comma");
2376
0
    return 0;
2377
0
  }
2378
15
  groupDots.chars[k] = '-';
2379
15
  if (!parseDots(file, &dotsParsed, &groupDots)) return 0;
2380
15
  if (groupChars.length != 2 || dotsParsed.length != 2) {
2381
0
    compileError(file,
2382
0
        "two Unicode characters and two cells separated by a comma are needed.");
2383
0
    return 0;
2384
0
  }
2385
15
  if (table) {
2386
15
    TranslationTableOffset ruleOffset;
2387
15
    TranslationTableCharacter *charsDotsPtr;
2388
15
    charsDotsPtr =
2389
15
        putChar(file, groupChars.chars[0], table, NULL, (*table)->ruleCounter);
2390
15
    charsDotsPtr->attributes |= CTC_Math;
2391
15
    charsDotsPtr =
2392
15
        putChar(file, groupChars.chars[1], table, NULL, (*table)->ruleCounter);
2393
15
    charsDotsPtr->attributes |= CTC_Math;
2394
15
    charsDotsPtr = putDots(file, dotsParsed.chars[0], table, (*table)->ruleCounter);
2395
15
    charsDotsPtr->attributes |= CTC_Math;
2396
15
    charsDotsPtr = putDots(file, dotsParsed.chars[1], table, (*table)->ruleCounter);
2397
15
    charsDotsPtr->attributes |= CTC_Math;
2398
15
    if (!addRule(file, CTO_Grouping, &groupChars, &dotsParsed, 0, 0, &ruleOffset,
2399
15
          NULL, noback, nofor, table))
2400
0
      return 0;
2401
15
    if (!addRuleName(file, &name, ruleOffset, *table)) return 0;
2402
15
  }
2403
15
  if (displayTable) {
2404
15
    putCharDotsMapping(file, groupChars.chars[0], dotsParsed.chars[0], displayTable);
2405
15
    putCharDotsMapping(file, groupChars.chars[1], dotsParsed.chars[1], displayTable);
2406
15
  }
2407
15
  if (table) {
2408
15
    widechar endChar;
2409
15
    widechar endDots;
2410
15
    endChar = groupChars.chars[1];
2411
15
    endDots = dotsParsed.chars[1];
2412
15
    groupChars.length = dotsParsed.length = 1;
2413
15
    if (!addRule(file, CTO_Math, &groupChars, &dotsParsed, 0, 0, NULL, NULL, noback,
2414
15
          nofor, table))
2415
0
      return 0;
2416
15
    groupChars.chars[0] = endChar;
2417
15
    dotsParsed.chars[0] = endDots;
2418
15
    if (!addRule(file, CTO_Math, &groupChars, &dotsParsed, 0, 0, NULL, NULL, noback,
2419
15
          nofor, table))
2420
0
      return 0;
2421
15
  }
2422
15
  return 1;
2423
15
}
2424
2425
/* Functions for compiling hyphenation tables */
2426
2427
typedef struct HyphenDict { /* hyphenation dictionary: finite state machine */
2428
  int numStates;
2429
  HyphenationState *states;
2430
} HyphenDict;
2431
2432
1.41M
#define DEFAULTSTATE 0xffff
2433
951k
#define HYPHENHASHSIZE 8191
2434
2435
typedef struct HyphenHashEntry {
2436
  struct HyphenHashEntry *next;
2437
  CharsString *key;
2438
  int val;
2439
} HyphenHashEntry;
2440
2441
typedef struct HyphenHashTab {
2442
  HyphenHashEntry *entries[HYPHENHASHSIZE];
2443
} HyphenHashTab;
2444
2445
/* a hash function from ASU - adapted from Gtk+ */
2446
static unsigned int
2447
706k
hyphenStringHash(const CharsString *s) {
2448
706k
  int k;
2449
706k
  unsigned int h = 0, g;
2450
191M
  for (k = 0; k < s->length; k++) {
2451
190M
    h = (h << 4) + s->chars[k];
2452
190M
    if ((g = h & 0xf0000000)) {
2453
172M
      h = h ^ (g >> 24);
2454
172M
      h = h ^ g;
2455
172M
    }
2456
190M
  }
2457
706k
  return h;
2458
706k
}
2459
2460
static HyphenHashTab *
2461
15
hyphenHashNew(void) {
2462
15
  HyphenHashTab *hashTab;
2463
15
  if (!(hashTab = malloc(sizeof(HyphenHashTab)))) _lou_outOfMemory();
2464
15
  memset(hashTab, 0, sizeof(HyphenHashTab));
2465
15
  return hashTab;
2466
15
}
2467
2468
static void
2469
15
hyphenHashFree(HyphenHashTab *hashTab) {
2470
15
  int i;
2471
15
  HyphenHashEntry *e, *next;
2472
122k
  for (i = 0; i < HYPHENHASHSIZE; i++)
2473
126k
    for (e = hashTab->entries[i]; e; e = next) {
2474
3.47k
      next = e->next;
2475
3.47k
      free(e->key);
2476
3.47k
      free(e);
2477
3.47k
    }
2478
15
  free(hashTab);
2479
15
}
2480
2481
/* assumes that key is not already present! */
2482
static void
2483
3.47k
hyphenHashInsert(HyphenHashTab *hashTab, const CharsString *key, int val) {
2484
3.47k
  int i, j;
2485
3.47k
  HyphenHashEntry *e;
2486
3.47k
  i = hyphenStringHash(key) % HYPHENHASHSIZE;
2487
3.47k
  if (!(e = malloc(sizeof(HyphenHashEntry)))) _lou_outOfMemory();
2488
3.47k
  e->next = hashTab->entries[i];
2489
3.47k
  e->key = malloc((key->length + 1) * CHARSIZE);
2490
3.47k
  if (!e->key) _lou_outOfMemory();
2491
3.47k
  e->key->length = key->length;
2492
706k
  for (j = 0; j < key->length; j++) e->key->chars[j] = key->chars[j];
2493
3.47k
  e->val = val;
2494
3.47k
  hashTab->entries[i] = e;
2495
3.47k
}
2496
2497
/* return val if found, otherwise DEFAULTSTATE */
2498
static int
2499
706k
hyphenHashLookup(HyphenHashTab *hashTab, const CharsString *key) {
2500
706k
  int i, j;
2501
706k
  HyphenHashEntry *e;
2502
706k
  if (key->length == 0) return 0;
2503
702k
  i = hyphenStringHash(key) % HYPHENHASHSIZE;
2504
774k
  for (e = hashTab->entries[i]; e; e = e->next) {
2505
71.6k
    if (key->length != e->key->length) continue;
2506
1.23k
    for (j = 0; j < key->length; j++)
2507
1.06k
      if (key->chars[j] != e->key->chars[j]) break;
2508
237
    if (j == key->length) return e->val;
2509
237
  }
2510
702k
  return DEFAULTSTATE;
2511
702k
}
2512
2513
static int
2514
3.47k
hyphenGetNewState(HyphenDict *dict, HyphenHashTab *hashTab, const CharsString *string) {
2515
3.47k
  hyphenHashInsert(hashTab, string, dict->numStates);
2516
  /* predicate is true if dict->numStates is a power of two */
2517
3.47k
  if (!(dict->numStates & (dict->numStates - 1)))
2518
104
    dict->states =
2519
104
        realloc(dict->states, (dict->numStates << 1) * sizeof(HyphenationState));
2520
3.47k
  if (!dict->states) _lou_outOfMemory();
2521
3.47k
  dict->states[dict->numStates].hyphenPattern = 0;
2522
3.47k
  dict->states[dict->numStates].fallbackState = DEFAULTSTATE;
2523
3.47k
  dict->states[dict->numStates].numTrans = 0;
2524
3.47k
  dict->states[dict->numStates].trans.pointer = NULL;
2525
3.47k
  return dict->numStates++;
2526
3.47k
}
2527
2528
/* add a transition from state1 to state2 through ch - assumes that the
2529
 * transition does not already exist */
2530
static void
2531
3.47k
hyphenAddTrans(HyphenDict *dict, int state1, int state2, widechar ch) {
2532
3.47k
  int numTrans;
2533
3.47k
  numTrans = dict->states[state1].numTrans;
2534
3.47k
  if (numTrans == 0)
2535
3.43k
    dict->states[state1].trans.pointer = malloc(sizeof(HyphenationTrans));
2536
42
  else if (!(numTrans & (numTrans - 1)))
2537
36
    dict->states[state1].trans.pointer = realloc(dict->states[state1].trans.pointer,
2538
36
        (numTrans << 1) * sizeof(HyphenationTrans));
2539
3.47k
  dict->states[state1].trans.pointer[numTrans].ch = ch;
2540
3.47k
  dict->states[state1].trans.pointer[numTrans].newState = state2;
2541
3.47k
  dict->states[state1].numTrans++;
2542
3.47k
}
2543
2544
static int
2545
compileHyphenation(
2546
15
    FileInfo *file, CharsString *encoding, TranslationTableHeader **table) {
2547
15
  CharsString hyph;
2548
15
  HyphenationTrans *holdPointer;
2549
15
  HyphenHashTab *hashTab;
2550
15
  CharsString word;
2551
15
  char pattern[MAXSTRING + 1];
2552
15
  unsigned int stateNum = 0, lastState = 0;
2553
15
  int i, j, k = encoding->length;
2554
15
  widechar ch;
2555
15
  int found;
2556
15
  HyphenHashEntry *e;
2557
15
  HyphenDict dict;
2558
15
  TranslationTableOffset holdOffset;
2559
  /* Set aside enough space for hyphenation states and transitions in
2560
   * translation table. Must be done before anything else */
2561
15
  allocateSpaceInTranslationTable(file, NULL, 250000, table);
2562
15
  hashTab = hyphenHashNew();
2563
15
  dict.numStates = 1;
2564
15
  dict.states = malloc(sizeof(HyphenationState));
2565
15
  if (!dict.states) _lou_outOfMemory();
2566
15
  dict.states[0].hyphenPattern = 0;
2567
15
  dict.states[0].fallbackState = DEFAULTSTATE;
2568
15
  dict.states[0].numTrans = 0;
2569
15
  dict.states[0].trans.pointer = NULL;
2570
197
  do {
2571
197
    if (encoding->chars[0] == 'I') {
2572
146
      if (!getToken(file, &hyph, NULL)) continue;
2573
146
    } else {
2574
      /* UTF-8 */
2575
51
      if (!getToken(file, &word, NULL)) continue;
2576
50
      parseChars(file, &hyph, &word);
2577
50
    }
2578
190
    if (hyph.length == 0 || hyph.chars[0] == '#' || hyph.chars[0] == '%' ||
2579
114
        hyph.chars[0] == '<')
2580
76
      continue; /* comment */
2581
114
    j = 0;
2582
114
    pattern[j] = '0';
2583
4.45k
    for (i = 0; i < hyph.length; i++) {
2584
4.33k
      if (hyph.chars[i] >= '0' && hyph.chars[i] <= '9')
2585
17
        pattern[j] = (char)hyph.chars[i];
2586
4.32k
      else {
2587
4.32k
        word.chars[j] = hyph.chars[i];
2588
4.32k
        pattern[++j] = '0';
2589
4.32k
      }
2590
4.33k
    }
2591
114
    word.chars[j] = 0;
2592
114
    word.length = j;
2593
114
    pattern[j + 1] = 0;
2594
3.52k
    for (i = 0; pattern[i] == '0'; i++);
2595
114
    found = hyphenHashLookup(hashTab, &word);
2596
114
    if (found != DEFAULTSTATE)
2597
56
      stateNum = found;
2598
58
    else
2599
58
      stateNum = hyphenGetNewState(&dict, hashTab, &word);
2600
114
    k = j + 2 - i;
2601
114
    if (k > 0) {
2602
114
      allocateSpaceInTranslationTable(
2603
114
          file, &dict.states[stateNum].hyphenPattern, k, table);
2604
114
      memcpy(&(*table)->ruleArea[dict.states[stateNum].hyphenPattern], &pattern[i],
2605
114
          k);
2606
114
    }
2607
    /* now, put in the prefix transitions */
2608
3.59k
    while (found == DEFAULTSTATE) {
2609
3.47k
      lastState = stateNum;
2610
3.47k
      ch = word.chars[word.length-- - 1];
2611
3.47k
      found = hyphenHashLookup(hashTab, &word);
2612
3.47k
      if (found != DEFAULTSTATE)
2613
58
        stateNum = found;
2614
3.41k
      else
2615
3.41k
        stateNum = hyphenGetNewState(&dict, hashTab, &word);
2616
3.47k
      hyphenAddTrans(&dict, stateNum, lastState, ch);
2617
3.47k
    }
2618
197
  } while (_lou_getALine(file));
2619
  /* put in the fallback states */
2620
122k
  for (i = 0; i < HYPHENHASHSIZE; i++) {
2621
126k
    for (e = hashTab->entries[i]; e; e = e->next) {
2622
702k
      for (j = 1; j <= e->key->length; j++) {
2623
702k
        word.length = 0;
2624
189M
        for (k = j; k < e->key->length; k++)
2625
189M
          word.chars[word.length++] = e->key->chars[k];
2626
702k
        stateNum = hyphenHashLookup(hashTab, &word);
2627
702k
        if (stateNum != DEFAULTSTATE) break;
2628
702k
      }
2629
3.47k
      if (e->val) dict.states[e->val].fallbackState = stateNum;
2630
3.47k
    }
2631
122k
  }
2632
15
  hyphenHashFree(hashTab);
2633
  /* Transfer hyphenation information to table */
2634
3.50k
  for (i = 0; i < dict.numStates; i++) {
2635
3.49k
    if (dict.states[i].numTrans == 0)
2636
57
      dict.states[i].trans.offset = 0;
2637
3.43k
    else {
2638
3.43k
      holdPointer = dict.states[i].trans.pointer;
2639
3.43k
      allocateSpaceInTranslationTable(file, &dict.states[i].trans.offset,
2640
3.43k
          dict.states[i].numTrans * sizeof(HyphenationTrans), table);
2641
3.43k
      memcpy(&(*table)->ruleArea[dict.states[i].trans.offset], holdPointer,
2642
3.43k
          dict.states[i].numTrans * sizeof(HyphenationTrans));
2643
3.43k
      free(holdPointer);
2644
3.43k
    }
2645
3.49k
  }
2646
15
  allocateSpaceInTranslationTable(
2647
15
      file, &holdOffset, dict.numStates * sizeof(HyphenationState), table);
2648
15
  (*table)->hyphenStatesArray = holdOffset;
2649
  /* Prevents segmentation fault if table is reallocated */
2650
15
  memcpy(&(*table)->ruleArea[(*table)->hyphenStatesArray], &dict.states[0],
2651
15
      dict.numStates * sizeof(HyphenationState));
2652
15
  free(dict.states);
2653
15
  return 1;
2654
15
}
2655
2656
static int
2657
compileCharDef(FileInfo *file, TranslationTableOpcode opcode,
2658
    TranslationTableCharacterAttributes attributes, int noback, int nofor,
2659
344
    TranslationTableHeader **table, DisplayTableHeader **displayTable) {
2660
344
  CharsString ruleChars;
2661
344
  CharsString ruleDots;
2662
344
  if (!getRuleCharsText(file, &ruleChars)) return 0;
2663
344
  if (!getRuleDotsPattern(file, &ruleDots)) return 0;
2664
343
  if (ruleChars.length != 1) {
2665
0
    compileError(file, "Exactly one character is required.");
2666
0
    return 0;
2667
0
  }
2668
343
  if (ruleDots.length < 1) {
2669
0
    compileError(file, "At least one cell is required.");
2670
0
    return 0;
2671
0
  }
2672
343
  if (table) {
2673
343
    TranslationTableCharacter *character;
2674
343
    TranslationTableCharacter *cell = NULL;
2675
343
    int k;
2676
343
    if (attributes & (CTC_UpperCase | CTC_LowerCase)) attributes |= CTC_Letter;
2677
343
    character = putChar(file, ruleChars.chars[0], table, NULL, (*table)->ruleCounter);
2678
343
    character->attributes |= attributes;
2679
688
    for (k = ruleDots.length - 1; k >= 0; k -= 1) {
2680
345
      cell = getDots(ruleDots.chars[k], *table);
2681
345
      if (!cell)
2682
324
        cell = putDots(file, ruleDots.chars[k], table, (*table)->ruleCounter);
2683
345
    }
2684
343
    if (ruleDots.length == 1) cell->attributes |= attributes;
2685
343
  }
2686
343
  if (displayTable && ruleDots.length == 1)
2687
341
    putCharDotsMapping(file, ruleChars.chars[0], ruleDots.chars[0], displayTable);
2688
343
  if (table)
2689
343
    if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, NULL, NULL, noback, nofor,
2690
343
          table))
2691
0
      return 0;
2692
343
  return 1;
2693
343
}
2694
2695
static int
2696
0
compileBeforeAfter(FileInfo *file) {
2697
  /* 1=before, 2=after, 0=error */
2698
0
  CharsString token;
2699
0
  CharsString tmp;
2700
0
  if (!getToken(file, &token, "last word before or after")) return 0;
2701
0
  if (!parseChars(file, &tmp, &token)) return 0;
2702
0
  if (eqasc2uni((unsigned char *)"before", tmp.chars, 6))
2703
0
    return 1;
2704
0
  else if (eqasc2uni((unsigned char *)"after", tmp.chars, 5))
2705
0
    return 2;
2706
0
  return 0;
2707
0
}
2708
2709
/**
2710
 * Macro
2711
 */
2712
typedef struct {
2713
  const char *name;
2714
  const widechar *definition;  // fixed part
2715
  int definition_length;
2716
  const int *substitutions;  // variable part: position and argument index of each
2717
                 // variable substitution
2718
  int substitution_count;
2719
  int argument_count;  // number of expected arguments
2720
} Macro;
2721
2722
/**
2723
 * List of in-scope macros
2724
 */
2725
typedef struct MacroList {
2726
  const Macro *head;
2727
  const struct MacroList *tail;
2728
} MacroList;
2729
2730
/**
2731
 * Create new macro.
2732
 */
2733
static const Macro *
2734
create_macro(const char *name, const widechar *definition, int definition_length,
2735
0
    const int *substitutions, int substitution_count, int argument_count) {
2736
0
  Macro *m = malloc(sizeof(Macro));
2737
0
  m->name = strdup(name);
2738
0
  widechar *definition_copy = malloc(definition_length * sizeof(widechar));
2739
0
  memcpy(definition_copy, definition, definition_length * sizeof(widechar));
2740
0
  m->definition = definition_copy;
2741
0
  m->definition_length = definition_length;
2742
0
  int *substitutions_copy = malloc(2 * substitution_count * sizeof(int));
2743
0
  memcpy(substitutions_copy, substitutions, 2 * substitution_count * sizeof(int));
2744
0
  m->substitutions = substitutions_copy;
2745
0
  m->substitution_count = substitution_count;
2746
0
  m->argument_count = argument_count;
2747
0
  return m;
2748
0
}
2749
2750
/**
2751
 * Create new macro list from "head" macro and "tail" list.
2752
 */
2753
static const MacroList *
2754
0
cons_macro(const Macro *head, const MacroList *tail) {
2755
0
  MacroList *list = malloc(sizeof(MacroList));
2756
0
  list->head = head;
2757
0
  list->tail = tail;
2758
0
  return list;
2759
0
}
2760
2761
/**
2762
 * Free macro returned by create_macro.
2763
 */
2764
static void
2765
0
free_macro(const Macro *macro) {
2766
0
  if (macro) {
2767
0
    free((char *)macro->name);
2768
0
    free((char *)macro->definition);
2769
0
    free((int *)macro->substitutions);
2770
0
    free((Macro *)macro);
2771
0
  }
2772
0
}
2773
2774
/**
2775
 * Free macro list returned by cons_macro.
2776
 */
2777
static void
2778
292
free_macro_list(const MacroList *list) {
2779
292
  if (list) {
2780
0
    free_macro((Macro *)list->head);
2781
0
    free_macro_list((MacroList *)list->tail);
2782
0
    free((MacroList *)list);
2783
0
  }
2784
292
}
2785
2786
/**
2787
 * Compile macro
2788
 */
2789
static int
2790
0
compileMacro(FileInfo *file, const Macro **macro) {
2791
0
2792
0
  // parse name
2793
0
  CharsString token;
2794
0
  if (!getToken(file, &token, "macro name")) return 0;
2795
0
  switch (getOpcode(file, &token)) {
2796
0
  case CTO_UpLow:  // deprecated so "uplow" may be used as macro name
2797
0
  case CTO_None:
2798
0
    break;
2799
0
  default:
2800
0
    compileError(file, "Invalid macro name: already taken by an opcode");
2801
0
    return 0;
2802
0
  }
2803
0
  for (int i = 0; i < token.length; i++) {
2804
0
    if (!((token.chars[i] >= 'a' && token.chars[i] <= 'z') ||
2805
0
          (token.chars[i] >= 'A' && token.chars[i] <= 'Z') ||
2806
0
          (token.chars[i] >= '0' && token.chars[i] <= '9'))) {
2807
0
      compileError(file,
2808
0
          "Invalid macro name: must be a word containing only letters and "
2809
0
          "digits");
2810
0
      return 0;
2811
0
    }
2812
0
  }
2813
0
  static char name[MAXSTRING + 1];
2814
0
  int name_length;
2815
0
  for (name_length = 0; name_length < token.length;
2816
0
      name_length++)  // we know token can not be longer than MAXSTRING
2817
0
    name[name_length] = (char)token.chars[name_length];
2818
0
  name[name_length] = '\0';
2819
0
2820
0
  // parse body
2821
0
  static widechar definition[MAXSTRING];
2822
0
  static int substitutions[2 * MAX_MACRO_VAR];
2823
0
  int definition_length = 0;
2824
0
  int substitution_count = 0;
2825
0
  int argument_count = 0;
2826
0
  int dollar = 0;
2827
0
2828
0
  // ignore rest of line after name and read lines until "eom" is encountered
2829
0
  while (_lou_getALine(file)) {
2830
0
    if (file->linelen >= 3 && file->line[0] == 'e' && file->line[1] == 'o' &&
2831
0
        file->line[2] == 'm') {
2832
0
      *macro = create_macro(name, definition, definition_length, substitutions,
2833
0
          substitution_count, argument_count);
2834
0
      return 1;
2835
0
    }
2836
0
    while (!atEndOfLine(file)) {
2837
0
      widechar c = file->line[file->linepos++];
2838
0
      if (dollar) {
2839
0
        dollar = 0;
2840
0
        if (c >= '0' && c <= '9') {
2841
0
          if (substitution_count >= MAX_MACRO_VAR) {
2842
0
            compileError(file,
2843
0
                "Macro can not have more than %d variable substitutions",
2844
0
                MAXSTRING);
2845
0
            return 0;
2846
0
          }
2847
0
          substitutions[2 * substitution_count] = definition_length;
2848
0
          int arg = c - '0';
2849
0
          substitutions[2 * substitution_count + 1] = arg;
2850
0
          if (arg > argument_count) argument_count = arg;
2851
0
          substitution_count++;
2852
0
          continue;
2853
0
        }
2854
0
      } else if (c == '$') {
2855
0
        dollar = 1;
2856
0
        continue;
2857
0
      }
2858
0
      if (definition_length >= MAXSTRING) {
2859
0
        compileError(file, "Macro exceeds %d characters", MAXSTRING);
2860
0
        return 0;
2861
0
      } else
2862
0
        definition[definition_length++] = c;
2863
0
    }
2864
0
    dollar = 0;
2865
0
    if (definition_length >= MAXSTRING) {
2866
0
      compileError(file, "Macro exceeds %d characters", MAXSTRING);
2867
0
      return 0;
2868
0
    }
2869
0
    definition[definition_length++] = '\n';
2870
0
  }
2871
0
  compileError(file, "macro must be terminated with 'eom'");
2872
0
  return 0;
2873
0
}
2874
2875
static int
2876
compileRule(FileInfo *file, TranslationTableHeader **table,
2877
1.98k
    DisplayTableHeader **displayTable, const MacroList **inScopeMacros) {
2878
1.98k
  CharsString token;
2879
1.98k
  TranslationTableOpcode opcode;
2880
1.98k
  CharsString ruleChars;
2881
1.98k
  CharsString ruleDots;
2882
1.98k
  CharsString cells;
2883
1.98k
  CharsString scratchPad;
2884
1.98k
  CharsString emphClass;
2885
1.98k
  TranslationTableCharacterAttributes after = 0;
2886
1.98k
  TranslationTableCharacterAttributes before = 0;
2887
1.98k
  int noback, nofor, nocross;
2888
1.98k
  noback = nofor = nocross = 0;
2889
2.35k
doOpcode:
2890
2.35k
  if (!getToken(file, &token, NULL)) return 1;          /* blank line */
2891
1.99k
  if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */
2892
1.77k
  if (file->lineNumber == 1 &&
2893
722
      (eqasc2uni((unsigned char *)"ISO", token.chars, 3) ||
2894
709
          eqasc2uni((unsigned char *)"UTF-8", token.chars, 5))) {
2895
15
    if (file->in == NULL)
2896
      /* When compileRule is invokded by compileString, it leaves file->in a NULL
2897
       * pointer. Add a check to avoid dereferencing the NULL pointer in
2898
       * compileHyphenation*/
2899
0
      return 0;
2900
15
    if (table)
2901
15
      compileHyphenation(file, &token, table);
2902
0
    else
2903
      /* ignore the whole file */
2904
0
      while (_lou_getALine(file));
2905
15
    return 1;
2906
15
  }
2907
1.75k
  opcode = getOpcode(file, &token);
2908
1.75k
  switch (opcode) {
2909
0
  case CTO_Macro: {
2910
0
    const Macro *macro;
2911
#ifdef ENABLE_MACROS
2912
    if (!inScopeMacros) {
2913
      compileError(file, "Defining macros only allowed in table files.");
2914
      return 0;
2915
    }
2916
    if (compileMacro(file, &macro)) {
2917
      *inScopeMacros = cons_macro(macro, *inScopeMacros);
2918
      return 1;
2919
    }
2920
    return 0;
2921
#else
2922
0
    compileError(file, "Macro feature is disabled.");
2923
0
    return 0;
2924
0
#endif
2925
0
  }
2926
2
  case CTO_IncludeFile: {
2927
2
    CharsString includedFile;
2928
2
    if (!getToken(file, &token, "include file name")) return 0;
2929
2
    if (!parseChars(file, &includedFile, &token)) return 0;
2930
2
    return includeFile(file, &includedFile, table, displayTable);
2931
2
  }
2932
281
  case CTO_NoBack:
2933
281
    if (nofor) {
2934
0
      compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoFor));
2935
0
      return 0;
2936
0
    }
2937
281
    noback = 1;
2938
281
    goto doOpcode;
2939
46
  case CTO_NoFor:
2940
46
    if (noback) {
2941
0
      compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoBack));
2942
0
      return 0;
2943
0
    }
2944
46
    nofor = 1;
2945
46
    goto doOpcode;
2946
290
  case CTO_Space:
2947
290
    return compileCharDef(
2948
290
        file, opcode, CTC_Space, noback, nofor, table, displayTable);
2949
2
  case CTO_Digit:
2950
2
    return compileCharDef(
2951
2
        file, opcode, CTC_Digit, noback, nofor, table, displayTable);
2952
4
  case CTO_LitDigit:
2953
4
    return compileCharDef(
2954
4
        file, opcode, CTC_LitDigit, noback, nofor, table, displayTable);
2955
7
  case CTO_Punctuation:
2956
7
    return compileCharDef(
2957
7
        file, opcode, CTC_Punctuation, noback, nofor, table, displayTable);
2958
1
  case CTO_Math:
2959
1
    return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable);
2960
7
  case CTO_Sign:
2961
7
    return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable);
2962
17
  case CTO_Letter:
2963
17
    return compileCharDef(
2964
17
        file, opcode, CTC_Letter, noback, nofor, table, displayTable);
2965
15
  case CTO_UpperCase:
2966
15
    return compileCharDef(
2967
15
        file, opcode, CTC_UpperCase, noback, nofor, table, displayTable);
2968
1
  case CTO_LowerCase:
2969
1
    return compileCharDef(
2970
1
        file, opcode, CTC_LowerCase, noback, nofor, table, displayTable);
2971
15
  case CTO_Grouping:
2972
15
    return compileGrouping(file, noback, nofor, table, displayTable);
2973
0
  case CTO_Display:
2974
0
    if (!displayTable) return 1;  // ignore
2975
0
    if (!getRuleCharsText(file, &ruleChars)) return 0;
2976
0
    if (!getRuleDotsPattern(file, &ruleDots)) return 0;
2977
0
    if (ruleChars.length != 1 || ruleDots.length != 1) {
2978
0
      compileError(file, "Exactly one character and one cell are required.");
2979
0
      return 0;
2980
0
    }
2981
0
    return putCharDotsMapping(
2982
0
        file, ruleChars.chars[0], ruleDots.chars[0], displayTable);
2983
0
  case CTO_UpLow:
2984
12
  case CTO_None: {
2985
    // check if token is a macro name
2986
12
    if (inScopeMacros) {
2987
12
      const MacroList *macros = *inScopeMacros;
2988
12
      while (macros) {
2989
0
        const Macro *m = macros->head;
2990
0
        if (token.length == strlen(m->name) &&
2991
0
            eqasc2uni((unsigned char *)m->name, token.chars, token.length)) {
2992
0
          if (!inScopeMacros) {
2993
0
            compileError(file, "Calling macros only allowed in table files.");
2994
0
            return 0;
2995
0
          }
2996
0
          FileInfo tmpFile;
2997
0
          memset(&tmpFile, 0, sizeof(tmpFile));
2998
0
          tmpFile.fileName = file->fileName;
2999
0
          tmpFile.sourceFile = file->sourceFile;
3000
0
          tmpFile.lineNumber = file->lineNumber;
3001
0
          tmpFile.encoding = noEncoding;
3002
0
          tmpFile.status = 0;
3003
0
          tmpFile.linepos = 0;
3004
0
          tmpFile.linelen = 0;
3005
0
          int argument_count = 0;
3006
0
          CharsString *arguments =
3007
0
              malloc(m->argument_count * sizeof(CharsString));
3008
0
          while (argument_count < m->argument_count) {
3009
0
            if (getToken(file, &token, "macro argument"))
3010
0
              arguments[argument_count++] = token;
3011
0
            else
3012
0
              break;
3013
0
          }
3014
0
          if (argument_count < m->argument_count) {
3015
0
            compileError(file, "Expected %d arguments", m->argument_count);
3016
0
            return 0;
3017
0
          }
3018
0
          int i = 0;
3019
0
          int subst = 0;
3020
0
          int next = subst < m->substitution_count ? m->substitutions[2 * subst]
3021
0
                               : m->definition_length;
3022
0
          for (;;) {
3023
0
            while (i < next) {
3024
0
              widechar c = m->definition[i++];
3025
0
              if (c == '\n') {
3026
0
                if (!compileRule(&tmpFile, table, displayTable,
3027
0
                      inScopeMacros)) {
3028
0
                  _lou_logMessage(LOU_LOG_ERROR,
3029
0
                      "result of macro expansion was: %s",
3030
0
                      _lou_showString(
3031
0
                          tmpFile.line, tmpFile.linelen, 0));
3032
0
                  return 0;
3033
0
                }
3034
0
                tmpFile.linepos = 0;
3035
0
                tmpFile.linelen = 0;
3036
0
              } else if (tmpFile.linelen >= MAXSTRING) {
3037
0
                compileError(file,
3038
0
                    "Line exceeds %d characters (post macro "
3039
0
                    "expansion)",
3040
0
                    MAXSTRING);
3041
0
                return 0;
3042
0
              } else
3043
0
                tmpFile.line[tmpFile.linelen++] = c;
3044
0
            }
3045
0
            if (subst < m->substitution_count) {
3046
0
              CharsString arg =
3047
0
                  arguments[m->substitutions[2 * subst + 1] - 1];
3048
0
              for (int j = 0; j < arg.length; j++)
3049
0
                tmpFile.line[tmpFile.linelen++] = arg.chars[j];
3050
0
              subst++;
3051
0
              next = subst < m->substitution_count
3052
0
                  ? m->substitutions[2 * subst]
3053
0
                  : m->definition_length;
3054
0
            } else {
3055
0
              if (!compileRule(
3056
0
                    &tmpFile, table, displayTable, inScopeMacros)) {
3057
0
                _lou_logMessage(LOU_LOG_ERROR,
3058
0
                    "result of macro expansion was: %s",
3059
0
                    _lou_showString(
3060
0
                        tmpFile.line, tmpFile.linelen, 0));
3061
0
                return 0;
3062
0
              }
3063
0
              break;
3064
0
            }
3065
0
          }
3066
0
          return 1;
3067
0
        }
3068
0
        macros = macros->tail;
3069
0
      }
3070
12
    }
3071
12
    if (opcode == CTO_UpLow) {
3072
0
      compileError(file, "The uplow opcode is deprecated.");
3073
0
      return 0;
3074
0
    }
3075
12
    compileError(file, "opcode %s not defined.",
3076
12
        _lou_showString(token.chars, token.length, 0));
3077
12
    return 0;
3078
12
  }
3079
3080
  /* now only opcodes follow that don't modify the display table */
3081
1.05k
  default:
3082
1.05k
    if (!table) return 1;
3083
1.05k
    switch (opcode) {
3084
6
    case CTO_Locale:
3085
6
      compileWarning(file,
3086
6
          "The locale opcode is not implemented. Use the locale meta data "
3087
6
          "instead.");
3088
6
      return 1;
3089
31
    case CTO_Undefined: {
3090
      // not passing pointer to location inside table because
3091
      // compileBrailleIndicator may reallocate table
3092
31
      TranslationTableOffset ruleOffset;
3093
31
      if (!compileBrailleIndicator(file, "undefined character opcode",
3094
31
            CTO_Undefined, &ruleOffset, noback, nofor, table))
3095
0
        return 0;
3096
31
      (*table)->undefined = ruleOffset;
3097
31
      return 1;
3098
31
    }
3099
6
    case CTO_Match: {
3100
6
      int ok = 0;
3101
6
      widechar *patterns = NULL;
3102
6
      TranslationTableRule *rule;
3103
6
      TranslationTableOffset ruleOffset;
3104
6
      CharsString ptn_before, ptn_after;
3105
6
      TranslationTableOffset patternsOffset;
3106
6
      int len, mrk;
3107
6
      size_t patternsByteSize = sizeof(*patterns) * 27720;
3108
6
      patterns = (widechar *)malloc(patternsByteSize);
3109
6
      if (!patterns) _lou_outOfMemory();
3110
6
      memset(patterns, 0xffff, patternsByteSize);
3111
6
      noback = 1;
3112
6
      getMatchPatternCharacters(file, &ptn_before);
3113
6
      getRuleCharsText(file, &ruleChars);
3114
6
      getMatchPatternCharacters(file, &ptn_after);
3115
6
      getRuleDotsPattern(file, &ruleDots);
3116
6
      if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,
3117
6
            &rule, noback, nofor, table))
3118
0
        goto CTO_Match_cleanup;
3119
6
      if (ptn_before.chars[0] == '-' && ptn_before.length == 1)
3120
0
        len = _lou_pattern_compile(
3121
0
            &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);
3122
6
      else
3123
6
        len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,
3124
6
            &patterns[1], 13841, *table, file);
3125
6
      if (!len) goto CTO_Match_cleanup;
3126
6
      mrk = patterns[0] = len + 1;
3127
6
      _lou_pattern_reverse(&patterns[1]);
3128
6
      if (ptn_after.chars[0] == '-' && ptn_after.length == 1)
3129
0
        len = _lou_pattern_compile(
3130
0
            &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);
3131
6
      else
3132
6
        len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,
3133
6
            &patterns[mrk], 13841, *table, file);
3134
6
      if (!len) goto CTO_Match_cleanup;
3135
6
      len += mrk;
3136
6
      if (!allocateSpaceInTranslationTable(
3137
6
            file, &patternsOffset, len * sizeof(widechar), table))
3138
0
        goto CTO_Match_cleanup;
3139
      // allocateSpaceInTranslationTable may have moved table, so make sure rule is
3140
      // still valid
3141
6
      rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
3142
6
      memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar));
3143
6
      rule->patterns = patternsOffset;
3144
6
      ok = 1;
3145
6
    CTO_Match_cleanup:
3146
6
      free(patterns);
3147
6
      return ok;
3148
6
    }
3149
3150
3
    case CTO_BackMatch: {
3151
3
      int ok = 0;
3152
3
      widechar *patterns = NULL;
3153
3
      TranslationTableRule *rule;
3154
3
      TranslationTableOffset ruleOffset;
3155
3
      CharsString ptn_before, ptn_after;
3156
3
      TranslationTableOffset patternOffset;
3157
3
      int len, mrk;
3158
3
      size_t patternsByteSize = sizeof(*patterns) * 27720;
3159
3
      patterns = (widechar *)malloc(patternsByteSize);
3160
3
      if (!patterns) _lou_outOfMemory();
3161
3
      memset(patterns, 0xffff, patternsByteSize);
3162
3
      nofor = 1;
3163
3
      getMatchPatternCharacters(file, &ptn_before);
3164
3
      getRuleCharsText(file, &ruleChars);
3165
3
      getMatchPatternCharacters(file, &ptn_after);
3166
3
      getRuleDotsPattern(file, &ruleDots);
3167
3
      if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule,
3168
3
            noback, nofor, table))
3169
0
        goto CTO_BackMatch_cleanup;
3170
3
      if (ptn_before.chars[0] == '-' && ptn_before.length == 1)
3171
0
        len = _lou_pattern_compile(
3172
0
            &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);
3173
3
      else
3174
3
        len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,
3175
3
            &patterns[1], 13841, *table, file);
3176
3
      if (!len) goto CTO_BackMatch_cleanup;
3177
3
      mrk = patterns[0] = len + 1;
3178
3
      _lou_pattern_reverse(&patterns[1]);
3179
3
      if (ptn_after.chars[0] == '-' && ptn_after.length == 1)
3180
0
        len = _lou_pattern_compile(
3181
0
            &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);
3182
3
      else
3183
3
        len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,
3184
3
            &patterns[mrk], 13841, *table, file);
3185
3
      if (!len) goto CTO_BackMatch_cleanup;
3186
3
      len += mrk;
3187
3
      if (!allocateSpaceInTranslationTable(
3188
3
            file, &patternOffset, len * sizeof(widechar), table))
3189
0
        goto CTO_BackMatch_cleanup;
3190
      // allocateSpaceInTranslationTable may have moved table, so make sure rule is
3191
      // still valid
3192
3
      rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
3193
3
      memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar));
3194
3
      rule->patterns = patternOffset;
3195
3
      ok = 1;
3196
3
    CTO_BackMatch_cleanup:
3197
3
      free(patterns);
3198
3
      return ok;
3199
3
    }
3200
3201
15
    case CTO_CapsLetter:
3202
54
    case CTO_BegCapsWord:
3203
61
    case CTO_EndCapsWord:
3204
63
    case CTO_BegCaps:
3205
65
    case CTO_EndCaps:
3206
70
    case CTO_BegCapsPhrase:
3207
70
    case CTO_EndCapsPhrase:
3208
87
    case CTO_LenCapsPhrase:
3209
    /* these 8 general purpose opcodes are compiled further down to more specific
3210
     * internal opcodes:
3211
     * - modeletter
3212
     * - begmodeword
3213
     * - endmodeword
3214
     * - begmode
3215
     * - endmode
3216
     * - begmodephrase
3217
     * - endmodephrase
3218
     * - lenmodephrase
3219
     */
3220
87
    case CTO_ModeLetter:
3221
88
    case CTO_BegModeWord:
3222
88
    case CTO_EndModeWord:
3223
88
    case CTO_BegMode:
3224
91
    case CTO_EndMode:
3225
92
    case CTO_BegModePhrase:
3226
92
    case CTO_EndModePhrase:
3227
92
    case CTO_LenModePhrase: {
3228
92
      TranslationTableCharacterAttributes mode;
3229
92
      int i;
3230
92
      switch (opcode) {
3231
15
      case CTO_CapsLetter:
3232
54
      case CTO_BegCapsWord:
3233
61
      case CTO_EndCapsWord:
3234
63
      case CTO_BegCaps:
3235
65
      case CTO_EndCaps:
3236
70
      case CTO_BegCapsPhrase:
3237
70
      case CTO_EndCapsPhrase:
3238
87
      case CTO_LenCapsPhrase:
3239
87
        mode = CTC_UpperCase;
3240
87
        i = 0;
3241
87
        opcode += (CTO_ModeLetter - CTO_CapsLetter);
3242
87
        break;
3243
5
      default:
3244
5
        if (!getToken(file, &token, "attribute name")) return 0;
3245
5
        if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
3246
0
          return 0;
3247
0
        }
3248
5
        const CharacterClass *characterClass = findCharacterClass(&token, *table);
3249
5
        if (!characterClass) {
3250
5
          characterClass =
3251
5
              addCharacterClass(file, token.chars, token.length, *table, 1);
3252
5
          if (!characterClass) return 0;
3253
5
        }
3254
5
        mode = characterClass->attribute;
3255
5
        if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space &&
3256
5
            mode <= CTC_LitDigit) {
3257
0
          compileError(file,
3258
0
              "mode must be \"uppercase\", \"digit\", or a custom "
3259
0
              "attribute name.");
3260
0
          return 0;
3261
0
        }
3262
        /* check if this mode is already defined and if the number of modes does
3263
         * not exceed the maximal number */
3264
5
        if (mode == CTC_UpperCase)
3265
0
          i = 0;
3266
5
        else {
3267
5
          for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) {
3268
0
            if ((*table)->modes[i].mode == mode) {
3269
0
              break;
3270
0
            }
3271
0
          }
3272
5
          if (i == MAX_MODES) {
3273
0
            compileError(file, "Max number of modes (%i) reached", MAX_MODES);
3274
0
            return 0;
3275
0
          }
3276
5
        }
3277
92
      }
3278
92
      if (!(*table)->modes[i].value)
3279
55
        (*table)->modes[i] = (EmphasisClass){ plain_text, mode,
3280
55
          0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i };
3281
92
      switch (opcode) {
3282
6
      case CTO_BegModePhrase: {
3283
        // not passing pointer to location inside table because
3284
        // compileBrailleIndicator may reallocate table
3285
6
        TranslationTableOffset ruleOffset;
3286
6
        if (!compileBrailleIndicator(file, "first word capital sign",
3287
              // when mode is not caps (i != 0), provide enough information
3288
              // for back-translator to be able to recognize and ignore the
3289
              // indicator (but it won't be able to determine the mode)
3290
6
              i == 0 ? CTO_BegCapsPhrase : CTO_BegModePhrase, &ruleOffset,
3291
6
              noback, nofor, table))
3292
0
          return 0;
3293
6
        (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset;
3294
6
        return 1;
3295
6
      }
3296
0
      case CTO_EndModePhrase: {
3297
0
        TranslationTableOffset ruleOffset;
3298
0
        switch (compileBeforeAfter(file)) {
3299
0
        case 1:  // before
3300
0
          if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) {
3301
0
            compileError(
3302
0
                file, "Capital sign after last word already defined.");
3303
0
            return 0;
3304
0
          }
3305
          // not passing pointer to location inside table because
3306
          // compileBrailleIndicator may reallocate table
3307
0
          if (!compileBrailleIndicator(file, "capital sign before last word",
3308
0
                i == 0 ? CTO_EndCapsPhraseBefore : CTO_EndModePhrase,
3309
0
                &ruleOffset, noback, nofor, table))
3310
0
            return 0;
3311
0
          (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] =
3312
0
              ruleOffset;
3313
0
          return 1;
3314
0
        case 2:  // after
3315
0
          if ((*table)->emphRules[MAX_EMPH_CLASSES + i]
3316
0
                       [endPhraseBeforeOffset]) {
3317
0
            compileError(
3318
0
                file, "Capital sign before last word already defined.");
3319
0
            return 0;
3320
0
          }
3321
          // not passing pointer to location inside table because
3322
          // compileBrailleIndicator may reallocate table
3323
0
          if (!compileBrailleIndicator(file, "capital sign after last word",
3324
0
                i == 0 ? CTO_EndCapsPhraseAfter : CTO_EndModePhrase,
3325
0
                &ruleOffset, noback, nofor, table))
3326
0
            return 0;
3327
0
          (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] =
3328
0
              ruleOffset;
3329
0
          return 1;
3330
0
        default:  // error
3331
0
          compileError(file, "Invalid lastword indicator location.");
3332
0
          return 0;
3333
0
        }
3334
0
        return 0;
3335
0
      }
3336
2
      case CTO_BegMode: {
3337
        // not passing pointer to location inside table because
3338
        // compileBrailleIndicator may reallocate table
3339
2
        TranslationTableOffset ruleOffset;
3340
2
        if (!compileBrailleIndicator(file, "first letter capital sign",
3341
2
              i == 0 ? CTO_BegCaps : CTO_BegMode, &ruleOffset, noback,
3342
2
              nofor, table))
3343
0
          return 0;
3344
2
        (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset;
3345
2
        return 1;
3346
2
      }
3347
5
      case CTO_EndMode: {
3348
        // not passing pointer to location inside table because
3349
        // compileBrailleIndicator may reallocate table
3350
5
        TranslationTableOffset ruleOffset;
3351
5
        if (!compileBrailleIndicator(file, "last letter capital sign",
3352
5
              i == 0 ? CTO_EndCaps : CTO_EndMode, &ruleOffset, noback,
3353
5
              nofor, table))
3354
0
          return 0;
3355
5
        (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset;
3356
5
        return 1;
3357
5
      }
3358
15
      case CTO_ModeLetter: {
3359
        // not passing pointer to location inside table because
3360
        // compileBrailleIndicator may reallocate table
3361
15
        TranslationTableOffset ruleOffset;
3362
15
        if (!compileBrailleIndicator(file, "single letter capital sign",
3363
15
              i == 0 ? CTO_CapsLetter : CTO_ModeLetter, &ruleOffset, noback,
3364
15
              nofor, table))
3365
0
          return 0;
3366
15
        (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset;
3367
15
        return 1;
3368
15
      }
3369
40
      case CTO_BegModeWord: {
3370
        // not passing pointer to location inside table because
3371
        // compileBrailleIndicator may reallocate table
3372
40
        TranslationTableOffset ruleOffset;
3373
40
        if (!compileBrailleIndicator(file, "capital word",
3374
40
              i == 0 ? CTO_BegCapsWord : CTO_BegModeWord, &ruleOffset,
3375
40
              noback, nofor, table))
3376
0
          return 0;
3377
40
        (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset;
3378
40
        return 1;
3379
40
      }
3380
7
      case CTO_EndModeWord: {
3381
        // not passing pointer to location inside table because
3382
        // compileBrailleIndicator may reallocate table
3383
7
        TranslationTableOffset ruleOffset;
3384
7
        if (!compileBrailleIndicator(file, "capital word stop",
3385
7
              i == 0 ? CTO_EndCapsWord : CTO_EndModeWord, &ruleOffset,
3386
7
              noback, nofor, table))
3387
0
          return 0;
3388
7
        (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset;
3389
7
        return 1;
3390
7
      }
3391
17
      case CTO_LenModePhrase:
3392
17
        return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] =
3393
17
                 compileNumber(file);
3394
0
      default:
3395
0
        break;
3396
92
      }
3397
0
      break;
3398
92
    }
3399
3400
    /* these 8 general purpose emphasis opcodes are compiled further down to more
3401
     * specific internal opcodes:
3402
     * - emphletter
3403
     * - begemphword
3404
     * - endemphword
3405
     * - begemph
3406
     * - endemph
3407
     * - begemphphrase
3408
     * - endemphphrase
3409
     * - lenemphphrase
3410
     */
3411
14
    case CTO_EmphClass:
3412
14
      if (!getToken(file, &emphClass, "emphasis class")) {
3413
0
        compileError(file, "emphclass must be followed by a valid class name.");
3414
0
        return 0;
3415
0
      }
3416
14
      int k, i;
3417
14
      char *s = malloc(sizeof(char) * (emphClass.length + 1));
3418
92
      for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];
3419
14
      s[k++] = '\0';
3420
34
      for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)
3421
20
        if (strcmp(s, (*table)->emphClassNames[i]) == 0) {
3422
0
          _lou_logMessage(LOU_LOG_DEBUG, "Duplicate emphasis class: %s", s);
3423
0
          free(s);
3424
0
          return 1;
3425
0
        }
3426
14
      if (i == MAX_EMPH_CLASSES) {
3427
0
        _lou_logMessage(LOU_LOG_ERROR,
3428
0
            "Max number of emphasis classes (%i) reached", MAX_EMPH_CLASSES);
3429
0
        errorCount++;
3430
0
        free(s);
3431
0
        return 0;
3432
0
      }
3433
14
      switch (i) {
3434
      /* For backwards compatibility (i.e. because programs will assume
3435
       * the first 3 typeform bits are `italic', `underline' and `bold')
3436
       * we require that the first 3 emphclass definitions are (in that
3437
       * order):
3438
       *
3439
       *   emphclass italic
3440
       *   emphclass underline
3441
       *   emphclass bold
3442
       *
3443
       * While it would be possible to use the emphclass opcode only for
3444
       * defining _additional_ classes (not allowing for them to be called
3445
       * italic, underline or bold), thereby reducing the amount of
3446
       * boilerplate, we deliberately choose not to do that in order to
3447
       * not give italic, underline and bold any special status. The
3448
       * hope is that eventually all programs will use liblouis for
3449
       * emphasis the recommended way (i.e. by looking up the supported
3450
       * typeforms in the documentation or API) so that we can drop this
3451
       * restriction.
3452
       */
3453
6
      case 0:
3454
6
        if (strcmp(s, "italic") != 0) {
3455
0
          _lou_logMessage(LOU_LOG_ERROR,
3456
0
              "First emphasis class must be \"italic\" but got "
3457
0
              "%s",
3458
0
              s);
3459
0
          errorCount++;
3460
0
          free(s);
3461
0
          return 0;
3462
0
        }
3463
6
        break;
3464
6
      case 1:
3465
2
        if (strcmp(s, "underline") != 0) {
3466
0
          _lou_logMessage(LOU_LOG_ERROR,
3467
0
              "Second emphasis class must be \"underline\" but "
3468
0
              "got "
3469
0
              "%s",
3470
0
              s);
3471
0
          errorCount++;
3472
0
          free(s);
3473
0
          return 0;
3474
0
        }
3475
2
        break;
3476
2
      case 2:
3477
2
        if (strcmp(s, "bold") != 0) {
3478
0
          _lou_logMessage(LOU_LOG_ERROR,
3479
0
              "Third emphasis class must be \"bold\" but got "
3480
0
              "%s",
3481
0
              s);
3482
0
          errorCount++;
3483
0
          free(s);
3484
0
          return 0;
3485
0
        }
3486
2
        break;
3487
14
      }
3488
14
      (*table)->emphClassNames[i] = s;
3489
14
      (*table)->emphClasses[i] = (EmphasisClass){ emph_1
3490
14
            << i, /* relies on the order of typeforms emph_1..emph_10 */
3491
14
        0, 0x1 << i, i };
3492
14
      return 1;
3493
0
    case CTO_EmphLetter:
3494
1
    case CTO_BegEmphWord:
3495
1
    case CTO_EndEmphWord:
3496
17
    case CTO_BegEmph:
3497
17
    case CTO_EndEmph:
3498
17
    case CTO_BegEmphPhrase:
3499
17
    case CTO_EndEmphPhrase:
3500
17
    case CTO_LenEmphPhrase:
3501
17
    case CTO_EmphModeChars:
3502
21
    case CTO_NoEmphChars: {
3503
21
      if (!getToken(file, &token, "emphasis class")) return 0;
3504
21
      if (!parseChars(file, &emphClass, &token)) return 0;
3505
21
      char *s = malloc(sizeof(char) * (emphClass.length + 1));
3506
21
      int k, i;
3507
147
      for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];
3508
21
      s[k++] = '\0';
3509
21
      for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)
3510
21
        if (strcmp(s, (*table)->emphClassNames[i]) == 0) break;
3511
21
      if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) {
3512
0
        _lou_logMessage(LOU_LOG_ERROR, "Emphasis class %s not declared", s);
3513
0
        errorCount++;
3514
0
        free(s);
3515
0
        return 0;
3516
0
      }
3517
21
      int ok = 0;
3518
21
      switch (opcode) {
3519
0
      case CTO_EmphLetter: {
3520
        // not passing pointer to location inside table because
3521
        // compileBrailleIndicator may reallocate table
3522
0
        TranslationTableOffset ruleOffset;
3523
        // provide enough information for back-translator to be able to recognize
3524
        // and ignore the indicator (but it won't be able to determine the
3525
        // emphasis class)
3526
0
        if (!compileBrailleIndicator(file, "single letter", CTO_EmphLetter,
3527
0
              &ruleOffset, noback, nofor, table))
3528
0
          break;
3529
0
        (*table)->emphRules[i][letterOffset] = ruleOffset;
3530
0
        ok = 1;
3531
0
        break;
3532
0
      }
3533
1
      case CTO_BegEmphWord: {
3534
        // not passing pointer to location inside table because
3535
        // compileBrailleIndicator may reallocate table
3536
1
        TranslationTableOffset ruleOffset;
3537
1
        if (!compileBrailleIndicator(file, "word", CTO_BegEmphWord, &ruleOffset,
3538
1
              noback, nofor, table))
3539
0
          break;
3540
1
        (*table)->emphRules[i][begWordOffset] = ruleOffset;
3541
1
        ok = 1;
3542
1
        break;
3543
1
      }
3544
0
      case CTO_EndEmphWord: {
3545
        // not passing pointer to location inside table because
3546
        // compileBrailleIndicator may reallocate table
3547
0
        TranslationTableOffset ruleOffset;
3548
0
        if (!compileBrailleIndicator(file, "word stop", CTO_EndEmphWord,
3549
0
              &ruleOffset, noback, nofor, table))
3550
0
          break;
3551
0
        (*table)->emphRules[i][endWordOffset] = ruleOffset;
3552
0
        ok = 1;
3553
0
        break;
3554
0
      }
3555
16
      case CTO_BegEmph: {
3556
        /* fail if both begemph and any of begemphphrase or begemphword are
3557
         * defined */
3558
16
        if ((*table)->emphRules[i][begWordOffset] ||
3559
16
            (*table)->emphRules[i][begPhraseOffset]) {
3560
0
          compileError(file,
3561
0
              "Cannot define emphasis for both no context and word or "
3562
0
              "phrase context, i.e. cannot have both begemph and "
3563
0
              "begemphword or begemphphrase.");
3564
0
          break;
3565
0
        }
3566
        // not passing pointer to location inside table because
3567
        // compileBrailleIndicator may reallocate table
3568
16
        TranslationTableOffset ruleOffset;
3569
16
        if (!compileBrailleIndicator(file, "first letter", CTO_BegEmph,
3570
16
              &ruleOffset, noback, nofor, table))
3571
0
          break;
3572
16
        (*table)->emphRules[i][begOffset] = ruleOffset;
3573
16
        ok = 1;
3574
16
        break;
3575
16
      }
3576
0
      case CTO_EndEmph: {
3577
0
        if ((*table)->emphRules[i][endWordOffset] ||
3578
0
            (*table)->emphRules[i][endPhraseBeforeOffset] ||
3579
0
            (*table)->emphRules[i][endPhraseAfterOffset]) {
3580
0
          compileError(file,
3581
0
              "Cannot define emphasis for both no context and word or "
3582
0
              "phrase context, i.e. cannot have both endemph and "
3583
0
              "endemphword or endemphphrase.");
3584
0
          break;
3585
0
        }
3586
        // not passing pointer to location inside table because
3587
        // compileBrailleIndicator may reallocate table
3588
0
        TranslationTableOffset ruleOffset;
3589
0
        if (!compileBrailleIndicator(file, "last letter", CTO_EndEmph,
3590
0
              &ruleOffset, noback, nofor, table))
3591
0
          break;
3592
0
        (*table)->emphRules[i][endOffset] = ruleOffset;
3593
0
        ok = 1;
3594
0
        break;
3595
0
      }
3596
0
      case CTO_BegEmphPhrase: {
3597
        // not passing pointer to location inside table because
3598
        // compileBrailleIndicator may reallocate table
3599
0
        TranslationTableOffset ruleOffset;
3600
0
        if (!compileBrailleIndicator(file, "first word", CTO_BegEmphPhrase,
3601
0
              &ruleOffset, noback, nofor, table))
3602
0
          break;
3603
0
        (*table)->emphRules[i][begPhraseOffset] = ruleOffset;
3604
0
        ok = 1;
3605
0
        break;
3606
0
      }
3607
0
      case CTO_EndEmphPhrase:
3608
0
        switch (compileBeforeAfter(file)) {
3609
0
        case 1: {  // before
3610
0
          if ((*table)->emphRules[i][endPhraseAfterOffset]) {
3611
0
            compileError(file, "last word after already defined.");
3612
0
            break;
3613
0
          }
3614
          // not passing pointer to location inside table because
3615
          // compileBrailleIndicator may reallocate table
3616
0
          TranslationTableOffset ruleOffset;
3617
0
          if (!compileBrailleIndicator(file, "last word before",
3618
0
                CTO_EndEmphPhrase, &ruleOffset, noback, nofor, table))
3619
0
            break;
3620
0
          (*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset;
3621
0
          ok = 1;
3622
0
          break;
3623
0
        }
3624
0
        case 2: {  // after
3625
0
          if ((*table)->emphRules[i][endPhraseBeforeOffset]) {
3626
0
            compileError(file, "last word before already defined.");
3627
0
            break;
3628
0
          }
3629
          // not passing pointer to location inside table because
3630
          // compileBrailleIndicator may reallocate table
3631
0
          TranslationTableOffset ruleOffset;
3632
0
          if (!compileBrailleIndicator(file, "last word after",
3633
0
                CTO_EndEmphPhrase, &ruleOffset, noback, nofor, table))
3634
0
            break;
3635
0
          (*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset;
3636
0
          ok = 1;
3637
0
          break;
3638
0
        }
3639
0
        default:  // error
3640
0
          compileError(file, "Invalid lastword indicator location.");
3641
0
          break;
3642
0
        }
3643
0
        break;
3644
0
      case CTO_LenEmphPhrase:
3645
0
        if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file)))
3646
0
          ok = 1;
3647
0
        break;
3648
0
      case CTO_EmphModeChars: {
3649
0
        if (!getRuleCharsText(file, &ruleChars)) break;
3650
0
        widechar *emphmodechars = (*table)->emphModeChars[i];
3651
0
        int len;
3652
0
        for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++);
3653
0
        if (len + ruleChars.length > EMPHMODECHARSSIZE) {
3654
0
          compileError(file, "More than %d characters", EMPHMODECHARSSIZE);
3655
0
          break;
3656
0
        }
3657
0
        ok = 1;
3658
0
        for (int k = 0; k < ruleChars.length; k++) {
3659
0
          if (!getChar(ruleChars.chars[k], *table, NULL)) {
3660
0
            compileError(file, "Emphasis mode character undefined");
3661
0
            ok = 0;
3662
0
            break;
3663
0
          }
3664
0
          emphmodechars[len++] = ruleChars.chars[k];
3665
0
        }
3666
0
        break;
3667
0
      }
3668
4
      case CTO_NoEmphChars: {
3669
4
        if (!getRuleCharsText(file, &ruleChars)) break;
3670
4
        widechar *noemphchars = (*table)->noEmphChars[i];
3671
4
        int len;
3672
458
        for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++);
3673
4
        if (len + ruleChars.length > NOEMPHCHARSSIZE) {
3674
0
          compileError(file, "More than %d characters", NOEMPHCHARSSIZE);
3675
0
          break;
3676
0
        }
3677
4
        ok = 1;
3678
260
        for (int k = 0; k < ruleChars.length; k++) {
3679
256
          if (!getChar(ruleChars.chars[k], *table, NULL)) {
3680
0
            compileError(file, "Character undefined");
3681
0
            ok = 0;
3682
0
            break;
3683
0
          }
3684
256
          noemphchars[len++] = ruleChars.chars[k];
3685
256
        }
3686
4
        break;
3687
4
      }
3688
0
      default:
3689
0
        break;
3690
21
      }
3691
21
      free(s);
3692
21
      return ok;
3693
21
    }
3694
6
    case CTO_LetterSign: {
3695
      // not passing pointer to location inside table because
3696
      // compileBrailleIndicator may reallocate table
3697
6
      TranslationTableOffset ruleOffset;
3698
6
      if (!compileBrailleIndicator(file, "letter sign", CTO_LetterSign, &ruleOffset,
3699
6
            noback, nofor, table))
3700
0
        return 0;
3701
6
      (*table)->letterSign = ruleOffset;
3702
6
      return 1;
3703
6
    }
3704
12
    case CTO_NoLetsignBefore:
3705
12
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3706
12
      if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) {
3707
0
        compileError(file, "More than %d characters", LETSIGNBEFORESIZE);
3708
0
        return 0;
3709
0
      }
3710
99
      for (int k = 0; k < ruleChars.length; k++)
3711
87
        (*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] =
3712
87
            ruleChars.chars[k];
3713
12
      return 1;
3714
4
    case CTO_NoLetsign:
3715
4
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3716
4
      if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) {
3717
0
        compileError(file, "More than %d characters", LETSIGNSIZE);
3718
0
        return 0;
3719
0
      }
3720
45
      for (int k = 0; k < ruleChars.length; k++)
3721
41
        (*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k];
3722
4
      return 1;
3723
4
    case CTO_NoLetsignAfter:
3724
4
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3725
4
      if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) {
3726
0
        compileError(file, "More than %d characters", LETSIGNAFTERSIZE);
3727
0
        return 0;
3728
0
      }
3729
20
      for (int k = 0; k < ruleChars.length; k++)
3730
16
        (*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] =
3731
16
            ruleChars.chars[k];
3732
4
      return 1;
3733
18
    case CTO_NumberSign: {
3734
      // not passing pointer to location inside table because
3735
      // compileBrailleIndicator may reallocate table
3736
18
      TranslationTableOffset ruleOffset;
3737
18
      if (!compileBrailleIndicator(file, "number sign", CTO_NumberSign, &ruleOffset,
3738
18
            noback, nofor, table))
3739
0
        return 0;
3740
18
      (*table)->numberSign = ruleOffset;
3741
18
      return 1;
3742
18
    }
3743
4
    case CTO_NoNumberSign: {
3744
      // not passing pointer to location inside table because
3745
      // compileBrailleIndicator may reallocate table
3746
4
      TranslationTableOffset ruleOffset;
3747
4
      if (!compileBrailleIndicator(file, "no number sign", CTO_NoNumberSign,
3748
4
            &ruleOffset, noback, nofor, table))
3749
0
        return 0;
3750
4
      (*table)->noNumberSign = ruleOffset;
3751
4
      return 1;
3752
4
    }
3753
3754
9
    case CTO_NumericModeChars:
3755
9
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3756
1.49k
      for (int k = 0; k < ruleChars.length; k++) {
3757
1.48k
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3758
1.48k
        if (!c) {
3759
0
          compileError(file, "Numeric mode character undefined: %s",
3760
0
              _lou_showString(&ruleChars.chars[k], 1, 0));
3761
0
          return 0;
3762
0
        }
3763
1.48k
        c->attributes |= CTC_NumericMode;
3764
1.48k
        (*table)->usesNumericMode = 1;
3765
1.48k
      }
3766
9
      return 1;
3767
3768
0
    case CTO_MidEndNumericModeChars:
3769
0
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3770
0
      for (int k = 0; k < ruleChars.length; k++) {
3771
0
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3772
0
        if (!c) {
3773
0
          compileError(file, "Midendnumeric mode character undefined");
3774
0
          return 0;
3775
0
        }
3776
0
        c->attributes |= CTC_MidEndNumericMode;
3777
0
        (*table)->usesNumericMode = 1;
3778
0
      }
3779
0
      return 1;
3780
3781
3
    case CTO_NumericNoContractChars:
3782
3
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3783
18
      for (int k = 0; k < ruleChars.length; k++) {
3784
15
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3785
15
        if (!c) {
3786
0
          compileError(file, "Numeric no contraction character undefined");
3787
0
          return 0;
3788
0
        }
3789
15
        c->attributes |= CTC_NumericNoContract;
3790
15
        (*table)->usesNumericMode = 1;
3791
15
      }
3792
3
      return 1;
3793
3794
1
    case CTO_NoContractSign: {
3795
      // not passing pointer to location inside table because
3796
      // compileBrailleIndicator may reallocate table
3797
1
      TranslationTableOffset ruleOffset;
3798
1
      if (!compileBrailleIndicator(file, "no contractions sign", CTO_NoContractSign,
3799
1
            &ruleOffset, noback, nofor, table))
3800
0
        return 0;
3801
1
      (*table)->noContractSign = ruleOffset;
3802
1
      return 1;
3803
1
    }
3804
7
    case CTO_SeqDelimiter:
3805
7
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3806
29
      for (int k = 0; k < ruleChars.length; k++) {
3807
22
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3808
22
        if (!c) {
3809
0
          compileError(file, "Sequence delimiter character undefined");
3810
0
          return 0;
3811
0
        }
3812
22
        c->attributes |= CTC_SeqDelimiter;
3813
22
        (*table)->usesSequences = 1;
3814
22
      }
3815
7
      return 1;
3816
3817
0
    case CTO_SeqBeforeChars:
3818
0
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3819
0
      for (int k = 0; k < ruleChars.length; k++) {
3820
0
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3821
0
        if (!c) {
3822
0
          compileError(file, "Sequence before character undefined");
3823
0
          return 0;
3824
0
        }
3825
0
        c->attributes |= CTC_SeqBefore;
3826
0
      }
3827
0
      return 1;
3828
3829
1
    case CTO_SeqAfterChars:
3830
1
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3831
2
      for (int k = 0; k < ruleChars.length; k++) {
3832
1
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3833
1
        if (!c) {
3834
0
          compileError(file, "Sequence after character undefined");
3835
0
          return 0;
3836
0
        }
3837
1
        c->attributes |= CTC_SeqAfter;
3838
1
      }
3839
1
      return 1;
3840
3841
32
    case CTO_SeqAfterPattern:
3842
32
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3843
32
      if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) {
3844
0
        compileError(file, "More than %d characters", SEQPATTERNSIZE);
3845
0
        return 0;
3846
0
      }
3847
356
      for (int k = 0; k < ruleChars.length; k++)
3848
324
        (*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k];
3849
32
      (*table)->seqPatterns[(*table)->seqPatternsCount++] = 0;
3850
32
      return 1;
3851
3852
2
    case CTO_SeqAfterExpression:
3853
2
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3854
2
      if ((ruleChars.length + 1) > SEQPATTERNSIZE) {
3855
0
        compileError(file, "More than %d characters", SEQPATTERNSIZE);
3856
0
        return 0;
3857
0
      }
3858
121
      for (int k = 0; k < ruleChars.length; k++)
3859
119
        (*table)->seqAfterExpression[k] = ruleChars.chars[k];
3860
2
      (*table)->seqAfterExpression[ruleChars.length] = 0;
3861
2
      (*table)->seqAfterExpressionLength = ruleChars.length;
3862
2
      return 1;
3863
3864
0
    case CTO_CapsModeChars:
3865
0
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3866
0
      for (int k = 0; k < ruleChars.length; k++) {
3867
0
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
3868
0
        if (!c) {
3869
0
          compileError(file, "Capital mode character undefined");
3870
0
          return 0;
3871
0
        }
3872
0
        c->attributes |= CTC_CapsMode;
3873
0
        (*table)->hasCapsModeChars = 1;
3874
0
      }
3875
0
      return 1;
3876
3877
0
    case CTO_BegComp: {
3878
      // not passing pointer to location inside table because
3879
      // compileBrailleIndicator may reallocate table
3880
0
      TranslationTableOffset ruleOffset;
3881
0
      if (!compileBrailleIndicator(file, "begin computer braille", CTO_BegComp,
3882
0
            &ruleOffset, noback, nofor, table))
3883
0
        return 0;
3884
0
      (*table)->begComp = ruleOffset;
3885
0
      return 1;
3886
0
    }
3887
1
    case CTO_EndComp: {
3888
      // not passing pointer to location inside table because
3889
      // compileBrailleIndicator may reallocate table
3890
1
      TranslationTableOffset ruleOffset;
3891
1
      if (!compileBrailleIndicator(file, "end computer braslle", CTO_EndComp,
3892
1
            &ruleOffset, noback, nofor, table))
3893
0
        return 0;
3894
1
      (*table)->endComp = ruleOffset;
3895
1
      return 1;
3896
1
    }
3897
15
    case CTO_NoCross:
3898
15
      if (nocross) {
3899
0
        compileError(
3900
0
            file, "%s already specified.", _lou_findOpcodeName(CTO_NoCross));
3901
0
        return 0;
3902
0
      }
3903
15
      nocross = 1;
3904
15
      goto doOpcode;
3905
3
    case CTO_Syllable:
3906
3
      (*table)->syllables = 1;
3907
3
    case CTO_Always:
3908
8
    case CTO_LargeSign:
3909
17
    case CTO_WholeWord:
3910
19
    case CTO_PartWord:
3911
24
    case CTO_JoinNum:
3912
37
    case CTO_JoinableWord:
3913
37
    case CTO_LowWord:
3914
37
    case CTO_SuffixableWord:
3915
39
    case CTO_PrefixableWord:
3916
46
    case CTO_BegWord:
3917
47
    case CTO_BegMidWord:
3918
49
    case CTO_MidWord:
3919
49
    case CTO_MidEndWord:
3920
63
    case CTO_EndWord:
3921
67
    case CTO_PrePunc:
3922
71
    case CTO_PostPunc:
3923
71
    case CTO_BegNum:
3924
71
    case CTO_MidNum:
3925
71
    case CTO_EndNum:
3926
73
    case CTO_Repeated:
3927
85
    case CTO_RepWord:
3928
85
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3929
85
      if (!getRuleDotsPattern(file, &ruleDots)) return 0;
3930
85
      if (ruleDots.length == 0)
3931
        // check that all characters in a rule with `=` as second operand are
3932
        // defined (or based on another character)
3933
8
        for (int k = 0; k < ruleChars.length; k++) {
3934
6
          TranslationTableCharacter *c =
3935
6
              getChar(ruleChars.chars[k], *table, NULL);
3936
6
          if (!(c && (c->definitionRule || c->basechar))) {
3937
0
            compileError(file, "Character %s is not defined",
3938
0
                _lou_showString(&ruleChars.chars[k], 1, 0));
3939
0
            return 0;
3940
0
          }
3941
6
        }
3942
85
      TranslationTableRule *r;
3943
85
      if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r,
3944
85
            noback, nofor, table))
3945
0
        return 0;
3946
85
      if (nocross) r->nocross = 1;
3947
85
      return 1;
3948
      // if (opcode == CTO_MidNum)
3949
      // {
3950
      //   TranslationTableCharacter *c = getChar(ruleChars.chars[0]);
3951
      //   if(c)
3952
      //     c->attributes |= CTC_NumericMode;
3953
      // }
3954
5
    case CTO_RepEndWord:
3955
5
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3956
5
      CharsString dots;
3957
5
      if (!getToken(file, &dots, "dots,dots operand")) return 0;
3958
5
      int len = dots.length;
3959
19
      for (int k = 0; k < len - 1; k++) {
3960
19
        if (dots.chars[k] == ',') {
3961
5
          dots.length = k;
3962
5
          if (!parseDots(file, &ruleDots, &dots)) return 0;
3963
5
          ruleDots.chars[ruleDots.length++] = ',';
3964
5
          k++;
3965
5
          if (k == len - 1 && dots.chars[k] == '=') {
3966
            // check that all characters are defined (or based on another
3967
            // character)
3968
6
            for (int l = 0; l < ruleChars.length; l++) {
3969
3
              TranslationTableCharacter *c =
3970
3
                  getChar(ruleChars.chars[l], *table, NULL);
3971
3
              if (!(c && (c->definitionRule || c->basechar))) {
3972
0
                compileError(file, "Character %s is not defined",
3973
0
                    _lou_showString(&ruleChars.chars[l], 1, 0));
3974
0
                return 0;
3975
0
              }
3976
3
            }
3977
3
          } else {
3978
2
            CharsString x, y;
3979
2
            x.length = 0;
3980
89
            while (k < len) x.chars[x.length++] = dots.chars[k++];
3981
2
            if (parseDots(file, &y, &x))
3982
31
              for (int l = 0; l < y.length; l++)
3983
29
                ruleDots.chars[ruleDots.length++] = y.chars[l];
3984
2
          }
3985
5
          return addRule(file, opcode, &ruleChars, &ruleDots, after, before,
3986
5
              NULL, NULL, noback, nofor, table);
3987
5
        }
3988
19
      }
3989
0
      return 0;
3990
25
    case CTO_CompDots:
3991
25
    case CTO_Comp6: {
3992
25
      TranslationTableOffset ruleOffset;
3993
25
      if (!getRuleCharsText(file, &ruleChars)) return 0;
3994
25
      if (ruleChars.length != 1) {
3995
0
        compileError(file, "first operand must be 1 character");
3996
0
        return 0;
3997
0
      }
3998
25
      if (nofor || noback) {
3999
0
        compileWarning(file, "nofor and noback not allowed on comp6 rules");
4000
0
      }
4001
25
      if (!getRuleDotsPattern(file, &ruleDots)) return 0;
4002
25
      if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,
4003
25
            NULL, noback, nofor, table))
4004
0
        return 0;
4005
25
      return 1;
4006
25
    }
4007
0
    case CTO_ExactDots:
4008
0
      if (!getRuleCharsText(file, &ruleChars)) return 0;
4009
0
      if (ruleChars.chars[0] != '@') {
4010
0
        compileError(file, "The operand must begin with an at sign (@)");
4011
0
        return 0;
4012
0
      }
4013
0
      for (int k = 1; k < ruleChars.length; k++)
4014
0
        scratchPad.chars[k - 1] = ruleChars.chars[k];
4015
0
      scratchPad.length = ruleChars.length - 1;
4016
0
      if (!parseDots(file, &ruleDots, &scratchPad)) return 0;
4017
0
      return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,
4018
0
          noback, nofor, table);
4019
6
    case CTO_CapsNoCont: {
4020
6
      TranslationTableOffset ruleOffset;
4021
6
      ruleChars.length = 1;
4022
6
      ruleChars.chars[0] = 'a';
4023
6
      if (!addRule(file, opcode, &ruleChars, NULL, after, before, &ruleOffset, NULL,
4024
6
            noback, nofor, table))
4025
0
        return 0;
4026
6
      (*table)->capsNoCont = ruleOffset;
4027
6
      return 1;
4028
6
    }
4029
100
    case CTO_Replace:
4030
100
      if (!getRuleCharsText(file, &ruleChars)) return 0;
4031
99
      if (atEndOfLine(file))
4032
3
        ruleDots.length = ruleDots.chars[0] = 0;
4033
96
      else {
4034
96
        if (!getRuleDotsText(file, &ruleDots)) return 0;
4035
96
        if (ruleDots.length > 0 && ruleDots.chars[0] == '#')
4036
2
          ruleDots.length = ruleDots.chars[0] = 0;
4037
94
        else if (ruleDots.length > 1 && ruleDots.chars[0] == '\\' &&
4038
9
            ruleDots.chars[1] == '#') {
4039
8
          ruleDots.length--;
4040
8
          memmove(&ruleDots.chars[0], &ruleDots.chars[1],
4041
8
              ruleDots.length * CHARSIZE);
4042
8
        }
4043
96
      }
4044
2.97k
      for (int k = 0; k < ruleChars.length; k++)
4045
2.87k
        putChar(file, ruleChars.chars[k], table, NULL, (*table)->ruleCounter);
4046
3.73k
      for (int k = 0; k < ruleDots.length; k++)
4047
3.63k
        putChar(file, ruleDots.chars[k], table, NULL, (*table)->ruleCounter);
4048
99
      return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,
4049
99
          noback, nofor, table);
4050
167
    case CTO_Correct:
4051
167
      (*table)->corrections = 1;
4052
167
      goto doPass;
4053
18
    case CTO_Pass2:
4054
18
      if ((*table)->numPasses < 2) (*table)->numPasses = 2;
4055
18
      goto doPass;
4056
8
    case CTO_Pass3:
4057
8
      if ((*table)->numPasses < 3) (*table)->numPasses = 3;
4058
8
      goto doPass;
4059
30
    case CTO_Pass4:
4060
30
      if ((*table)->numPasses < 4) (*table)->numPasses = 4;
4061
223
    doPass:
4062
280
    case CTO_Context:
4063
280
      if (!(nofor || noback)) {
4064
0
        compileError(file, "%s or %s must be specified.",
4065
0
            _lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack));
4066
0
        return 0;
4067
0
      }
4068
280
      return compilePassOpcode(file, opcode, noback, nofor, table);
4069
1
    case CTO_Contraction:
4070
7
    case CTO_NoCont:
4071
7
    case CTO_CompBrl:
4072
8
    case CTO_Literal:
4073
8
      if (!getRuleCharsText(file, &ruleChars)) return 0;
4074
      // check that all characters in a compbrl, contraction,
4075
      // nocont or literal rule are defined (or based on another
4076
      // character)
4077
16
      for (int k = 0; k < ruleChars.length; k++) {
4078
8
        TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
4079
8
        if (!(c && (c->definitionRule || c->basechar))) {
4080
0
          compileError(file, "Character %s is not defined",
4081
0
              _lou_showString(&ruleChars.chars[k], 1, 0));
4082
0
          return 0;
4083
0
        }
4084
8
      }
4085
8
      if (opcode == CTO_Literal) {
4086
1
        compileWarning(file, "literal is deprecated, use compbrl instead");
4087
1
        opcode = CTO_CompBrl;
4088
1
      }
4089
8
      return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL,
4090
8
          noback, nofor, table);
4091
0
    case CTO_MultInd: {
4092
0
      ruleChars.length = 0;
4093
0
      if (!getToken(file, &token, "multiple braille indicators") ||
4094
0
          !parseDots(file, &cells, &token))
4095
0
        return 0;
4096
0
      while (getToken(file, &token, "multind opcodes")) {
4097
0
        opcode = getOpcode(file, &token);
4098
0
        if (opcode == CTO_None) {
4099
0
          compileError(file, "opcode %s not defined.",
4100
0
              _lou_showString(token.chars, token.length, 0));
4101
0
          return 0;
4102
0
        }
4103
0
        if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) {
4104
0
          compileError(file, "Not a braille indicator opcode.");
4105
0
          return 0;
4106
0
        }
4107
0
        ruleChars.chars[ruleChars.length++] = (widechar)opcode;
4108
0
        if (atEndOfLine(file)) break;
4109
0
      }
4110
0
      return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL,
4111
0
          NULL, noback, nofor, table);
4112
0
    }
4113
4114
167
    case CTO_Class:
4115
167
      compileWarning(file, "class is deprecated, use attribute instead");
4116
172
    case CTO_Attribute: {
4117
172
      if (nofor || noback) {
4118
0
        compileWarning(
4119
0
            file, "nofor and noback not allowed before class/attribute");
4120
0
      }
4121
172
      if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) ||
4122
172
          (opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) {
4123
0
        compileError(file,
4124
0
            "attribute and class rules must not be both present in a table");
4125
0
        return 0;
4126
0
      }
4127
172
      if (opcode == CTO_Class)
4128
167
        (*table)->usesAttributeOrClass = 2;
4129
5
      else
4130
5
        (*table)->usesAttributeOrClass = 1;
4131
172
      if (!getToken(file, &token, "attribute name")) {
4132
0
        compileError(file, "Expected %s", "attribute name");
4133
0
        return 0;
4134
0
      }
4135
172
      if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
4136
0
        return 0;
4137
0
      }
4138
4139
172
      TranslationTableCharacterAttributes attribute = 0;
4140
172
      {
4141
172
        int attrNumber = -1;
4142
172
        switch (token.chars[0]) {
4143
0
        case '0':
4144
0
        case '1':
4145
0
        case '2':
4146
0
        case '3':
4147
0
        case '4':
4148
0
        case '5':
4149
0
        case '6':
4150
0
        case '7':
4151
0
        case '8':
4152
0
        case '9':
4153
0
          attrNumber = token.chars[0] - '0';
4154
0
          break;
4155
172
        }
4156
172
        if (attrNumber >= 0) {
4157
0
          if (opcode == CTO_Class) {
4158
0
            compileError(file,
4159
0
                "Invalid class name: may not contain digits, use "
4160
0
                "attribute instead of class");
4161
0
            return 0;
4162
0
          }
4163
0
          if (token.length > 1 || attrNumber > 7) {
4164
0
            compileError(file,
4165
0
                "Invalid attribute name: must be a digit between 0 and 7 "
4166
0
                "or a word containing only letters");
4167
0
            return 0;
4168
0
          }
4169
0
          if (!(*table)->numberedAttributes[attrNumber])
4170
            // attribute not used before yet: assign it a value
4171
0
            (*table)->numberedAttributes[attrNumber] =
4172
0
                getNextNumberedAttribute(*table);
4173
0
          attribute = (*table)->numberedAttributes[attrNumber];
4174
172
        } else {
4175
172
          const CharacterClass *namedAttr = findCharacterClass(&token, *table);
4176
172
          if (!namedAttr) {
4177
            // no class with that name: create one
4178
43
            namedAttr = addCharacterClass(
4179
43
                file, &token.chars[0], token.length, *table, 1);
4180
43
            if (!namedAttr) return 0;
4181
43
          }
4182
          // there is a class with that name or a new class was successfully
4183
          // created
4184
172
          attribute = namedAttr->attribute;
4185
172
          if (attribute == CTC_UpperCase || attribute == CTC_LowerCase)
4186
62
            attribute |= CTC_Letter;
4187
172
        }
4188
172
      }
4189
172
      CharsString characters;
4190
172
      if (!getCharacters(file, &characters)) return 0;
4191
4.89k
      for (int i = 0; i < characters.length; i++) {
4192
        // get the character from the table, or if it is not defined yet,
4193
        // define it
4194
4.72k
        TranslationTableCharacter *character = putChar(
4195
4.72k
            file, characters.chars[i], table, NULL, (*table)->ruleCounter);
4196
        // set the attribute
4197
4.72k
        character->attributes |= attribute;
4198
        // also set the attribute on the associated dots (if any)
4199
4.72k
        if (character->basechar)
4200
23
          character = (TranslationTableCharacter *)&(*table)
4201
23
                    ->ruleArea[character->basechar];
4202
4.72k
        if (character->definitionRule) {
4203
56
          TranslationTableRule *defRule =
4204
56
              (TranslationTableRule *)&(*table)
4205
56
                  ->ruleArea[character->definitionRule];
4206
56
          if (defRule->dotslen == 1) {
4207
36
            TranslationTableCharacter *dots =
4208
36
                getDots(defRule->charsdots[defRule->charslen], *table);
4209
36
            if (dots) dots->attributes |= attribute;
4210
36
          }
4211
56
        }
4212
4.72k
      }
4213
172
      (*table)->ruleCounter++;
4214
172
      return 1;
4215
172
    }
4216
4217
0
      {
4218
0
        TranslationTableCharacterAttributes *attributes;
4219
0
        const CharacterClass *class;
4220
0
      case CTO_After:
4221
0
        attributes = &after;
4222
0
        goto doBeforeAfter;
4223
8
      case CTO_Before:
4224
8
        attributes = &before;
4225
8
      doBeforeAfter:
4226
8
        if (!(*table)->characterClasses) {
4227
0
          if (!allocateCharacterClasses(*table)) return 0;
4228
0
        }
4229
8
        if (!getToken(file, &token, "attribute name")) return 0;
4230
8
        if (!(class = findCharacterClass(&token, *table))) {
4231
0
          compileError(file, "attribute not defined");
4232
0
          return 0;
4233
0
        }
4234
8
        *attributes |= class->attribute;
4235
8
        goto doOpcode;
4236
8
      }
4237
36
    case CTO_Base:
4238
36
      if (nofor || noback) {
4239
0
        compileWarning(file, "nofor and noback not allowed before base");
4240
0
      }
4241
36
      if (!getToken(file, &token, "attribute name")) {
4242
0
        compileError(
4243
0
            file, "base opcode must be followed by a valid attribute name.");
4244
0
        return 0;
4245
0
      }
4246
36
      if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
4247
0
        return 0;
4248
0
      }
4249
36
      const CharacterClass *mode = findCharacterClass(&token, *table);
4250
36
      if (!mode) {
4251
34
        mode = addCharacterClass(file, token.chars, token.length, *table, 1);
4252
34
        if (!mode) return 0;
4253
34
      }
4254
36
      if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) &&
4255
36
          mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) {
4256
0
        compileError(file,
4257
0
            "base opcode must be followed by \"uppercase\", \"digit\", or a "
4258
0
            "custom attribute name.");
4259
0
        return 0;
4260
0
      }
4261
36
      if (!getRuleCharsText(file, &token)) return 0;
4262
36
      if (token.length != 1) {
4263
0
        compileError(file,
4264
0
            "Exactly one character followed by one base character is "
4265
0
            "required.");
4266
0
        return 0;
4267
0
      }
4268
36
      TranslationTableOffset characterOffset;
4269
36
      TranslationTableCharacter *character = putChar(
4270
36
          file, token.chars[0], table, &characterOffset, (*table)->ruleCounter);
4271
36
      if (!getRuleCharsText(file, &token)) return 0;
4272
36
      if (token.length != 1) {
4273
0
        compileError(file, "Exactly one base character is required.");
4274
0
        return 0;
4275
0
      }
4276
36
      TranslationTableOffset basechar;
4277
36
      putChar(file, token.chars[0], table, &basechar, (*table)->ruleCounter);
4278
      // putChar may have moved table, so make sure character is still valid
4279
36
      character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset];
4280
36
      if (character->basechar) {
4281
2
        if (character->basechar == basechar &&
4282
2
            character->mode == mode->attribute) {
4283
2
          _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Duplicate base rule.",
4284
2
              file->fileName, file->lineNumber);
4285
2
        } else {
4286
0
          _lou_logMessage(LOU_LOG_DEBUG,
4287
0
              "%s:%d: A different base rule already exists for this "
4288
0
              "character (%s). The existing rule will take precedence "
4289
0
              "over the new one.",
4290
0
              file->fileName, file->lineNumber,
4291
0
              printSource(file->sourceFile, character->sourceFile,
4292
0
                  character->sourceLine));
4293
0
        }
4294
34
      } else {
4295
34
        character->basechar = basechar;
4296
34
        character->mode = mode->attribute;
4297
34
        character->sourceFile = file->sourceFile;
4298
34
        character->sourceLine = file->lineNumber;
4299
34
        character->ruleIndex = (*table)->ruleCounter;
4300
        /* some other processing is done at the end of the compilation, in
4301
         * finalizeTable() */
4302
34
      }
4303
36
      (*table)->ruleCounter++;
4304
36
      return 1;
4305
2
    case CTO_EmpMatchBefore:
4306
2
      before |= CTC_EmpMatch;
4307
2
      goto doOpcode;
4308
14
    case CTO_EmpMatchAfter:
4309
14
      after |= CTC_EmpMatch;
4310
14
      goto doOpcode;
4311
4312
2
    case CTO_SwapCc:
4313
5
    case CTO_SwapCd:
4314
6
    case CTO_SwapDd:
4315
6
      return compileSwap(file, opcode, noback, nofor, table);
4316
0
    case CTO_Hyphen:
4317
16
    case CTO_DecPoint:
4318
      //  case CTO_Apostrophe:
4319
      //  case CTO_Initial:
4320
16
      if (!getRuleCharsText(file, &ruleChars)) return 0;
4321
16
      if (!getRuleDotsPattern(file, &ruleDots)) return 0;
4322
16
      if (ruleChars.length != 1 || ruleDots.length < 1) {
4323
0
        compileError(file,
4324
0
            "One Unicode character and at least one cell are "
4325
0
            "required.");
4326
0
        return 0;
4327
0
      }
4328
16
      return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,
4329
16
          noback, nofor, table);
4330
      // if (opcode == CTO_DecPoint)
4331
      // {
4332
      //   TranslationTableCharacter *c =
4333
      //   getChar(ruleChars.chars[0]);
4334
      //   if(c)
4335
      //     c->attributes |= CTC_NumericMode;
4336
      // }
4337
0
    default:
4338
0
      compileError(file, "unimplemented opcode.");
4339
0
      return 0;
4340
1.05k
    }
4341
1.75k
  }
4342
0
  return 0;
4343
1.75k
}
4344
4345
int EXPORT_CALL
4346
0
lou_readCharFromFile(const char *fileName, int *mode) {
4347
  /* Read a character from a file, whether big-endian, little-endian or
4348
   * ASCII8 */
4349
0
  int ch;
4350
0
  static FileInfo file;
4351
4352
  /* Check for NULL pointers before dereferencing.
4353
   * This prevents segmentation faults when invalid arguments are passed. */
4354
0
  if (fileName == NULL || mode == NULL) return EOF;
4355
4356
0
  if (*mode == 1) {
4357
0
    *mode = 0;
4358
0
    file.fileName = fileName;
4359
0
    file.encoding = noEncoding;
4360
0
    file.status = 0;
4361
0
    file.lineNumber = 0;
4362
0
    if (!(file.in = fopen(file.fileName, "r"))) {
4363
0
      _lou_logMessage(LOU_LOG_ERROR, "Cannot open file '%s'", file.fileName);
4364
0
      *mode = 1;
4365
0
      return EOF;
4366
0
    }
4367
0
  }
4368
0
  if (file.in == NULL) {
4369
0
    *mode = 1;
4370
0
    return EOF;
4371
0
  }
4372
0
  ch = getAChar(&file);
4373
0
  if (ch == EOF) {
4374
0
    fclose(file.in);
4375
0
    file.in = NULL;
4376
0
    *mode = 1;
4377
0
  }
4378
0
  return ch;
4379
0
}
4380
4381
static TranslationTableCharacter *
4382
finalizeCharacter(TranslationTableHeader *table, TranslationTableOffset characterOffset,
4383
2.70k
    int detect_loop) {
4384
2.70k
  TranslationTableCharacter *character =
4385
2.70k
      (TranslationTableCharacter *)&table->ruleArea[characterOffset];
4386
2.70k
  if (character->finalized) return character;
4387
2.67k
  if (character->basechar) {
4388
30
    TranslationTableOffset basecharOffset = 0;
4389
30
    TranslationTableCharacter *basechar = character;
4390
30
    TranslationTableCharacterAttributes mode = 0;
4391
60
    while (basechar->basechar) {
4392
30
      if (basechar->basechar == characterOffset || detect_loop++ > MAX_MODES) {
4393
0
        _lou_logMessage(LOU_LOG_ERROR,
4394
0
            "%s: error: Character can not be (indirectly) based on "
4395
0
            "itself.",
4396
0
            printSource(NULL, character->sourceFile, character->sourceLine));
4397
0
        errorCount++;
4398
0
        return NULL;
4399
0
      }
4400
      // inherit basechar mode
4401
30
      mode |= basechar->mode;
4402
      // compute basechar recursively
4403
30
      basecharOffset = basechar->basechar;
4404
30
      basechar = finalizeCharacter(table, basecharOffset, detect_loop);
4405
30
      if (!basechar) return NULL;
4406
30
      if (character->mode & (basechar->attributes | basechar->mode)) {
4407
0
        char *attributeName = NULL;
4408
0
        const CharacterClass *class = table->characterClasses;
4409
0
        while (class) {
4410
0
          if (class->attribute == character->mode) {
4411
0
            attributeName =
4412
0
                strdup(_lou_showString(class->name, class->length, 0));
4413
0
            break;
4414
0
          }
4415
0
          class = class->next;
4416
0
        }
4417
0
        _lou_logMessage(LOU_LOG_ERROR,
4418
0
            "%s: error: Base character %s can not have the %s "
4419
0
            "attribute.",
4420
0
            printSource(NULL, character->sourceFile, character->sourceLine),
4421
0
            _lou_showString(&basechar->value, 1, 0),
4422
0
            attributeName != NULL ? attributeName : "?");
4423
0
        errorCount++;
4424
0
        free(attributeName);
4425
0
        return NULL;
4426
0
      }
4427
30
    }
4428
    // unset character definition rule or base rule (whichever was declared
4429
    // last) if the dot patterns are not compatible, meaning if the real parts
4430
    // (1-8) of the dot patterns do not match
4431
30
    TranslationTableRule *basecharDefRule =
4432
30
        (TranslationTableRule *)&table->ruleArea[basechar->definitionRule];
4433
30
    if (character->definitionRule) {
4434
0
      TranslationTableRule *defRule =
4435
0
          (TranslationTableRule *)&table->ruleArea[character->definitionRule];
4436
0
      if (defRule->dotslen != basecharDefRule->dotslen ||
4437
0
          memcmp(&defRule->charsdots[defRule->charslen],
4438
0
              &basecharDefRule->charsdots[basecharDefRule->charslen],
4439
0
              defRule->dotslen * CHARSIZE)) {
4440
0
        char *defOpcodeName = strdup(_lou_findOpcodeName(defRule->opcode));
4441
0
        if (defRule->index < character->ruleIndex) {
4442
          // character definition rule was defined before base rule; ignore base
4443
          // rule
4444
0
          _lou_logMessage(LOU_LOG_DEBUG,
4445
0
              "%s:%d: Character already defined (%s). The existing %s rule "
4446
0
              "will take precedence over the new base rule.",
4447
0
              character->sourceFile, character->sourceLine,
4448
0
              printSource(character->sourceFile, defRule->sourceFile,
4449
0
                  defRule->sourceLine),
4450
0
              defOpcodeName);
4451
0
          free(defOpcodeName);
4452
0
          character->basechar = 0;
4453
0
          character->mode = 0;
4454
0
          character->sourceFile = defRule->sourceFile;
4455
0
          character->sourceLine = defRule->sourceLine;
4456
0
          character->ruleIndex = defRule->index;
4457
0
          character->finalized = 1;
4458
0
          return character;
4459
0
        } else {
4460
0
          _lou_logMessage(LOU_LOG_DEBUG,
4461
0
              "%s:%d: A base rule already exists for this character (%s). "
4462
0
              "The "
4463
0
              "existing base rule will take precedence over the new %s "
4464
0
              "rule.",
4465
0
              defRule->sourceFile, defRule->sourceLine,
4466
0
              printSource(defRule->sourceFile, character->sourceFile,
4467
0
                  character->sourceLine),
4468
0
              defOpcodeName);
4469
0
          free(defOpcodeName);
4470
0
          character->definitionRule = 0;
4471
0
        }
4472
0
      }
4473
0
    }
4474
30
    character->mode = mode;
4475
30
    character->basechar = basecharOffset;
4476
    // add mode to attributes
4477
30
    character->attributes |= character->mode;
4478
30
    if (character->attributes & (CTC_UpperCase | CTC_LowerCase))
4479
12
      character->attributes |= CTC_Letter;
4480
    // also set the new attributes on the associated dots of the base
4481
    // character
4482
30
    if (basecharDefRule->dotslen == 1) {
4483
1
      TranslationTableCharacter *dots =
4484
1
          getDots(basecharDefRule->charsdots[basecharDefRule->charslen], table);
4485
1
      if (dots) {
4486
1
        dots->attributes |= character->mode;
4487
1
        if (dots->attributes & (CTC_UpperCase | CTC_LowerCase))
4488
0
          dots->attributes |= CTC_Letter;
4489
1
      }
4490
1
    }
4491
    // store all characters that are based on a base character in list
4492
30
    if (basechar->linked) character->linked = basechar->linked;
4493
30
    basechar->linked = characterOffset;
4494
30
  }
4495
2.67k
  character->finalized = 1;
4496
2.67k
  return character;
4497
2.67k
}
4498
4499
static int
4500
526
finalizeTable(TranslationTableHeader *table) {
4501
526
  if (table->finalized) return 1;
4502
  // normalize basechar and mode of all characters
4503
304k
  for (int i = 0; i < HASHNUM; i++) {
4504
304k
    TranslationTableOffset characterOffset = table->characters[i];
4505
307k
    while (characterOffset) {
4506
2.67k
      TranslationTableCharacter *character =
4507
2.67k
          finalizeCharacter(table, characterOffset, 0);
4508
2.67k
      if (!character) return 0;
4509
2.67k
      characterOffset = character->next;
4510
2.67k
    }
4511
304k
  }
4512
  // add noletsign rules from single-letter word and largesign rules
4513
304k
  for (int i = 0; i < HASHNUM; i++) {
4514
304k
    TranslationTableOffset characterOffset = table->characters[i];
4515
307k
    while (characterOffset) {
4516
2.67k
      TranslationTableCharacter *character =
4517
2.67k
          (TranslationTableCharacter *)&table->ruleArea[characterOffset];
4518
2.67k
      if (character->attributes & CTC_Letter) {
4519
725
        TranslationTableOffset *otherRule = &character->otherRules;
4520
783
        while (*otherRule) {
4521
58
          TranslationTableRule *rule =
4522
58
              (TranslationTableRule *)&table->ruleArea[*otherRule];
4523
58
          if (rule->opcode == CTO_WholeWord || rule->opcode == CTO_LargeSign)
4524
0
            if (table->noLetsignCount < LETSIGNSIZE)
4525
0
              table->noLetsign[table->noLetsignCount++] =
4526
0
                  rule->charsdots[0];
4527
58
          otherRule = &rule->charsnext;
4528
58
        }
4529
725
      }
4530
2.67k
      characterOffset = character->next;
4531
2.67k
    }
4532
304k
  }
4533
  // Rearrange rules in `forRules' so that when iterating over candidate rules in
4534
  // for_selectRule(), both case-sensitive and case-insensitive rules are contained
4535
  // within the same ordered list. We do the rearrangement by iterating over all
4536
  // case-sensitive rules and if needed move them to another bucket. This may slow down
4537
  // the compilation of tables with a lot of context rules, but the good news is that
4538
  // translation speed is not affected.
4539
304k
  for (unsigned long int i = 0; i < HASHNUM; i++) {
4540
304k
    TranslationTableOffset *p = &table->forRules[i];
4541
304k
    while (*p) {
4542
142
      TranslationTableRule *rule = (TranslationTableRule *)&table->ruleArea[*p];
4543
      // For now only move the rules that we know are case-sensitive, namely
4544
      // `context' rules. (Note that there may be other case-sensitive rules that
4545
      // we're currently not aware of.) We don't move case insensitive rules because
4546
      // the user can/should define them using all lowercases.
4547
142
      if (rule->opcode == CTO_Context) {
4548
0
        unsigned long int hash = _lou_stringHash(&rule->charsdots[0], 1, table);
4549
        // no need to do anything if the first two characters are not uppercase
4550
        // letters
4551
0
        if (hash != i) {
4552
          // compute new position
4553
0
          TranslationTableOffset *insert_at = &table->forRules[hash];
4554
0
          while (*insert_at) {
4555
0
            TranslationTableRule *r =
4556
0
                (TranslationTableRule *)&table->ruleArea[*insert_at];
4557
0
            if (rule->charslen > r->charslen)
4558
0
              break;
4559
0
            else if (rule->charslen == r->charslen && r->opcode == CTO_Always)
4560
0
              break;
4561
0
            insert_at = &r->charsnext;
4562
0
          }
4563
          // remove rule from current list and insert it at the correct position
4564
          // in the new list
4565
0
          TranslationTableOffset next = rule->charsnext;
4566
0
          rule->charsnext = *insert_at;
4567
0
          *insert_at = *p;
4568
0
          *p = next;
4569
0
          continue;
4570
0
        }
4571
0
      }
4572
142
      p = &rule->charsnext;
4573
142
    }
4574
304k
  }
4575
271
  table->finalized = 1;
4576
271
  return 1;
4577
271
}
4578
4579
static int
4580
compileString(const char *inString, TranslationTableHeader **table,
4581
292
    DisplayTableHeader **displayTable) {
4582
  /* This function can be used to make changes to tables on the fly. */
4583
292
  int k;
4584
292
  FileInfo file;
4585
292
  if (inString == NULL) return 0;
4586
292
  memset(&file, 0, sizeof(file));
4587
292
  file.fileName = inString;
4588
292
  file.encoding = noEncoding;
4589
292
  file.lineNumber = 1;
4590
292
  file.status = 0;
4591
292
  file.linepos = 0;
4592
12.8k
  for (k = 0; k < MAXSTRING - 1 && inString[k]; k++) file.line[k] = inString[k];
4593
292
  file.line[k] = 0;
4594
292
  file.linelen = k;
4595
292
  if (table && *table && (*table)->finalized) {
4596
0
    compileError(&file, "Table is finalized");
4597
0
    return 0;
4598
0
  }
4599
292
  return compileRule(&file, table, displayTable, NULL);
4600
292
}
4601
4602
static int
4603
273
setDefaults(TranslationTableHeader *table) {
4604
1.09k
  for (int i = 0; i < 3; i++)
4605
819
    if (!table->emphRules[i][lenPhraseOffset])
4606
819
      table->emphRules[i][lenPhraseOffset] = 4;
4607
273
  if (table->numPasses == 0) table->numPasses = 1;
4608
273
  return 1;
4609
273
}
4610
4611
/* =============== *
4612
 * TABLE RESOLVING *
4613
 * =============== *
4614
 *
4615
 * A table resolver is a function that resolves a `tableList` path against a
4616
 * `base` path, and returns the resolved table(s) as a list of absolute file
4617
 * paths.
4618
 *
4619
 * The function must have the following signature:
4620
 *
4621
 *     char ** (const char * tableList, const char * base)
4622
 *
4623
 * In general, `tableList` is a path in the broad sense. The default
4624
 * implementation accepts only *file* paths. But another implementation could
4625
 * for instance handle URI's. `base` is always a file path however.
4626
 *
4627
 * The idea is to give other programs that use liblouis the ability to define
4628
 * their own table resolver (in C, Java, Python, etc.) when the default
4629
 * resolver is not satisfying. (see also lou_registerTableResolver)
4630
 *
4631
 */
4632
4633
/**
4634
 * Resolve a single (sub)table.
4635
 *
4636
 * Tries to resolve `table` against `base` if base is an absolute path. If
4637
 * that fails, searches `searchPath`.
4638
 *
4639
 */
4640
static char *
4641
292
resolveSubtable(const char *table, const char *base, const char *searchPath) {
4642
292
  char *tableFile;
4643
292
  static struct stat info;
4644
4645
588
#define MAX_TABLEFILE_SIZE (MAXSTRING * sizeof(char) * 2)
4646
292
  if (table == NULL || table[0] == '\0') return NULL;
4647
292
  tableFile = (char *)malloc(MAX_TABLEFILE_SIZE);
4648
4649
  //
4650
  // First try to resolve against base
4651
  //
4652
292
  if (base) {
4653
2
    int k;
4654
2
    if (strlen(base) >= MAX_TABLEFILE_SIZE) goto failure;
4655
2
    strcpy(tableFile, base);
4656
2
    k = (int)strlen(tableFile);
4657
30
    while (k >= 0 && tableFile[k] != '/' && tableFile[k] != '\\') k--;
4658
2
    tableFile[++k] = '\0';
4659
2
    if (strlen(tableFile) + strlen(table) >= MAX_TABLEFILE_SIZE) goto failure;
4660
2
    strcat(tableFile, table);
4661
2
    if (stat(tableFile, &info) == 0 && !(info.st_mode & S_IFDIR)) {
4662
0
      _lou_logMessage(LOU_LOG_DEBUG, "found table %s", tableFile);
4663
0
      return tableFile;
4664
0
    }
4665
2
  }
4666
4667
  //
4668
  // It could be an absolute path, or a path relative to the current working
4669
  // directory
4670
  //
4671
292
  if (strlen(table) >= MAX_TABLEFILE_SIZE) goto failure;
4672
292
  strcpy(tableFile, table);
4673
292
  if (stat(tableFile, &info) == 0 && !(info.st_mode & S_IFDIR)) {
4674
292
    _lou_logMessage(LOU_LOG_DEBUG, "found table %s", tableFile);
4675
292
    return tableFile;
4676
292
  }
4677
4678
  //
4679
  // Then search `LOUIS_TABLEPATH`, `dataPath` and `programPath`
4680
  //
4681
  // searchPath may be NULL if _lou_getTablePath failed (e.g. because the
4682
  // data path was too long); the earlier resolution steps still apply.
4683
0
  if (searchPath != NULL && searchPath[0] != '\0') {
4684
0
    char *dir;
4685
0
    int last;
4686
0
    char *cp;
4687
0
    char *searchPath_copy = strdup(searchPath);
4688
0
    for (dir = searchPath_copy;; dir = cp + 1) {
4689
0
      for (cp = dir; *cp != '\0' && *cp != ','; cp++);
4690
0
      last = (*cp == '\0');
4691
0
      *cp = '\0';
4692
0
      if (dir == cp) dir = ".";
4693
0
      if (strlen(dir) + strlen(table) + 1 >= MAX_TABLEFILE_SIZE) {
4694
0
        free(searchPath_copy);
4695
0
        goto failure;
4696
0
      }
4697
0
      sprintf(tableFile, "%s%c%s", dir, DIR_SEP, table);
4698
0
      if (stat(tableFile, &info) == 0 && !(info.st_mode & S_IFDIR)) {
4699
0
        _lou_logMessage(LOU_LOG_DEBUG, "found table %s", tableFile);
4700
0
        free(searchPath_copy);
4701
0
        return tableFile;
4702
0
      }
4703
0
      if (last) break;
4704
0
      if (strlen(dir) + strlen("liblouis") + strlen("tables") + strlen(table) + 3 >=
4705
0
          MAX_TABLEFILE_SIZE) {
4706
0
        free(searchPath_copy);
4707
0
        goto failure;
4708
0
      }
4709
0
      sprintf(tableFile, "%s%c%s%c%s%c%s", dir, DIR_SEP, "liblouis", DIR_SEP,
4710
0
          "tables", DIR_SEP, table);
4711
0
      if (stat(tableFile, &info) == 0 && !(info.st_mode & S_IFDIR)) {
4712
0
        _lou_logMessage(LOU_LOG_DEBUG, "found table %s", tableFile);
4713
0
        free(searchPath_copy);
4714
0
        return tableFile;
4715
0
      }
4716
0
      if (last) break;
4717
0
    }
4718
0
    free(searchPath_copy);
4719
0
  }
4720
0
failure:
4721
0
  free(tableFile);
4722
0
  return NULL;
4723
0
}
4724
4725
char *EXPORT_CALL
4726
292
_lou_getTablePath(void) {
4727
292
  char searchPath[MAXSTRING];
4728
292
  int remaining = MAXSTRING;
4729
292
  char *path;
4730
292
  char *cp;
4731
292
  int envset = 0;
4732
292
  cp = searchPath;
4733
292
  path = getenv("LOUIS_TABLEPATH");
4734
292
  if (path != NULL && path[0] != '\0') {
4735
0
    envset = 1;
4736
0
    int written = snprintf(cp, remaining, ",%s", path);
4737
0
    if (written < 0 || written >= remaining) {
4738
0
      _lou_logMessage(LOU_LOG_ERROR, "LOUIS_TABLEPATH too long");
4739
0
      return NULL;
4740
0
    }
4741
0
    cp += written;
4742
0
    remaining -= written;
4743
0
  }
4744
292
  path = dataPathPtr;
4745
292
  if (path != NULL && path[0] != '\0') {
4746
0
    int written = snprintf(cp, remaining, ",%s%c%s%c%s", path, DIR_SEP, "liblouis",
4747
0
        DIR_SEP, "tables");
4748
0
    if (written < 0 || written >= remaining) {
4749
0
      _lou_logMessage(LOU_LOG_ERROR, "Data path too long");
4750
0
      return NULL;
4751
0
    }
4752
0
    cp += written;
4753
0
    remaining -= written;
4754
0
  }
4755
292
  if (!envset) {
4756
#ifdef _WIN32
4757
    path = lou_getProgramPath();
4758
    if (path != NULL) {
4759
      if (path[0] != '\0') {
4760
        // assuming the following directory structure:
4761
        // .
4762
        // ├── bin
4763
        // │   ├── liblouis.dll
4764
        // ├── include
4765
        // ├── lib
4766
        // └── share
4767
        //     ├── doc
4768
        //     ├── info
4769
        //     └── liblouis
4770
        //         └── tables
4771
        int written = snprintf(
4772
            cp, remaining, ",%s%s", path, "\\..\\share\\liblouis\\tables");
4773
        if (written < 0 || written >= remaining) {
4774
          _lou_logMessage(LOU_LOG_ERROR, "Program path too long");
4775
          free(path);
4776
          return NULL;
4777
        }
4778
        cp += written;
4779
        remaining -= written;
4780
      }
4781
      free(path);
4782
    }
4783
#else
4784
292
    int written = snprintf(cp, remaining, ",%s", TABLESDIR);
4785
292
    if (written < 0 || written >= remaining) {
4786
0
      _lou_logMessage(LOU_LOG_ERROR, "TABLESDIR too long");
4787
0
      return NULL;
4788
0
    }
4789
292
    cp += written;
4790
292
    remaining -= written;
4791
292
#endif
4792
292
  }
4793
292
  if (searchPath[0] != '\0')
4794
292
    return strdup(&searchPath[1]);
4795
0
  else
4796
0
    return strdup(".");
4797
292
}
4798
4799
/**
4800
 * The default table resolver
4801
 *
4802
 * Tries to resolve tableList against base. The search path is set to
4803
 * `LOUIS_TABLEPATH`, `dataPath` and `programPath` (in that order).
4804
 *
4805
 * @param table A file path, may be absolute or relative. May be a list of
4806
 *              tables separated by commas. In that case, the first table
4807
 *              is used as the base for the other subtables.
4808
 * @param base A file path or directory path, or NULL.
4809
 * @return The file paths of the resolved subtables, or NULL if the table
4810
 *         could not be resolved.
4811
 *
4812
 */
4813
char **EXPORT_CALL
4814
292
_lou_defaultTableResolver(const char *tableList, const char *base) {
4815
292
  char *searchPath;
4816
292
  char **tableFiles;
4817
292
  char *subTable;
4818
292
  char *tableList_copy;
4819
292
  char *cp;
4820
292
  int last;
4821
292
  int k;
4822
4823
  /* Set up search path */
4824
292
  searchPath = _lou_getTablePath();
4825
4826
  /* Count number of subtables in table list */
4827
292
  k = 0;
4828
6.47k
  for (cp = (char *)tableList; *cp != '\0'; cp++)
4829
6.18k
    if (*cp == ',') k++;
4830
292
  tableFiles = (char **)calloc(k + 2, sizeof(char *));
4831
292
  if (!tableFiles) _lou_outOfMemory();
4832
4833
  /* Resolve subtables */
4834
292
  k = 0;
4835
292
  tableList_copy = strdup(tableList);
4836
292
  for (subTable = tableList_copy;; subTable = cp + 1) {
4837
6.47k
    for (cp = subTable; *cp != '\0' && *cp != ','; cp++);
4838
292
    last = (*cp == '\0');
4839
292
    *cp = '\0';
4840
292
    if (!(tableFiles[k++] = resolveSubtable(subTable, base, searchPath))) {
4841
0
      char *path;
4842
0
      _lou_logMessage(LOU_LOG_ERROR, "Cannot resolve table '%s'", subTable);
4843
0
      path = getenv("LOUIS_TABLEPATH");
4844
0
      if (path != NULL && path[0] != '\0')
4845
0
        _lou_logMessage(LOU_LOG_ERROR, "LOUIS_TABLEPATH=%s", path);
4846
0
      free(searchPath);
4847
0
      free(tableList_copy);
4848
0
      lou_freeTableFiles(tableFiles);
4849
0
      return NULL;
4850
0
    }
4851
292
    if (k == 1) base = subTable;
4852
292
    if (last) break;
4853
292
  }
4854
292
  free(searchPath);
4855
292
  free(tableList_copy);
4856
292
  tableFiles[k] = NULL;
4857
292
  return tableFiles;
4858
292
}
4859
4860
static char **(EXPORT_CALL *tableResolver)(
4861
    const char *tableList, const char *base) = &_lou_defaultTableResolver;
4862
4863
static char **
4864
292
copyStringArray(char **array) {
4865
292
  int len;
4866
292
  char **copy;
4867
292
  if (!array) return NULL;
4868
292
  len = 0;
4869
584
  while (array[len]) len++;
4870
292
  copy = malloc((len + 1) * sizeof(char *));
4871
292
  copy[len] = NULL;
4872
584
  while (len) {
4873
292
    len--;
4874
292
    copy[len] = strdup(array[len]);
4875
292
  }
4876
292
  return copy;
4877
292
}
4878
4879
char **EXPORT_CALL
4880
292
_lou_resolveTable(const char *tableList, const char *base) {
4881
292
  if (!tableResolver) {
4882
0
    _lou_logMessage(LOU_LOG_ERROR, "Table resolver is not set");
4883
0
    return NULL;
4884
0
  }
4885
292
  char **tableFiles = (*tableResolver)(tableList, base);
4886
292
  char **result = copyStringArray(tableFiles);
4887
292
  if (tableResolver == &_lou_defaultTableResolver) lou_freeTableFiles(tableFiles);
4888
292
  return result;
4889
292
}
4890
4891
/**
4892
 * Register a new table resolver. Overrides the default resolver.
4893
 *
4894
 * @param resolver The new resolver as a function pointer.
4895
 *
4896
 */
4897
void EXPORT_CALL
4898
lou_registerTableResolver(
4899
0
    char **(EXPORT_CALL *resolver)(const char *tableList, const char *base)) {
4900
0
  if (!resolver) {
4901
0
    _lou_logMessage(LOU_LOG_ERROR, "Cannot register a NULL table resolver");
4902
0
    return;
4903
0
  }
4904
0
  tableResolver = resolver;
4905
0
}
4906
4907
static int fileCount = 0;
4908
4909
/**
4910
 * Compile a single file
4911
 *
4912
 */
4913
static int
4914
compileFile(const char *fileName, TranslationTableHeader **table,
4915
292
    DisplayTableHeader **displayTable) {
4916
292
  FileInfo file;
4917
292
  fileCount++;
4918
292
  file.fileName = fileName;
4919
292
  if (table) {
4920
292
    int i;
4921
294
    for (i = 0; (*table)->sourceFiles[i]; i++);
4922
292
    if (i >= MAX_SOURCE_FILES) {
4923
0
      _lou_logMessage(LOU_LOG_WARN, "Max number of source files (%i) reached",
4924
0
          MAX_SOURCE_FILES);
4925
0
      file.sourceFile = NULL;
4926
292
    } else {
4927
292
      file.sourceFile = (*table)->sourceFiles[i] = strdup(fileName);
4928
292
    }
4929
292
  }
4930
292
  file.encoding = noEncoding;
4931
292
  file.status = 0;
4932
292
  file.lineNumber = 0;
4933
292
  if ((file.in = fopen(file.fileName, "rb"))) {
4934
    // the scope of a macro is the current file (after the macro definition)
4935
292
    const MacroList *inscopeMacros = NULL;
4936
1.97k
    while (_lou_getALine(&file))
4937
1.69k
      if (!compileRule(&file, table, displayTable, &inscopeMacros)) {
4938
16
        if (!errorCount) compileError(&file, "Rule could not be compiled");
4939
16
        break;
4940
16
      }
4941
292
    fclose(file.in);
4942
292
    free_macro_list(inscopeMacros);
4943
292
  } else {
4944
0
    _lou_logMessage(LOU_LOG_ERROR, "Cannot open table '%s'", file.fileName);
4945
0
    errorCount++;
4946
0
  }
4947
292
  return !errorCount;
4948
292
}
4949
4950
static void
4951
290
freeTranslationTable(TranslationTableHeader *t) {
4952
304
  for (int i = 0; i < MAX_EMPH_CLASSES && t->emphClassNames[i]; i++)
4953
290
    free(t->emphClassNames[i]);
4954
582
  for (int i = 0; t->sourceFiles[i]; i++) free(t->sourceFiles[i]);
4955
290
  if (t->characterClasses) deallocateCharacterClasses(t);
4956
290
  if (t->ruleNames) deallocateRuleNames(t);
4957
290
  free(t);
4958
290
}
4959
4960
static void
4961
290
freeDisplayTable(DisplayTableHeader *t) {
4962
290
  free(t);
4963
290
}
4964
4965
/**
4966
 * Free a char** array
4967
 */
4968
void EXPORT_CALL
4969
584
lou_freeTableFiles(char **tables) {
4970
584
  if (!tables) return;
4971
1.16k
  for (char **table = tables; *table; table++) free(*table);
4972
584
  free(tables);
4973
584
}
4974
4975
/**
4976
 * Implement include opcode
4977
 *
4978
 */
4979
static int
4980
includeFile(const FileInfo *file, CharsString *includedFile,
4981
2
    TranslationTableHeader **table, DisplayTableHeader **displayTable) {
4982
2
  int k;
4983
2
  char includeThis[MAXSTRING];
4984
2
  char **tableFiles;
4985
2
  int rv;
4986
38
  for (k = 0; k < includedFile->length; k++)
4987
36
    includeThis[k] = (char)includedFile->chars[k];
4988
2
  if (k >= MAXSTRING) {
4989
0
    compileError(file, "Include statement too long: 'include %s'", includeThis);
4990
0
    return 0;
4991
0
  }
4992
2
  includeThis[k] = 0;
4993
2
  tableFiles = _lou_resolveTable(includeThis, file->fileName);
4994
2
  if (tableFiles == NULL) {
4995
0
    errorCount++;
4996
0
    return 0;
4997
0
  }
4998
2
  if (tableFiles[1] != NULL) {
4999
0
    lou_freeTableFiles(tableFiles);
5000
0
    compileError(file, "Table list not supported in include statement: 'include %s'",
5001
0
        includeThis);
5002
0
    return 0;
5003
0
  }
5004
2
  rv = compileFile(*tableFiles, table, displayTable);
5005
2
  lou_freeTableFiles(tableFiles);
5006
2
  if (!rv)
5007
0
    _lou_logMessage(LOU_LOG_ERROR, "%s:%d: Error in included file", file->fileName,
5008
0
        file->lineNumber);
5009
2
  return rv;
5010
2
}
5011
5012
/**
5013
 * Compile source tables into a table in memory
5014
 *
5015
 */
5016
static int
5017
compileTable(const char *tableList, const char *displayTableList,
5018
290
    TranslationTableHeader **translationTable, DisplayTableHeader **displayTable) {
5019
290
  char **tableFiles;
5020
290
  char **subTable;
5021
290
  if (translationTable && !tableList) return 0;
5022
290
  if (displayTable && !displayTableList) return 0;
5023
290
  if (!translationTable && !displayTable) return 0;
5024
290
  if (translationTable) *translationTable = NULL;
5025
290
  if (displayTable) *displayTable = NULL;
5026
290
  errorCount = warningCount = fileCount = 0;
5027
290
  if (!opcodeLengths[0]) {
5028
290
    TranslationTableOpcode opcode;
5029
34.2k
    for (opcode = 0; opcode < CTO_None; opcode++)
5030
33.9k
      opcodeLengths[opcode] = (short)strlen(opcodeNames[opcode]);
5031
290
  }
5032
290
  if (translationTable) allocateTranslationTable(NULL, translationTable);
5033
290
  if (displayTable) allocateDisplayTable(NULL, displayTable);
5034
5035
290
  if (translationTable) {
5036
290
    (*translationTable)->emphClassNames[0] = NULL;
5037
290
    (*translationTable)->characterClasses = NULL;
5038
290
    (*translationTable)->ruleNames = NULL;
5039
290
  }
5040
5041
  /* Compile things that are necessary for the proper operation of
5042
   * liblouis or liblouisxml or liblouisutdml */
5043
  /* TODO: These definitions seem to be necessary for proper functioning of
5044
     liblouisutdml. Find a way to satisfy those requirements without hard coding
5045
     some characters in every table notably behind the user's back */
5046
290
  compileString("space \\xffff 123456789abcdef LOU_ENDSEGMENT", translationTable,
5047
290
      displayTable);
5048
5049
290
  if (displayTable && translationTable && strcmp(tableList, displayTableList) == 0) {
5050
    /* Compile the display and translation tables in one go */
5051
5052
    /* Compile all subtables in the list */
5053
290
    if (!(tableFiles = _lou_resolveTable(tableList, NULL))) {
5054
0
      errorCount++;
5055
0
      goto cleanup;
5056
0
    }
5057
563
    for (subTable = tableFiles; *subTable; subTable++)
5058
290
      if (!compileFile(*subTable, translationTable, displayTable)) goto cleanup;
5059
290
  } else {
5060
    /* Compile the display and translation tables separately */
5061
5062
0
    if (displayTable) {
5063
0
      if (!(tableFiles = _lou_resolveTable(displayTableList, NULL))) {
5064
0
        errorCount++;
5065
0
        goto cleanup;
5066
0
      }
5067
0
      for (subTable = tableFiles; *subTable; subTable++)
5068
0
        if (!compileFile(*subTable, NULL, displayTable)) goto cleanup;
5069
0
      lou_freeTableFiles(tableFiles);
5070
0
      tableFiles = NULL;
5071
0
    }
5072
0
    if (translationTable) {
5073
0
      if (!(tableFiles = _lou_resolveTable(tableList, NULL))) {
5074
0
        errorCount++;
5075
0
        goto cleanup;
5076
0
      }
5077
0
      for (subTable = tableFiles; *subTable; subTable++)
5078
0
        if (!compileFile(*subTable, translationTable, NULL)) goto cleanup;
5079
0
    }
5080
0
  }
5081
5082
/* Clean up after compiling files */
5083
290
cleanup:
5084
290
  lou_freeTableFiles(tableFiles);
5085
290
  if (warningCount)
5086
205
    _lou_logMessage(LOU_LOG_WARN, "%s: %d warnings issued", tableList, warningCount);
5087
290
  if (!errorCount) {
5088
273
    if (translationTable) setDefaults(*translationTable);
5089
273
    return 1;
5090
273
  } else {
5091
17
    _lou_logMessage(LOU_LOG_ERROR, "%d errors found.", errorCount);
5092
17
    if (translationTable) {
5093
17
      if (*translationTable) freeTranslationTable(*translationTable);
5094
17
      *translationTable = NULL;
5095
17
    }
5096
17
    if (displayTable) {
5097
17
      if (*displayTable) freeDisplayTable(*displayTable);
5098
17
      *displayTable = NULL;
5099
17
    }
5100
17
    return 0;
5101
17
  }
5102
290
}
5103
5104
/* Return the emphasis classes declared in tableList. */
5105
char const **EXPORT_CALL
5106
0
lou_getEmphClasses(const char *tableList) {
5107
0
  const char *names[MAX_EMPH_CLASSES + 1];
5108
0
  unsigned int count = 0;
5109
0
  const TranslationTableHeader *table = _lou_getTranslationTable(tableList);
5110
0
  if (!table) return NULL;
5111
5112
0
  while (count < MAX_EMPH_CLASSES) {
5113
0
    char const *name = table->emphClassNames[count];
5114
0
    if (!name) break;
5115
0
    names[count++] = name;
5116
0
  }
5117
0
  names[count++] = NULL;
5118
5119
0
  {
5120
0
    unsigned int size = count * sizeof(names[0]);
5121
0
    char const **result = malloc(size);
5122
0
    if (!result) return NULL;
5123
    /* The void* cast is necessary to stop MSVC from warning about
5124
     * different 'const' qualifiers (C4090). */
5125
0
    memcpy((void *)result, names, size);
5126
0
    return result;
5127
0
  }
5128
0
}
5129
5130
void EXPORT_CALL
5131
0
lou_freeEmphClasses(char const **classes) {
5132
0
  free(classes);
5133
0
}
5134
5135
void
5136
getTable(const char *tableList, const char *displayTableList,
5137
    TranslationTableHeader **translationTable, DisplayTableHeader **displayTable);
5138
5139
void EXPORT_CALL
5140
_lou_getTable(const char *tableList, const char *displayTableList,
5141
    const TranslationTableHeader **translationTable,
5142
543
    const DisplayTableHeader **displayTable) {
5143
543
  TranslationTableHeader *newTable = NULL;
5144
543
  DisplayTableHeader *newDisplayTable = NULL;
5145
543
  getTable(tableList, displayTableList, &newTable, &newDisplayTable);
5146
543
  if (newTable)
5147
526
    if (!finalizeTable(newTable)) newTable = NULL;
5148
543
  *translationTable = newTable;
5149
543
  *displayTable = newDisplayTable;
5150
543
}
5151
5152
/* Checks and loads tableList. */
5153
const void *EXPORT_CALL
5154
288
lou_getTable(const char *tableList) {
5155
288
  const TranslationTableHeader *table = NULL;
5156
288
  const DisplayTableHeader *displayTable = NULL;
5157
288
  _lou_getTable(tableList, tableList, &table, &displayTable);
5158
288
  if (!table || !displayTable) return NULL;
5159
271
  return table;
5160
288
}
5161
5162
const TranslationTableHeader *EXPORT_CALL
5163
0
_lou_getTranslationTable(const char *tableList) {
5164
0
  TranslationTableHeader *table = NULL;
5165
0
  getTable(tableList, NULL, &table, NULL);
5166
0
  if (table)
5167
0
    if (!finalizeTable(table)) table = NULL;
5168
0
  return table;
5169
0
}
5170
5171
const DisplayTableHeader *EXPORT_CALL
5172
0
_lou_getDisplayTable(const char *tableList) {
5173
0
  DisplayTableHeader *table = NULL;
5174
0
  getTable(NULL, tableList, NULL, &table);
5175
0
  return table;
5176
0
}
5177
5178
void
5179
getTable(const char *translationTableList, const char *displayTableList,
5180
545
    TranslationTableHeader **translationTable, DisplayTableHeader **displayTable) {
5181
  /* Keep track of which tables have already been compiled */
5182
545
  int translationTableListLen, displayTableListLen = 0;
5183
545
  if (translationTableList == NULL || *translationTableList == 0)
5184
0
    translationTable = NULL;
5185
545
  if (displayTableList == NULL || *displayTableList == 0) displayTable = NULL;
5186
  /* See if translation table has already been compiled */
5187
545
  if (translationTable) {
5188
545
    translationTableListLen = (int)strlen(translationTableList);
5189
545
    *translationTable = NULL;
5190
545
    TranslationTableChainEntry *currentEntry = translationTableChain;
5191
545
    TranslationTableChainEntry *prevEntry = NULL;
5192
545
    while (currentEntry != NULL) {
5193
255
      if (translationTableListLen == currentEntry->tableListLength &&
5194
255
          (memcmp(&currentEntry->tableList[0], translationTableList,
5195
255
              translationTableListLen)) == 0) {
5196
        /* Move the table to the top of the table chain. */
5197
255
        if (prevEntry != NULL) {
5198
0
          prevEntry->next = currentEntry->next;
5199
0
          currentEntry->next = translationTableChain;
5200
0
          translationTableChain = currentEntry;
5201
0
        }
5202
255
        *translationTable = currentEntry->table;
5203
255
        break;
5204
255
      }
5205
0
      prevEntry = currentEntry;
5206
0
      currentEntry = currentEntry->next;
5207
0
    }
5208
545
  }
5209
  /* See if display table has already been compiled */
5210
545
  if (displayTable) {
5211
545
    displayTableListLen = (int)strlen(displayTableList);
5212
545
    *displayTable = NULL;
5213
545
    DisplayTableChainEntry *currentEntry = displayTableChain;
5214
545
    DisplayTableChainEntry *prevEntry = NULL;
5215
545
    while (currentEntry != NULL) {
5216
255
      if (displayTableListLen == currentEntry->tableListLength &&
5217
255
          (memcmp(&currentEntry->tableList[0], displayTableList,
5218
255
              displayTableListLen)) == 0) {
5219
        /* Move the table to the top of the table chain. */
5220
255
        if (prevEntry != NULL) {
5221
0
          prevEntry->next = currentEntry->next;
5222
0
          currentEntry->next = displayTableChain;
5223
0
          displayTableChain = currentEntry;
5224
0
        }
5225
255
        *displayTable = currentEntry->table;
5226
255
        break;
5227
255
      }
5228
0
      prevEntry = currentEntry;
5229
0
      currentEntry = currentEntry->next;
5230
0
    }
5231
545
  }
5232
545
  if ((translationTable && *translationTable == NULL) ||
5233
290
      (displayTable && *displayTable == NULL)) {
5234
290
    TranslationTableHeader *newTranslationTable = NULL;
5235
290
    DisplayTableHeader *newDisplayTable = NULL;
5236
290
    if (compileTable(translationTableList, displayTableList,
5237
290
          (translationTable && *translationTable == NULL) ? &newTranslationTable
5238
290
                                  : NULL,
5239
290
          (displayTable && *displayTable == NULL) ? &newDisplayTable : NULL)) {
5240
      /* Add a new entry to the top of the table chain. */
5241
273
      if (newTranslationTable != NULL) {
5242
273
        int entrySize =
5243
273
            sizeof(TranslationTableChainEntry) + translationTableListLen;
5244
273
        TranslationTableChainEntry *newEntry = malloc(entrySize);
5245
273
        if (!newEntry) _lou_outOfMemory();
5246
273
        newEntry->next = translationTableChain;
5247
273
        newEntry->table = newTranslationTable;
5248
273
        newEntry->tableListLength = translationTableListLen;
5249
273
        memcpy(&newEntry->tableList[0], translationTableList,
5250
273
            translationTableListLen);
5251
273
        translationTableChain = newEntry;
5252
273
        *translationTable = newTranslationTable;
5253
273
      }
5254
273
      if (newDisplayTable != NULL) {
5255
273
        int entrySize = sizeof(DisplayTableChainEntry) + displayTableListLen;
5256
273
        DisplayTableChainEntry *newEntry = malloc(entrySize);
5257
273
        if (!newEntry) _lou_outOfMemory();
5258
273
        newEntry->next = displayTableChain;
5259
273
        newEntry->table = newDisplayTable;
5260
273
        newEntry->tableListLength = displayTableListLen;
5261
273
        memcpy(&newEntry->tableList[0], displayTableList, displayTableListLen);
5262
273
        displayTableChain = newEntry;
5263
273
        *displayTable = newDisplayTable;
5264
273
      }
5265
273
    } else {
5266
17
      _lou_logMessage(
5267
17
          LOU_LOG_ERROR, "%s could not be compiled", translationTableList);
5268
17
      return;
5269
17
    }
5270
290
  }
5271
545
}
5272
5273
int EXPORT_CALL
5274
288
lou_checkTable(const char *tableList) {
5275
288
  if (lou_getTable(tableList)) return 1;
5276
17
  return 0;
5277
288
}
5278
5279
formtype EXPORT_CALL
5280
0
lou_getTypeformForEmphClass(const char *tableList, const char *emphClass) {
5281
0
  const TranslationTableHeader *table = _lou_getTranslationTable(tableList);
5282
0
  if (!table) return 0;
5283
0
  for (int i = 0; i < MAX_EMPH_CLASSES && table->emphClassNames[i]; i++)
5284
0
    if (strcmp(emphClass, table->emphClassNames[i]) == 0) return italic << i;
5285
0
  return 0;
5286
0
}
5287
5288
static formtype *typebuf = NULL;
5289
static unsigned int *wordBuffer = NULL;
5290
static EmphasisInfo *emphasisBuffer = NULL;
5291
static int sizeTypebuf = 0;
5292
static widechar *passbuf[MAXPASSBUF] = { NULL };
5293
static int sizePassbuf[MAXPASSBUF] = { 0 };
5294
static int *posMapping1 = NULL;
5295
static int sizePosMapping1 = 0;
5296
static int *posMapping2 = NULL;
5297
static int sizePosMapping2 = 0;
5298
static int *posMapping3 = NULL;
5299
static int sizePosMapping3 = 0;
5300
void *EXPORT_CALL
5301
1.68k
_lou_allocMem(AllocBuf buffer, int index, int srcmax, int destmax) {
5302
1.68k
  if (srcmax < 1024) srcmax = 1024;
5303
1.68k
  if (destmax < 1024) destmax = 1024;
5304
1.68k
  switch (buffer) {
5305
177
  case alloc_typebuf:
5306
177
    if (destmax > sizeTypebuf) {
5307
177
      if (typebuf != NULL) free(typebuf);
5308
      // TODO: should this be srcmax?
5309
177
      typebuf = malloc((destmax + 4) * sizeof(formtype));
5310
177
      if (!typebuf) _lou_outOfMemory();
5311
177
      sizeTypebuf = destmax;
5312
177
    }
5313
177
    return typebuf;
5314
5315
177
  case alloc_wordBuffer:
5316
5317
177
    if (wordBuffer != NULL) free(wordBuffer);
5318
177
    wordBuffer = calloc(srcmax + 4, sizeof(unsigned int));
5319
177
    if (wordBuffer == NULL) _lou_outOfMemory();
5320
177
    return wordBuffer;
5321
5322
177
  case alloc_emphasisBuffer:
5323
5324
177
    if (emphasisBuffer != NULL) free(emphasisBuffer);
5325
177
    emphasisBuffer = calloc(srcmax + 4, sizeof(EmphasisInfo));
5326
177
    if (emphasisBuffer == NULL) _lou_outOfMemory();
5327
177
    return emphasisBuffer;
5328
5329
572
  case alloc_passbuf:
5330
572
    if (index < 0 || index >= MAXPASSBUF) {
5331
0
      _lou_logMessage(LOU_LOG_FATAL, "Index out of bounds: %d\n", index);
5332
0
      exit(3);
5333
0
    }
5334
572
    if (destmax > sizePassbuf[index]) {
5335
497
      if (passbuf[index] != NULL) free(passbuf[index]);
5336
497
      passbuf[index] = malloc((destmax + 4) * CHARSIZE);
5337
497
      if (!passbuf[index]) _lou_outOfMemory();
5338
497
      sizePassbuf[index] = destmax;
5339
497
    }
5340
572
    return passbuf[index];
5341
255
  case alloc_posMapping1: {
5342
255
    int mapSize;
5343
255
    if (srcmax >= destmax)
5344
27
      mapSize = srcmax;
5345
228
    else
5346
228
      mapSize = destmax;
5347
255
    if (mapSize > sizePosMapping1) {
5348
255
      if (posMapping1 != NULL) free(posMapping1);
5349
255
      posMapping1 = malloc((mapSize + 4) * sizeof(int));
5350
255
      if (!posMapping1) _lou_outOfMemory();
5351
255
      sizePosMapping1 = mapSize;
5352
255
    }
5353
255
  }
5354
255
    return posMapping1;
5355
165
  case alloc_posMapping2: {
5356
165
    int mapSize;
5357
165
    if (srcmax >= destmax)
5358
18
      mapSize = srcmax;
5359
147
    else
5360
147
      mapSize = destmax;
5361
165
    if (mapSize > sizePosMapping2) {
5362
165
      if (posMapping2 != NULL) free(posMapping2);
5363
165
      posMapping2 = malloc((mapSize + 4) * sizeof(int));
5364
165
      if (!posMapping2) _lou_outOfMemory();
5365
165
      sizePosMapping2 = mapSize;
5366
165
    }
5367
165
  }
5368
165
    return posMapping2;
5369
165
  case alloc_posMapping3: {
5370
165
    int mapSize;
5371
165
    if (srcmax >= destmax)
5372
18
      mapSize = srcmax;
5373
147
    else
5374
147
      mapSize = destmax;
5375
165
    if (mapSize > sizePosMapping3) {
5376
165
      if (posMapping3 != NULL) free(posMapping3);
5377
165
      posMapping3 = malloc((mapSize + 4) * sizeof(int));
5378
165
      if (!posMapping3) _lou_outOfMemory();
5379
165
      sizePosMapping3 = mapSize;
5380
165
    }
5381
165
  }
5382
165
    return posMapping3;
5383
0
  default:
5384
0
    return NULL;
5385
1.68k
  }
5386
1.68k
}
5387
5388
void EXPORT_CALL
5389
290
lou_free(void) {
5390
290
  lou_logEnd();
5391
290
  if (translationTableChain != NULL) {
5392
273
    TranslationTableChainEntry *currentEntry = translationTableChain;
5393
273
    TranslationTableChainEntry *previousEntry;
5394
546
    while (currentEntry) {
5395
273
      freeTranslationTable(currentEntry->table);
5396
273
      previousEntry = currentEntry;
5397
273
      currentEntry = currentEntry->next;
5398
273
      free(previousEntry);
5399
273
    }
5400
273
    translationTableChain = NULL;
5401
273
  }
5402
290
  if (displayTableChain != NULL) {
5403
273
    DisplayTableChainEntry *currentEntry = displayTableChain;
5404
273
    DisplayTableChainEntry *previousEntry;
5405
546
    while (currentEntry) {
5406
273
      freeDisplayTable(currentEntry->table);
5407
273
      previousEntry = currentEntry;
5408
273
      currentEntry = currentEntry->next;
5409
273
      free(previousEntry);
5410
273
    }
5411
273
    displayTableChain = NULL;
5412
273
  }
5413
290
  if (typebuf != NULL) free(typebuf);
5414
290
  typebuf = NULL;
5415
290
  if (wordBuffer != NULL) free(wordBuffer);
5416
290
  wordBuffer = NULL;
5417
290
  if (emphasisBuffer != NULL) free(emphasisBuffer);
5418
290
  emphasisBuffer = NULL;
5419
290
  sizeTypebuf = 0;
5420
290
  {
5421
290
    int k;
5422
1.16k
    for (k = 0; k < MAXPASSBUF; k++) {
5423
870
      if (passbuf[k] != NULL) free(passbuf[k]);
5424
870
      passbuf[k] = NULL;
5425
870
      sizePassbuf[k] = 0;
5426
870
    }
5427
290
  }
5428
290
  if (posMapping1 != NULL) free(posMapping1);
5429
290
  posMapping1 = NULL;
5430
290
  sizePosMapping1 = 0;
5431
290
  if (posMapping2 != NULL) free(posMapping2);
5432
290
  posMapping2 = NULL;
5433
290
  sizePosMapping2 = 0;
5434
290
  if (posMapping3 != NULL) free(posMapping3);
5435
290
  posMapping3 = NULL;
5436
290
  sizePosMapping3 = 0;
5437
290
  opcodeLengths[0] = 0;
5438
290
  _lou_freeTableIndex();
5439
290
}
5440
5441
const char *EXPORT_CALL
5442
0
lou_version(void) {
5443
0
  static const char *version = PACKAGE_VERSION;
5444
0
  return version;
5445
0
}
5446
5447
int EXPORT_CALL
5448
0
lou_charSize(void) {
5449
0
  return CHARSIZE;
5450
0
}
5451
5452
int EXPORT_CALL
5453
2
lou_compileString(const char *tableList, const char *inString) {
5454
2
  TranslationTableHeader *table;
5455
2
  DisplayTableHeader *displayTable;
5456
2
  getTable(tableList, tableList, &table, &displayTable);
5457
2
  if (!table) return 0;
5458
2
  if (!compileString(inString, &table, &displayTable)) return 0;
5459
2
  return 1;
5460
2
}
5461
5462
int EXPORT_CALL
5463
0
_lou_compileTranslationRule(const char *tableList, const char *inString) {
5464
0
  TranslationTableHeader *table;
5465
0
  getTable(tableList, NULL, &table, NULL);
5466
0
  if (!table) return 0;
5467
0
  return compileString(inString, &table, NULL);
5468
0
}
5469
5470
int EXPORT_CALL
5471
0
_lou_compileDisplayRule(const char *tableList, const char *inString) {
5472
0
  DisplayTableHeader *table;
5473
0
  getTable(NULL, tableList, NULL, &table);
5474
0
  if (!table) return 0;
5475
0
  return compileString(inString, NULL, &table);
5476
0
}
5477
5478
/**
5479
 * This procedure provides a target for cals that serve as breakpoints
5480
 * for gdb.
5481
 */
5482
// char *EXPORT_CALL
5483
// lou_getTablePaths (void)
5484
// {
5485
//   static char paths[MAXSTRING];
5486
//   static char scratchBuf[MAXSTRING];
5487
//   char *pathList;
5488
//   strcpy (paths, tablePath);
5489
//   strcat (paths, ",");
5490
//   pathList = getenv ("LOUIS_TABLEPATH");
5491
//   if (pathList)
5492
//     {
5493
//       strcat (paths, pathList);
5494
//       strcat (paths, ",");
5495
//     }
5496
//   pathList = getcwd (scratchBuf, MAXSTRING);
5497
//   if (pathList)
5498
//     {
5499
//       strcat (paths, pathList);
5500
//       strcat (paths, ",");
5501
//     }
5502
//   pathList = lou_getDataPath ();
5503
//   if (pathList)
5504
//     {
5505
//       strcat (paths, pathList);
5506
//       strcat (paths, ",");
5507
//     }
5508
// #ifdef _WIN32
5509
//   strcpy (paths, lou_getProgramPath ());
5510
//   strcat (paths, "\\share\\liblouss\\tables\\");
5511
// #else
5512
//   strcpy (paths, TABLESDIR);
5513
// #endif
5514
//   return paths;
5515
// }